1
0

three.webgpu.js 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, error, EventDispatcher, MathUtils, warn, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBufferAttribute, InterleavedBuffer, DynamicDrawUsage, NoColorSpace, log as log$1, warnOnce, Texture, UnsignedIntType, IntType, Compatibility, LessCompare, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, NoNormalPacking, NormalRGPacking, NormalGAPacking, ObjectSpaceNormalMap, RGFormat, RED_GREEN_RGTC2_Format, RG11_EAC_Format, InstancedBufferAttribute, InstancedInterleavedBuffer, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, DataTexture, HalfFloatType, ClampToEdgeWrapping, BufferGeometry, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, CubeUVReflectionMapping, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, NormalBlending, SrcAlphaFactor, OneMinusSrcAlphaFactor, AddEquation, MaterialBlending, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessEqualCompare, PCFShadowMap, PCFSoftShadowMap, BasicShadowMap, CubeDepthTexture, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, FrustumArray, Frustum, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, TimestampQuery, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, SIGNED_RG11_EAC_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_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, isTypedArray, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, getConsoleFunction, setConsoleFunction } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.context.modelViewMatrix || builder.context.modelNormalViewMatrix || builder.context.getAO || builder.context.getShadow )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. renderObjectData.morphTargetInfluences[ i ] = object.morphTargetInfluences[ i ];
  330. morphChanged = true;
  331. }
  332. }
  333. if ( morphChanged ) return false;
  334. }
  335. // lights
  336. if ( renderObjectData.lights ) {
  337. for ( let i = 0; i < lightsData.length; i ++ ) {
  338. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  339. return false;
  340. }
  341. }
  342. }
  343. // center
  344. if ( renderObjectData.center ) {
  345. if ( renderObjectData.center.equals( object.center ) === false ) {
  346. renderObjectData.center.copy( object.center );
  347. return true;
  348. }
  349. }
  350. // bundle
  351. if ( renderObject.bundle !== null ) {
  352. renderObjectData.version = renderObject.bundle.version;
  353. }
  354. return true;
  355. }
  356. /**
  357. * Returns the lights data for the given material lights.
  358. *
  359. * @param {Array<Light>} materialLights - The material lights.
  360. * @return {Array<Object>} The lights data for the given material lights.
  361. */
  362. getLightsData( materialLights ) {
  363. const lights = [];
  364. for ( const light of materialLights ) {
  365. if ( light.isSpotLight === true && light.map !== null ) {
  366. // only add lights that have a map
  367. lights.push( { map: light.map.version } );
  368. }
  369. }
  370. return lights;
  371. }
  372. /**
  373. * Returns the lights for the given lights node and render ID.
  374. *
  375. * @param {LightsNode} lightsNode - The lights node.
  376. * @param {number} renderId - The render ID.
  377. * @return {Array<Object>} The lights for the given lights node and render ID.
  378. */
  379. getLights( lightsNode, renderId ) {
  380. if ( _lightsCache.has( lightsNode ) ) {
  381. const cached = _lightsCache.get( lightsNode );
  382. if ( cached.renderId === renderId ) {
  383. return cached.lightsData;
  384. }
  385. }
  386. const lightsData = this.getLightsData( lightsNode.getLights() );
  387. _lightsCache.set( lightsNode, { renderId, lightsData } );
  388. return lightsData;
  389. }
  390. /**
  391. * Checks if the given render object requires a refresh.
  392. *
  393. * @param {RenderObject} renderObject - The render object.
  394. * @param {NodeFrame} nodeFrame - The current node frame.
  395. * @return {boolean} Whether the given render object requires a refresh or not.
  396. */
  397. needsRefresh( renderObject, nodeFrame ) {
  398. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  399. return true;
  400. const { renderId } = nodeFrame;
  401. if ( this.renderId !== renderId ) {
  402. this.renderId = renderId;
  403. return true;
  404. }
  405. const isStatic = renderObject.object.static === true;
  406. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  407. if ( isStatic || isBundle )
  408. return false;
  409. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  410. const notEqual = this.equals( renderObject, lightsData ) !== true;
  411. return notEqual;
  412. }
  413. }
  414. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  415. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  416. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  417. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  418. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  419. function cyrb53( value, seed = 0 ) {
  420. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  421. if ( value instanceof Array ) {
  422. for ( let i = 0, val; i < value.length; i ++ ) {
  423. val = value[ i ];
  424. h1 = Math.imul( h1 ^ val, 2654435761 );
  425. h2 = Math.imul( h2 ^ val, 1597334677 );
  426. }
  427. } else {
  428. for ( let i = 0, ch; i < value.length; i ++ ) {
  429. ch = value.charCodeAt( i );
  430. h1 = Math.imul( h1 ^ ch, 2654435761 );
  431. h2 = Math.imul( h2 ^ ch, 1597334677 );
  432. }
  433. }
  434. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  435. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  436. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  437. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  438. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  439. }
  440. /**
  441. * Computes a hash for the given string.
  442. *
  443. * @private
  444. * @method
  445. * @param {string} str - The string to be hashed.
  446. * @return {number} The hash.
  447. */
  448. const hashString = ( str ) => cyrb53( str );
  449. /**
  450. * Computes a hash for the given array.
  451. *
  452. * @private
  453. * @method
  454. * @param {Array<number>} array - The array to be hashed.
  455. * @return {number} The hash.
  456. */
  457. const hashArray = ( array ) => cyrb53( array );
  458. /**
  459. * Computes a hash for the given list of parameters.
  460. *
  461. * @private
  462. * @method
  463. * @param {...number} params - A list of parameters.
  464. * @return {number} The hash.
  465. */
  466. const hash$1 = ( ...params ) => cyrb53( params );
  467. const typeFromLength = /*@__PURE__*/ new Map( [
  468. [ 1, 'float' ],
  469. [ 2, 'vec2' ],
  470. [ 3, 'vec3' ],
  471. [ 4, 'vec4' ],
  472. [ 9, 'mat3' ],
  473. [ 16, 'mat4' ]
  474. ] );
  475. const dataFromObject = /*@__PURE__*/ new WeakMap();
  476. /**
  477. * Returns the data type for the given the length.
  478. *
  479. * @private
  480. * @method
  481. * @param {number} length - The length.
  482. * @return {string} The data type.
  483. */
  484. function getTypeFromLength( length ) {
  485. return typeFromLength.get( length );
  486. }
  487. /**
  488. * Returns the typed array for the given data type.
  489. *
  490. * @private
  491. * @method
  492. * @param {string} type - The data type.
  493. * @return {TypedArray} The typed array.
  494. */
  495. function getTypedArrayFromType( type ) {
  496. // Handle component type for vectors and matrices
  497. if ( /[iu]?vec\d/.test( type ) ) {
  498. // Handle int vectors
  499. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  500. // Handle uint vectors
  501. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  502. // Default to float vectors
  503. return Float32Array;
  504. }
  505. // Handle matrices (always float)
  506. if ( /mat\d/.test( type ) ) return Float32Array;
  507. // Basic types
  508. if ( /float/.test( type ) ) return Float32Array;
  509. if ( /uint/.test( type ) ) return Uint32Array;
  510. if ( /int/.test( type ) ) return Int32Array;
  511. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  512. }
  513. /**
  514. * Returns the length for the given data type.
  515. *
  516. * @private
  517. * @method
  518. * @param {string} type - The data type.
  519. * @return {number} The length.
  520. */
  521. function getLengthFromType( type ) {
  522. if ( /float|int|uint/.test( type ) ) return 1;
  523. if ( /vec2/.test( type ) ) return 2;
  524. if ( /vec3/.test( type ) ) return 3;
  525. if ( /vec4/.test( type ) ) return 4;
  526. if ( /mat2/.test( type ) ) return 4;
  527. if ( /mat3/.test( type ) ) return 9;
  528. if ( /mat4/.test( type ) ) return 16;
  529. error( 'TSL: Unsupported type:', type );
  530. }
  531. /**
  532. * Returns the gpu memory length for the given data type.
  533. *
  534. * @private
  535. * @method
  536. * @param {string} type - The data type.
  537. * @return {number} The length.
  538. */
  539. function getMemoryLengthFromType( type ) {
  540. if ( /float|int|uint/.test( type ) ) return 1;
  541. if ( /vec2/.test( type ) ) return 2;
  542. if ( /vec3/.test( type ) ) return 3;
  543. if ( /vec4/.test( type ) ) return 4;
  544. if ( /mat2/.test( type ) ) return 4;
  545. if ( /mat3/.test( type ) ) return 12;
  546. if ( /mat4/.test( type ) ) return 16;
  547. error( 'TSL: Unsupported type:', type );
  548. }
  549. /**
  550. * Returns the alignment requirement for the given data type.
  551. *
  552. * @private
  553. * @method
  554. * @param {string} type - The data type.
  555. * @return {number} The alignment requirement in bytes.
  556. */
  557. function getAlignmentFromType( type ) {
  558. if ( /float|int|uint/.test( type ) ) return 4;
  559. if ( /vec2/.test( type ) ) return 8;
  560. if ( /vec3/.test( type ) ) return 16;
  561. if ( /vec4/.test( type ) ) return 16;
  562. if ( /mat2/.test( type ) ) return 8;
  563. if ( /mat3/.test( type ) ) return 16;
  564. if ( /mat4/.test( type ) ) return 16;
  565. error( 'TSL: Unsupported type:', type );
  566. }
  567. /**
  568. * Returns the data type for the given value.
  569. *
  570. * @private
  571. * @method
  572. * @param {any} value - The value.
  573. * @return {?string} The data type.
  574. */
  575. function getValueType( value ) {
  576. if ( value === undefined || value === null ) return null;
  577. const typeOf = typeof value;
  578. if ( value.isNode === true ) {
  579. return 'node';
  580. } else if ( typeOf === 'number' ) {
  581. return 'float';
  582. } else if ( typeOf === 'boolean' ) {
  583. return 'bool';
  584. } else if ( typeOf === 'string' ) {
  585. return 'string';
  586. } else if ( typeOf === 'function' ) {
  587. return 'shader';
  588. } else if ( value.isVector2 === true ) {
  589. return 'vec2';
  590. } else if ( value.isVector3 === true ) {
  591. return 'vec3';
  592. } else if ( value.isVector4 === true ) {
  593. return 'vec4';
  594. } else if ( value.isMatrix2 === true ) {
  595. return 'mat2';
  596. } else if ( value.isMatrix3 === true ) {
  597. return 'mat3';
  598. } else if ( value.isMatrix4 === true ) {
  599. return 'mat4';
  600. } else if ( value.isColor === true ) {
  601. return 'color';
  602. } else if ( value instanceof ArrayBuffer ) {
  603. return 'ArrayBuffer';
  604. }
  605. return null;
  606. }
  607. /**
  608. * Returns the value/object for the given data type and parameters.
  609. *
  610. * @private
  611. * @method
  612. * @param {string} type - The given type.
  613. * @param {...any} params - A parameter list.
  614. * @return {any} The value/object.
  615. */
  616. function getValueFromType( type, ...params ) {
  617. const last4 = type ? type.slice( -4 ) : undefined;
  618. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  619. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  620. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  621. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  622. }
  623. if ( type === 'color' ) {
  624. return new Color( ...params );
  625. } else if ( last4 === 'vec2' ) {
  626. return new Vector2( ...params );
  627. } else if ( last4 === 'vec3' ) {
  628. return new Vector3( ...params );
  629. } else if ( last4 === 'vec4' ) {
  630. return new Vector4( ...params );
  631. } else if ( last4 === 'mat2' ) {
  632. return new Matrix2( ...params );
  633. } else if ( last4 === 'mat3' ) {
  634. return new Matrix3( ...params );
  635. } else if ( last4 === 'mat4' ) {
  636. return new Matrix4( ...params );
  637. } else if ( type === 'bool' ) {
  638. return params[ 0 ] || false;
  639. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  640. return params[ 0 ] || 0;
  641. } else if ( type === 'string' ) {
  642. return params[ 0 ] || '';
  643. } else if ( type === 'ArrayBuffer' ) {
  644. return base64ToArrayBuffer( params[ 0 ] );
  645. }
  646. return null;
  647. }
  648. /**
  649. * Gets the object data that can be shared between different rendering steps.
  650. *
  651. * @private
  652. * @param {Object} object - The object to get the data for.
  653. * @return {Object} The object data.
  654. */
  655. function getDataFromObject( object ) {
  656. let data = dataFromObject.get( object );
  657. if ( data === undefined ) {
  658. data = {};
  659. dataFromObject.set( object, data );
  660. }
  661. return data;
  662. }
  663. /**
  664. * Converts the given array buffer to a Base64 string.
  665. *
  666. * @private
  667. * @method
  668. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  669. * @return {string} The Base64 string.
  670. */
  671. function arrayBufferToBase64( arrayBuffer ) {
  672. let chars = '';
  673. const array = new Uint8Array( arrayBuffer );
  674. for ( let i = 0; i < array.length; i ++ ) {
  675. chars += String.fromCharCode( array[ i ] );
  676. }
  677. return btoa( chars );
  678. }
  679. /**
  680. * Converts the given Base64 string to an array buffer.
  681. *
  682. * @private
  683. * @method
  684. * @param {string} base64 - The Base64 string.
  685. * @return {ArrayBuffer} The array buffer.
  686. */
  687. function base64ToArrayBuffer( base64 ) {
  688. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  689. }
  690. var NodeUtils = /*#__PURE__*/Object.freeze({
  691. __proto__: null,
  692. arrayBufferToBase64: arrayBufferToBase64,
  693. base64ToArrayBuffer: base64ToArrayBuffer,
  694. getAlignmentFromType: getAlignmentFromType,
  695. getDataFromObject: getDataFromObject,
  696. getLengthFromType: getLengthFromType,
  697. getMemoryLengthFromType: getMemoryLengthFromType,
  698. getTypeFromLength: getTypeFromLength,
  699. getTypedArrayFromType: getTypedArrayFromType,
  700. getValueFromType: getValueFromType,
  701. getValueType: getValueType,
  702. hash: hash$1,
  703. hashArray: hashArray,
  704. hashString: hashString
  705. });
  706. /**
  707. * Possible shader stages.
  708. *
  709. * @property {string} VERTEX The vertex shader stage.
  710. * @property {string} FRAGMENT The fragment shader stage.
  711. */
  712. const NodeShaderStage = {
  713. VERTEX: 'vertex',
  714. FRAGMENT: 'fragment'
  715. };
  716. /**
  717. * Update types of a node.
  718. *
  719. * @property {string} NONE The update method is not executed.
  720. * @property {string} FRAME The update method is executed per frame.
  721. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  722. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  723. */
  724. const NodeUpdateType = {
  725. NONE: 'none',
  726. FRAME: 'frame',
  727. RENDER: 'render',
  728. OBJECT: 'object'
  729. };
  730. /**
  731. * Data types of a node.
  732. *
  733. * @property {string} BOOLEAN Boolean type.
  734. * @property {string} INTEGER Integer type.
  735. * @property {string} FLOAT Float type.
  736. * @property {string} VECTOR2 Two-dimensional vector type.
  737. * @property {string} VECTOR3 Three-dimensional vector type.
  738. * @property {string} VECTOR4 Four-dimensional vector type.
  739. * @property {string} MATRIX2 2x2 matrix type.
  740. * @property {string} MATRIX3 3x3 matrix type.
  741. * @property {string} MATRIX4 4x4 matrix type.
  742. */
  743. const NodeType = {
  744. BOOLEAN: 'bool',
  745. INTEGER: 'int',
  746. FLOAT: 'float',
  747. VECTOR2: 'vec2',
  748. VECTOR3: 'vec3',
  749. VECTOR4: 'vec4',
  750. MATRIX2: 'mat2',
  751. MATRIX3: 'mat3',
  752. MATRIX4: 'mat4'
  753. };
  754. /**
  755. * Access types of a node. These are relevant for compute and storage usage.
  756. *
  757. * @property {string} READ_ONLY Read-only access
  758. * @property {string} WRITE_ONLY Write-only access.
  759. * @property {string} READ_WRITE Read and write access.
  760. */
  761. const NodeAccess = {
  762. READ_ONLY: 'readOnly',
  763. WRITE_ONLY: 'writeOnly',
  764. READ_WRITE: 'readWrite',
  765. };
  766. const defaultShaderStages = [ 'fragment', 'vertex' ];
  767. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  768. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  769. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  770. const _parentBuildStage = {
  771. analyze: 'setup',
  772. generate: 'analyze'
  773. };
  774. let _nodeId = 0;
  775. /**
  776. * Base class for all nodes.
  777. *
  778. * @augments EventDispatcher
  779. */
  780. class Node extends EventDispatcher {
  781. static get type() {
  782. return 'Node';
  783. }
  784. /**
  785. * Constructs a new node.
  786. *
  787. * @param {?string} nodeType - The node type.
  788. */
  789. constructor( nodeType = null ) {
  790. super();
  791. /**
  792. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  793. *
  794. * @type {?string}
  795. * @default null
  796. */
  797. this.nodeType = nodeType;
  798. /**
  799. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  800. *
  801. * @type {string}
  802. * @default 'none'
  803. */
  804. this.updateType = NodeUpdateType.NONE;
  805. /**
  806. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  807. *
  808. * @type {string}
  809. * @default 'none'
  810. */
  811. this.updateBeforeType = NodeUpdateType.NONE;
  812. /**
  813. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  814. *
  815. * @type {string}
  816. * @default 'none'
  817. */
  818. this.updateAfterType = NodeUpdateType.NONE;
  819. /**
  820. * The UUID of the node.
  821. *
  822. * @type {string}
  823. * @readonly
  824. */
  825. this.uuid = MathUtils.generateUUID();
  826. /**
  827. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  828. *
  829. * @type {number}
  830. * @readonly
  831. * @default 0
  832. */
  833. this.version = 0;
  834. /**
  835. * The name of the node.
  836. *
  837. * @type {string}
  838. * @default ''
  839. */
  840. this.name = '';
  841. /**
  842. * Whether this node is global or not. This property is relevant for the internal
  843. * node caching system. All nodes which should be declared just once should
  844. * set this flag to `true` (a typical example is {@link AttributeNode}).
  845. *
  846. * @type {boolean}
  847. * @default false
  848. */
  849. this.global = false;
  850. /**
  851. * Create a list of parents for this node during the build process.
  852. *
  853. * @type {boolean}
  854. * @default false
  855. */
  856. this.parents = false;
  857. /**
  858. * This flag can be used for type testing.
  859. *
  860. * @type {boolean}
  861. * @readonly
  862. * @default true
  863. */
  864. this.isNode = true;
  865. // private
  866. this._beforeNodes = null;
  867. /**
  868. * The cache key of this node.
  869. *
  870. * @private
  871. * @type {?number}
  872. * @default null
  873. */
  874. this._cacheKey = null;
  875. /**
  876. * The cache key's version.
  877. *
  878. * @private
  879. * @type {number}
  880. * @default 0
  881. */
  882. this._cacheKeyVersion = 0;
  883. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  884. }
  885. /**
  886. * Set this property to `true` when the node should be regenerated.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. * @param {boolean} value
  891. */
  892. set needsUpdate( value ) {
  893. if ( value === true ) {
  894. this.version ++;
  895. }
  896. }
  897. /**
  898. * The type of the class. The value is usually the constructor name.
  899. *
  900. * @type {string}
  901. * @readonly
  902. */
  903. get type() {
  904. return this.constructor.type;
  905. }
  906. /**
  907. * Convenient method for defining {@link Node#update}.
  908. *
  909. * @param {Function} callback - The update method.
  910. * @param {string} updateType - The update type.
  911. * @return {Node} A reference to this node.
  912. */
  913. onUpdate( callback, updateType ) {
  914. this.updateType = updateType;
  915. this.update = callback.bind( this );
  916. return this;
  917. }
  918. /**
  919. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  920. * this method automatically sets the update type to `FRAME`.
  921. *
  922. * @param {Function} callback - The update method.
  923. * @return {Node} A reference to this node.
  924. */
  925. onFrameUpdate( callback ) {
  926. return this.onUpdate( callback, NodeUpdateType.FRAME );
  927. }
  928. /**
  929. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  930. * this method automatically sets the update type to `RENDER`.
  931. *
  932. * @param {Function} callback - The update method.
  933. * @return {Node} A reference to this node.
  934. */
  935. onRenderUpdate( callback ) {
  936. return this.onUpdate( callback, NodeUpdateType.RENDER );
  937. }
  938. /**
  939. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  940. * this method automatically sets the update type to `OBJECT`.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @return {Node} A reference to this node.
  944. */
  945. onObjectUpdate( callback ) {
  946. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  947. }
  948. /**
  949. * Convenient method for defining {@link Node#updateReference}.
  950. *
  951. * @param {Function} callback - The update method.
  952. * @return {Node} A reference to this node.
  953. */
  954. onReference( callback ) {
  955. this.updateReference = callback.bind( this );
  956. return this;
  957. }
  958. /**
  959. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  960. * to such objects based on a given state (e.g. the current node frame or builder).
  961. *
  962. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  963. * @return {any} The updated reference.
  964. */
  965. updateReference( /*state*/ ) {
  966. return this;
  967. }
  968. /**
  969. * By default this method returns the value of the {@link Node#global} flag. This method
  970. * can be overwritten in derived classes if an analytical way is required to determine the
  971. * global cache referring to the current shader-stage.
  972. *
  973. * @param {NodeBuilder} builder - The current node builder.
  974. * @return {boolean} Whether this node is global or not.
  975. */
  976. isGlobal( /*builder*/ ) {
  977. return this.global;
  978. }
  979. /**
  980. * Generator function that can be used to iterate over the child nodes.
  981. *
  982. * @generator
  983. * @yields {Node} A child node.
  984. */
  985. * getChildren() {
  986. for ( const { childNode } of this._getChildren() ) {
  987. yield childNode;
  988. }
  989. }
  990. /**
  991. * Calling this method dispatches the `dispose` event. This event can be used
  992. * to register event listeners for clean up tasks.
  993. */
  994. dispose() {
  995. this.dispatchEvent( { type: 'dispose' } );
  996. }
  997. /**
  998. * Callback for {@link Node#traverse}.
  999. *
  1000. * @callback traverseCallback
  1001. * @param {Node} node - The current node.
  1002. */
  1003. /**
  1004. * Can be used to traverse through the node's hierarchy.
  1005. *
  1006. * @param {traverseCallback} callback - A callback that is executed per node.
  1007. */
  1008. traverse( callback ) {
  1009. callback( this );
  1010. for ( const childNode of this.getChildren() ) {
  1011. childNode.traverse( callback );
  1012. }
  1013. }
  1014. /**
  1015. * Returns the child nodes of this node.
  1016. *
  1017. * @private
  1018. * @param {Set<Node>} [ignores=new Set()] - A set of nodes to ignore during the search to avoid circular references.
  1019. * @returns {Array<Object>} An array of objects describing the child nodes.
  1020. */
  1021. _getChildren( ignores = new Set() ) {
  1022. const children = [];
  1023. // avoid circular references
  1024. ignores.add( this );
  1025. for ( const property of Object.getOwnPropertyNames( this ) ) {
  1026. const object = this[ property ];
  1027. // Ignore private properties and ignored nodes.
  1028. if ( property.startsWith( '_' ) === true || ignores.has( object ) ) continue;
  1029. if ( Array.isArray( object ) === true ) {
  1030. for ( let i = 0; i < object.length; i ++ ) {
  1031. const child = object[ i ];
  1032. if ( child && child.isNode === true ) {
  1033. children.push( { property, index: i, childNode: child } );
  1034. }
  1035. }
  1036. } else if ( object && object.isNode === true ) {
  1037. children.push( { property, childNode: object } );
  1038. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  1039. for ( const subProperty in object ) {
  1040. // Ignore private sub-properties.
  1041. if ( subProperty.startsWith( '_' ) === true ) continue;
  1042. const child = object[ subProperty ];
  1043. if ( child && child.isNode === true ) {
  1044. children.push( { property, index: subProperty, childNode: child } );
  1045. }
  1046. }
  1047. }
  1048. }
  1049. //
  1050. return children;
  1051. }
  1052. /**
  1053. * Returns the cache key for this node.
  1054. *
  1055. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1056. * @param {Set<Node>} [ignores=null] - A set of nodes to ignore during the computation of the cache key.
  1057. * @return {number} The cache key of the node.
  1058. */
  1059. getCacheKey( force = false, ignores = null ) {
  1060. force = force || this.version !== this._cacheKeyVersion;
  1061. if ( force === true || this._cacheKey === null ) {
  1062. if ( ignores === null ) ignores = new Set();
  1063. //
  1064. const values = [];
  1065. for ( const { property, childNode } of this._getChildren( ignores ) ) {
  1066. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey( force, ignores ) );
  1067. }
  1068. //
  1069. this._cacheKey = hash$1( hashArray( values ), this.customCacheKey() );
  1070. this._cacheKeyVersion = this.version;
  1071. }
  1072. return this._cacheKey;
  1073. }
  1074. /**
  1075. * Generate a custom cache key for this node.
  1076. *
  1077. * @return {number} The cache key of the node.
  1078. */
  1079. customCacheKey() {
  1080. return this.id;
  1081. }
  1082. /**
  1083. * Returns the references to this node which is by default `this`.
  1084. *
  1085. * @return {Node} A reference to this node.
  1086. */
  1087. getScope() {
  1088. return this;
  1089. }
  1090. /**
  1091. * Returns the hash of the node which is used to identify the node. By default it's
  1092. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1093. * depending on their implementation.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. * @return {string} The hash.
  1097. */
  1098. getHash( /*builder*/ ) {
  1099. return this.uuid;
  1100. }
  1101. /**
  1102. * Returns the update type of {@link Node#update}.
  1103. *
  1104. * @return {NodeUpdateType} The update type.
  1105. */
  1106. getUpdateType() {
  1107. return this.updateType;
  1108. }
  1109. /**
  1110. * Returns the update type of {@link Node#updateBefore}.
  1111. *
  1112. * @return {NodeUpdateType} The update type.
  1113. */
  1114. getUpdateBeforeType() {
  1115. return this.updateBeforeType;
  1116. }
  1117. /**
  1118. * Returns the update type of {@link Node#updateAfter}.
  1119. *
  1120. * @return {NodeUpdateType} The update type.
  1121. */
  1122. getUpdateAfterType() {
  1123. return this.updateAfterType;
  1124. }
  1125. /**
  1126. * Certain types are composed of multiple elements. For example a `vec3`
  1127. * is composed of three `float` values. This method returns the type of
  1128. * these elements.
  1129. *
  1130. * @param {NodeBuilder} builder - The current node builder.
  1131. * @return {string} The type of the node.
  1132. */
  1133. getElementType( builder ) {
  1134. const type = this.getNodeType( builder );
  1135. const elementType = builder.getElementType( type );
  1136. return elementType;
  1137. }
  1138. /**
  1139. * Returns the node member type for the given name.
  1140. *
  1141. * @param {NodeBuilder} builder - The current node builder.
  1142. * @param {string} name - The name of the member.
  1143. * @return {string} The type of the node.
  1144. */
  1145. getMemberType( /*builder, name*/ ) {
  1146. return 'void';
  1147. }
  1148. /**
  1149. * Returns the node's type.
  1150. *
  1151. * @param {NodeBuilder} builder - The current node builder.
  1152. * @return {string} The type of the node.
  1153. */
  1154. getNodeType( builder ) {
  1155. const nodeProperties = builder.getNodeProperties( this );
  1156. if ( nodeProperties.outputNode ) {
  1157. return nodeProperties.outputNode.getNodeType( builder );
  1158. }
  1159. return this.nodeType;
  1160. }
  1161. /**
  1162. * This method is used during the build process of a node and ensures
  1163. * equal nodes are not built multiple times but just once. For example if
  1164. * `attribute( 'uv' )` is used multiple times by the user, the build
  1165. * process makes sure to process just the first node.
  1166. *
  1167. * @param {NodeBuilder} builder - The current node builder.
  1168. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1169. */
  1170. getShared( builder ) {
  1171. const hash = this.getHash( builder );
  1172. const nodeFromHash = builder.getNodeFromHash( hash );
  1173. return nodeFromHash || this;
  1174. }
  1175. /**
  1176. * Returns the number of elements in the node array.
  1177. *
  1178. * @param {NodeBuilder} builder - The current node builder.
  1179. * @return {?number} The number of elements in the node array.
  1180. */
  1181. getArrayCount( /*builder*/ ) {
  1182. return null;
  1183. }
  1184. /**
  1185. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1186. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1187. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1188. *
  1189. * @param {NodeBuilder} builder - The current node builder.
  1190. * @return {?Node} The output node.
  1191. */
  1192. setup( builder ) {
  1193. const nodeProperties = builder.getNodeProperties( this );
  1194. let index = 0;
  1195. for ( const childNode of this.getChildren() ) {
  1196. nodeProperties[ 'node' + index ++ ] = childNode;
  1197. }
  1198. // return a outputNode if exists or null
  1199. return nodeProperties.outputNode || null;
  1200. }
  1201. /**
  1202. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1203. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1204. *
  1205. * @param {NodeBuilder} builder - The current node builder.
  1206. * @param {?Node} output - The target output node.
  1207. */
  1208. analyze( builder, output = null ) {
  1209. const usageCount = builder.increaseUsage( this );
  1210. if ( this.parents === true ) {
  1211. const nodeData = builder.getDataFromNode( this, 'any' );
  1212. nodeData.stages = nodeData.stages || {};
  1213. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1214. nodeData.stages[ builder.shaderStage ].push( output );
  1215. }
  1216. if ( usageCount === 1 ) {
  1217. // node flow children
  1218. const nodeProperties = builder.getNodeProperties( this );
  1219. for ( const childNode of Object.values( nodeProperties ) ) {
  1220. if ( childNode && childNode.isNode === true ) {
  1221. childNode.build( builder, this );
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /**
  1227. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1228. * This state builds the output node and returns the resulting shader string.
  1229. *
  1230. * @param {NodeBuilder} builder - The current node builder.
  1231. * @param {?string} [output] - Can be used to define the output type.
  1232. * @return {?string} The generated shader string.
  1233. */
  1234. generate( builder, output ) {
  1235. const { outputNode } = builder.getNodeProperties( this );
  1236. if ( outputNode && outputNode.isNode === true ) {
  1237. return outputNode.build( builder, output );
  1238. }
  1239. }
  1240. /**
  1241. * The method can be implemented to update the node's internal state before it is used to render an object.
  1242. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1243. *
  1244. * @abstract
  1245. * @param {NodeFrame} frame - A reference to the current node frame.
  1246. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1247. */
  1248. updateBefore( /*frame*/ ) {
  1249. warn( 'Abstract function.' );
  1250. }
  1251. /**
  1252. * The method can be implemented to update the node's internal state after it was used to render an object.
  1253. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1254. *
  1255. * @abstract
  1256. * @param {NodeFrame} frame - A reference to the current node frame.
  1257. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1258. */
  1259. updateAfter( /*frame*/ ) {
  1260. warn( 'Abstract function.' );
  1261. }
  1262. /**
  1263. * The method can be implemented to update the node's internal state when it is used to render an object.
  1264. * The {@link Node#updateType} property defines how often the update is executed.
  1265. *
  1266. * @abstract
  1267. * @param {NodeFrame} frame - A reference to the current node frame.
  1268. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1269. */
  1270. update( /*frame*/ ) {
  1271. warn( 'Abstract function.' );
  1272. }
  1273. before( node ) {
  1274. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1275. this._beforeNodes.push( node );
  1276. return this;
  1277. }
  1278. /**
  1279. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1280. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1281. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1282. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1283. *
  1284. * @param {NodeBuilder} builder - The current node builder.
  1285. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1286. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1287. */
  1288. build( builder, output = null ) {
  1289. const refNode = this.getShared( builder );
  1290. if ( this !== refNode ) {
  1291. return refNode.build( builder, output );
  1292. }
  1293. //
  1294. if ( this._beforeNodes !== null ) {
  1295. const currentBeforeNodes = this._beforeNodes;
  1296. this._beforeNodes = null;
  1297. for ( const beforeNode of currentBeforeNodes ) {
  1298. beforeNode.build( builder, output );
  1299. }
  1300. this._beforeNodes = currentBeforeNodes;
  1301. }
  1302. //
  1303. const nodeData = builder.getDataFromNode( this );
  1304. nodeData.buildStages = nodeData.buildStages || {};
  1305. nodeData.buildStages[ builder.buildStage ] = true;
  1306. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1307. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1308. // force parent build stage (setup or analyze)
  1309. const previousBuildStage = builder.getBuildStage();
  1310. builder.setBuildStage( parentBuildStage );
  1311. this.build( builder );
  1312. builder.setBuildStage( previousBuildStage );
  1313. }
  1314. //
  1315. builder.addNode( this );
  1316. builder.addChain( this );
  1317. /* Build stages expected results:
  1318. - "setup" -> Node
  1319. - "analyze" -> null
  1320. - "generate" -> String
  1321. */
  1322. let result = null;
  1323. const buildStage = builder.getBuildStage();
  1324. if ( buildStage === 'setup' ) {
  1325. this.updateReference( builder );
  1326. const properties = builder.getNodeProperties( this );
  1327. if ( properties.initialized !== true ) {
  1328. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1329. properties.initialized = true;
  1330. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1331. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1332. // !! no outputNode !!
  1333. //outputNode = builder.stack;
  1334. }*/
  1335. for ( const childNode of Object.values( properties ) ) {
  1336. if ( childNode && childNode.isNode === true ) {
  1337. if ( childNode.parents === true ) {
  1338. const childProperties = builder.getNodeProperties( childNode );
  1339. childProperties.parents = childProperties.parents || [];
  1340. childProperties.parents.push( this );
  1341. }
  1342. childNode.build( builder );
  1343. }
  1344. }
  1345. }
  1346. result = properties.outputNode;
  1347. } else if ( buildStage === 'analyze' ) {
  1348. this.analyze( builder, output );
  1349. } else if ( buildStage === 'generate' ) {
  1350. // If generate has just one argument, it means the output type is not required.
  1351. // This means that the node does not handle output conversions internally,
  1352. // so the value is stored in a cache and the builder handles the conversion
  1353. // for all requested output types.
  1354. const isGenerateOnce = this.generate.length < 2;
  1355. if ( isGenerateOnce ) {
  1356. const type = this.getNodeType( builder );
  1357. const nodeData = builder.getDataFromNode( this );
  1358. result = nodeData.snippet;
  1359. if ( result === undefined ) {
  1360. if ( nodeData.generated === undefined ) {
  1361. nodeData.generated = true;
  1362. result = this.generate( builder ) || '';
  1363. nodeData.snippet = result;
  1364. } else {
  1365. warn( 'Node: Recursion detected.', this );
  1366. result = '/* Recursion detected. */';
  1367. }
  1368. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1369. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1370. }
  1371. result = builder.format( result, type, output );
  1372. } else {
  1373. result = this.generate( builder, output ) || '';
  1374. }
  1375. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1376. // if no snippet is generated, return a default value
  1377. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1378. result = builder.generateConst( output );
  1379. }
  1380. }
  1381. builder.removeChain( this );
  1382. builder.addSequentialNode( this );
  1383. return result;
  1384. }
  1385. /**
  1386. * Returns the child nodes as a JSON object.
  1387. *
  1388. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1389. */
  1390. getSerializeChildren() {
  1391. return this._getChildren();
  1392. }
  1393. /**
  1394. * Serializes the node to JSON.
  1395. *
  1396. * @param {Object} json - The output JSON object.
  1397. */
  1398. serialize( json ) {
  1399. const nodeChildren = this.getSerializeChildren();
  1400. const inputNodes = {};
  1401. for ( const { property, index, childNode } of nodeChildren ) {
  1402. if ( index !== undefined ) {
  1403. if ( inputNodes[ property ] === undefined ) {
  1404. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1405. }
  1406. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1407. } else {
  1408. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1409. }
  1410. }
  1411. if ( Object.keys( inputNodes ).length > 0 ) {
  1412. json.inputNodes = inputNodes;
  1413. }
  1414. }
  1415. /**
  1416. * Deserializes the node from the given JSON.
  1417. *
  1418. * @param {Object} json - The JSON object.
  1419. */
  1420. deserialize( json ) {
  1421. if ( json.inputNodes !== undefined ) {
  1422. const nodes = json.meta.nodes;
  1423. for ( const property in json.inputNodes ) {
  1424. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1425. const inputArray = [];
  1426. for ( const uuid of json.inputNodes[ property ] ) {
  1427. inputArray.push( nodes[ uuid ] );
  1428. }
  1429. this[ property ] = inputArray;
  1430. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1431. const inputObject = {};
  1432. for ( const subProperty in json.inputNodes[ property ] ) {
  1433. const uuid = json.inputNodes[ property ][ subProperty ];
  1434. inputObject[ subProperty ] = nodes[ uuid ];
  1435. }
  1436. this[ property ] = inputObject;
  1437. } else {
  1438. const uuid = json.inputNodes[ property ];
  1439. this[ property ] = nodes[ uuid ];
  1440. }
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * Serializes the node into the three.js JSON Object/Scene format.
  1446. *
  1447. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1448. * @return {Object} The serialized node.
  1449. */
  1450. toJSON( meta ) {
  1451. const { uuid, type } = this;
  1452. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1453. if ( isRoot ) {
  1454. meta = {
  1455. textures: {},
  1456. images: {},
  1457. nodes: {}
  1458. };
  1459. }
  1460. // serialize
  1461. let data = meta.nodes[ uuid ];
  1462. if ( data === undefined ) {
  1463. data = {
  1464. uuid,
  1465. type,
  1466. meta,
  1467. metadata: {
  1468. version: 4.7,
  1469. type: 'Node',
  1470. generator: 'Node.toJSON'
  1471. }
  1472. };
  1473. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1474. this.serialize( data );
  1475. delete data.meta;
  1476. }
  1477. // TODO: Copied from Object3D.toJSON
  1478. function extractFromCache( cache ) {
  1479. const values = [];
  1480. for ( const key in cache ) {
  1481. const data = cache[ key ];
  1482. delete data.metadata;
  1483. values.push( data );
  1484. }
  1485. return values;
  1486. }
  1487. if ( isRoot ) {
  1488. const textures = extractFromCache( meta.textures );
  1489. const images = extractFromCache( meta.images );
  1490. const nodes = extractFromCache( meta.nodes );
  1491. if ( textures.length > 0 ) data.textures = textures;
  1492. if ( images.length > 0 ) data.images = images;
  1493. if ( nodes.length > 0 ) data.nodes = nodes;
  1494. }
  1495. return data;
  1496. }
  1497. }
  1498. /**
  1499. * Base class for representing element access on an array-like
  1500. * node data structures.
  1501. *
  1502. * @augments Node
  1503. */
  1504. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1505. static get type() {
  1506. return 'ArrayElementNode';
  1507. }
  1508. /**
  1509. * Constructs an array element node.
  1510. *
  1511. * @param {Node} node - The array-like node.
  1512. * @param {Node} indexNode - The index node that defines the element access.
  1513. */
  1514. constructor( node, indexNode ) {
  1515. super();
  1516. /**
  1517. * The array-like node.
  1518. *
  1519. * @type {Node}
  1520. */
  1521. this.node = node;
  1522. /**
  1523. * The index node that defines the element access.
  1524. *
  1525. * @type {Node}
  1526. */
  1527. this.indexNode = indexNode;
  1528. /**
  1529. * This flag can be used for type testing.
  1530. *
  1531. * @type {boolean}
  1532. * @readonly
  1533. * @default true
  1534. */
  1535. this.isArrayElementNode = true;
  1536. }
  1537. /**
  1538. * This method is overwritten since the node type is inferred from the array-like node.
  1539. *
  1540. * @param {NodeBuilder} builder - The current node builder.
  1541. * @return {string} The node type.
  1542. */
  1543. getNodeType( builder ) {
  1544. return this.node.getElementType( builder );
  1545. }
  1546. /**
  1547. * This method is overwritten since the member type is inferred from the array-like node.
  1548. *
  1549. * @param {NodeBuilder} builder - The current node builder.
  1550. * @param {string} name - The member name.
  1551. * @return {string} The member type.
  1552. */
  1553. getMemberType( builder, name ) {
  1554. return this.node.getMemberType( builder, name );
  1555. }
  1556. generate( builder ) {
  1557. const indexType = this.indexNode.getNodeType( builder );
  1558. const nodeSnippet = this.node.build( builder );
  1559. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1560. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1561. }
  1562. }
  1563. /**
  1564. * This module is part of the TSL core and usually not used in app level code.
  1565. * It represents a convert operation during the shader generation process
  1566. * meaning it converts the data type of a node to a target data type.
  1567. *
  1568. * @augments Node
  1569. */
  1570. class ConvertNode extends Node {
  1571. static get type() {
  1572. return 'ConvertNode';
  1573. }
  1574. /**
  1575. * Constructs a new convert node.
  1576. *
  1577. * @param {Node} node - The node which type should be converted.
  1578. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1579. */
  1580. constructor( node, convertTo ) {
  1581. super();
  1582. /**
  1583. * The node which type should be converted.
  1584. *
  1585. * @type {Node}
  1586. */
  1587. this.node = node;
  1588. /**
  1589. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1590. *
  1591. * @type {string}
  1592. */
  1593. this.convertTo = convertTo;
  1594. }
  1595. /**
  1596. * This method is overwritten since the implementation tries to infer the best
  1597. * matching type from the {@link ConvertNode#convertTo} property.
  1598. *
  1599. * @param {NodeBuilder} builder - The current node builder.
  1600. * @return {string} The node type.
  1601. */
  1602. getNodeType( builder ) {
  1603. const requestType = this.node.getNodeType( builder );
  1604. let convertTo = null;
  1605. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1606. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1607. convertTo = overloadingType;
  1608. }
  1609. }
  1610. return convertTo;
  1611. }
  1612. serialize( data ) {
  1613. super.serialize( data );
  1614. data.convertTo = this.convertTo;
  1615. }
  1616. deserialize( data ) {
  1617. super.deserialize( data );
  1618. this.convertTo = data.convertTo;
  1619. }
  1620. generate( builder, output ) {
  1621. const node = this.node;
  1622. const type = this.getNodeType( builder );
  1623. const snippet = node.build( builder, type );
  1624. return builder.format( snippet, type, output );
  1625. }
  1626. }
  1627. /**
  1628. * This module uses cache management to create temporary variables
  1629. * if the node is used more than once to prevent duplicate calculations.
  1630. *
  1631. * The class acts as a base class for many other nodes types.
  1632. *
  1633. * @augments Node
  1634. */
  1635. class TempNode extends Node {
  1636. static get type() {
  1637. return 'TempNode';
  1638. }
  1639. /**
  1640. * Constructs a temp node.
  1641. *
  1642. * @param {?string} nodeType - The node type.
  1643. */
  1644. constructor( nodeType = null ) {
  1645. super( nodeType );
  1646. /**
  1647. * This flag can be used for type testing.
  1648. *
  1649. * @type {boolean}
  1650. * @readonly
  1651. * @default true
  1652. */
  1653. this.isTempNode = true;
  1654. }
  1655. /**
  1656. * Whether this node is used more than once in context of other nodes.
  1657. *
  1658. * @param {NodeBuilder} builder - The node builder.
  1659. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1660. */
  1661. hasDependencies( builder ) {
  1662. return builder.getDataFromNode( this ).usageCount > 1;
  1663. }
  1664. build( builder, output ) {
  1665. const buildStage = builder.getBuildStage();
  1666. if ( buildStage === 'generate' ) {
  1667. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1668. const nodeData = builder.getDataFromNode( this );
  1669. if ( nodeData.propertyName !== undefined ) {
  1670. return builder.format( nodeData.propertyName, type, output );
  1671. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1672. const snippet = super.build( builder, type );
  1673. const nodeVar = builder.getVarFromNode( this, null, type );
  1674. const propertyName = builder.getPropertyName( nodeVar );
  1675. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1676. nodeData.snippet = snippet;
  1677. nodeData.propertyName = propertyName;
  1678. return builder.format( nodeData.propertyName, type, output );
  1679. }
  1680. }
  1681. return super.build( builder, output );
  1682. }
  1683. }
  1684. /**
  1685. * This module is part of the TSL core and usually not used in app level code.
  1686. * It represents a join operation during the shader generation process.
  1687. * For example in can compose/join two single floats into a `vec2` type.
  1688. *
  1689. * @augments TempNode
  1690. */
  1691. class JoinNode extends TempNode {
  1692. static get type() {
  1693. return 'JoinNode';
  1694. }
  1695. /**
  1696. * Constructs a new join node.
  1697. *
  1698. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1699. * @param {?string} [nodeType=null] - The node type.
  1700. */
  1701. constructor( nodes = [], nodeType = null ) {
  1702. super( nodeType );
  1703. /**
  1704. * An array of nodes that should be joined.
  1705. *
  1706. * @type {Array<Node>}
  1707. */
  1708. this.nodes = nodes;
  1709. }
  1710. /**
  1711. * This method is overwritten since the node type must be inferred from the
  1712. * joined data length if not explicitly defined.
  1713. *
  1714. * @param {NodeBuilder} builder - The current node builder.
  1715. * @return {string} The node type.
  1716. */
  1717. getNodeType( builder ) {
  1718. if ( this.nodeType !== null ) {
  1719. return builder.getVectorType( this.nodeType );
  1720. }
  1721. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1722. }
  1723. generate( builder, output ) {
  1724. const type = this.getNodeType( builder );
  1725. const maxLength = builder.getTypeLength( type );
  1726. const nodes = this.nodes;
  1727. const primitiveType = builder.getComponentType( type );
  1728. const snippetValues = [];
  1729. let length = 0;
  1730. for ( const input of nodes ) {
  1731. if ( length >= maxLength ) {
  1732. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1733. break;
  1734. }
  1735. let inputType = input.getNodeType( builder );
  1736. let inputTypeLength = builder.getTypeLength( inputType );
  1737. let inputSnippet;
  1738. if ( length + inputTypeLength > maxLength ) {
  1739. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1740. inputTypeLength = maxLength - length;
  1741. inputType = builder.getTypeFromLength( inputTypeLength );
  1742. }
  1743. length += inputTypeLength;
  1744. inputSnippet = input.build( builder, inputType );
  1745. const inputPrimitiveType = builder.getComponentType( inputType );
  1746. if ( inputPrimitiveType !== primitiveType ) {
  1747. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1748. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1749. }
  1750. snippetValues.push( inputSnippet );
  1751. }
  1752. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1753. return builder.format( snippet, type, output );
  1754. }
  1755. }
  1756. const _stringVectorComponents = vectorComponents.join( '' );
  1757. /**
  1758. * This module is part of the TSL core and usually not used in app level code.
  1759. * `SplitNode` represents a property access operation which means it is
  1760. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1761. * For example:
  1762. * ```js
  1763. * const redValue = color.r;
  1764. * ```
  1765. *
  1766. * @augments Node
  1767. */
  1768. class SplitNode extends Node {
  1769. static get type() {
  1770. return 'SplitNode';
  1771. }
  1772. /**
  1773. * Constructs a new split node.
  1774. *
  1775. * @param {Node} node - The node that should be accessed.
  1776. * @param {string} [components='x'] - The components that should be accessed.
  1777. */
  1778. constructor( node, components = 'x' ) {
  1779. super();
  1780. /**
  1781. * The node that should be accessed.
  1782. *
  1783. * @type {Node}
  1784. */
  1785. this.node = node;
  1786. /**
  1787. * The components that should be accessed.
  1788. *
  1789. * @type {string}
  1790. */
  1791. this.components = components;
  1792. /**
  1793. * This flag can be used for type testing.
  1794. *
  1795. * @type {boolean}
  1796. * @readonly
  1797. * @default true
  1798. */
  1799. this.isSplitNode = true;
  1800. }
  1801. /**
  1802. * Returns the vector length which is computed based on the requested components.
  1803. *
  1804. * @return {number} The vector length.
  1805. */
  1806. getVectorLength() {
  1807. let vectorLength = this.components.length;
  1808. for ( const c of this.components ) {
  1809. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1810. }
  1811. return vectorLength;
  1812. }
  1813. /**
  1814. * Returns the component type of the node's type.
  1815. *
  1816. * @param {NodeBuilder} builder - The current node builder.
  1817. * @return {string} The component type.
  1818. */
  1819. getComponentType( builder ) {
  1820. return builder.getComponentType( this.node.getNodeType( builder ) );
  1821. }
  1822. /**
  1823. * This method is overwritten since the node type is inferred from requested components.
  1824. *
  1825. * @param {NodeBuilder} builder - The current node builder.
  1826. * @return {string} The node type.
  1827. */
  1828. getNodeType( builder ) {
  1829. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1830. }
  1831. /**
  1832. * Returns the scope of the node.
  1833. *
  1834. * @return {Node} The scope of the node.
  1835. */
  1836. getScope() {
  1837. return this.node.getScope();
  1838. }
  1839. generate( builder, output ) {
  1840. const node = this.node;
  1841. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1842. let snippet = null;
  1843. if ( nodeTypeLength > 1 ) {
  1844. let type = null;
  1845. const componentsLength = this.getVectorLength();
  1846. if ( componentsLength >= nodeTypeLength ) {
  1847. // needed expand the input node
  1848. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1849. }
  1850. const nodeSnippet = node.build( builder, type );
  1851. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1852. // unnecessary swizzle
  1853. snippet = builder.format( nodeSnippet, type, output );
  1854. } else {
  1855. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1856. }
  1857. } else {
  1858. // ignore .components if .node returns float/integer
  1859. snippet = node.build( builder, output );
  1860. }
  1861. return snippet;
  1862. }
  1863. serialize( data ) {
  1864. super.serialize( data );
  1865. data.components = this.components;
  1866. }
  1867. deserialize( data ) {
  1868. super.deserialize( data );
  1869. this.components = data.components;
  1870. }
  1871. }
  1872. /**
  1873. * This module is part of the TSL core and usually not used in app level code.
  1874. * `SetNode` represents a set operation which means it is used to implement any
  1875. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1876. * For example:
  1877. * ```js
  1878. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1879. * ```
  1880. *
  1881. * @augments TempNode
  1882. */
  1883. class SetNode extends TempNode {
  1884. static get type() {
  1885. return 'SetNode';
  1886. }
  1887. /**
  1888. * Constructs a new set node.
  1889. *
  1890. * @param {Node} sourceNode - The node that should be updated.
  1891. * @param {string} components - The components that should be updated.
  1892. * @param {Node} targetNode - The value node.
  1893. */
  1894. constructor( sourceNode, components, targetNode ) {
  1895. super();
  1896. /**
  1897. * The node that should be updated.
  1898. *
  1899. * @type {Node}
  1900. */
  1901. this.sourceNode = sourceNode;
  1902. /**
  1903. * The components that should be updated.
  1904. *
  1905. * @type {string}
  1906. */
  1907. this.components = components;
  1908. /**
  1909. * The value node.
  1910. *
  1911. * @type {Node}
  1912. */
  1913. this.targetNode = targetNode;
  1914. }
  1915. /**
  1916. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1917. *
  1918. * @param {NodeBuilder} builder - The current node builder.
  1919. * @return {string} The node type.
  1920. */
  1921. getNodeType( builder ) {
  1922. return this.sourceNode.getNodeType( builder );
  1923. }
  1924. generate( builder ) {
  1925. const { sourceNode, components, targetNode } = this;
  1926. const sourceType = this.getNodeType( builder );
  1927. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1928. const targetType = builder.getTypeFromLength( components.length, componentType );
  1929. const targetSnippet = targetNode.build( builder, targetType );
  1930. const sourceSnippet = sourceNode.build( builder, sourceType );
  1931. const length = builder.getTypeLength( sourceType );
  1932. const snippetValues = [];
  1933. for ( let i = 0; i < length; i ++ ) {
  1934. const component = vectorComponents[ i ];
  1935. if ( component === components[ 0 ] ) {
  1936. snippetValues.push( targetSnippet );
  1937. i += components.length - 1;
  1938. } else {
  1939. snippetValues.push( sourceSnippet + '.' + component );
  1940. }
  1941. }
  1942. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1943. }
  1944. }
  1945. /**
  1946. * This module is part of the TSL core and usually not used in app level code.
  1947. * It represents a flip operation during the shader generation process
  1948. * meaning it flips normalized values with the following formula:
  1949. * ```
  1950. * x = 1 - x;
  1951. * ```
  1952. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1953. * `flipSTPQ()` method invocations on node objects. For example:
  1954. * ```js
  1955. * uvNode = uvNode.flipY();
  1956. * ```
  1957. *
  1958. * @augments TempNode
  1959. */
  1960. class FlipNode extends TempNode {
  1961. static get type() {
  1962. return 'FlipNode';
  1963. }
  1964. /**
  1965. * Constructs a new flip node.
  1966. *
  1967. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1968. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1969. */
  1970. constructor( sourceNode, components ) {
  1971. super();
  1972. /**
  1973. * The node which component(s) should be flipped.
  1974. *
  1975. * @type {Node}
  1976. */
  1977. this.sourceNode = sourceNode;
  1978. /**
  1979. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1980. *
  1981. * @type {string}
  1982. */
  1983. this.components = components;
  1984. }
  1985. /**
  1986. * This method is overwritten since the node type is inferred from the source node.
  1987. *
  1988. * @param {NodeBuilder} builder - The current node builder.
  1989. * @return {string} The node type.
  1990. */
  1991. getNodeType( builder ) {
  1992. return this.sourceNode.getNodeType( builder );
  1993. }
  1994. generate( builder ) {
  1995. const { components, sourceNode } = this;
  1996. const sourceType = this.getNodeType( builder );
  1997. const sourceSnippet = sourceNode.build( builder );
  1998. const sourceCache = builder.getVarFromNode( this );
  1999. const sourceProperty = builder.getPropertyName( sourceCache );
  2000. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  2001. const length = builder.getTypeLength( sourceType );
  2002. const snippetValues = [];
  2003. let componentIndex = 0;
  2004. for ( let i = 0; i < length; i ++ ) {
  2005. const component = vectorComponents[ i ];
  2006. if ( component === components[ componentIndex ] ) {
  2007. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  2008. componentIndex ++;
  2009. } else {
  2010. snippetValues.push( sourceProperty + '.' + component );
  2011. }
  2012. }
  2013. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  2014. }
  2015. }
  2016. /**
  2017. * Base class for representing data input nodes.
  2018. *
  2019. * @augments Node
  2020. */
  2021. class InputNode extends Node {
  2022. static get type() {
  2023. return 'InputNode';
  2024. }
  2025. /**
  2026. * Constructs a new input node.
  2027. *
  2028. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2029. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2030. */
  2031. constructor( value, nodeType = null ) {
  2032. super( nodeType );
  2033. /**
  2034. * This flag can be used for type testing.
  2035. *
  2036. * @type {boolean}
  2037. * @readonly
  2038. * @default true
  2039. */
  2040. this.isInputNode = true;
  2041. /**
  2042. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2043. *
  2044. * @type {any}
  2045. */
  2046. this.value = value;
  2047. /**
  2048. * The precision of the value in the shader.
  2049. *
  2050. * @type {?('low'|'medium'|'high')}
  2051. * @default null
  2052. */
  2053. this.precision = null;
  2054. }
  2055. getNodeType( /*builder*/ ) {
  2056. if ( this.nodeType === null ) {
  2057. return getValueType( this.value );
  2058. }
  2059. return this.nodeType;
  2060. }
  2061. /**
  2062. * Returns the input type of the node which is by default the node type. Derived modules
  2063. * might overwrite this method and use a fixed type or compute one analytically.
  2064. *
  2065. * A typical example for different input and node types are textures. The input type of a
  2066. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2067. *
  2068. * @param {NodeBuilder} builder - The current node builder.
  2069. * @return {string} The input type.
  2070. */
  2071. getInputType( builder ) {
  2072. return this.getNodeType( builder );
  2073. }
  2074. /**
  2075. * Sets the precision to the given value. The method can be
  2076. * overwritten in derived classes if the final precision must be computed
  2077. * analytically.
  2078. *
  2079. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2080. * @return {InputNode} A reference to this node.
  2081. */
  2082. setPrecision( precision ) {
  2083. this.precision = precision;
  2084. return this;
  2085. }
  2086. serialize( data ) {
  2087. super.serialize( data );
  2088. data.value = this.value;
  2089. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2090. data.valueType = getValueType( this.value );
  2091. data.nodeType = this.nodeType;
  2092. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2093. data.precision = this.precision;
  2094. }
  2095. deserialize( data ) {
  2096. super.deserialize( data );
  2097. this.nodeType = data.nodeType;
  2098. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2099. this.precision = data.precision || null;
  2100. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2101. }
  2102. generate( /*builder, output*/ ) {
  2103. warn( 'Abstract function.' );
  2104. }
  2105. }
  2106. const _regNum = /float|u?int/;
  2107. /**
  2108. * Class for representing a constant value in the shader.
  2109. *
  2110. * @augments InputNode
  2111. */
  2112. class ConstNode extends InputNode {
  2113. static get type() {
  2114. return 'ConstNode';
  2115. }
  2116. /**
  2117. * Constructs a new input node.
  2118. *
  2119. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2120. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2121. */
  2122. constructor( value, nodeType = null ) {
  2123. super( value, nodeType );
  2124. /**
  2125. * This flag can be used for type testing.
  2126. *
  2127. * @type {boolean}
  2128. * @readonly
  2129. * @default true
  2130. */
  2131. this.isConstNode = true;
  2132. }
  2133. /**
  2134. * Generates the shader string of the value with the current node builder.
  2135. *
  2136. * @param {NodeBuilder} builder - The current node builder.
  2137. * @return {string} The generated value as a shader string.
  2138. */
  2139. generateConst( builder ) {
  2140. return builder.generateConst( this.getNodeType( builder ), this.value );
  2141. }
  2142. generate( builder, output ) {
  2143. const type = this.getNodeType( builder );
  2144. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2145. return builder.generateConst( output, this.value );
  2146. }
  2147. return builder.format( this.generateConst( builder ), type, output );
  2148. }
  2149. }
  2150. /**
  2151. * Base class for representing member access on an object-like
  2152. * node data structures.
  2153. *
  2154. * @augments Node
  2155. */
  2156. class MemberNode extends Node {
  2157. static get type() {
  2158. return 'MemberNode';
  2159. }
  2160. /**
  2161. * Constructs a member node.
  2162. *
  2163. * @param {Node} structNode - The struct node.
  2164. * @param {string} property - The property name.
  2165. */
  2166. constructor( structNode, property ) {
  2167. super();
  2168. /**
  2169. * The struct node.
  2170. *
  2171. * @type {Node}
  2172. */
  2173. this.structNode = structNode;
  2174. /**
  2175. * The property name.
  2176. *
  2177. * @type {Node}
  2178. */
  2179. this.property = property;
  2180. /**
  2181. * This flag can be used for type testing.
  2182. *
  2183. * @type {boolean}
  2184. * @readonly
  2185. * @default true
  2186. */
  2187. this.isMemberNode = true;
  2188. }
  2189. hasMember( builder ) {
  2190. if ( this.structNode.isMemberNode ) {
  2191. if ( this.structNode.hasMember( builder ) === false ) {
  2192. return false;
  2193. }
  2194. }
  2195. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2196. }
  2197. getNodeType( builder ) {
  2198. if ( this.hasMember( builder ) === false ) {
  2199. // default type if member does not exist
  2200. return 'float';
  2201. }
  2202. return this.structNode.getMemberType( builder, this.property );
  2203. }
  2204. getMemberType( builder, name ) {
  2205. if ( this.hasMember( builder ) === false ) {
  2206. // default type if member does not exist
  2207. return 'float';
  2208. }
  2209. const type = this.getNodeType( builder );
  2210. const struct = builder.getStructTypeNode( type );
  2211. return struct.getMemberType( builder, name );
  2212. }
  2213. generate( builder ) {
  2214. if ( this.hasMember( builder ) === false ) {
  2215. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2216. const type = this.getNodeType( builder );
  2217. return builder.generateConst( type );
  2218. }
  2219. const propertyName = this.structNode.build( builder );
  2220. return propertyName + '.' + this.property;
  2221. }
  2222. }
  2223. let currentStack = null;
  2224. const NodeElements = new Map();
  2225. // Extend Node Class for TSL using prototype
  2226. function addMethodChaining( name, nodeElement ) {
  2227. if ( NodeElements.has( name ) ) {
  2228. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2229. return;
  2230. }
  2231. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2232. NodeElements.set( name, nodeElement );
  2233. if ( name !== 'assign' ) {
  2234. // Changing Node prototype to add method chaining
  2235. Node.prototype[ name ] = function ( ...params ) {
  2236. //if ( name === 'toVarIntent' ) return this;
  2237. return this.isStackNode ? this.addToStack( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2238. };
  2239. // Adding assign method chaining
  2240. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2241. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2242. };
  2243. }
  2244. }
  2245. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2246. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2247. Node.prototype.assign = function ( ...params ) {
  2248. if ( this.isStackNode !== true ) {
  2249. if ( currentStack !== null ) {
  2250. currentStack.assign( this, ...params );
  2251. } else {
  2252. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2253. }
  2254. return this;
  2255. } else {
  2256. const nodeElement = NodeElements.get( 'assign' );
  2257. return this.addToStack( nodeElement( ...params ) );
  2258. }
  2259. };
  2260. Node.prototype.toVarIntent = function () {
  2261. return this;
  2262. };
  2263. Node.prototype.get = function ( value ) {
  2264. return new MemberNode( this, value );
  2265. };
  2266. // Cache prototype for TSL
  2267. const proto = {};
  2268. // Set swizzle properties for xyzw, rgba, and stpq.
  2269. function setProtoSwizzle( property, altA, altB ) {
  2270. // swizzle properties
  2271. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2272. get() {
  2273. this._cache = this._cache || {};
  2274. //
  2275. let split = this._cache[ property ];
  2276. if ( split === undefined ) {
  2277. split = new SplitNode( this, property );
  2278. this._cache[ property ] = split;
  2279. }
  2280. return split;
  2281. },
  2282. set( value ) {
  2283. this[ property ].assign( nodeObject( value ) );
  2284. }
  2285. };
  2286. // set properties ( swizzle ) and sort to xyzw sequence
  2287. const propUpper = property.toUpperCase();
  2288. const altAUpper = altA.toUpperCase();
  2289. const altBUpper = altB.toUpperCase();
  2290. // Set methods for swizzle properties
  2291. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2292. const swizzle = parseSwizzleAndSort( property );
  2293. return new SetNode( this, swizzle, nodeObject( value ) );
  2294. };
  2295. // Set methods for flip properties
  2296. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2297. const swizzle = parseSwizzleAndSort( property );
  2298. return new FlipNode( this, swizzle );
  2299. };
  2300. }
  2301. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2302. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2303. const swizzleC = [ 's', 't', 'p', 'q' ];
  2304. for ( let a = 0; a < 4; a ++ ) {
  2305. let prop = swizzleA[ a ];
  2306. let altA = swizzleB[ a ];
  2307. let altB = swizzleC[ a ];
  2308. setProtoSwizzle( prop, altA, altB );
  2309. for ( let b = 0; b < 4; b ++ ) {
  2310. prop = swizzleA[ a ] + swizzleA[ b ];
  2311. altA = swizzleB[ a ] + swizzleB[ b ];
  2312. altB = swizzleC[ a ] + swizzleC[ b ];
  2313. setProtoSwizzle( prop, altA, altB );
  2314. for ( let c = 0; c < 4; c ++ ) {
  2315. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2316. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2317. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2318. setProtoSwizzle( prop, altA, altB );
  2319. for ( let d = 0; d < 4; d ++ ) {
  2320. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2321. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2322. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2323. setProtoSwizzle( prop, altA, altB );
  2324. }
  2325. }
  2326. }
  2327. }
  2328. // Set/get static properties for array elements (0-31).
  2329. for ( let i = 0; i < 32; i ++ ) {
  2330. proto[ i ] = {
  2331. get() {
  2332. this._cache = this._cache || {};
  2333. //
  2334. let element = this._cache[ i ];
  2335. if ( element === undefined ) {
  2336. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2337. this._cache[ i ] = element;
  2338. }
  2339. return element;
  2340. },
  2341. set( value ) {
  2342. this[ i ].assign( nodeObject( value ) );
  2343. }
  2344. };
  2345. }
  2346. /*
  2347. // Set properties for width, height, and depth.
  2348. function setProtoProperty( property, target ) {
  2349. proto[ property ] = {
  2350. get() {
  2351. this._cache = this._cache || {};
  2352. //
  2353. let split = this._cache[ target ];
  2354. if ( split === undefined ) {
  2355. split = new SplitNode( this, target );
  2356. this._cache[ target ] = split;
  2357. }
  2358. return split;
  2359. },
  2360. set( value ) {
  2361. this[ target ].assign( nodeObject( value ) );
  2362. }
  2363. };
  2364. }
  2365. setProtoProperty( 'width', 'x' );
  2366. setProtoProperty( 'height', 'y' );
  2367. setProtoProperty( 'depth', 'z' );
  2368. */
  2369. Object.defineProperties( Node.prototype, proto );
  2370. // --- FINISH ---
  2371. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2372. const ShaderNodeObject = function ( obj, altType = null ) {
  2373. const type = getValueType( obj );
  2374. if ( type === 'node' ) {
  2375. return obj;
  2376. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2377. return nodeObject( getConstNode( obj, altType ) );
  2378. } else if ( type === 'shader' ) {
  2379. return obj.isFn ? obj : Fn( obj );
  2380. }
  2381. return obj;
  2382. };
  2383. const ShaderNodeObjects = function ( objects, altType = null ) {
  2384. for ( const name in objects ) {
  2385. objects[ name ] = nodeObject( objects[ name ], altType );
  2386. }
  2387. return objects;
  2388. };
  2389. const ShaderNodeArray = function ( array, altType = null ) {
  2390. const len = array.length;
  2391. for ( let i = 0; i < len; i ++ ) {
  2392. array[ i ] = nodeObject( array[ i ], altType );
  2393. }
  2394. return array;
  2395. };
  2396. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2397. function assignNode( node ) {
  2398. if ( settings !== null ) {
  2399. node = nodeObject( Object.assign( node, settings ) );
  2400. if ( settings.intent === true ) {
  2401. node = node.toVarIntent();
  2402. }
  2403. } else {
  2404. node = nodeObject( node );
  2405. }
  2406. return node;
  2407. }
  2408. let fn, name = scope, minParams, maxParams;
  2409. function verifyParamsLimit( params ) {
  2410. let tslName;
  2411. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2412. else tslName = NodeClass.type;
  2413. if ( minParams !== undefined && params.length < minParams ) {
  2414. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2415. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2416. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2417. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2418. return params.slice( 0, maxParams );
  2419. }
  2420. return params;
  2421. }
  2422. if ( scope === null ) {
  2423. fn = ( ...params ) => {
  2424. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2425. };
  2426. } else if ( factor !== null ) {
  2427. factor = nodeObject( factor );
  2428. fn = ( ...params ) => {
  2429. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2430. };
  2431. } else {
  2432. fn = ( ...params ) => {
  2433. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2434. };
  2435. }
  2436. fn.setParameterLength = ( ...params ) => {
  2437. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2438. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2439. return fn;
  2440. };
  2441. fn.setName = ( value ) => {
  2442. name = value;
  2443. return fn;
  2444. };
  2445. return fn;
  2446. };
  2447. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2448. return new NodeClass( ...nodeArray( params ) );
  2449. };
  2450. class ShaderCallNodeInternal extends Node {
  2451. constructor( shaderNode, rawInputs ) {
  2452. super();
  2453. this.shaderNode = shaderNode;
  2454. this.rawInputs = rawInputs;
  2455. this.isShaderCallNodeInternal = true;
  2456. }
  2457. getNodeType( builder ) {
  2458. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2459. }
  2460. getElementType( builder ) {
  2461. return this.getOutputNode( builder ).getElementType( builder );
  2462. }
  2463. getMemberType( builder, name ) {
  2464. return this.getOutputNode( builder ).getMemberType( builder, name );
  2465. }
  2466. call( builder ) {
  2467. const { shaderNode, rawInputs } = this;
  2468. const properties = builder.getNodeProperties( shaderNode );
  2469. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2470. const subBuildProperty = subBuild || 'default';
  2471. if ( properties[ subBuildProperty ] ) {
  2472. return properties[ subBuildProperty ];
  2473. }
  2474. //
  2475. const previousSubBuildFn = builder.subBuildFn;
  2476. const previousFnCall = builder.fnCall;
  2477. builder.subBuildFn = subBuild;
  2478. builder.fnCall = this;
  2479. let result = null;
  2480. if ( shaderNode.layout ) {
  2481. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2482. if ( functionNodesCacheMap === undefined ) {
  2483. functionNodesCacheMap = new WeakMap();
  2484. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2485. }
  2486. let functionNode = functionNodesCacheMap.get( shaderNode );
  2487. if ( functionNode === undefined ) {
  2488. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2489. functionNodesCacheMap.set( shaderNode, functionNode );
  2490. }
  2491. builder.addInclude( functionNode );
  2492. //
  2493. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2494. result = nodeObject( functionNode.call( inputs ) );
  2495. } else {
  2496. const secureNodeBuilder = new Proxy( builder, {
  2497. get: ( target, property, receiver ) => {
  2498. let value;
  2499. if ( Symbol.iterator === property ) {
  2500. value = function* () {
  2501. yield undefined;
  2502. };
  2503. } else {
  2504. value = Reflect.get( target, property, receiver );
  2505. }
  2506. return value;
  2507. }
  2508. } );
  2509. //
  2510. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2511. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2512. const jsFunc = shaderNode.jsFunc;
  2513. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2514. result = nodeObject( outputNode );
  2515. }
  2516. builder.subBuildFn = previousSubBuildFn;
  2517. builder.fnCall = previousFnCall;
  2518. if ( shaderNode.once ) {
  2519. properties[ subBuildProperty ] = result;
  2520. }
  2521. return result;
  2522. }
  2523. setupOutput( builder ) {
  2524. builder.addStack();
  2525. builder.stack.outputNode = this.call( builder );
  2526. return builder.removeStack();
  2527. }
  2528. getOutputNode( builder ) {
  2529. const properties = builder.getNodeProperties( this );
  2530. const subBuildOutput = builder.getSubBuildOutput( this );
  2531. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2532. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2533. return properties[ subBuildOutput ];
  2534. }
  2535. build( builder, output = null ) {
  2536. let result = null;
  2537. const buildStage = builder.getBuildStage();
  2538. const properties = builder.getNodeProperties( this );
  2539. const subBuildOutput = builder.getSubBuildOutput( this );
  2540. const outputNode = this.getOutputNode( builder );
  2541. const previousFnCall = builder.fnCall;
  2542. builder.fnCall = this;
  2543. if ( buildStage === 'setup' ) {
  2544. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2545. if ( properties[ subBuildInitialized ] !== true ) {
  2546. properties[ subBuildInitialized ] = true;
  2547. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2548. properties[ subBuildOutput ].build( builder );
  2549. // If the shaderNode has subBuilds, add them to the chaining nodes
  2550. // so they can be built later in the build process.
  2551. if ( this.shaderNode.subBuilds ) {
  2552. for ( const node of builder.chaining ) {
  2553. const nodeData = builder.getDataFromNode( node, 'any' );
  2554. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2555. for ( const subBuild of this.shaderNode.subBuilds ) {
  2556. nodeData.subBuilds.add( subBuild );
  2557. }
  2558. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2559. }
  2560. }
  2561. }
  2562. result = properties[ subBuildOutput ];
  2563. } else if ( buildStage === 'analyze' ) {
  2564. outputNode.build( builder, output );
  2565. } else if ( buildStage === 'generate' ) {
  2566. result = outputNode.build( builder, output ) || '';
  2567. }
  2568. builder.fnCall = previousFnCall;
  2569. return result;
  2570. }
  2571. }
  2572. function getLayoutParameters( params ) {
  2573. let output;
  2574. nodeObjects( params );
  2575. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2576. if ( isArrayAsParameter ) {
  2577. output = [ ...params ];
  2578. } else {
  2579. output = params[ 0 ];
  2580. }
  2581. return output;
  2582. }
  2583. function getProxyParameters( params ) {
  2584. let index = 0;
  2585. nodeObjects( params );
  2586. return new Proxy( params, {
  2587. get: ( target, property, receiver ) => {
  2588. let value;
  2589. if ( property === 'length' ) {
  2590. value = params.length;
  2591. return value;
  2592. }
  2593. if ( Symbol.iterator === property ) {
  2594. value = function* () {
  2595. for ( const inputNode of params ) {
  2596. yield nodeObject( inputNode );
  2597. }
  2598. };
  2599. } else {
  2600. if ( params.length > 0 ) {
  2601. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2602. const objectTarget = params[ 0 ];
  2603. if ( objectTarget[ property ] === undefined ) {
  2604. value = objectTarget[ index ++ ];
  2605. } else {
  2606. value = Reflect.get( objectTarget, property, receiver );
  2607. }
  2608. } else if ( params[ 0 ] instanceof Node ) {
  2609. if ( params[ property ] === undefined ) {
  2610. value = params[ index ++ ];
  2611. } else {
  2612. value = Reflect.get( params, property, receiver );
  2613. }
  2614. }
  2615. } else {
  2616. value = Reflect.get( target, property, receiver );
  2617. }
  2618. value = nodeObject( value );
  2619. }
  2620. return value;
  2621. }
  2622. } );
  2623. }
  2624. class ShaderNodeInternal extends Node {
  2625. constructor( jsFunc, nodeType ) {
  2626. super( nodeType );
  2627. this.jsFunc = jsFunc;
  2628. this.layout = null;
  2629. this.global = true;
  2630. this.once = false;
  2631. }
  2632. setLayout( layout ) {
  2633. this.layout = layout;
  2634. return this;
  2635. }
  2636. getLayout() {
  2637. return this.layout;
  2638. }
  2639. call( rawInputs = null ) {
  2640. return new ShaderCallNodeInternal( this, rawInputs );
  2641. }
  2642. setup() {
  2643. return this.call();
  2644. }
  2645. }
  2646. const bools = [ false, true ];
  2647. const uints = [ 0, 1, 2, 3 ];
  2648. const ints = [ -1, -2 ];
  2649. 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 ];
  2650. const boolsCacheMap = new Map();
  2651. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2652. const uintsCacheMap = new Map();
  2653. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2654. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2655. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2656. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2657. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2658. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2659. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2660. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2661. const getConstNode = ( value, type ) => {
  2662. if ( constNodesCacheMap.has( value ) ) {
  2663. return constNodesCacheMap.get( value );
  2664. } else if ( value.isNode === true ) {
  2665. return value;
  2666. } else {
  2667. return new ConstNode( value, type );
  2668. }
  2669. };
  2670. const ConvertType = function ( type, cacheMap = null ) {
  2671. return ( ...params ) => {
  2672. for ( const param of params ) {
  2673. if ( param === undefined ) {
  2674. error( `TSL: Invalid parameter for the type "${ type }".` );
  2675. return new ConstNode( 0, type );
  2676. }
  2677. }
  2678. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2679. const paramType = typeof param;
  2680. return paramType !== 'object' && paramType !== 'function';
  2681. } ) ) ) {
  2682. params = [ getValueFromType( type, ...params ) ];
  2683. }
  2684. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2685. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2686. }
  2687. if ( params.length === 1 ) {
  2688. const node = getConstNode( params[ 0 ], type );
  2689. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2690. return nodeObjectIntent( new ConvertNode( node, type ) );
  2691. }
  2692. const nodes = params.map( param => getConstNode( param ) );
  2693. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2694. };
  2695. };
  2696. // exports
  2697. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2698. // utils
  2699. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2700. // shader node base
  2701. function ShaderNode( jsFunc, nodeType ) {
  2702. return new ShaderNodeInternal( jsFunc, nodeType );
  2703. }
  2704. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2705. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2706. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2707. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2708. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2709. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2710. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { ...settings, intent: true } );
  2711. let fnId = 0;
  2712. class FnNode extends Node {
  2713. constructor( jsFunc, layout = null ) {
  2714. super();
  2715. let nodeType = null;
  2716. if ( layout !== null ) {
  2717. if ( typeof layout === 'object' ) {
  2718. nodeType = layout.return;
  2719. } else {
  2720. if ( typeof layout === 'string' ) {
  2721. nodeType = layout;
  2722. } else {
  2723. error( 'TSL: Invalid layout type.' );
  2724. }
  2725. layout = null;
  2726. }
  2727. }
  2728. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2729. if ( layout !== null ) {
  2730. this.setLayout( layout );
  2731. }
  2732. this.isFn = true;
  2733. }
  2734. setLayout( layout ) {
  2735. const nodeType = this.shaderNode.nodeType;
  2736. if ( typeof layout.inputs !== 'object' ) {
  2737. const fullLayout = {
  2738. name: 'fn' + fnId ++,
  2739. type: nodeType,
  2740. inputs: []
  2741. };
  2742. for ( const name in layout ) {
  2743. if ( name === 'return' ) continue;
  2744. fullLayout.inputs.push( {
  2745. name: name,
  2746. type: layout[ name ]
  2747. } );
  2748. }
  2749. layout = fullLayout;
  2750. }
  2751. this.shaderNode.setLayout( layout );
  2752. return this;
  2753. }
  2754. getNodeType( builder ) {
  2755. return this.shaderNode.getNodeType( builder ) || 'float';
  2756. }
  2757. call( ...params ) {
  2758. const fnCall = this.shaderNode.call( params );
  2759. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2760. return fnCall.toVarIntent();
  2761. }
  2762. once( subBuilds = null ) {
  2763. this.shaderNode.once = true;
  2764. this.shaderNode.subBuilds = subBuilds;
  2765. return this;
  2766. }
  2767. generate( builder ) {
  2768. const type = this.getNodeType( builder );
  2769. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2770. return builder.generateConst( type );
  2771. }
  2772. }
  2773. function Fn( jsFunc, layout = null ) {
  2774. const instance = new FnNode( jsFunc, layout );
  2775. return new Proxy( () => {}, {
  2776. apply( target, thisArg, params ) {
  2777. return instance.call( ...params );
  2778. },
  2779. get( target, prop, receiver ) {
  2780. return Reflect.get( instance, prop, receiver );
  2781. },
  2782. set( target, prop, value, receiver ) {
  2783. return Reflect.set( instance, prop, value, receiver );
  2784. }
  2785. } );
  2786. }
  2787. //
  2788. const setCurrentStack = ( stack ) => {
  2789. currentStack = stack;
  2790. };
  2791. const getCurrentStack = () => currentStack;
  2792. /**
  2793. * Represent a conditional node using if/else statements.
  2794. *
  2795. * ```js
  2796. * If( condition, function )
  2797. * .ElseIf( condition, function )
  2798. * .Else( function )
  2799. * ```
  2800. * @tsl
  2801. * @function
  2802. * @param {...any} params - The parameters for the conditional node.
  2803. * @returns {StackNode} The conditional node.
  2804. */
  2805. const If = ( ...params ) => currentStack.If( ...params );
  2806. /**
  2807. * Represent a conditional node using switch/case statements.
  2808. *
  2809. * ```js
  2810. * Switch( value )
  2811. * .Case( 1, function )
  2812. * .Case( 2, 3, 4, function )
  2813. * .Default( function )
  2814. * ```
  2815. * @tsl
  2816. * @function
  2817. * @param {...any} params - The parameters for the conditional node.
  2818. * @returns {StackNode} The conditional node.
  2819. */
  2820. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2821. /**
  2822. * Add the given node to the current stack.
  2823. *
  2824. * @param {Node} node - The node to add.
  2825. * @returns {Node} The node that was added to the stack.
  2826. */
  2827. function Stack( node ) {
  2828. if ( currentStack ) currentStack.addToStack( node );
  2829. return node;
  2830. }
  2831. addMethodChaining( 'toStack', Stack );
  2832. // types
  2833. const color = new ConvertType( 'color' );
  2834. const float = new ConvertType( 'float', cacheMaps.float );
  2835. const int = new ConvertType( 'int', cacheMaps.ints );
  2836. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2837. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2838. const vec2 = new ConvertType( 'vec2' );
  2839. const ivec2 = new ConvertType( 'ivec2' );
  2840. const uvec2 = new ConvertType( 'uvec2' );
  2841. const bvec2 = new ConvertType( 'bvec2' );
  2842. const vec3 = new ConvertType( 'vec3' );
  2843. const ivec3 = new ConvertType( 'ivec3' );
  2844. const uvec3 = new ConvertType( 'uvec3' );
  2845. const bvec3 = new ConvertType( 'bvec3' );
  2846. const vec4 = new ConvertType( 'vec4' );
  2847. const ivec4 = new ConvertType( 'ivec4' );
  2848. const uvec4 = new ConvertType( 'uvec4' );
  2849. const bvec4 = new ConvertType( 'bvec4' );
  2850. const mat2 = new ConvertType( 'mat2' );
  2851. const mat3 = new ConvertType( 'mat3' );
  2852. const mat4 = new ConvertType( 'mat4' );
  2853. const string = ( value = '' ) => new ConstNode( value, 'string' );
  2854. const arrayBuffer = ( value ) => new ConstNode( value, 'ArrayBuffer' );
  2855. addMethodChaining( 'toColor', color );
  2856. addMethodChaining( 'toFloat', float );
  2857. addMethodChaining( 'toInt', int );
  2858. addMethodChaining( 'toUint', uint );
  2859. addMethodChaining( 'toBool', bool );
  2860. addMethodChaining( 'toVec2', vec2 );
  2861. addMethodChaining( 'toIVec2', ivec2 );
  2862. addMethodChaining( 'toUVec2', uvec2 );
  2863. addMethodChaining( 'toBVec2', bvec2 );
  2864. addMethodChaining( 'toVec3', vec3 );
  2865. addMethodChaining( 'toIVec3', ivec3 );
  2866. addMethodChaining( 'toUVec3', uvec3 );
  2867. addMethodChaining( 'toBVec3', bvec3 );
  2868. addMethodChaining( 'toVec4', vec4 );
  2869. addMethodChaining( 'toIVec4', ivec4 );
  2870. addMethodChaining( 'toUVec4', uvec4 );
  2871. addMethodChaining( 'toBVec4', bvec4 );
  2872. addMethodChaining( 'toMat2', mat2 );
  2873. addMethodChaining( 'toMat3', mat3 );
  2874. addMethodChaining( 'toMat4', mat4 );
  2875. // basic nodes
  2876. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2877. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2878. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2879. addMethodChaining( 'element', element );
  2880. addMethodChaining( 'convert', convert );
  2881. // deprecated
  2882. /**
  2883. * @tsl
  2884. * @function
  2885. * @deprecated since r176. Use {@link Stack} instead.
  2886. *
  2887. * @param {Node} node - The node to add.
  2888. * @returns {Function}
  2889. */
  2890. const append = ( node ) => { // @deprecated, r176
  2891. warn( 'TSL: append() has been renamed to Stack().' );
  2892. return Stack( node );
  2893. };
  2894. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2895. warn( 'TSL: .append() has been renamed to .toStack().' );
  2896. return Stack( node );
  2897. } );
  2898. /**
  2899. * This class represents a shader property. It can be used
  2900. * to explicitly define a property and assign a value to it.
  2901. *
  2902. * ```js
  2903. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2904. *```
  2905. * `PropertyNode` is used by the engine to predefined common material properties
  2906. * for TSL code.
  2907. *
  2908. * @augments Node
  2909. */
  2910. class PropertyNode extends Node {
  2911. static get type() {
  2912. return 'PropertyNode';
  2913. }
  2914. /**
  2915. * Constructs a new property node.
  2916. *
  2917. * @param {string} nodeType - The type of the node.
  2918. * @param {?string} [name=null] - The name of the property in the shader.
  2919. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2920. */
  2921. constructor( nodeType, name = null, varying = false ) {
  2922. super( nodeType );
  2923. /**
  2924. * The name of the property in the shader. If no name is defined,
  2925. * the node system auto-generates one.
  2926. *
  2927. * @type {?string}
  2928. * @default null
  2929. */
  2930. this.name = name;
  2931. /**
  2932. * Whether this property is a varying or not.
  2933. *
  2934. * @type {boolean}
  2935. * @default false
  2936. */
  2937. this.varying = varying;
  2938. /**
  2939. * This flag can be used for type testing.
  2940. *
  2941. * @type {boolean}
  2942. * @readonly
  2943. * @default true
  2944. */
  2945. this.isPropertyNode = true;
  2946. /**
  2947. * This flag is used for global cache.
  2948. *
  2949. * @type {boolean}
  2950. * @default true
  2951. */
  2952. this.global = true;
  2953. }
  2954. customCacheKey() {
  2955. return hashString( this.type + ':' + ( this.name || '' ) + ':' + ( this.varying ? '1' : '0' ) );
  2956. }
  2957. getHash( builder ) {
  2958. return this.name || super.getHash( builder );
  2959. }
  2960. generate( builder ) {
  2961. let nodeVar;
  2962. if ( this.varying === true ) {
  2963. nodeVar = builder.getVaryingFromNode( this, this.name );
  2964. nodeVar.needsInterpolation = true;
  2965. } else {
  2966. nodeVar = builder.getVarFromNode( this, this.name );
  2967. }
  2968. return builder.getPropertyName( nodeVar );
  2969. }
  2970. }
  2971. /**
  2972. * TSL function for creating a property node.
  2973. *
  2974. * @tsl
  2975. * @function
  2976. * @param {string} type - The type of the node.
  2977. * @param {?string} [name=null] - The name of the property in the shader.
  2978. * @returns {PropertyNode}
  2979. */
  2980. const property = ( type, name ) => new PropertyNode( type, name );
  2981. /**
  2982. * TSL function for creating a varying property node.
  2983. *
  2984. * @tsl
  2985. * @function
  2986. * @param {string} type - The type of the node.
  2987. * @param {?string} [name=null] - The name of the varying in the shader.
  2988. * @returns {PropertyNode}
  2989. */
  2990. const varyingProperty = ( type, name ) => new PropertyNode( type, name, true );
  2991. /**
  2992. * TSL object that represents the shader variable `DiffuseColor`.
  2993. *
  2994. * @tsl
  2995. * @type {PropertyNode<vec4>}
  2996. */
  2997. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2998. /**
  2999. * TSL object that represents the shader variable `DiffuseContribution`.
  3000. *
  3001. * @tsl
  3002. * @type {PropertyNode<vec3>}
  3003. */
  3004. const diffuseContribution = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'DiffuseContribution' );
  3005. /**
  3006. * TSL object that represents the shader variable `EmissiveColor`.
  3007. *
  3008. * @tsl
  3009. * @type {PropertyNode<vec3>}
  3010. */
  3011. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  3012. /**
  3013. * TSL object that represents the shader variable `Roughness`.
  3014. *
  3015. * @tsl
  3016. * @type {PropertyNode<float>}
  3017. */
  3018. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  3019. /**
  3020. * TSL object that represents the shader variable `Metalness`.
  3021. *
  3022. * @tsl
  3023. * @type {PropertyNode<float>}
  3024. */
  3025. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  3026. /**
  3027. * TSL object that represents the shader variable `Clearcoat`.
  3028. *
  3029. * @tsl
  3030. * @type {PropertyNode<float>}
  3031. */
  3032. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  3033. /**
  3034. * TSL object that represents the shader variable `ClearcoatRoughness`.
  3035. *
  3036. * @tsl
  3037. * @type {PropertyNode<float>}
  3038. */
  3039. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3040. /**
  3041. * TSL object that represents the shader variable `Sheen`.
  3042. *
  3043. * @tsl
  3044. * @type {PropertyNode<vec3>}
  3045. */
  3046. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3047. /**
  3048. * TSL object that represents the shader variable `SheenRoughness`.
  3049. *
  3050. * @tsl
  3051. * @type {PropertyNode<float>}
  3052. */
  3053. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3054. /**
  3055. * TSL object that represents the shader variable `Iridescence`.
  3056. *
  3057. * @tsl
  3058. * @type {PropertyNode<float>}
  3059. */
  3060. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3061. /**
  3062. * TSL object that represents the shader variable `IridescenceIOR`.
  3063. *
  3064. * @tsl
  3065. * @type {PropertyNode<float>}
  3066. */
  3067. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3068. /**
  3069. * TSL object that represents the shader variable `IridescenceThickness`.
  3070. *
  3071. * @tsl
  3072. * @type {PropertyNode<float>}
  3073. */
  3074. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3075. /**
  3076. * TSL object that represents the shader variable `AlphaT`.
  3077. *
  3078. * @tsl
  3079. * @type {PropertyNode<float>}
  3080. */
  3081. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3082. /**
  3083. * TSL object that represents the shader variable `Anisotropy`.
  3084. *
  3085. * @tsl
  3086. * @type {PropertyNode<float>}
  3087. */
  3088. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3089. /**
  3090. * TSL object that represents the shader variable `AnisotropyT`.
  3091. *
  3092. * @tsl
  3093. * @type {PropertyNode<vec3>}
  3094. */
  3095. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3096. /**
  3097. * TSL object that represents the shader variable `AnisotropyB`.
  3098. *
  3099. * @tsl
  3100. * @type {PropertyNode<vec3>}
  3101. */
  3102. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3103. /**
  3104. * TSL object that represents the shader variable `SpecularColor`.
  3105. *
  3106. * @tsl
  3107. * @type {PropertyNode<color>}
  3108. */
  3109. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3110. /**
  3111. * TSL object that represents the shader variable `SpecularColorBlended`.
  3112. *
  3113. * @tsl
  3114. * @type {PropertyNode<color>}
  3115. */
  3116. const specularColorBlended = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColorBlended' );
  3117. /**
  3118. * TSL object that represents the shader variable `SpecularF90`.
  3119. *
  3120. * @tsl
  3121. * @type {PropertyNode<float>}
  3122. */
  3123. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3124. /**
  3125. * TSL object that represents the shader variable `Shininess`.
  3126. *
  3127. * @tsl
  3128. * @type {PropertyNode<float>}
  3129. */
  3130. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3131. /**
  3132. * TSL object that represents the shader variable `Output`.
  3133. *
  3134. * @tsl
  3135. * @type {PropertyNode<vec4>}
  3136. */
  3137. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3138. /**
  3139. * TSL object that represents the shader variable `dashSize`.
  3140. *
  3141. * @tsl
  3142. * @type {PropertyNode<float>}
  3143. */
  3144. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3145. /**
  3146. * TSL object that represents the shader variable `gapSize`.
  3147. *
  3148. * @tsl
  3149. * @type {PropertyNode<float>}
  3150. */
  3151. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3152. /**
  3153. * TSL object that represents the shader variable `pointWidth`.
  3154. *
  3155. * @tsl
  3156. * @type {PropertyNode<float>}
  3157. */
  3158. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3159. /**
  3160. * TSL object that represents the shader variable `IOR`.
  3161. *
  3162. * @tsl
  3163. * @type {PropertyNode<float>}
  3164. */
  3165. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3166. /**
  3167. * TSL object that represents the shader variable `Transmission`.
  3168. *
  3169. * @tsl
  3170. * @type {PropertyNode<float>}
  3171. */
  3172. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3173. /**
  3174. * TSL object that represents the shader variable `Thickness`.
  3175. *
  3176. * @tsl
  3177. * @type {PropertyNode<float>}
  3178. */
  3179. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3180. /**
  3181. * TSL object that represents the shader variable `AttenuationDistance`.
  3182. *
  3183. * @tsl
  3184. * @type {PropertyNode<float>}
  3185. */
  3186. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3187. /**
  3188. * TSL object that represents the shader variable `AttenuationColor`.
  3189. *
  3190. * @tsl
  3191. * @type {PropertyNode<color>}
  3192. */
  3193. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3194. /**
  3195. * TSL object that represents the shader variable `Dispersion`.
  3196. *
  3197. * @tsl
  3198. * @type {PropertyNode<float>}
  3199. */
  3200. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3201. /**
  3202. * This node can be used to group single instances of {@link UniformNode}
  3203. * and manage them as a uniform buffer.
  3204. *
  3205. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3206. * will be used when defining the {@link UniformNode#groupNode} property.
  3207. *
  3208. * - `objectGroup`: Uniform buffer per object.
  3209. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3210. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3211. *
  3212. * @augments Node
  3213. */
  3214. class UniformGroupNode extends Node {
  3215. static get type() {
  3216. return 'UniformGroupNode';
  3217. }
  3218. /**
  3219. * Constructs a new uniform group node.
  3220. *
  3221. * @param {string} name - The name of the uniform group node.
  3222. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3223. * @param {number} [order=1] - Influences the internal sorting.
  3224. */
  3225. constructor( name, shared = false, order = 1 ) {
  3226. super( 'string' );
  3227. /**
  3228. * The name of the uniform group node.
  3229. *
  3230. * @type {string}
  3231. */
  3232. this.name = name;
  3233. /**
  3234. * Whether this uniform group node is shared or not.
  3235. *
  3236. * @type {boolean}
  3237. * @default false
  3238. */
  3239. this.shared = shared;
  3240. /**
  3241. * Influences the internal sorting.
  3242. * TODO: Add details when this property should be changed.
  3243. *
  3244. * @type {number}
  3245. * @default 1
  3246. */
  3247. this.order = order;
  3248. /**
  3249. * This flag can be used for type testing.
  3250. *
  3251. * @type {boolean}
  3252. * @readonly
  3253. * @default true
  3254. */
  3255. this.isUniformGroup = true;
  3256. }
  3257. serialize( data ) {
  3258. super.serialize( data );
  3259. data.name = this.name;
  3260. data.version = this.version;
  3261. data.shared = this.shared;
  3262. }
  3263. deserialize( data ) {
  3264. super.deserialize( data );
  3265. this.name = data.name;
  3266. this.version = data.version;
  3267. this.shared = data.shared;
  3268. }
  3269. }
  3270. /**
  3271. * TSL function for creating a uniform group node with the given name.
  3272. *
  3273. * @tsl
  3274. * @function
  3275. * @param {string} name - The name of the uniform group node.
  3276. * @returns {UniformGroupNode}
  3277. */
  3278. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3279. /**
  3280. * TSL function for creating a shared uniform group node with the given name and order.
  3281. *
  3282. * @tsl
  3283. * @function
  3284. * @param {string} name - The name of the uniform group node.
  3285. * @param {number} [order=0] - Influences the internal sorting.
  3286. * @returns {UniformGroupNode}
  3287. */
  3288. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3289. /**
  3290. * TSL object that represents a shared uniform group node which is updated once per frame.
  3291. *
  3292. * @tsl
  3293. * @type {UniformGroupNode}
  3294. */
  3295. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3296. /**
  3297. * TSL object that represents a shared uniform group node which is updated once per render.
  3298. *
  3299. * @tsl
  3300. * @type {UniformGroupNode}
  3301. */
  3302. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3303. /**
  3304. * TSL object that represents a uniform group node which is updated once per object.
  3305. *
  3306. * @tsl
  3307. * @type {UniformGroupNode}
  3308. */
  3309. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3310. /**
  3311. * Class for representing a uniform.
  3312. *
  3313. * @augments InputNode
  3314. */
  3315. class UniformNode extends InputNode {
  3316. static get type() {
  3317. return 'UniformNode';
  3318. }
  3319. /**
  3320. * Constructs a new uniform node.
  3321. *
  3322. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3323. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3324. */
  3325. constructor( value, nodeType = null ) {
  3326. super( value, nodeType );
  3327. /**
  3328. * This flag can be used for type testing.
  3329. *
  3330. * @type {boolean}
  3331. * @readonly
  3332. * @default true
  3333. */
  3334. this.isUniformNode = true;
  3335. /**
  3336. * The name or label of the uniform.
  3337. *
  3338. * @type {string}
  3339. * @default ''
  3340. */
  3341. this.name = '';
  3342. /**
  3343. * The uniform group of this uniform. By default, uniforms are
  3344. * managed per object but they might belong to a shared group
  3345. * which is updated per frame or render call.
  3346. *
  3347. * @type {UniformGroupNode}
  3348. */
  3349. this.groupNode = objectGroup;
  3350. }
  3351. /**
  3352. * Sets the {@link UniformNode#name} property.
  3353. *
  3354. * @param {string} name - The name of the uniform.
  3355. * @return {UniformNode} A reference to this node.
  3356. */
  3357. setName( name ) {
  3358. this.name = name;
  3359. return this;
  3360. }
  3361. /**
  3362. * Sets the {@link UniformNode#name} property.
  3363. *
  3364. * @deprecated
  3365. * @param {string} name - The name of the uniform.
  3366. * @return {UniformNode} A reference to this node.
  3367. */
  3368. label( name ) {
  3369. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3370. return this.setName( name );
  3371. }
  3372. /**
  3373. * Sets the {@link UniformNode#groupNode} property.
  3374. *
  3375. * @param {UniformGroupNode} group - The uniform group.
  3376. * @return {UniformNode} A reference to this node.
  3377. */
  3378. setGroup( group ) {
  3379. this.groupNode = group;
  3380. return this;
  3381. }
  3382. /**
  3383. * Returns the {@link UniformNode#groupNode}.
  3384. *
  3385. * @return {UniformGroupNode} The uniform group.
  3386. */
  3387. getGroup() {
  3388. return this.groupNode;
  3389. }
  3390. /**
  3391. * By default, this method returns the result of {@link Node#getHash} but derived
  3392. * classes might overwrite this method with a different implementation.
  3393. *
  3394. * @param {NodeBuilder} builder - The current node builder.
  3395. * @return {string} The uniform hash.
  3396. */
  3397. getUniformHash( builder ) {
  3398. return this.getHash( builder );
  3399. }
  3400. onUpdate( callback, updateType ) {
  3401. callback = callback.bind( this );
  3402. return super.onUpdate( ( frame ) => {
  3403. const value = callback( frame, this );
  3404. if ( value !== undefined ) {
  3405. this.value = value;
  3406. }
  3407. }, updateType );
  3408. }
  3409. getInputType( builder ) {
  3410. let type = super.getInputType( builder );
  3411. if ( type === 'bool' ) {
  3412. type = 'uint';
  3413. }
  3414. return type;
  3415. }
  3416. generate( builder, output ) {
  3417. const type = this.getNodeType( builder );
  3418. const hash = this.getUniformHash( builder );
  3419. let sharedNode = builder.getNodeFromHash( hash );
  3420. if ( sharedNode === undefined ) {
  3421. builder.setHashNode( this, hash );
  3422. sharedNode = this;
  3423. }
  3424. const sharedNodeType = sharedNode.getInputType( builder );
  3425. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3426. const uniformName = builder.getPropertyName( nodeUniform );
  3427. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3428. //
  3429. let snippet = uniformName;
  3430. if ( type === 'bool' ) {
  3431. // cache to variable
  3432. const nodeData = builder.getDataFromNode( this );
  3433. let propertyName = nodeData.propertyName;
  3434. if ( propertyName === undefined ) {
  3435. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3436. propertyName = builder.getPropertyName( nodeVar );
  3437. nodeData.propertyName = propertyName;
  3438. snippet = builder.format( uniformName, sharedNodeType, type );
  3439. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3440. }
  3441. snippet = propertyName;
  3442. }
  3443. return builder.format( snippet, type, output );
  3444. }
  3445. }
  3446. /**
  3447. * TSL function for creating a uniform node.
  3448. *
  3449. * @tsl
  3450. * @function
  3451. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3452. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3453. * @returns {UniformNode}
  3454. */
  3455. const uniform = ( value, type ) => {
  3456. const nodeType = getConstNodeType( type || value );
  3457. if ( nodeType === value ) {
  3458. // if the value is a type but no having a value
  3459. value = getValueFromType( nodeType );
  3460. }
  3461. if ( value && value.isNode === true ) {
  3462. let v = value.value;
  3463. value.traverse( n => {
  3464. if ( n.isConstNode === true ) {
  3465. v = n.value;
  3466. }
  3467. } );
  3468. value = v;
  3469. }
  3470. return new UniformNode( value, nodeType );
  3471. };
  3472. /**
  3473. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3474. * ```js
  3475. * const colors = array( [
  3476. * vec3( 1, 0, 0 ),
  3477. * vec3( 0, 1, 0 ),
  3478. * vec3( 0, 0, 1 )
  3479. * ] );
  3480. *
  3481. * const redColor = tintColors.element( 0 );
  3482. * ```
  3483. *
  3484. * @augments TempNode
  3485. */
  3486. class ArrayNode extends TempNode {
  3487. static get type() {
  3488. return 'ArrayNode';
  3489. }
  3490. /**
  3491. * Constructs a new array node.
  3492. *
  3493. * @param {?string} nodeType - The data type of the elements.
  3494. * @param {number} count - Size of the array.
  3495. * @param {?Array<Node>} [values=null] - Array default values.
  3496. */
  3497. constructor( nodeType, count, values = null ) {
  3498. super( nodeType );
  3499. /**
  3500. * Array size.
  3501. *
  3502. * @type {number}
  3503. */
  3504. this.count = count;
  3505. /**
  3506. * Array default values.
  3507. *
  3508. * @type {?Array<Node>}
  3509. */
  3510. this.values = values;
  3511. /**
  3512. * This flag can be used for type testing.
  3513. *
  3514. * @type {boolean}
  3515. * @readonly
  3516. * @default true
  3517. */
  3518. this.isArrayNode = true;
  3519. }
  3520. /**
  3521. * Returns the number of elements in the node array.
  3522. *
  3523. * @param {NodeBuilder} builder - The current node builder.
  3524. * @return {number} The number of elements in the node array.
  3525. */
  3526. getArrayCount( /*builder*/ ) {
  3527. return this.count;
  3528. }
  3529. /**
  3530. * Returns the node's type.
  3531. *
  3532. * @param {NodeBuilder} builder - The current node builder.
  3533. * @return {string} The type of the node.
  3534. */
  3535. getNodeType( builder ) {
  3536. if ( this.nodeType === null ) {
  3537. return this.values[ 0 ].getNodeType( builder );
  3538. }
  3539. return this.nodeType;
  3540. }
  3541. /**
  3542. * Returns the node's type.
  3543. *
  3544. * @param {NodeBuilder} builder - The current node builder.
  3545. * @return {string} The type of the node.
  3546. */
  3547. getElementType( builder ) {
  3548. return this.getNodeType( builder );
  3549. }
  3550. /**
  3551. * Returns the type of a member variable.
  3552. *
  3553. * @param {NodeBuilder} builder - The current node builder.
  3554. * @param {string} name - The name of the member variable.
  3555. * @return {string} The type of the member variable.
  3556. */
  3557. getMemberType( builder, name ) {
  3558. if ( this.nodeType === null ) {
  3559. return this.values[ 0 ].getMemberType( builder, name );
  3560. }
  3561. return super.getMemberType( builder, name );
  3562. }
  3563. /**
  3564. * This method builds the output node and returns the resulting array as a shader string.
  3565. *
  3566. * @param {NodeBuilder} builder - The current node builder.
  3567. * @return {string} The generated shader string.
  3568. */
  3569. generate( builder ) {
  3570. const type = this.getNodeType( builder );
  3571. return builder.generateArray( type, this.count, this.values );
  3572. }
  3573. }
  3574. /**
  3575. * TSL function for creating an array node.
  3576. *
  3577. * @tsl
  3578. * @function
  3579. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3580. * or an array containing the default values (e.g., [ vec3() ]).
  3581. * @param {?number} [count] - Size of the array.
  3582. * @returns {ArrayNode}
  3583. */
  3584. const array = ( ...params ) => {
  3585. let node;
  3586. if ( params.length === 1 ) {
  3587. const values = params[ 0 ];
  3588. node = new ArrayNode( null, values.length, values );
  3589. } else {
  3590. const nodeType = params[ 0 ];
  3591. const count = params[ 1 ];
  3592. node = new ArrayNode( nodeType, count );
  3593. }
  3594. return nodeObject( node );
  3595. };
  3596. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3597. /**
  3598. * These node represents an assign operation. Meaning a node is assigned
  3599. * to another node.
  3600. *
  3601. * @augments TempNode
  3602. */
  3603. class AssignNode extends TempNode {
  3604. static get type() {
  3605. return 'AssignNode';
  3606. }
  3607. /**
  3608. * Constructs a new assign node.
  3609. *
  3610. * @param {Node} targetNode - The target node.
  3611. * @param {Node} sourceNode - The source type.
  3612. */
  3613. constructor( targetNode, sourceNode ) {
  3614. super();
  3615. /**
  3616. * The target node.
  3617. *
  3618. * @type {Node}
  3619. */
  3620. this.targetNode = targetNode;
  3621. /**
  3622. * The source node.
  3623. *
  3624. * @type {Node}
  3625. */
  3626. this.sourceNode = sourceNode;
  3627. /**
  3628. * This flag can be used for type testing.
  3629. *
  3630. * @type {boolean}
  3631. * @readonly
  3632. * @default true
  3633. */
  3634. this.isAssignNode = true;
  3635. }
  3636. /**
  3637. * Whether this node is used more than once in context of other nodes. This method
  3638. * is overwritten since it always returns `false` (assigns are unique).
  3639. *
  3640. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3641. */
  3642. hasDependencies() {
  3643. return false;
  3644. }
  3645. getNodeType( builder, output ) {
  3646. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3647. }
  3648. /**
  3649. * Whether a split is required when assigning source to target. This can happen when the component length of
  3650. * target and source data type does not match.
  3651. *
  3652. * @param {NodeBuilder} builder - The current node builder.
  3653. * @return {boolean} Whether a split is required when assigning source to target.
  3654. */
  3655. needsSplitAssign( builder ) {
  3656. const { targetNode } = this;
  3657. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3658. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3659. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3660. return assignDifferentVector;
  3661. }
  3662. return false;
  3663. }
  3664. setup( builder ) {
  3665. const { targetNode, sourceNode } = this;
  3666. const scope = targetNode.getScope();
  3667. const scopeData = builder.getDataFromNode( scope );
  3668. scopeData.assign = true;
  3669. const properties = builder.getNodeProperties( this );
  3670. properties.sourceNode = sourceNode;
  3671. properties.targetNode = targetNode.context( { assign: true } );
  3672. }
  3673. generate( builder, output ) {
  3674. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3675. const needsSplitAssign = this.needsSplitAssign( builder );
  3676. const target = targetNode.build( builder );
  3677. const targetType = targetNode.getNodeType( builder );
  3678. const source = sourceNode.build( builder, targetType );
  3679. const sourceType = sourceNode.getNodeType( builder );
  3680. const nodeData = builder.getDataFromNode( this );
  3681. //
  3682. let snippet;
  3683. if ( nodeData.initialized === true ) {
  3684. if ( output !== 'void' ) {
  3685. snippet = target;
  3686. }
  3687. } else if ( needsSplitAssign ) {
  3688. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3689. const sourceProperty = builder.getPropertyName( sourceVar );
  3690. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3691. const splitNode = targetNode.node;
  3692. const splitTargetNode = splitNode.node.context( { assign: true } );
  3693. const targetRoot = splitTargetNode.build( builder );
  3694. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3695. const component = splitNode.components[ i ];
  3696. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3697. }
  3698. if ( output !== 'void' ) {
  3699. snippet = target;
  3700. }
  3701. } else {
  3702. snippet = `${ target } = ${ source }`;
  3703. if ( output === 'void' || sourceType === 'void' ) {
  3704. builder.addLineFlowCode( snippet, this );
  3705. if ( output !== 'void' ) {
  3706. snippet = target;
  3707. }
  3708. }
  3709. }
  3710. nodeData.initialized = true;
  3711. return builder.format( snippet, targetType, output );
  3712. }
  3713. }
  3714. /**
  3715. * TSL function for creating an assign node.
  3716. *
  3717. * @tsl
  3718. * @function
  3719. * @param {Node} targetNode - The target node.
  3720. * @param {Node} sourceNode - The source type.
  3721. * @returns {AssignNode}
  3722. */
  3723. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3724. addMethodChaining( 'assign', assign );
  3725. /**
  3726. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3727. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3728. * this logic.
  3729. *
  3730. * @augments TempNode
  3731. */
  3732. class FunctionCallNode extends TempNode {
  3733. static get type() {
  3734. return 'FunctionCallNode';
  3735. }
  3736. /**
  3737. * Constructs a new function call node.
  3738. *
  3739. * @param {?FunctionNode} functionNode - The function node.
  3740. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3741. */
  3742. constructor( functionNode = null, parameters = {} ) {
  3743. super();
  3744. /**
  3745. * The function node.
  3746. *
  3747. * @type {?FunctionNode}
  3748. * @default null
  3749. */
  3750. this.functionNode = functionNode;
  3751. /**
  3752. * The parameters of the function call.
  3753. *
  3754. * @type {Object<string, Node>}
  3755. * @default {}
  3756. */
  3757. this.parameters = parameters;
  3758. }
  3759. /**
  3760. * Sets the parameters of the function call node.
  3761. *
  3762. * @param {Object<string, Node>} parameters - The parameters to set.
  3763. * @return {FunctionCallNode} A reference to this node.
  3764. */
  3765. setParameters( parameters ) {
  3766. this.parameters = parameters;
  3767. return this;
  3768. }
  3769. /**
  3770. * Returns the parameters of the function call node.
  3771. *
  3772. * @return {Object<string, Node>} The parameters of this node.
  3773. */
  3774. getParameters() {
  3775. return this.parameters;
  3776. }
  3777. /**
  3778. * Returns the type of this function call node.
  3779. *
  3780. * @param {NodeBuilder} builder - The current node builder.
  3781. * @returns {string} The type of this node.
  3782. */
  3783. getNodeType( builder ) {
  3784. return this.functionNode.getNodeType( builder );
  3785. }
  3786. /**
  3787. * Returns the function node of this function call node.
  3788. *
  3789. * @param {NodeBuilder} builder - The current node builder.
  3790. * @param {string} [name] - The name of the member.
  3791. * @returns {string} The type of the member.
  3792. */
  3793. getMemberType( builder, name ) {
  3794. return this.functionNode.getMemberType( builder, name );
  3795. }
  3796. generate( builder ) {
  3797. const params = [];
  3798. const functionNode = this.functionNode;
  3799. const inputs = functionNode.getInputs( builder );
  3800. const parameters = this.parameters;
  3801. const generateInput = ( node, inputNode ) => {
  3802. const type = inputNode.type;
  3803. const pointer = type === 'pointer';
  3804. let output;
  3805. if ( pointer ) output = '&' + node.build( builder );
  3806. else output = node.build( builder, type );
  3807. return output;
  3808. };
  3809. if ( Array.isArray( parameters ) ) {
  3810. if ( parameters.length > inputs.length ) {
  3811. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3812. parameters.length = inputs.length;
  3813. } else if ( parameters.length < inputs.length ) {
  3814. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3815. while ( parameters.length < inputs.length ) {
  3816. parameters.push( float( 0 ) );
  3817. }
  3818. }
  3819. for ( let i = 0; i < parameters.length; i ++ ) {
  3820. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3821. }
  3822. } else {
  3823. for ( const inputNode of inputs ) {
  3824. const node = parameters[ inputNode.name ];
  3825. if ( node !== undefined ) {
  3826. params.push( generateInput( node, inputNode ) );
  3827. } else {
  3828. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3829. params.push( generateInput( float( 0 ), inputNode ) );
  3830. }
  3831. }
  3832. }
  3833. const functionName = functionNode.build( builder, 'property' );
  3834. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3835. }
  3836. }
  3837. const call = ( func, ...params ) => {
  3838. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3839. return new FunctionCallNode( nodeObject( func ), params );
  3840. };
  3841. addMethodChaining( 'call', call );
  3842. const _vectorOperators = {
  3843. '==': 'equal',
  3844. '!=': 'notEqual',
  3845. '<': 'lessThan',
  3846. '>': 'greaterThan',
  3847. '<=': 'lessThanEqual',
  3848. '>=': 'greaterThanEqual',
  3849. '%': 'mod'
  3850. };
  3851. /**
  3852. * This node represents basic mathematical and logical operations like addition,
  3853. * subtraction or comparisons (e.g. `equal()`).
  3854. *
  3855. * @augments TempNode
  3856. */
  3857. class OperatorNode extends TempNode {
  3858. static get type() {
  3859. return 'OperatorNode';
  3860. }
  3861. /**
  3862. * Constructs a new operator node.
  3863. *
  3864. * @param {string} op - The operator.
  3865. * @param {Node} aNode - The first input.
  3866. * @param {Node} bNode - The second input.
  3867. * @param {...Node} params - Additional input parameters.
  3868. */
  3869. constructor( op, aNode, bNode, ...params ) {
  3870. super();
  3871. if ( params.length > 0 ) {
  3872. let finalOp = new OperatorNode( op, aNode, bNode );
  3873. for ( let i = 0; i < params.length - 1; i ++ ) {
  3874. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3875. }
  3876. aNode = finalOp;
  3877. bNode = params[ params.length - 1 ];
  3878. }
  3879. /**
  3880. * The operator.
  3881. *
  3882. * @type {string}
  3883. */
  3884. this.op = op;
  3885. /**
  3886. * The first input.
  3887. *
  3888. * @type {Node}
  3889. */
  3890. this.aNode = aNode;
  3891. /**
  3892. * The second input.
  3893. *
  3894. * @type {Node}
  3895. */
  3896. this.bNode = bNode;
  3897. /**
  3898. * This flag can be used for type testing.
  3899. *
  3900. * @type {boolean}
  3901. * @readonly
  3902. * @default true
  3903. */
  3904. this.isOperatorNode = true;
  3905. }
  3906. /**
  3907. * Returns the operator method name.
  3908. *
  3909. * @param {NodeBuilder} builder - The current node builder.
  3910. * @param {string} output - The output type.
  3911. * @returns {string} The operator method name.
  3912. */
  3913. getOperatorMethod( builder, output ) {
  3914. return builder.getMethod( _vectorOperators[ this.op ], output );
  3915. }
  3916. /**
  3917. * This method is overwritten since the node type is inferred from the operator
  3918. * and the input node types.
  3919. *
  3920. * @param {NodeBuilder} builder - The current node builder.
  3921. * @param {?string} [output=null] - The output type.
  3922. * @return {string} The node type.
  3923. */
  3924. getNodeType( builder, output = null ) {
  3925. const op = this.op;
  3926. const aNode = this.aNode;
  3927. const bNode = this.bNode;
  3928. const typeA = aNode.getNodeType( builder );
  3929. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3930. if ( typeA === 'void' || typeB === 'void' ) {
  3931. return output || 'void';
  3932. } else if ( op === '%' ) {
  3933. return typeA;
  3934. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3935. return builder.getIntegerType( typeA );
  3936. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3937. return 'bool';
  3938. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3939. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3940. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3941. } else {
  3942. // Handle matrix operations
  3943. if ( builder.isMatrix( typeA ) ) {
  3944. if ( typeB === 'float' ) {
  3945. return typeA; // matrix * scalar = matrix
  3946. } else if ( builder.isVector( typeB ) ) {
  3947. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3948. } else if ( builder.isMatrix( typeB ) ) {
  3949. return typeA; // matrix * matrix
  3950. }
  3951. } else if ( builder.isMatrix( typeB ) ) {
  3952. if ( typeA === 'float' ) {
  3953. return typeB; // scalar * matrix = matrix
  3954. } else if ( builder.isVector( typeA ) ) {
  3955. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3956. }
  3957. }
  3958. // Handle non-matrix cases
  3959. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3960. // anytype x anytype: use the greater length vector
  3961. return typeB;
  3962. }
  3963. return typeA;
  3964. }
  3965. }
  3966. generate( builder, output ) {
  3967. const op = this.op;
  3968. const { aNode, bNode } = this;
  3969. const type = this.getNodeType( builder, output );
  3970. let typeA = null;
  3971. let typeB = null;
  3972. if ( type !== 'void' ) {
  3973. typeA = aNode.getNodeType( builder );
  3974. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3975. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3976. if ( builder.isVector( typeA ) ) {
  3977. typeB = typeA;
  3978. } else if ( builder.isVector( typeB ) ) {
  3979. typeA = typeB;
  3980. } else if ( typeA !== typeB ) {
  3981. typeA = typeB = 'float';
  3982. }
  3983. } else if ( op === '>>' || op === '<<' ) {
  3984. typeA = type;
  3985. typeB = builder.changeComponentType( typeB, 'uint' );
  3986. } else if ( op === '%' ) {
  3987. typeA = type;
  3988. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3989. } else if ( builder.isMatrix( typeA ) ) {
  3990. if ( typeB === 'float' ) {
  3991. // Keep matrix type for typeA, but ensure typeB stays float
  3992. typeB = 'float';
  3993. } else if ( builder.isVector( typeB ) ) {
  3994. // matrix x vector
  3995. typeB = builder.getVectorFromMatrix( typeA );
  3996. } else if ( builder.isMatrix( typeB ) ) ; else {
  3997. typeA = typeB = type;
  3998. }
  3999. } else if ( builder.isMatrix( typeB ) ) {
  4000. if ( typeA === 'float' ) {
  4001. // Keep matrix type for typeB, but ensure typeA stays float
  4002. typeA = 'float';
  4003. } else if ( builder.isVector( typeA ) ) {
  4004. // vector x matrix
  4005. typeA = builder.getVectorFromMatrix( typeB );
  4006. } else {
  4007. typeA = typeB = type;
  4008. }
  4009. } else {
  4010. // anytype x anytype
  4011. typeA = typeB = type;
  4012. }
  4013. } else {
  4014. typeA = typeB = type;
  4015. }
  4016. const a = aNode.build( builder, typeA );
  4017. const b = bNode ? bNode.build( builder, typeB ) : null;
  4018. const fnOpSnippet = builder.getFunctionOperator( op );
  4019. if ( output !== 'void' ) {
  4020. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  4021. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  4022. if ( isGLSL ) {
  4023. if ( builder.isVector( typeA ) ) {
  4024. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  4025. } else {
  4026. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4027. }
  4028. } else {
  4029. // WGSL
  4030. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  4031. }
  4032. } else if ( op === '%' ) {
  4033. if ( builder.isInteger( typeB ) ) {
  4034. return builder.format( `( ${ a } % ${ b } )`, type, output );
  4035. } else {
  4036. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  4037. }
  4038. } else if ( op === '!' || op === '~' ) {
  4039. return builder.format( `(${op}${a})`, typeA, output );
  4040. } else if ( fnOpSnippet ) {
  4041. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4042. } else {
  4043. // Handle matrix operations
  4044. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4045. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  4046. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  4047. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4048. } else {
  4049. let snippet = `( ${ a } ${ op } ${ b } )`;
  4050. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  4051. snippet = `all${ snippet }`;
  4052. }
  4053. return builder.format( snippet, type, output );
  4054. }
  4055. }
  4056. } else if ( typeA !== 'void' ) {
  4057. if ( fnOpSnippet ) {
  4058. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  4059. } else {
  4060. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  4061. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  4062. } else {
  4063. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  4064. }
  4065. }
  4066. }
  4067. }
  4068. serialize( data ) {
  4069. super.serialize( data );
  4070. data.op = this.op;
  4071. }
  4072. deserialize( data ) {
  4073. super.deserialize( data );
  4074. this.op = data.op;
  4075. }
  4076. }
  4077. /**
  4078. * Returns the addition of two or more value.
  4079. *
  4080. * @tsl
  4081. * @function
  4082. * @param {Node} a - The first input.
  4083. * @param {Node} b - The second input.
  4084. * @param {...Node} params - Additional input parameters.
  4085. * @returns {OperatorNode}
  4086. */
  4087. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4088. /**
  4089. * Returns the subtraction of two or more value.
  4090. *
  4091. * @tsl
  4092. * @function
  4093. * @param {Node} a - The first input.
  4094. * @param {Node} b - The second input.
  4095. * @param {...Node} params - Additional input parameters.
  4096. * @returns {OperatorNode}
  4097. */
  4098. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4099. /**
  4100. * Returns the multiplication of two or more value.
  4101. *
  4102. * @tsl
  4103. * @function
  4104. * @param {Node} a - The first input.
  4105. * @param {Node} b - The second input.
  4106. * @param {...Node} params - Additional input parameters.
  4107. * @returns {OperatorNode}
  4108. */
  4109. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4110. /**
  4111. * Returns the division of two or more value.
  4112. *
  4113. * @tsl
  4114. * @function
  4115. * @param {Node} a - The first input.
  4116. * @param {Node} b - The second input.
  4117. * @param {...Node} params - Additional input parameters.
  4118. * @returns {OperatorNode}
  4119. */
  4120. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4121. /**
  4122. * Computes the remainder of dividing the first node by the second one.
  4123. *
  4124. * @tsl
  4125. * @function
  4126. * @param {Node} a - The first input.
  4127. * @param {Node} b - The second input.
  4128. * @returns {OperatorNode}
  4129. */
  4130. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4131. /**
  4132. * Checks if two nodes are equal.
  4133. *
  4134. * @tsl
  4135. * @function
  4136. * @param {Node} a - The first input.
  4137. * @param {Node} b - The second input.
  4138. * @returns {OperatorNode}
  4139. */
  4140. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4141. /**
  4142. * Checks if two nodes are not equal.
  4143. *
  4144. * @tsl
  4145. * @function
  4146. * @param {Node} a - The first input.
  4147. * @param {Node} b - The second input.
  4148. * @returns {OperatorNode}
  4149. */
  4150. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4151. /**
  4152. * Checks if the first node is less than the second.
  4153. *
  4154. * @tsl
  4155. * @function
  4156. * @param {Node} a - The first input.
  4157. * @param {Node} b - The second input.
  4158. * @returns {OperatorNode}
  4159. */
  4160. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4161. /**
  4162. * Checks if the first node is greater than the second.
  4163. *
  4164. * @tsl
  4165. * @function
  4166. * @param {Node} a - The first input.
  4167. * @param {Node} b - The second input.
  4168. * @returns {OperatorNode}
  4169. */
  4170. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4171. /**
  4172. * Checks if the first node is less than or equal to the second.
  4173. *
  4174. * @tsl
  4175. * @function
  4176. * @param {Node} a - The first input.
  4177. * @param {Node} b - The second input.
  4178. * @returns {OperatorNode}
  4179. */
  4180. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4181. /**
  4182. * Checks if the first node is greater than or equal to the second.
  4183. *
  4184. * @tsl
  4185. * @function
  4186. * @param {Node} a - The first input.
  4187. * @param {Node} b - The second input.
  4188. * @returns {OperatorNode}
  4189. */
  4190. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4191. /**
  4192. * Performs a logical AND operation on multiple nodes.
  4193. *
  4194. * @tsl
  4195. * @function
  4196. * @param {...Node} nodes - The input nodes to be combined using AND.
  4197. * @returns {OperatorNode}
  4198. */
  4199. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4200. /**
  4201. * Performs a logical OR operation on multiple nodes.
  4202. *
  4203. * @tsl
  4204. * @function
  4205. * @param {...Node} nodes - The input nodes to be combined using OR.
  4206. * @returns {OperatorNode}
  4207. */
  4208. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4209. /**
  4210. * Performs logical NOT on a node.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} value - The value.
  4215. * @returns {OperatorNode}
  4216. */
  4217. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4218. /**
  4219. * Performs logical XOR on two nodes.
  4220. *
  4221. * @tsl
  4222. * @function
  4223. * @param {Node} a - The first input.
  4224. * @param {Node} b - The second input.
  4225. * @returns {OperatorNode}
  4226. */
  4227. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4228. /**
  4229. * Performs bitwise AND on two nodes.
  4230. *
  4231. * @tsl
  4232. * @function
  4233. * @param {Node} a - The first input.
  4234. * @param {Node} b - The second input.
  4235. * @returns {OperatorNode}
  4236. */
  4237. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4238. /**
  4239. * Performs bitwise NOT on a node.
  4240. *
  4241. * @tsl
  4242. * @function
  4243. * @param {Node} a - The first input.
  4244. * @param {Node} b - The second input.
  4245. * @returns {OperatorNode}
  4246. */
  4247. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4248. /**
  4249. * Performs bitwise OR on two nodes.
  4250. *
  4251. * @tsl
  4252. * @function
  4253. * @param {Node} a - The first input.
  4254. * @param {Node} b - The second input.
  4255. * @returns {OperatorNode}
  4256. */
  4257. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4258. /**
  4259. * Performs bitwise XOR on two nodes.
  4260. *
  4261. * @tsl
  4262. * @function
  4263. * @param {Node} a - The first input.
  4264. * @param {Node} b - The second input.
  4265. * @returns {OperatorNode}
  4266. */
  4267. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4268. /**
  4269. * Shifts a node to the left.
  4270. *
  4271. * @tsl
  4272. * @function
  4273. * @param {Node} a - The node to shift.
  4274. * @param {Node} b - The value to shift.
  4275. * @returns {OperatorNode}
  4276. */
  4277. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4278. /**
  4279. * Shifts a node to the right.
  4280. *
  4281. * @tsl
  4282. * @function
  4283. * @param {Node} a - The node to shift.
  4284. * @param {Node} b - The value to shift.
  4285. * @returns {OperatorNode}
  4286. */
  4287. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4288. /**
  4289. * Increments a node by 1.
  4290. *
  4291. * @tsl
  4292. * @function
  4293. * @param {Node} a - The node to increment.
  4294. * @returns {OperatorNode}
  4295. */
  4296. const incrementBefore = Fn( ( [ a ] ) => {
  4297. a.addAssign( 1 );
  4298. return a;
  4299. } );
  4300. /**
  4301. * Decrements a node by 1.
  4302. *
  4303. * @tsl
  4304. * @function
  4305. * @param {Node} a - The node to decrement.
  4306. * @returns {OperatorNode}
  4307. */
  4308. const decrementBefore = Fn( ( [ a ] ) => {
  4309. a.subAssign( 1 );
  4310. return a;
  4311. } );
  4312. /**
  4313. * Increments a node by 1 and returns the previous value.
  4314. *
  4315. * @tsl
  4316. * @function
  4317. * @param {Node} a - The node to increment.
  4318. * @returns {OperatorNode}
  4319. */
  4320. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4321. const temp = int( a ).toConst();
  4322. a.addAssign( 1 );
  4323. return temp;
  4324. } );
  4325. /**
  4326. * Decrements a node by 1 and returns the previous value.
  4327. *
  4328. * @tsl
  4329. * @function
  4330. * @param {Node} a - The node to decrement.
  4331. * @returns {OperatorNode}
  4332. */
  4333. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4334. const temp = int( a ).toConst();
  4335. a.subAssign( 1 );
  4336. return temp;
  4337. } );
  4338. addMethodChaining( 'add', add );
  4339. addMethodChaining( 'sub', sub );
  4340. addMethodChaining( 'mul', mul );
  4341. addMethodChaining( 'div', div );
  4342. addMethodChaining( 'mod', mod );
  4343. addMethodChaining( 'equal', equal );
  4344. addMethodChaining( 'notEqual', notEqual );
  4345. addMethodChaining( 'lessThan', lessThan );
  4346. addMethodChaining( 'greaterThan', greaterThan );
  4347. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4348. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4349. addMethodChaining( 'and', and );
  4350. addMethodChaining( 'or', or );
  4351. addMethodChaining( 'not', not );
  4352. addMethodChaining( 'xor', xor );
  4353. addMethodChaining( 'bitAnd', bitAnd );
  4354. addMethodChaining( 'bitNot', bitNot );
  4355. addMethodChaining( 'bitOr', bitOr );
  4356. addMethodChaining( 'bitXor', bitXor );
  4357. addMethodChaining( 'shiftLeft', shiftLeft );
  4358. addMethodChaining( 'shiftRight', shiftRight );
  4359. addMethodChaining( 'incrementBefore', incrementBefore );
  4360. addMethodChaining( 'decrementBefore', decrementBefore );
  4361. addMethodChaining( 'increment', increment );
  4362. addMethodChaining( 'decrement', decrement );
  4363. /**
  4364. * @tsl
  4365. * @function
  4366. * @deprecated since r175. Use {@link mod} instead.
  4367. *
  4368. * @param {Node} a - The first input.
  4369. * @param {Node} b - The second input.
  4370. * @returns {OperatorNode}
  4371. */
  4372. const modInt = ( a, b ) => { // @deprecated, r175
  4373. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4374. return mod( int( a ), int( b ) );
  4375. };
  4376. addMethodChaining( 'modInt', modInt );
  4377. /**
  4378. * This node represents a variety of mathematical methods available in shaders.
  4379. * They are divided into three categories:
  4380. *
  4381. * - Methods with one input like `sin`, `cos` or `normalize`.
  4382. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4383. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4384. *
  4385. * @augments TempNode
  4386. */
  4387. class MathNode extends TempNode {
  4388. static get type() {
  4389. return 'MathNode';
  4390. }
  4391. /**
  4392. * Constructs a new math node.
  4393. *
  4394. * @param {string} method - The method name.
  4395. * @param {Node} aNode - The first input.
  4396. * @param {?Node} [bNode=null] - The second input.
  4397. * @param {?Node} [cNode=null] - The third input.
  4398. */
  4399. constructor( method, aNode, bNode = null, cNode = null ) {
  4400. super();
  4401. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4402. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4403. let finalOp = new MathNode( method, aNode, bNode );
  4404. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4405. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4406. }
  4407. aNode = finalOp;
  4408. bNode = arguments[ arguments.length - 1 ];
  4409. cNode = null;
  4410. }
  4411. /**
  4412. * The method name.
  4413. *
  4414. * @type {string}
  4415. */
  4416. this.method = method;
  4417. /**
  4418. * The first input.
  4419. *
  4420. * @type {Node}
  4421. */
  4422. this.aNode = aNode;
  4423. /**
  4424. * The second input.
  4425. *
  4426. * @type {?Node}
  4427. * @default null
  4428. */
  4429. this.bNode = bNode;
  4430. /**
  4431. * The third input.
  4432. *
  4433. * @type {?Node}
  4434. * @default null
  4435. */
  4436. this.cNode = cNode;
  4437. /**
  4438. * This flag can be used for type testing.
  4439. *
  4440. * @type {boolean}
  4441. * @readonly
  4442. * @default true
  4443. */
  4444. this.isMathNode = true;
  4445. }
  4446. /**
  4447. * The input type is inferred from the node types of the input nodes.
  4448. *
  4449. * @param {NodeBuilder} builder - The current node builder.
  4450. * @return {string} The input type.
  4451. */
  4452. getInputType( builder ) {
  4453. const aType = this.aNode.getNodeType( builder );
  4454. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4455. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4456. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4457. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4458. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4459. if ( aLen > bLen && aLen > cLen ) {
  4460. return aType;
  4461. } else if ( bLen > cLen ) {
  4462. return bType;
  4463. } else if ( cLen > aLen ) {
  4464. return cType;
  4465. }
  4466. return aType;
  4467. }
  4468. /**
  4469. * The selected method as well as the input type determine the node type of this node.
  4470. *
  4471. * @param {NodeBuilder} builder - The current node builder.
  4472. * @return {string} The node type.
  4473. */
  4474. getNodeType( builder ) {
  4475. const method = this.method;
  4476. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4477. return 'float';
  4478. } else if ( method === MathNode.CROSS ) {
  4479. return 'vec3';
  4480. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4481. return 'bool';
  4482. } else if ( method === MathNode.EQUALS ) {
  4483. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4484. } else {
  4485. return this.getInputType( builder );
  4486. }
  4487. }
  4488. setup( builder ) {
  4489. const { aNode, bNode, method } = this;
  4490. let outputNode = null;
  4491. if ( method === MathNode.ONE_MINUS ) {
  4492. outputNode = sub( 1.0, aNode );
  4493. } else if ( method === MathNode.RECIPROCAL ) {
  4494. outputNode = div( 1.0, aNode );
  4495. } else if ( method === MathNode.DIFFERENCE ) {
  4496. outputNode = abs( sub( aNode, bNode ) );
  4497. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4498. // dir can be either a direction vector or a normal vector
  4499. // upper-left 3x3 of matrix is assumed to be orthogonal
  4500. let tA = aNode;
  4501. let tB = bNode;
  4502. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4503. tB = vec4( vec3( tB ), 0.0 );
  4504. } else {
  4505. tA = vec4( vec3( tA ), 0.0 );
  4506. }
  4507. const mulNode = mul( tA, tB ).xyz;
  4508. outputNode = normalize( mulNode );
  4509. }
  4510. if ( outputNode !== null ) {
  4511. return outputNode;
  4512. } else {
  4513. return super.setup( builder );
  4514. }
  4515. }
  4516. generate( builder, output ) {
  4517. const properties = builder.getNodeProperties( this );
  4518. if ( properties.outputNode ) {
  4519. return super.generate( builder, output );
  4520. }
  4521. let method = this.method;
  4522. const type = this.getNodeType( builder );
  4523. const inputType = this.getInputType( builder );
  4524. const a = this.aNode;
  4525. const b = this.bNode;
  4526. const c = this.cNode;
  4527. const coordinateSystem = builder.renderer.coordinateSystem;
  4528. if ( method === MathNode.NEGATE ) {
  4529. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4530. } else {
  4531. const params = [];
  4532. if ( method === MathNode.CROSS ) {
  4533. params.push(
  4534. a.build( builder, type ),
  4535. b.build( builder, type )
  4536. );
  4537. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4538. params.push(
  4539. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4540. b.build( builder, inputType )
  4541. );
  4542. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4543. params.push(
  4544. a.build( builder, inputType ),
  4545. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4546. );
  4547. } else if ( method === MathNode.REFRACT ) {
  4548. params.push(
  4549. a.build( builder, inputType ),
  4550. b.build( builder, inputType ),
  4551. c.build( builder, 'float' )
  4552. );
  4553. } else if ( method === MathNode.MIX ) {
  4554. params.push(
  4555. a.build( builder, inputType ),
  4556. b.build( builder, inputType ),
  4557. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4558. );
  4559. } else {
  4560. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4561. method = 'atan2';
  4562. }
  4563. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4564. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4565. method = '/*' + method + '*/';
  4566. }
  4567. params.push( a.build( builder, inputType ) );
  4568. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4569. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4570. }
  4571. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4572. }
  4573. }
  4574. serialize( data ) {
  4575. super.serialize( data );
  4576. data.method = this.method;
  4577. }
  4578. deserialize( data ) {
  4579. super.deserialize( data );
  4580. this.method = data.method;
  4581. }
  4582. }
  4583. // 1 input
  4584. MathNode.ALL = 'all';
  4585. MathNode.ANY = 'any';
  4586. MathNode.RADIANS = 'radians';
  4587. MathNode.DEGREES = 'degrees';
  4588. MathNode.EXP = 'exp';
  4589. MathNode.EXP2 = 'exp2';
  4590. MathNode.LOG = 'log';
  4591. MathNode.LOG2 = 'log2';
  4592. MathNode.SQRT = 'sqrt';
  4593. MathNode.INVERSE_SQRT = 'inversesqrt';
  4594. MathNode.FLOOR = 'floor';
  4595. MathNode.CEIL = 'ceil';
  4596. MathNode.NORMALIZE = 'normalize';
  4597. MathNode.FRACT = 'fract';
  4598. MathNode.SIN = 'sin';
  4599. MathNode.COS = 'cos';
  4600. MathNode.TAN = 'tan';
  4601. MathNode.ASIN = 'asin';
  4602. MathNode.ACOS = 'acos';
  4603. MathNode.ATAN = 'atan';
  4604. MathNode.ABS = 'abs';
  4605. MathNode.SIGN = 'sign';
  4606. MathNode.LENGTH = 'length';
  4607. MathNode.NEGATE = 'negate';
  4608. MathNode.ONE_MINUS = 'oneMinus';
  4609. MathNode.DFDX = 'dFdx';
  4610. MathNode.DFDY = 'dFdy';
  4611. MathNode.ROUND = 'round';
  4612. MathNode.RECIPROCAL = 'reciprocal';
  4613. MathNode.TRUNC = 'trunc';
  4614. MathNode.FWIDTH = 'fwidth';
  4615. MathNode.TRANSPOSE = 'transpose';
  4616. MathNode.DETERMINANT = 'determinant';
  4617. MathNode.INVERSE = 'inverse';
  4618. // 2 inputs
  4619. MathNode.EQUALS = 'equals';
  4620. MathNode.MIN = 'min';
  4621. MathNode.MAX = 'max';
  4622. MathNode.STEP = 'step';
  4623. MathNode.REFLECT = 'reflect';
  4624. MathNode.DISTANCE = 'distance';
  4625. MathNode.DIFFERENCE = 'difference';
  4626. MathNode.DOT = 'dot';
  4627. MathNode.CROSS = 'cross';
  4628. MathNode.POW = 'pow';
  4629. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4630. // 3 inputs
  4631. MathNode.MIX = 'mix';
  4632. MathNode.CLAMP = 'clamp';
  4633. MathNode.REFRACT = 'refract';
  4634. MathNode.SMOOTHSTEP = 'smoothstep';
  4635. MathNode.FACEFORWARD = 'faceforward';
  4636. // 1 inputs
  4637. /**
  4638. * A small value used to handle floating-point precision errors.
  4639. *
  4640. * @tsl
  4641. * @type {Node<float>}
  4642. */
  4643. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4644. /**
  4645. * Represents infinity.
  4646. *
  4647. * @tsl
  4648. * @type {Node<float>}
  4649. */
  4650. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4651. /**
  4652. * Represents PI.
  4653. *
  4654. * @tsl
  4655. * @type {Node<float>}
  4656. */
  4657. const PI = /*@__PURE__*/ float( Math.PI );
  4658. /**
  4659. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4660. *
  4661. * @tsl
  4662. * @deprecated
  4663. * @type {Node<float>}
  4664. */
  4665. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4666. /**
  4667. * Represents PI * 2.
  4668. *
  4669. * @tsl
  4670. * @type {Node<float>}
  4671. */
  4672. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4673. /**
  4674. * Represents PI / 2.
  4675. *
  4676. * @tsl
  4677. * @type {Node<float>}
  4678. */
  4679. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4680. /**
  4681. * Returns `true` if all components of `x` are `true`.
  4682. *
  4683. * @tsl
  4684. * @function
  4685. * @param {Node | number} x - The parameter.
  4686. * @returns {Node<bool>}
  4687. */
  4688. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4689. /**
  4690. * Returns `true` if any components of `x` are `true`.
  4691. *
  4692. * @tsl
  4693. * @function
  4694. * @param {Node | number} x - The parameter.
  4695. * @returns {Node<bool>}
  4696. */
  4697. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4698. /**
  4699. * Converts a quantity in degrees to radians.
  4700. *
  4701. * @tsl
  4702. * @function
  4703. * @param {Node | number} x - The input in degrees.
  4704. * @returns {Node}
  4705. */
  4706. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4707. /**
  4708. * Convert a quantity in radians to degrees.
  4709. *
  4710. * @tsl
  4711. * @function
  4712. * @param {Node | number} x - The input in radians.
  4713. * @returns {Node}
  4714. */
  4715. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4716. /**
  4717. * Returns the natural exponentiation of the parameter.
  4718. *
  4719. * @tsl
  4720. * @function
  4721. * @param {Node | number} x - The parameter.
  4722. * @returns {Node}
  4723. */
  4724. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4725. /**
  4726. * Returns 2 raised to the power of the parameter.
  4727. *
  4728. * @tsl
  4729. * @function
  4730. * @param {Node | number} x - The parameter.
  4731. * @returns {Node}
  4732. */
  4733. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4734. /**
  4735. * Returns the natural logarithm of the parameter.
  4736. *
  4737. * @tsl
  4738. * @function
  4739. * @param {Node | number} x - The parameter.
  4740. * @returns {Node}
  4741. */
  4742. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4743. /**
  4744. * Returns the base 2 logarithm of the parameter.
  4745. *
  4746. * @tsl
  4747. * @function
  4748. * @param {Node | number} x - The parameter.
  4749. * @returns {Node}
  4750. */
  4751. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4752. /**
  4753. * Returns the square root of the parameter.
  4754. *
  4755. * @tsl
  4756. * @function
  4757. * @param {Node | number} x - The parameter.
  4758. * @returns {Node}
  4759. */
  4760. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4761. /**
  4762. * Returns the inverse of the square root of the parameter.
  4763. *
  4764. * @tsl
  4765. * @function
  4766. * @param {Node | number} x - The parameter.
  4767. * @returns {Node}
  4768. */
  4769. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4770. /**
  4771. * Finds the nearest integer less than or equal to the parameter.
  4772. *
  4773. * @tsl
  4774. * @function
  4775. * @param {Node | number} x - The parameter.
  4776. * @returns {Node}
  4777. */
  4778. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4779. /**
  4780. * Finds the nearest integer that is greater than or equal to the parameter.
  4781. *
  4782. * @tsl
  4783. * @function
  4784. * @param {Node | number} x - The parameter.
  4785. * @returns {Node}
  4786. */
  4787. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4788. /**
  4789. * Calculates the unit vector in the same direction as the original vector.
  4790. *
  4791. * @tsl
  4792. * @function
  4793. * @param {Node} x - The input vector.
  4794. * @returns {Node}
  4795. */
  4796. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4797. /**
  4798. * Computes the fractional part of the parameter.
  4799. *
  4800. * @tsl
  4801. * @function
  4802. * @param {Node | number} x - The parameter.
  4803. * @returns {Node}
  4804. */
  4805. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4806. /**
  4807. * Returns the sine of the parameter.
  4808. *
  4809. * @tsl
  4810. * @function
  4811. * @param {Node | number} x - The parameter.
  4812. * @returns {Node}
  4813. */
  4814. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4815. /**
  4816. * Returns the cosine of the parameter.
  4817. *
  4818. * @tsl
  4819. * @function
  4820. * @param {Node | number} x - The parameter.
  4821. * @returns {Node}
  4822. */
  4823. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4824. /**
  4825. * Returns the tangent of the parameter.
  4826. *
  4827. * @tsl
  4828. * @function
  4829. * @param {Node | number} x - The parameter.
  4830. * @returns {Node}
  4831. */
  4832. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4833. /**
  4834. * Returns the arcsine of the parameter.
  4835. *
  4836. * @tsl
  4837. * @function
  4838. * @param {Node | number} x - The parameter.
  4839. * @returns {Node}
  4840. */
  4841. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4842. /**
  4843. * Returns the arccosine of the parameter.
  4844. *
  4845. * @tsl
  4846. * @function
  4847. * @param {Node | number} x - The parameter.
  4848. * @returns {Node}
  4849. */
  4850. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4851. /**
  4852. * Returns the arc-tangent of the parameter.
  4853. * If two parameters are provided, the result is `atan2(y/x)`.
  4854. *
  4855. * @tsl
  4856. * @function
  4857. * @param {Node | number} y - The y parameter.
  4858. * @param {?(Node | number)} x - The x parameter.
  4859. * @returns {Node}
  4860. */
  4861. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4862. /**
  4863. * Returns the absolute value of the parameter.
  4864. *
  4865. * @tsl
  4866. * @function
  4867. * @param {Node | number} x - The parameter.
  4868. * @returns {Node}
  4869. */
  4870. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4871. /**
  4872. * Extracts the sign of the parameter.
  4873. *
  4874. * @tsl
  4875. * @function
  4876. * @param {Node | number} x - The parameter.
  4877. * @returns {Node}
  4878. */
  4879. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4880. /**
  4881. * Calculates the length of a vector.
  4882. *
  4883. * @tsl
  4884. * @function
  4885. * @param {Node} x - The parameter.
  4886. * @returns {Node<float>}
  4887. */
  4888. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4889. /**
  4890. * Negates the value of the parameter (-x).
  4891. *
  4892. * @tsl
  4893. * @function
  4894. * @param {Node | number} x - The parameter.
  4895. * @returns {Node}
  4896. */
  4897. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4898. /**
  4899. * Return `1` minus the parameter.
  4900. *
  4901. * @tsl
  4902. * @function
  4903. * @param {Node | number} x - The parameter.
  4904. * @returns {Node}
  4905. */
  4906. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4907. /**
  4908. * Returns the partial derivative of the parameter with respect to x.
  4909. *
  4910. * @tsl
  4911. * @function
  4912. * @param {Node | number} x - The parameter.
  4913. * @returns {Node}
  4914. */
  4915. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4916. /**
  4917. * Returns the partial derivative of the parameter with respect to y.
  4918. *
  4919. * @tsl
  4920. * @function
  4921. * @param {Node | number} x - The parameter.
  4922. * @returns {Node}
  4923. */
  4924. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4925. /**
  4926. * Rounds the parameter to the nearest integer.
  4927. *
  4928. * @tsl
  4929. * @function
  4930. * @param {Node | number} x - The parameter.
  4931. * @returns {Node}
  4932. */
  4933. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4934. /**
  4935. * Returns the reciprocal of the parameter `(1/x)`.
  4936. *
  4937. * @tsl
  4938. * @function
  4939. * @param {Node | number} x - The parameter.
  4940. * @returns {Node}
  4941. */
  4942. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4943. /**
  4944. * Truncates the parameter, removing the fractional part.
  4945. *
  4946. * @tsl
  4947. * @function
  4948. * @param {Node | number} x - The parameter.
  4949. * @returns {Node}
  4950. */
  4951. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4952. /**
  4953. * Returns the sum of the absolute derivatives in x and y.
  4954. *
  4955. * @tsl
  4956. * @function
  4957. * @param {Node | number} x - The parameter.
  4958. * @returns {Node}
  4959. */
  4960. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4961. /**
  4962. * Returns the transpose of a matrix.
  4963. *
  4964. * @tsl
  4965. * @function
  4966. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4967. * @returns {Node}
  4968. */
  4969. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4970. /**
  4971. * Returns the determinant of a matrix.
  4972. *
  4973. * @tsl
  4974. * @function
  4975. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4976. * @returns {Node<float>}
  4977. */
  4978. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4979. /**
  4980. * Returns the inverse of a matrix.
  4981. *
  4982. * @tsl
  4983. * @function
  4984. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4985. * @returns {Node<mat2|mat3|mat4>}
  4986. */
  4987. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4988. // 2 inputs
  4989. /**
  4990. * Returns the least of the given values.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {...(Node | number)} values - The values to compare.
  4995. * @returns {Node}
  4996. */
  4997. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4998. /**
  4999. * Returns the greatest of the given values.
  5000. *
  5001. * @tsl
  5002. * @function
  5003. * @param {...(Node | number)} values - The values to compare.
  5004. * @returns {Node}
  5005. */
  5006. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  5007. /**
  5008. * Generate a step function by comparing two values.
  5009. *
  5010. * @tsl
  5011. * @function
  5012. * @param {Node | number} x - The y parameter.
  5013. * @param {Node | number} y - The x parameter.
  5014. * @returns {Node}
  5015. */
  5016. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  5017. /**
  5018. * Calculates the reflection direction for an incident vector.
  5019. *
  5020. * @tsl
  5021. * @function
  5022. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5023. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5024. * @returns {Node<vec2|vec3|vec4>}
  5025. */
  5026. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  5027. /**
  5028. * Calculates the distance between two points.
  5029. *
  5030. * @tsl
  5031. * @function
  5032. * @param {Node<vec2|vec3|vec4>} x - The first point.
  5033. * @param {Node<vec2|vec3|vec4>} y - The second point.
  5034. * @returns {Node<float>}
  5035. */
  5036. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  5037. /**
  5038. * Calculates the absolute difference between two values.
  5039. *
  5040. * @tsl
  5041. * @function
  5042. * @param {Node | number} x - The first parameter.
  5043. * @param {Node | number} y - The second parameter.
  5044. * @returns {Node}
  5045. */
  5046. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  5047. /**
  5048. * Calculates the dot product of two vectors.
  5049. *
  5050. * @tsl
  5051. * @function
  5052. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  5053. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5054. * @returns {Node<float>}
  5055. */
  5056. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5057. /**
  5058. * Calculates the cross product of two vectors.
  5059. *
  5060. * @tsl
  5061. * @function
  5062. * @param {Node<vec2|vec3>} x - The first vector.
  5063. * @param {Node<vec2|vec3>} y - The second vector.
  5064. * @returns {Node<float|vec3>}
  5065. */
  5066. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5067. /**
  5068. * Return the value of the first parameter raised to the power of the second one.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node | number} x - The first parameter.
  5073. * @param {Node | number} y - The second parameter.
  5074. * @returns {Node}
  5075. */
  5076. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5077. /**
  5078. * Returns the square of the parameter.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} x - The first parameter.
  5083. * @returns {Node}
  5084. */
  5085. const pow2 = ( x ) => mul( x, x );
  5086. /**
  5087. * Returns the cube of the parameter.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node | number} x - The first parameter.
  5092. * @returns {Node}
  5093. */
  5094. const pow3 = ( x ) => mul( x, x, x );
  5095. /**
  5096. * Returns the fourth power of the parameter.
  5097. *
  5098. * @tsl
  5099. * @function
  5100. * @param {Node | number} x - The first parameter.
  5101. * @returns {Node}
  5102. */
  5103. const pow4 = ( x ) => mul( x, x, x, x );
  5104. /**
  5105. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5106. *
  5107. * @tsl
  5108. * @function
  5109. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5110. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5111. * @returns {Node}
  5112. */
  5113. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5114. /**
  5115. * Returns the cube root of a number.
  5116. *
  5117. * @tsl
  5118. * @function
  5119. * @param {Node | number} a - The first parameter.
  5120. * @returns {Node}
  5121. */
  5122. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5123. /**
  5124. * Calculate the squared length of a vector.
  5125. *
  5126. * @tsl
  5127. * @function
  5128. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5129. * @returns {Node<float>}
  5130. */
  5131. const lengthSq = ( a ) => dot( a, a );
  5132. /**
  5133. * Linearly interpolates between two values.
  5134. *
  5135. * @tsl
  5136. * @function
  5137. * @param {Node | number} a - The first parameter.
  5138. * @param {Node | number} b - The second parameter.
  5139. * @param {Node | number} t - The interpolation value.
  5140. * @returns {Node}
  5141. */
  5142. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5143. /**
  5144. * Constrains a value to lie between two further values.
  5145. *
  5146. * @tsl
  5147. * @function
  5148. * @param {Node | number} value - The value to constrain.
  5149. * @param {Node | number} [low=0] - The lower bound.
  5150. * @param {Node | number} [high=1] - The upper bound.
  5151. * @returns {Node}
  5152. */
  5153. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5154. /**
  5155. * Constrains a value between `0` and `1`.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node | number} value - The value to constrain.
  5160. * @returns {Node}
  5161. */
  5162. const saturate = ( value ) => clamp( value );
  5163. /**
  5164. * Calculates the refraction direction for an incident vector.
  5165. *
  5166. * @tsl
  5167. * @function
  5168. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5169. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5170. * @param {Node<float>} eta - The ratio of indices of refraction.
  5171. * @returns {Node<vec2|vec3|vec4>}
  5172. */
  5173. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5174. /**
  5175. * Performs a Hermite interpolation between two values.
  5176. *
  5177. * @tsl
  5178. * @function
  5179. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5180. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5181. * @param {Node | number} x - The source value for interpolation.
  5182. * @returns {Node}
  5183. */
  5184. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5185. /**
  5186. * Returns a vector pointing in the same direction as another.
  5187. *
  5188. * @tsl
  5189. * @function
  5190. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5191. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5192. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5193. * @returns {Node<vec2|vec3|vec4>}
  5194. */
  5195. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5196. /**
  5197. * Returns a random value for the given uv.
  5198. *
  5199. * @tsl
  5200. * @function
  5201. * @param {Node<vec2>} uv - The uv node.
  5202. * @returns {Node<float>}
  5203. */
  5204. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5205. const a = 12.9898, b = 78.233, c = 43758.5453;
  5206. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5207. return fract( sin( sn ).mul( c ) );
  5208. } );
  5209. /**
  5210. * Alias for `mix()` with a different parameter order.
  5211. *
  5212. * @tsl
  5213. * @function
  5214. * @param {Node | number} t - The interpolation value.
  5215. * @param {Node | number} e1 - The first parameter.
  5216. * @param {Node | number} e2 - The second parameter.
  5217. * @returns {Node}
  5218. */
  5219. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5220. /**
  5221. * Alias for `smoothstep()` with a different parameter order.
  5222. *
  5223. * @tsl
  5224. * @function
  5225. * @param {Node | number} x - The source value for interpolation.
  5226. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5227. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5228. * @returns {Node}
  5229. */
  5230. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5231. /**
  5232. * Alias for `step()` with a different parameter order.
  5233. *
  5234. * @tsl
  5235. * @function
  5236. * @param {Node | number} x - The source value for interpolation.
  5237. * @param {Node | number} edge - The edge value.
  5238. * @returns {Node}
  5239. */
  5240. const stepElement = ( x, edge ) => step( edge, x );
  5241. // GLSL alias function
  5242. const faceforward = faceForward;
  5243. const inversesqrt = inverseSqrt;
  5244. // Method chaining
  5245. addMethodChaining( 'all', all );
  5246. addMethodChaining( 'any', any );
  5247. addMethodChaining( 'radians', radians );
  5248. addMethodChaining( 'degrees', degrees );
  5249. addMethodChaining( 'exp', exp );
  5250. addMethodChaining( 'exp2', exp2 );
  5251. addMethodChaining( 'log', log );
  5252. addMethodChaining( 'log2', log2 );
  5253. addMethodChaining( 'sqrt', sqrt );
  5254. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5255. addMethodChaining( 'floor', floor );
  5256. addMethodChaining( 'ceil', ceil );
  5257. addMethodChaining( 'normalize', normalize );
  5258. addMethodChaining( 'fract', fract );
  5259. addMethodChaining( 'sin', sin );
  5260. addMethodChaining( 'cos', cos );
  5261. addMethodChaining( 'tan', tan );
  5262. addMethodChaining( 'asin', asin );
  5263. addMethodChaining( 'acos', acos );
  5264. addMethodChaining( 'atan', atan );
  5265. addMethodChaining( 'abs', abs );
  5266. addMethodChaining( 'sign', sign );
  5267. addMethodChaining( 'length', length );
  5268. addMethodChaining( 'lengthSq', lengthSq );
  5269. addMethodChaining( 'negate', negate );
  5270. addMethodChaining( 'oneMinus', oneMinus );
  5271. addMethodChaining( 'dFdx', dFdx );
  5272. addMethodChaining( 'dFdy', dFdy );
  5273. addMethodChaining( 'round', round );
  5274. addMethodChaining( 'reciprocal', reciprocal );
  5275. addMethodChaining( 'trunc', trunc );
  5276. addMethodChaining( 'fwidth', fwidth );
  5277. addMethodChaining( 'min', min$1 );
  5278. addMethodChaining( 'max', max$1 );
  5279. addMethodChaining( 'step', stepElement );
  5280. addMethodChaining( 'reflect', reflect );
  5281. addMethodChaining( 'distance', distance );
  5282. addMethodChaining( 'dot', dot );
  5283. addMethodChaining( 'cross', cross );
  5284. addMethodChaining( 'pow', pow );
  5285. addMethodChaining( 'pow2', pow2 );
  5286. addMethodChaining( 'pow3', pow3 );
  5287. addMethodChaining( 'pow4', pow4 );
  5288. addMethodChaining( 'transformDirection', transformDirection );
  5289. addMethodChaining( 'mix', mixElement );
  5290. addMethodChaining( 'clamp', clamp );
  5291. addMethodChaining( 'refract', refract );
  5292. addMethodChaining( 'smoothstep', smoothstepElement );
  5293. addMethodChaining( 'faceForward', faceForward );
  5294. addMethodChaining( 'difference', difference );
  5295. addMethodChaining( 'saturate', saturate );
  5296. addMethodChaining( 'cbrt', cbrt );
  5297. addMethodChaining( 'transpose', transpose );
  5298. addMethodChaining( 'determinant', determinant );
  5299. addMethodChaining( 'inverse', inverse );
  5300. addMethodChaining( 'rand', rand );
  5301. /**
  5302. * Represents a logical `if/else` statement. Can be used as an alternative
  5303. * to the `If()`/`Else()` syntax.
  5304. *
  5305. * The corresponding TSL `select()` looks like so:
  5306. * ```js
  5307. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5308. * ```
  5309. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5310. * determine the outcome of the entire statement.
  5311. *
  5312. * @augments Node
  5313. */
  5314. class ConditionalNode extends Node {
  5315. static get type() {
  5316. return 'ConditionalNode';
  5317. }
  5318. /**
  5319. * Constructs a new conditional node.
  5320. *
  5321. * @param {Node} condNode - The node that defines the condition.
  5322. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5323. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5324. */
  5325. constructor( condNode, ifNode, elseNode = null ) {
  5326. super();
  5327. /**
  5328. * The node that defines the condition.
  5329. *
  5330. * @type {Node}
  5331. */
  5332. this.condNode = condNode;
  5333. /**
  5334. * The node that is evaluate when the condition ends up `true`.
  5335. *
  5336. * @type {Node}
  5337. */
  5338. this.ifNode = ifNode;
  5339. /**
  5340. * The node that is evaluate when the condition ends up `false`.
  5341. *
  5342. * @type {?Node}
  5343. * @default null
  5344. */
  5345. this.elseNode = elseNode;
  5346. }
  5347. /**
  5348. * This method is overwritten since the node type is inferred from the if/else
  5349. * nodes.
  5350. *
  5351. * @param {NodeBuilder} builder - The current node builder.
  5352. * @return {string} The node type.
  5353. */
  5354. getNodeType( builder ) {
  5355. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5356. if ( ifNode === undefined ) {
  5357. // fallback setup
  5358. builder.flowBuildStage( this, 'setup' );
  5359. return this.getNodeType( builder );
  5360. }
  5361. const ifType = ifNode.getNodeType( builder );
  5362. if ( elseNode !== null ) {
  5363. const elseType = elseNode.getNodeType( builder );
  5364. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5365. return elseType;
  5366. }
  5367. }
  5368. return ifType;
  5369. }
  5370. setup( builder ) {
  5371. const condNode = this.condNode;
  5372. const ifNode = this.ifNode.isolate();
  5373. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5374. //
  5375. const currentNodeBlock = builder.context.nodeBlock;
  5376. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5377. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5378. //
  5379. const isUniformFlow = builder.context.uniformFlow;
  5380. const properties = builder.getNodeProperties( this );
  5381. properties.condNode = condNode;
  5382. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5383. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5384. }
  5385. generate( builder, output ) {
  5386. const type = this.getNodeType( builder );
  5387. const nodeData = builder.getDataFromNode( this );
  5388. if ( nodeData.nodeProperty !== undefined ) {
  5389. return nodeData.nodeProperty;
  5390. }
  5391. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5392. const functionNode = builder.currentFunctionNode;
  5393. const needsOutput = output !== 'void';
  5394. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5395. nodeData.nodeProperty = nodeProperty;
  5396. const nodeSnippet = condNode.build( builder, 'bool' );
  5397. const isUniformFlow = builder.context.uniformFlow;
  5398. if ( isUniformFlow && elseNode !== null ) {
  5399. const ifSnippet = ifNode.build( builder, type );
  5400. const elseSnippet = elseNode.build( builder, type );
  5401. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5402. // TODO: If node property already exists return something else
  5403. return builder.format( mathSnippet, type, output );
  5404. }
  5405. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5406. let ifSnippet = ifNode.build( builder, type );
  5407. if ( ifSnippet ) {
  5408. if ( needsOutput ) {
  5409. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5410. } else {
  5411. ifSnippet = 'return ' + ifSnippet + ';';
  5412. if ( functionNode === null ) {
  5413. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5414. ifSnippet = '// ' + ifSnippet;
  5415. }
  5416. }
  5417. }
  5418. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5419. if ( elseNode !== null ) {
  5420. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5421. let elseSnippet = elseNode.build( builder, type );
  5422. if ( elseSnippet ) {
  5423. if ( needsOutput ) {
  5424. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5425. } else {
  5426. elseSnippet = 'return ' + elseSnippet + ';';
  5427. if ( functionNode === null ) {
  5428. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5429. elseSnippet = '// ' + elseSnippet;
  5430. }
  5431. }
  5432. }
  5433. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5434. } else {
  5435. builder.addFlowCode( '\n\n' );
  5436. }
  5437. return builder.format( nodeProperty, type, output );
  5438. }
  5439. }
  5440. /**
  5441. * TSL function for creating a conditional node.
  5442. *
  5443. * @tsl
  5444. * @function
  5445. * @param {Node} condNode - The node that defines the condition.
  5446. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5447. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5448. * @returns {ConditionalNode}
  5449. */
  5450. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5451. addMethodChaining( 'select', select );
  5452. /**
  5453. * This node can be used as a context management component for another node.
  5454. * {@link NodeBuilder} performs its node building process in a specific context and
  5455. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5456. *
  5457. * ```js
  5458. *node.context( { getUV: () => customCoord } );
  5459. *\// or
  5460. *material.contextNode = context( { getUV: () => customCoord } );
  5461. *\// or
  5462. *renderer.contextNode = context( { getUV: () => customCoord } );
  5463. *\// or
  5464. *scenePass.contextNode = context( { getUV: () => customCoord } );
  5465. *```
  5466. * @augments Node
  5467. */
  5468. class ContextNode extends Node {
  5469. static get type() {
  5470. return 'ContextNode';
  5471. }
  5472. /**
  5473. * Constructs a new context node.
  5474. *
  5475. * @param {Node} node - The node whose context should be modified.
  5476. * @param {Object} [value={}] - The modified context data.
  5477. */
  5478. constructor( node = null, value = {} ) {
  5479. super();
  5480. /**
  5481. * This flag can be used for type testing.
  5482. *
  5483. * @type {boolean}
  5484. * @readonly
  5485. * @default true
  5486. */
  5487. this.isContextNode = true;
  5488. /**
  5489. * The node whose context should be modified.
  5490. *
  5491. * @type {Node}
  5492. */
  5493. this.node = node;
  5494. /**
  5495. * The modified context data.
  5496. *
  5497. * @type {Object}
  5498. * @default {}
  5499. */
  5500. this.value = value;
  5501. }
  5502. /**
  5503. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5504. *
  5505. * @return {Node} A reference to {@link ContextNode#node}.
  5506. */
  5507. getScope() {
  5508. return this.node.getScope();
  5509. }
  5510. /**
  5511. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5512. *
  5513. * @param {NodeBuilder} builder - The current node builder.
  5514. * @return {string} The node type.
  5515. */
  5516. getNodeType( builder ) {
  5517. return this.node.getNodeType( builder );
  5518. }
  5519. /**
  5520. * Gathers the context data from all parent context nodes.
  5521. *
  5522. * @return {Object} The gathered context data.
  5523. */
  5524. getFlowContextData() {
  5525. const children = [];
  5526. this.traverse( ( node ) => {
  5527. if ( node.isContextNode === true ) {
  5528. children.push( node.value );
  5529. }
  5530. } );
  5531. return Object.assign( {}, ...children );
  5532. }
  5533. /**
  5534. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5535. *
  5536. * @param {NodeBuilder} builder - The current node builder.
  5537. * @param {string} name - The member name.
  5538. * @returns {string} The member type.
  5539. */
  5540. getMemberType( builder, name ) {
  5541. return this.node.getMemberType( builder, name );
  5542. }
  5543. analyze( builder ) {
  5544. const previousContext = builder.addContext( this.value );
  5545. this.node.build( builder );
  5546. builder.setContext( previousContext );
  5547. }
  5548. setup( builder ) {
  5549. const previousContext = builder.addContext( this.value );
  5550. this.node.build( builder );
  5551. builder.setContext( previousContext );
  5552. }
  5553. generate( builder, output ) {
  5554. const previousContext = builder.addContext( this.value );
  5555. const snippet = this.node.build( builder, output );
  5556. builder.setContext( previousContext );
  5557. return snippet;
  5558. }
  5559. }
  5560. /**
  5561. * TSL function for creating a context node.
  5562. *
  5563. * @tsl
  5564. * @function
  5565. * @param {Node|Object} [nodeOrValue={}] - The node whose context should be modified or the modified context data.
  5566. * @param {Object} [value={}] - The modified context data.
  5567. * @returns {ContextNode}
  5568. */
  5569. const context = ( nodeOrValue = null, value = {} ) => {
  5570. let node = nodeOrValue;
  5571. if ( node === null || node.isNode !== true ) {
  5572. value = node || value;
  5573. node = null;
  5574. }
  5575. return new ContextNode( node, value );
  5576. };
  5577. /**
  5578. * TSL function for defining a uniformFlow context value for a given node.
  5579. *
  5580. * @tsl
  5581. * @function
  5582. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5583. * @returns {ContextNode}
  5584. */
  5585. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5586. /**
  5587. * TSL function for defining a name for the context value for a given node.
  5588. *
  5589. * @tsl
  5590. * @function
  5591. * @param {Node} node - The node whose context should be modified.
  5592. * @param {string} name - The name to set.
  5593. * @returns {ContextNode}
  5594. */
  5595. const setName = ( node, name ) => context( node, { nodeName: name } );
  5596. /**
  5597. * TSL function for defining a built-in shadow context for a given node.
  5598. *
  5599. * @tsl
  5600. * @function
  5601. * @param {ShadowNode} shadowNode - The shadow node representing the light's shadow.
  5602. * @param {Light} light - The light associated with the shadow.
  5603. * @param {Node} [node=null] - The node whose context should be modified.
  5604. * @returns {ContextNode}
  5605. */
  5606. function builtinShadowContext( shadowNode, light, node = null ) {
  5607. return context( node, {
  5608. getShadow: ( { light: shadowLight, shadowColorNode } ) => {
  5609. if ( light === shadowLight ) {
  5610. return shadowColorNode.mul( shadowNode );
  5611. }
  5612. return shadowColorNode;
  5613. }
  5614. } );
  5615. }
  5616. /**
  5617. * TSL function for defining a built-in ambient occlusion context for a given node.
  5618. *
  5619. * @tsl
  5620. * @function
  5621. * @param {Node} aoNode - The ambient occlusion value node to apply.
  5622. * @param {Node} [node=null] - The node whose context should be modified.
  5623. * @returns {ContextNode}
  5624. */
  5625. function builtinAOContext( aoNode, node = null ) {
  5626. return context( node, {
  5627. getAO: ( inputNode, { material } ) => {
  5628. if ( material.transparent === true ) return inputNode;
  5629. return inputNode !== null ? inputNode.mul( aoNode ) : aoNode;
  5630. }
  5631. } );
  5632. }
  5633. /**
  5634. * TSL function for defining a label context value for a given node.
  5635. *
  5636. * @tsl
  5637. * @function
  5638. * @deprecated
  5639. * @param {Node} node - The node whose context should be modified.
  5640. * @param {string} name - The name/label to set.
  5641. * @returns {ContextNode}
  5642. */
  5643. function label( node, name ) {
  5644. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5645. return setName( node, name );
  5646. }
  5647. addMethodChaining( 'context', context );
  5648. addMethodChaining( 'label', label );
  5649. addMethodChaining( 'uniformFlow', uniformFlow );
  5650. addMethodChaining( 'setName', setName );
  5651. addMethodChaining( 'builtinShadowContext', ( node, shadowNode, light ) => builtinShadowContext( shadowNode, light, node ) );
  5652. addMethodChaining( 'builtinAOContext', ( node, aoValue ) => builtinAOContext( aoValue, node ) );
  5653. /**
  5654. * Class for representing shader variables as nodes. Variables are created from
  5655. * existing nodes like the following:
  5656. *
  5657. * ```js
  5658. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5659. * ```
  5660. *
  5661. * @augments Node
  5662. */
  5663. class VarNode extends Node {
  5664. static get type() {
  5665. return 'VarNode';
  5666. }
  5667. /**
  5668. * Constructs a new variable node.
  5669. *
  5670. * @param {Node} node - The node for which a variable should be created.
  5671. * @param {?string} [name=null] - The name of the variable in the shader.
  5672. * @param {boolean} [readOnly=false] - The read-only flag.
  5673. */
  5674. constructor( node, name = null, readOnly = false ) {
  5675. super();
  5676. /**
  5677. * The node for which a variable should be created.
  5678. *
  5679. * @type {Node}
  5680. */
  5681. this.node = node;
  5682. /**
  5683. * The name of the variable in the shader. If no name is defined,
  5684. * the node system auto-generates one.
  5685. *
  5686. * @type {?string}
  5687. * @default null
  5688. */
  5689. this.name = name;
  5690. /**
  5691. * `VarNode` sets this property to `true` by default.
  5692. *
  5693. * @type {boolean}
  5694. * @default true
  5695. */
  5696. this.global = true;
  5697. /**
  5698. * This flag can be used for type testing.
  5699. *
  5700. * @type {boolean}
  5701. * @readonly
  5702. * @default true
  5703. */
  5704. this.isVarNode = true;
  5705. /**
  5706. *
  5707. * The read-only flag.
  5708. *
  5709. * @type {boolean}
  5710. * @default false
  5711. */
  5712. this.readOnly = readOnly;
  5713. /**
  5714. *
  5715. * Add this flag to the node system to indicate that this node require parents.
  5716. *
  5717. * @type {boolean}
  5718. * @default true
  5719. */
  5720. this.parents = true;
  5721. /**
  5722. * This flag is used to indicate that this node is used for intent.
  5723. *
  5724. * @type {boolean}
  5725. * @default false
  5726. */
  5727. this.intent = false;
  5728. }
  5729. /**
  5730. * Sets the intent flag for this node.
  5731. *
  5732. * This flag is used to indicate that this node is used for intent
  5733. * and should not be built directly. Instead, it is used to indicate that
  5734. * the node should be treated as a variable intent.
  5735. *
  5736. * It's useful for assigning variables without needing creating a new variable node.
  5737. *
  5738. * @param {boolean} value - The value to set for the intent flag.
  5739. * @returns {VarNode} This node.
  5740. */
  5741. setIntent( value ) {
  5742. this.intent = value;
  5743. return this;
  5744. }
  5745. /**
  5746. * Checks if this node is used for intent.
  5747. *
  5748. * @param {NodeBuilder} builder - The node builder.
  5749. * @returns {boolean} Whether this node is used for intent.
  5750. */
  5751. isIntent( builder ) {
  5752. const data = builder.getDataFromNode( this );
  5753. if ( data.forceDeclaration === true ) return false;
  5754. return this.intent;
  5755. }
  5756. /**
  5757. * Returns the intent flag of this node.
  5758. *
  5759. * @return {boolean} The intent flag.
  5760. */
  5761. getIntent() {
  5762. return this.intent;
  5763. }
  5764. getMemberType( builder, name ) {
  5765. return this.node.getMemberType( builder, name );
  5766. }
  5767. getElementType( builder ) {
  5768. return this.node.getElementType( builder );
  5769. }
  5770. getNodeType( builder ) {
  5771. return this.node.getNodeType( builder );
  5772. }
  5773. getArrayCount( builder ) {
  5774. return this.node.getArrayCount( builder );
  5775. }
  5776. isAssign( builder ) {
  5777. const data = builder.getDataFromNode( this );
  5778. return data.assign;
  5779. }
  5780. build( ...params ) {
  5781. const builder = params[ 0 ];
  5782. if ( this._hasStack( builder ) === false && builder.buildStage === 'setup' ) {
  5783. if ( builder.context.nodeLoop || builder.context.nodeBlock ) {
  5784. let addBefore = false;
  5785. if ( this.node.isShaderCallNodeInternal && this.node.shaderNode.getLayout() === null ) {
  5786. if ( builder.fnCall && builder.fnCall.shaderNode ) {
  5787. const shaderNodeData = builder.getDataFromNode( this.node.shaderNode );
  5788. if ( shaderNodeData.hasLoop ) {
  5789. const data = builder.getDataFromNode( this );
  5790. data.forceDeclaration = true;
  5791. addBefore = true;
  5792. }
  5793. }
  5794. }
  5795. const baseStack = builder.getBaseStack();
  5796. if ( addBefore ) {
  5797. baseStack.addToStackBefore( this );
  5798. } else {
  5799. baseStack.addToStack( this );
  5800. }
  5801. }
  5802. }
  5803. if ( this.isIntent( builder ) ) {
  5804. if ( this.isAssign( builder ) !== true ) {
  5805. return this.node.build( ...params );
  5806. }
  5807. }
  5808. return super.build( ...params );
  5809. }
  5810. generate( builder ) {
  5811. const { node, name, readOnly } = this;
  5812. const { renderer } = builder;
  5813. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5814. let isDeterministic = false;
  5815. let shouldTreatAsReadOnly = false;
  5816. if ( readOnly ) {
  5817. isDeterministic = builder.isDeterministic( node );
  5818. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5819. }
  5820. const nodeType = this.getNodeType( builder );
  5821. if ( nodeType == 'void' ) {
  5822. if ( this.isIntent( builder ) !== true ) {
  5823. error( 'TSL: ".toVar()" can not be used with void type.' );
  5824. }
  5825. const snippet = node.build( builder );
  5826. return snippet;
  5827. }
  5828. const vectorType = builder.getVectorType( nodeType );
  5829. const snippet = node.build( builder, vectorType );
  5830. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5831. const propertyName = builder.getPropertyName( nodeVar );
  5832. let declarationPrefix = propertyName;
  5833. if ( shouldTreatAsReadOnly ) {
  5834. if ( isWebGPUBackend ) {
  5835. declarationPrefix = isDeterministic
  5836. ? `const ${ propertyName }`
  5837. : `let ${ propertyName }`;
  5838. } else {
  5839. const count = node.getArrayCount( builder );
  5840. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5841. }
  5842. }
  5843. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5844. return propertyName;
  5845. }
  5846. _hasStack( builder ) {
  5847. const nodeData = builder.getDataFromNode( this );
  5848. return nodeData.stack !== undefined;
  5849. }
  5850. }
  5851. /**
  5852. * TSL function for creating a var node.
  5853. *
  5854. * @tsl
  5855. * @function
  5856. * @param {Node} node - The node for which a variable should be created.
  5857. * @param {?string} name - The name of the variable in the shader.
  5858. * @returns {VarNode}
  5859. */
  5860. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5861. /**
  5862. * TSL function for creating a var node.
  5863. *
  5864. * @tsl
  5865. * @function
  5866. * @param {Node} node - The node for which a variable should be created.
  5867. * @param {?string} name - The name of the variable in the shader.
  5868. * @returns {VarNode}
  5869. */
  5870. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5871. /**
  5872. * TSL function for creating a const node.
  5873. *
  5874. * @tsl
  5875. * @function
  5876. * @param {Node} node - The node for which a constant should be created.
  5877. * @param {?string} name - The name of the constant in the shader.
  5878. * @returns {VarNode}
  5879. */
  5880. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5881. //
  5882. //
  5883. /**
  5884. * TSL function for creating a var intent node.
  5885. *
  5886. * @tsl
  5887. * @function
  5888. * @param {Node} node - The node for which a variable should be created.
  5889. * @param {?string} name - The name of the variable in the shader.
  5890. * @returns {VarNode}
  5891. */
  5892. const VarIntent = ( node ) => {
  5893. return createVar( node ).setIntent( true ).toStack();
  5894. };
  5895. // Method chaining
  5896. addMethodChaining( 'toVar', Var );
  5897. addMethodChaining( 'toConst', Const );
  5898. addMethodChaining( 'toVarIntent', VarIntent );
  5899. /**
  5900. * This node is used to build a sub-build in the node system.
  5901. *
  5902. * @augments Node
  5903. * @param {Node} node - The node to be built in the sub-build.
  5904. * @param {string} name - The name of the sub-build.
  5905. * @param {?string} [nodeType=null] - The type of the node, if known.
  5906. */
  5907. class SubBuildNode extends Node {
  5908. static get type() {
  5909. return 'SubBuild';
  5910. }
  5911. constructor( node, name, nodeType = null ) {
  5912. super( nodeType );
  5913. /**
  5914. * The node to be built in the sub-build.
  5915. *
  5916. * @type {Node}
  5917. */
  5918. this.node = node;
  5919. /**
  5920. * The name of the sub-build.
  5921. *
  5922. * @type {string}
  5923. */
  5924. this.name = name;
  5925. /**
  5926. * This flag can be used for type testing.
  5927. *
  5928. * @type {boolean}
  5929. * @readonly
  5930. * @default true
  5931. */
  5932. this.isSubBuildNode = true;
  5933. }
  5934. getNodeType( builder ) {
  5935. if ( this.nodeType !== null ) return this.nodeType;
  5936. builder.addSubBuild( this.name );
  5937. const nodeType = this.node.getNodeType( builder );
  5938. builder.removeSubBuild();
  5939. return nodeType;
  5940. }
  5941. build( builder, ...params ) {
  5942. builder.addSubBuild( this.name );
  5943. const data = this.node.build( builder, ...params );
  5944. builder.removeSubBuild();
  5945. return data;
  5946. }
  5947. }
  5948. /**
  5949. * Creates a new sub-build node.
  5950. *
  5951. * @tsl
  5952. * @function
  5953. * @param {Node} node - The node to be built in the sub-build.
  5954. * @param {string} name - The name of the sub-build.
  5955. * @param {?string} [type=null] - The type of the node, if known.
  5956. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5957. */
  5958. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5959. /**
  5960. * Class for representing shader varyings as nodes. Varyings are create from
  5961. * existing nodes like the following:
  5962. *
  5963. * ```js
  5964. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5965. * ```
  5966. *
  5967. * @augments Node
  5968. */
  5969. class VaryingNode extends Node {
  5970. static get type() {
  5971. return 'VaryingNode';
  5972. }
  5973. /**
  5974. * Constructs a new varying node.
  5975. *
  5976. * @param {Node} node - The node for which a varying should be created.
  5977. * @param {?string} name - The name of the varying in the shader.
  5978. */
  5979. constructor( node, name = null ) {
  5980. super();
  5981. /**
  5982. * The node for which a varying should be created.
  5983. *
  5984. * @type {Node}
  5985. */
  5986. this.node = subBuild( node, 'VERTEX' );
  5987. /**
  5988. * The name of the varying in the shader. If no name is defined,
  5989. * the node system auto-generates one.
  5990. *
  5991. * @type {?string}
  5992. * @default null
  5993. */
  5994. this.name = name;
  5995. /**
  5996. * This flag can be used for type testing.
  5997. *
  5998. * @type {boolean}
  5999. * @readonly
  6000. * @default true
  6001. */
  6002. this.isVaryingNode = true;
  6003. /**
  6004. * The interpolation type of the varying data.
  6005. *
  6006. * @type {?string}
  6007. * @default null
  6008. */
  6009. this.interpolationType = null;
  6010. /**
  6011. * The interpolation sampling type of varying data.
  6012. *
  6013. * @type {?string}
  6014. * @default null
  6015. */
  6016. this.interpolationSampling = null;
  6017. /**
  6018. * This flag is used for global cache.
  6019. *
  6020. * @type {boolean}
  6021. * @default true
  6022. */
  6023. this.global = true;
  6024. }
  6025. /**
  6026. * Defines the interpolation type of the varying.
  6027. *
  6028. * @param {string} type - The interpolation type.
  6029. * @param {?string} sampling - The interpolation sampling type
  6030. * @return {VaryingNode} A reference to this node.
  6031. */
  6032. setInterpolation( type, sampling = null ) {
  6033. this.interpolationType = type;
  6034. this.interpolationSampling = sampling;
  6035. return this;
  6036. }
  6037. getHash( builder ) {
  6038. return this.name || super.getHash( builder );
  6039. }
  6040. getNodeType( builder ) {
  6041. // VaryingNode is auto type
  6042. return this.node.getNodeType( builder );
  6043. }
  6044. /**
  6045. * This method performs the setup of a varying node with the current node builder.
  6046. *
  6047. * @param {NodeBuilder} builder - The current node builder.
  6048. * @return {NodeVarying} The node varying from the node builder.
  6049. */
  6050. setupVarying( builder ) {
  6051. const properties = builder.getNodeProperties( this );
  6052. let varying = properties.varying;
  6053. if ( varying === undefined ) {
  6054. const name = this.name;
  6055. const type = this.getNodeType( builder );
  6056. const interpolationType = this.interpolationType;
  6057. const interpolationSampling = this.interpolationSampling;
  6058. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  6059. properties.node = subBuild( this.node, 'VERTEX' );
  6060. }
  6061. // this property can be used to check if the varying can be optimized for a variable
  6062. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  6063. return varying;
  6064. }
  6065. setup( builder ) {
  6066. this.setupVarying( builder );
  6067. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6068. }
  6069. analyze( builder ) {
  6070. this.setupVarying( builder );
  6071. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  6072. }
  6073. generate( builder ) {
  6074. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  6075. const properties = builder.getNodeProperties( this );
  6076. const varying = this.setupVarying( builder );
  6077. if ( properties[ propertyKey ] === undefined ) {
  6078. const type = this.getNodeType( builder );
  6079. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  6080. // force node run in vertex stage
  6081. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  6082. properties[ propertyKey ] = propertyName;
  6083. }
  6084. return builder.getPropertyName( varying );
  6085. }
  6086. }
  6087. /**
  6088. * TSL function for creating a varying node.
  6089. *
  6090. * @tsl
  6091. * @function
  6092. * @param {Node} node - The node for which a varying should be created.
  6093. * @param {?string} name - The name of the varying in the shader.
  6094. * @returns {VaryingNode}
  6095. */
  6096. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  6097. /**
  6098. * Computes a node in the vertex stage.
  6099. *
  6100. * @tsl
  6101. * @function
  6102. * @param {Node} node - The node which should be executed in the vertex stage.
  6103. * @returns {VaryingNode}
  6104. */
  6105. const vertexStage = ( node ) => varying( node );
  6106. addMethodChaining( 'toVarying', varying );
  6107. addMethodChaining( 'toVertexStage', vertexStage );
  6108. /**
  6109. * Converts the given color value from sRGB to linear-sRGB color space.
  6110. *
  6111. * @tsl
  6112. * @function
  6113. * @param {Node<vec3>} color - The sRGB color.
  6114. * @return {Node<vec3>} The linear-sRGB color.
  6115. */
  6116. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6117. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  6118. const b = color.mul( 0.0773993808 );
  6119. const factor = color.lessThanEqual( 0.04045 );
  6120. const rgbResult = mix( a, b, factor );
  6121. return rgbResult;
  6122. } ).setLayout( {
  6123. name: 'sRGBTransferEOTF',
  6124. type: 'vec3',
  6125. inputs: [
  6126. { name: 'color', type: 'vec3' }
  6127. ]
  6128. } );
  6129. /**
  6130. * Converts the given color value from linear-sRGB to sRGB color space.
  6131. *
  6132. * @tsl
  6133. * @function
  6134. * @param {Node<vec3>} color - The linear-sRGB color.
  6135. * @return {Node<vec3>} The sRGB color.
  6136. */
  6137. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6138. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6139. const b = color.mul( 12.92 );
  6140. const factor = color.lessThanEqual( 0.0031308 );
  6141. const rgbResult = mix( a, b, factor );
  6142. return rgbResult;
  6143. } ).setLayout( {
  6144. name: 'sRGBTransferOETF',
  6145. type: 'vec3',
  6146. inputs: [
  6147. { name: 'color', type: 'vec3' }
  6148. ]
  6149. } );
  6150. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6151. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6152. /**
  6153. * This node represents a color space conversion. Meaning it converts
  6154. * a color value from a source to a target color space.
  6155. *
  6156. * @augments TempNode
  6157. */
  6158. class ColorSpaceNode extends TempNode {
  6159. static get type() {
  6160. return 'ColorSpaceNode';
  6161. }
  6162. /**
  6163. * Constructs a new color space node.
  6164. *
  6165. * @param {Node} colorNode - Represents the color to convert.
  6166. * @param {string} source - The source color space.
  6167. * @param {string} target - The target color space.
  6168. */
  6169. constructor( colorNode, source, target ) {
  6170. super( 'vec4' );
  6171. /**
  6172. * Represents the color to convert.
  6173. *
  6174. * @type {Node}
  6175. */
  6176. this.colorNode = colorNode;
  6177. /**
  6178. * The source color space.
  6179. *
  6180. * @type {string}
  6181. */
  6182. this.source = source;
  6183. /**
  6184. * The target color space.
  6185. *
  6186. * @type {string}
  6187. */
  6188. this.target = target;
  6189. }
  6190. /**
  6191. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6192. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6193. * color management and renderer.
  6194. *
  6195. * @param {NodeBuilder} builder - The current node builder.
  6196. * @param {string} colorSpace - The color space to resolve.
  6197. * @return {string} The resolved color space.
  6198. */
  6199. resolveColorSpace( builder, colorSpace ) {
  6200. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6201. return ColorManagement.workingColorSpace;
  6202. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6203. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6204. }
  6205. return colorSpace;
  6206. }
  6207. setup( builder ) {
  6208. const { colorNode } = this;
  6209. const source = this.resolveColorSpace( builder, this.source );
  6210. const target = this.resolveColorSpace( builder, this.target );
  6211. let outputNode = colorNode;
  6212. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6213. return outputNode;
  6214. }
  6215. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6216. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6217. }
  6218. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6219. outputNode = vec4(
  6220. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6221. outputNode.a
  6222. );
  6223. }
  6224. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6225. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6226. }
  6227. return outputNode;
  6228. }
  6229. }
  6230. /**
  6231. * TSL function for converting a given color node from the current working color space to the given color space.
  6232. *
  6233. * @tsl
  6234. * @function
  6235. * @param {Node} node - Represents the node to convert.
  6236. * @param {string} targetColorSpace - The target color space.
  6237. * @returns {ColorSpaceNode}
  6238. */
  6239. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6240. /**
  6241. * TSL function for converting a given color node from the given color space to the current working color space.
  6242. *
  6243. * @tsl
  6244. * @function
  6245. * @param {Node} node - Represents the node to convert.
  6246. * @param {string} sourceColorSpace - The source color space.
  6247. * @returns {ColorSpaceNode}
  6248. */
  6249. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6250. /**
  6251. * TSL function for converting a given color node from one color space to another one.
  6252. *
  6253. * @tsl
  6254. * @function
  6255. * @param {Node} node - Represents the node to convert.
  6256. * @param {string} sourceColorSpace - The source color space.
  6257. * @param {string} targetColorSpace - The target color space.
  6258. * @returns {ColorSpaceNode}
  6259. */
  6260. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6261. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6262. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6263. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  6264. /**
  6265. * This class is only relevant if the referenced property is array-like.
  6266. * In this case, `ReferenceElementNode` allows to refer to a specific
  6267. * element inside the data structure via an index.
  6268. *
  6269. * @augments ArrayElementNode
  6270. */
  6271. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6272. static get type() {
  6273. return 'ReferenceElementNode';
  6274. }
  6275. /**
  6276. * Constructs a new reference element node.
  6277. *
  6278. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6279. * @param {Node} indexNode - The index node that defines the element access.
  6280. */
  6281. constructor( referenceNode, indexNode ) {
  6282. super( referenceNode, indexNode );
  6283. /**
  6284. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6285. * property references to the current node.
  6286. *
  6287. * @type {?ReferenceBaseNode}
  6288. * @default null
  6289. */
  6290. this.referenceNode = referenceNode;
  6291. /**
  6292. * This flag can be used for type testing.
  6293. *
  6294. * @type {boolean}
  6295. * @readonly
  6296. * @default true
  6297. */
  6298. this.isReferenceElementNode = true;
  6299. }
  6300. /**
  6301. * This method is overwritten since the node type is inferred from
  6302. * the uniform type of the reference node.
  6303. *
  6304. * @return {string} The node type.
  6305. */
  6306. getNodeType() {
  6307. return this.referenceNode.uniformType;
  6308. }
  6309. generate( builder ) {
  6310. const snippet = super.generate( builder );
  6311. const arrayType = this.referenceNode.getNodeType();
  6312. const elementType = this.getNodeType();
  6313. return builder.format( snippet, arrayType, elementType );
  6314. }
  6315. };
  6316. /**
  6317. * Base class for nodes which establishes a reference to a property of another object.
  6318. * In this way, the value of the node is automatically linked to the value of
  6319. * referenced object. Reference nodes internally represent the linked value
  6320. * as a uniform.
  6321. *
  6322. * @augments Node
  6323. */
  6324. class ReferenceBaseNode extends Node {
  6325. static get type() {
  6326. return 'ReferenceBaseNode';
  6327. }
  6328. /**
  6329. * Constructs a new reference base node.
  6330. *
  6331. * @param {string} property - The name of the property the node refers to.
  6332. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6333. * @param {?Object} [object=null] - The object the property belongs to.
  6334. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6335. */
  6336. constructor( property, uniformType, object = null, count = null ) {
  6337. super();
  6338. /**
  6339. * The name of the property the node refers to.
  6340. *
  6341. * @type {string}
  6342. */
  6343. this.property = property;
  6344. /**
  6345. * The uniform type that should be used to represent the property value.
  6346. *
  6347. * @type {string}
  6348. */
  6349. this.uniformType = uniformType;
  6350. /**
  6351. * The object the property belongs to.
  6352. *
  6353. * @type {?Object}
  6354. * @default null
  6355. */
  6356. this.object = object;
  6357. /**
  6358. * When the linked property is an array, this parameter defines its length.
  6359. *
  6360. * @type {?number}
  6361. * @default null
  6362. */
  6363. this.count = count;
  6364. /**
  6365. * The property name might have dots so nested properties can be referred.
  6366. * The hierarchy of the names is stored inside this array.
  6367. *
  6368. * @type {Array<string>}
  6369. */
  6370. this.properties = property.split( '.' );
  6371. /**
  6372. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6373. * since the final reference might be updated from calling code.
  6374. *
  6375. * @type {?Object}
  6376. * @default null
  6377. */
  6378. this.reference = object;
  6379. /**
  6380. * The uniform node that holds the value of the reference node.
  6381. *
  6382. * @type {UniformNode}
  6383. * @default null
  6384. */
  6385. this.node = null;
  6386. /**
  6387. * The uniform group of the internal uniform.
  6388. *
  6389. * @type {UniformGroupNode}
  6390. * @default null
  6391. */
  6392. this.group = null;
  6393. /**
  6394. * Overwritten since reference nodes are updated per object.
  6395. *
  6396. * @type {string}
  6397. * @default 'object'
  6398. */
  6399. this.updateType = NodeUpdateType.OBJECT;
  6400. }
  6401. /**
  6402. * Sets the uniform group for this reference node.
  6403. *
  6404. * @param {UniformGroupNode} group - The uniform group to set.
  6405. * @return {ReferenceBaseNode} A reference to this node.
  6406. */
  6407. setGroup( group ) {
  6408. this.group = group;
  6409. return this;
  6410. }
  6411. /**
  6412. * When the referred property is array-like, this method can be used
  6413. * to access elements via an index node.
  6414. *
  6415. * @param {IndexNode} indexNode - indexNode.
  6416. * @return {ReferenceElementNode} A reference to an element.
  6417. */
  6418. element( indexNode ) {
  6419. return new ReferenceElementNode$1( this, nodeObject( indexNode ) );
  6420. }
  6421. /**
  6422. * Sets the node type which automatically defines the internal
  6423. * uniform type.
  6424. *
  6425. * @param {string} uniformType - The type to set.
  6426. */
  6427. setNodeType( uniformType ) {
  6428. const node = uniform( null, uniformType );
  6429. if ( this.group !== null ) {
  6430. node.setGroup( this.group );
  6431. }
  6432. this.node = node;
  6433. }
  6434. /**
  6435. * This method is overwritten since the node type is inferred from
  6436. * the type of the reference node.
  6437. *
  6438. * @param {NodeBuilder} builder - The current node builder.
  6439. * @return {string} The node type.
  6440. */
  6441. getNodeType( builder ) {
  6442. if ( this.node === null ) {
  6443. this.updateReference( builder );
  6444. this.updateValue();
  6445. }
  6446. return this.node.getNodeType( builder );
  6447. }
  6448. /**
  6449. * Returns the property value from the given referred object.
  6450. *
  6451. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6452. * @return {any} The value.
  6453. */
  6454. getValueFromReference( object = this.reference ) {
  6455. const { properties } = this;
  6456. let value = object[ properties[ 0 ] ];
  6457. for ( let i = 1; i < properties.length; i ++ ) {
  6458. value = value[ properties[ i ] ];
  6459. }
  6460. return value;
  6461. }
  6462. /**
  6463. * Allows to update the reference based on the given state. The state is only
  6464. * evaluated {@link ReferenceBaseNode#object} is not set.
  6465. *
  6466. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6467. * @return {Object} The updated reference.
  6468. */
  6469. updateReference( state ) {
  6470. this.reference = this.object !== null ? this.object : state.object;
  6471. return this.reference;
  6472. }
  6473. /**
  6474. * The output of the reference node is the internal uniform node.
  6475. *
  6476. * @return {UniformNode} The output node.
  6477. */
  6478. setup() {
  6479. this.updateValue();
  6480. return this.node;
  6481. }
  6482. /**
  6483. * Overwritten to update the internal uniform value.
  6484. *
  6485. * @param {NodeFrame} frame - A reference to the current node frame.
  6486. */
  6487. update( /*frame*/ ) {
  6488. this.updateValue();
  6489. }
  6490. /**
  6491. * Retrieves the value from the referred object property and uses it
  6492. * to updated the internal uniform.
  6493. */
  6494. updateValue() {
  6495. if ( this.node === null ) this.setNodeType( this.uniformType );
  6496. const value = this.getValueFromReference();
  6497. if ( Array.isArray( value ) ) {
  6498. this.node.array = value;
  6499. } else {
  6500. this.node.value = value;
  6501. }
  6502. }
  6503. }
  6504. /**
  6505. * TSL function for creating a reference base node.
  6506. *
  6507. * @tsl
  6508. * @function
  6509. * @param {string} name - The name of the property the node refers to.
  6510. * @param {string} type - The uniform type that should be used to represent the property value.
  6511. * @param {Object} object - The object the property belongs to.
  6512. * @returns {ReferenceBaseNode}
  6513. */
  6514. const reference$1 = ( name, type, object ) => new ReferenceBaseNode( name, type, object );
  6515. /**
  6516. * This node is a special type of reference node which is intended
  6517. * for linking renderer properties with node values.
  6518. * ```js
  6519. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6520. * ```
  6521. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6522. * automatically be updated.
  6523. *
  6524. * @augments ReferenceBaseNode
  6525. */
  6526. class RendererReferenceNode extends ReferenceBaseNode {
  6527. static get type() {
  6528. return 'RendererReferenceNode';
  6529. }
  6530. /**
  6531. * Constructs a new renderer reference node.
  6532. *
  6533. * @param {string} property - The name of the property the node refers to.
  6534. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6535. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6536. * the node refers to the renderer of the current state.
  6537. */
  6538. constructor( property, inputType, renderer = null ) {
  6539. super( property, inputType, renderer );
  6540. /**
  6541. * The renderer the property belongs to. When no renderer is set,
  6542. * the node refers to the renderer of the current state.
  6543. *
  6544. * @type {?Renderer}
  6545. * @default null
  6546. */
  6547. this.renderer = renderer;
  6548. this.setGroup( renderGroup );
  6549. }
  6550. /**
  6551. * Updates the reference based on the given state. The state is only evaluated
  6552. * {@link RendererReferenceNode#renderer} is not set.
  6553. *
  6554. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6555. * @return {Object} The updated reference.
  6556. */
  6557. updateReference( state ) {
  6558. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6559. return this.reference;
  6560. }
  6561. }
  6562. /**
  6563. * TSL function for creating a renderer reference node.
  6564. *
  6565. * @tsl
  6566. * @function
  6567. * @param {string} name - The name of the property the node refers to.
  6568. * @param {string} type - The uniform type that should be used to represent the property value.
  6569. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6570. * the node refers to the renderer of the current state.
  6571. * @returns {RendererReferenceNode}
  6572. */
  6573. const rendererReference = ( name, type, renderer = null ) => new RendererReferenceNode( name, type, renderer );
  6574. /**
  6575. * This node represents a tone mapping operation.
  6576. *
  6577. * @augments TempNode
  6578. */
  6579. class ToneMappingNode extends TempNode {
  6580. static get type() {
  6581. return 'ToneMappingNode';
  6582. }
  6583. /**
  6584. * Constructs a new tone mapping node.
  6585. *
  6586. * @param {number} toneMapping - The tone mapping type.
  6587. * @param {Node} exposureNode - The tone mapping exposure.
  6588. * @param {Node} [colorNode=null] - The color node to process.
  6589. */
  6590. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6591. super( 'vec3' );
  6592. /**
  6593. * The tone mapping type.
  6594. *
  6595. * @private
  6596. * @type {number}
  6597. */
  6598. this._toneMapping = toneMapping;
  6599. /**
  6600. * The tone mapping exposure.
  6601. *
  6602. * @type {Node}
  6603. * @default null
  6604. */
  6605. this.exposureNode = exposureNode;
  6606. /**
  6607. * Represents the color to process.
  6608. *
  6609. * @type {?Node}
  6610. * @default null
  6611. */
  6612. this.colorNode = colorNode;
  6613. }
  6614. /**
  6615. * Overwrites the default `customCacheKey()` implementation by including the tone
  6616. * mapping type into the cache key.
  6617. *
  6618. * @return {number} The hash.
  6619. */
  6620. customCacheKey() {
  6621. return hash$1( this._toneMapping );
  6622. }
  6623. /**
  6624. * Sets the tone mapping type.
  6625. *
  6626. * @param {number} value - The tone mapping type.
  6627. * @return {ToneMappingNode} A reference to this node.
  6628. */
  6629. setToneMapping( value ) {
  6630. this._toneMapping = value;
  6631. return this;
  6632. }
  6633. /**
  6634. * Gets the tone mapping type.
  6635. *
  6636. * @returns {number} The tone mapping type.
  6637. */
  6638. getToneMapping() {
  6639. return this._toneMapping;
  6640. }
  6641. setup( builder ) {
  6642. const colorNode = this.colorNode || builder.context.color;
  6643. const toneMapping = this._toneMapping;
  6644. if ( toneMapping === NoToneMapping ) return colorNode;
  6645. let outputNode = null;
  6646. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6647. if ( toneMappingFn !== null ) {
  6648. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6649. } else {
  6650. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6651. outputNode = colorNode;
  6652. }
  6653. return outputNode;
  6654. }
  6655. }
  6656. /**
  6657. * TSL function for creating a tone mapping node.
  6658. *
  6659. * @tsl
  6660. * @function
  6661. * @param {number} mapping - The tone mapping type.
  6662. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6663. * @param {Node<vec3> | Color} color - The color node to process.
  6664. * @returns {ToneMappingNode<vec3>}
  6665. */
  6666. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6667. /**
  6668. * TSL object that represents the global tone mapping exposure of the renderer.
  6669. *
  6670. * @tsl
  6671. * @type {RendererReferenceNode<vec3>}
  6672. */
  6673. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6674. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6675. /**
  6676. * Internal buffer attribute library.
  6677. *
  6678. * @private
  6679. * @type {WeakMap<TypedArray, InterleavedBuffer>}
  6680. */
  6681. const _bufferLib = new WeakMap();
  6682. /**
  6683. * Internal method for retrieving or creating interleaved buffers.
  6684. *
  6685. * @private
  6686. * @param {TypedArray} value - The attribute data.
  6687. * @param {number} itemSize - The attribute item size.
  6688. * @returns {InterleavedBuffer} The interleaved buffer.
  6689. */
  6690. function _getBufferAttribute( value, itemSize ) {
  6691. let buffer = _bufferLib.get( value );
  6692. if ( buffer === undefined ) {
  6693. buffer = new InterleavedBuffer( value, itemSize );
  6694. _bufferLib.set( value, buffer );
  6695. }
  6696. return buffer;
  6697. }
  6698. /**
  6699. * In earlier `three.js` versions it was only possible to define attribute data
  6700. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6701. * on the node level.
  6702. * ```js
  6703. * const geometry = new THREE.PlaneGeometry();
  6704. * const positionAttribute = geometry.getAttribute( 'position' );
  6705. *
  6706. * const colors = [];
  6707. * for ( let i = 0; i < position.count; i ++ ) {
  6708. * colors.push( 1, 0, 0 );
  6709. * }
  6710. *
  6711. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6712. * ```
  6713. * This new approach is especially interesting when geometry data are generated via
  6714. * compute shaders. The below line converts a storage buffer into an attribute node.
  6715. * ```js
  6716. * material.positionNode = positionBuffer.toAttribute();
  6717. * ```
  6718. * @augments InputNode
  6719. */
  6720. class BufferAttributeNode extends InputNode {
  6721. static get type() {
  6722. return 'BufferAttributeNode';
  6723. }
  6724. /**
  6725. * Constructs a new buffer attribute node.
  6726. *
  6727. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6728. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6729. * @param {number} [bufferStride=0] - The buffer stride.
  6730. * @param {number} [bufferOffset=0] - The buffer offset.
  6731. */
  6732. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6733. super( value, bufferType );
  6734. /**
  6735. * This flag can be used for type testing.
  6736. *
  6737. * @type {boolean}
  6738. * @readonly
  6739. * @default true
  6740. */
  6741. this.isBufferNode = true;
  6742. /**
  6743. * The buffer type (e.g. `'vec3'`).
  6744. *
  6745. * @type {?string}
  6746. * @default null
  6747. */
  6748. this.bufferType = bufferType;
  6749. /**
  6750. * The buffer stride.
  6751. *
  6752. * @type {number}
  6753. * @default 0
  6754. */
  6755. this.bufferStride = bufferStride;
  6756. /**
  6757. * The buffer offset.
  6758. *
  6759. * @type {number}
  6760. * @default 0
  6761. */
  6762. this.bufferOffset = bufferOffset;
  6763. /**
  6764. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6765. * if you are planning to update the attribute data per frame.
  6766. *
  6767. * @type {number}
  6768. * @default StaticDrawUsage
  6769. */
  6770. this.usage = StaticDrawUsage;
  6771. /**
  6772. * Whether the attribute is instanced or not.
  6773. *
  6774. * @type {boolean}
  6775. * @default false
  6776. */
  6777. this.instanced = false;
  6778. /**
  6779. * A reference to the buffer attribute.
  6780. *
  6781. * @type {?BufferAttribute}
  6782. * @default null
  6783. */
  6784. this.attribute = null;
  6785. /**
  6786. * `BufferAttributeNode` sets this property to `true` by default.
  6787. *
  6788. * @type {boolean}
  6789. * @default true
  6790. */
  6791. this.global = true;
  6792. if ( value && value.isBufferAttribute === true && value.itemSize <= 4 ) {
  6793. this.attribute = value;
  6794. this.usage = value.usage;
  6795. this.instanced = value.isInstancedBufferAttribute;
  6796. }
  6797. }
  6798. /**
  6799. * This method is overwritten since the attribute data might be shared
  6800. * and thus the hash should be shared as well.
  6801. *
  6802. * @param {NodeBuilder} builder - The current node builder.
  6803. * @return {string} The hash.
  6804. */
  6805. getHash( builder ) {
  6806. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6807. let bufferData = builder.globalCache.getData( this.value );
  6808. if ( bufferData === undefined ) {
  6809. bufferData = {
  6810. node: this
  6811. };
  6812. builder.globalCache.setData( this.value, bufferData );
  6813. }
  6814. return bufferData.node.uuid;
  6815. }
  6816. return this.uuid;
  6817. }
  6818. /**
  6819. * This method is overwritten since the node type is inferred from
  6820. * the buffer attribute.
  6821. *
  6822. * @param {NodeBuilder} builder - The current node builder.
  6823. * @return {string} The node type.
  6824. */
  6825. getNodeType( builder ) {
  6826. if ( this.bufferType === null ) {
  6827. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6828. }
  6829. return this.bufferType;
  6830. }
  6831. /**
  6832. * Depending on which value was passed to the node, `setup()` behaves
  6833. * differently. If no instance of `BufferAttribute` was passed, the method
  6834. * creates an internal attribute and configures it respectively.
  6835. *
  6836. * @param {NodeBuilder} builder - The current node builder.
  6837. */
  6838. setup( builder ) {
  6839. if ( this.attribute !== null ) return;
  6840. //
  6841. const type = this.getNodeType( builder );
  6842. const itemSize = builder.getTypeLength( type );
  6843. const value = this.value;
  6844. const stride = this.bufferStride || itemSize;
  6845. const offset = this.bufferOffset;
  6846. let buffer;
  6847. if ( value.isInterleavedBuffer === true ) {
  6848. buffer = value;
  6849. } else if ( value.isBufferAttribute === true ) {
  6850. buffer = _getBufferAttribute( value.array, stride );
  6851. } else {
  6852. buffer = _getBufferAttribute( value, stride );
  6853. }
  6854. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6855. buffer.setUsage( this.usage );
  6856. this.attribute = bufferAttribute;
  6857. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6858. }
  6859. /**
  6860. * Generates the code snippet of the buffer attribute node.
  6861. *
  6862. * @param {NodeBuilder} builder - The current node builder.
  6863. * @return {string} The generated code snippet.
  6864. */
  6865. generate( builder ) {
  6866. const nodeType = this.getNodeType( builder );
  6867. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6868. const propertyName = builder.getPropertyName( nodeAttribute );
  6869. let output = null;
  6870. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6871. this.name = propertyName;
  6872. output = propertyName;
  6873. } else {
  6874. const nodeVarying = varying( this );
  6875. output = nodeVarying.build( builder, nodeType );
  6876. }
  6877. return output;
  6878. }
  6879. /**
  6880. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6881. *
  6882. * @param {NodeBuilder} builder - The current node builder.
  6883. * @return {string} The input type.
  6884. */
  6885. getInputType( /*builder*/ ) {
  6886. return 'bufferAttribute';
  6887. }
  6888. /**
  6889. * Sets the `usage` property to the given value.
  6890. *
  6891. * @param {number} value - The usage to set.
  6892. * @return {BufferAttributeNode} A reference to this node.
  6893. */
  6894. setUsage( value ) {
  6895. this.usage = value;
  6896. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6897. this.attribute.usage = value;
  6898. }
  6899. return this;
  6900. }
  6901. /**
  6902. * Sets the `instanced` property to the given value.
  6903. *
  6904. * @param {boolean} value - The value to set.
  6905. * @return {BufferAttributeNode} A reference to this node.
  6906. */
  6907. setInstanced( value ) {
  6908. this.instanced = value;
  6909. return this;
  6910. }
  6911. }
  6912. /**
  6913. * Internal method for creating buffer attribute nodes.
  6914. *
  6915. * @private
  6916. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6917. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6918. * @param {number} [stride=0] - The buffer stride.
  6919. * @param {number} [offset=0] - The buffer offset.
  6920. * @param {number} [usage=StaticDrawUsage] - The buffer usage.
  6921. * @param {boolean} [instanced=false] - Whether the buffer is instanced.
  6922. * @returns {BufferAttributeNode|Node} The buffer attribute node.
  6923. */
  6924. function createBufferAttribute( array, type = null, stride = 0, offset = 0, usage = StaticDrawUsage, instanced = false ) {
  6925. if ( type === 'mat3' || ( type === null && array.itemSize === 9 ) ) {
  6926. return mat3(
  6927. new BufferAttributeNode( array, 'vec3', 9, 0 ).setUsage( usage ).setInstanced( instanced ),
  6928. new BufferAttributeNode( array, 'vec3', 9, 3 ).setUsage( usage ).setInstanced( instanced ),
  6929. new BufferAttributeNode( array, 'vec3', 9, 6 ).setUsage( usage ).setInstanced( instanced )
  6930. );
  6931. } else if ( type === 'mat4' || ( type === null && array.itemSize === 16 ) ) {
  6932. return mat4(
  6933. new BufferAttributeNode( array, 'vec4', 16, 0 ).setUsage( usage ).setInstanced( instanced ),
  6934. new BufferAttributeNode( array, 'vec4', 16, 4 ).setUsage( usage ).setInstanced( instanced ),
  6935. new BufferAttributeNode( array, 'vec4', 16, 8 ).setUsage( usage ).setInstanced( instanced ),
  6936. new BufferAttributeNode( array, 'vec4', 16, 12 ).setUsage( usage ).setInstanced( instanced )
  6937. );
  6938. }
  6939. return new BufferAttributeNode( array, type, stride, offset ).setUsage( usage );
  6940. }
  6941. /**
  6942. * TSL function for creating a buffer attribute node.
  6943. *
  6944. * @tsl
  6945. * @function
  6946. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6947. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6948. * @param {number} [stride=0] - The buffer stride.
  6949. * @param {number} [offset=0] - The buffer offset.
  6950. * @returns {BufferAttributeNode|Node}
  6951. */
  6952. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset );
  6953. /**
  6954. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6955. * Use this function if attribute data are updated per frame.
  6956. *
  6957. * @tsl
  6958. * @function
  6959. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6960. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6961. * @param {number} [stride=0] - The buffer stride.
  6962. * @param {number} [offset=0] - The buffer offset.
  6963. * @returns {BufferAttributeNode|Node}
  6964. */
  6965. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage );
  6966. /**
  6967. * TSL function for creating a buffer attribute node but with enabled instancing
  6968. *
  6969. * @tsl
  6970. * @function
  6971. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6972. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6973. * @param {number} [stride=0] - The buffer stride.
  6974. * @param {number} [offset=0] - The buffer offset.
  6975. * @returns {BufferAttributeNode|Node}
  6976. */
  6977. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, StaticDrawUsage, true );
  6978. /**
  6979. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6980. *
  6981. * @tsl
  6982. * @function
  6983. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6984. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6985. * @param {number} [stride=0] - The buffer stride.
  6986. * @param {number} [offset=0] - The buffer offset.
  6987. * @returns {BufferAttributeNode|Node}
  6988. */
  6989. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => createBufferAttribute( array, type, stride, offset, DynamicDrawUsage, true );
  6990. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6991. /**
  6992. * TODO
  6993. *
  6994. * @augments Node
  6995. */
  6996. class ComputeNode extends Node {
  6997. static get type() {
  6998. return 'ComputeNode';
  6999. }
  7000. /**
  7001. * Constructs a new compute node.
  7002. *
  7003. * @param {Node} computeNode - TODO
  7004. * @param {Array<number>} workgroupSize - TODO.
  7005. */
  7006. constructor( computeNode, workgroupSize ) {
  7007. super( 'void' );
  7008. /**
  7009. * This flag can be used for type testing.
  7010. *
  7011. * @type {boolean}
  7012. * @readonly
  7013. * @default true
  7014. */
  7015. this.isComputeNode = true;
  7016. /**
  7017. * TODO
  7018. *
  7019. * @type {Node}
  7020. */
  7021. this.computeNode = computeNode;
  7022. /**
  7023. * TODO
  7024. *
  7025. * @type {Array<number>}
  7026. * @default [ 64 ]
  7027. */
  7028. this.workgroupSize = workgroupSize;
  7029. /**
  7030. * TODO
  7031. *
  7032. * @type {number|Array<number>}
  7033. */
  7034. this.count = null;
  7035. /**
  7036. * TODO
  7037. *
  7038. * @type {number}
  7039. */
  7040. this.version = 1;
  7041. /**
  7042. * The name or label of the uniform.
  7043. *
  7044. * @type {string}
  7045. * @default ''
  7046. */
  7047. this.name = '';
  7048. /**
  7049. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  7050. * is executed once per object by default.
  7051. *
  7052. * @type {string}
  7053. * @default 'object'
  7054. */
  7055. this.updateBeforeType = NodeUpdateType.OBJECT;
  7056. /**
  7057. * TODO
  7058. *
  7059. * @type {?Function}
  7060. */
  7061. this.onInitFunction = null;
  7062. }
  7063. /**
  7064. * TODO
  7065. *
  7066. * @param {number|Array<number>} count - Array with [ x, y, z ] values for dispatch or a single number for the count
  7067. * @return {ComputeNode}
  7068. */
  7069. setCount( count ) {
  7070. this.count = count;
  7071. return this;
  7072. }
  7073. /**
  7074. * TODO
  7075. *
  7076. * @return {number|Array<number>}
  7077. */
  7078. getCount() {
  7079. return this.count;
  7080. }
  7081. /**
  7082. * Executes the `dispose` event for this node.
  7083. */
  7084. dispose() {
  7085. this.dispatchEvent( { type: 'dispose' } );
  7086. }
  7087. /**
  7088. * Sets the {@link ComputeNode#name} property.
  7089. *
  7090. * @param {string} name - The name of the uniform.
  7091. * @return {ComputeNode} A reference to this node.
  7092. */
  7093. setName( name ) {
  7094. this.name = name;
  7095. return this;
  7096. }
  7097. /**
  7098. * Sets the {@link ComputeNode#name} property.
  7099. *
  7100. * @deprecated
  7101. * @param {string} name - The name of the uniform.
  7102. * @return {ComputeNode} A reference to this node.
  7103. */
  7104. label( name ) {
  7105. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  7106. return this.setName( name );
  7107. }
  7108. /**
  7109. * TODO
  7110. *
  7111. * @param {Function} callback - TODO.
  7112. * @return {ComputeNode} A reference to this node.
  7113. */
  7114. onInit( callback ) {
  7115. this.onInitFunction = callback;
  7116. return this;
  7117. }
  7118. /**
  7119. * The method execute the compute for this node.
  7120. *
  7121. * @param {NodeFrame} frame - A reference to the current node frame.
  7122. */
  7123. updateBefore( { renderer } ) {
  7124. renderer.compute( this );
  7125. }
  7126. setup( builder ) {
  7127. const result = this.computeNode.build( builder );
  7128. if ( result ) {
  7129. const properties = builder.getNodeProperties( this );
  7130. properties.outputComputeNode = result.outputNode;
  7131. result.outputNode = null;
  7132. }
  7133. return result;
  7134. }
  7135. generate( builder, output ) {
  7136. const { shaderStage } = builder;
  7137. if ( shaderStage === 'compute' ) {
  7138. const snippet = this.computeNode.build( builder, 'void' );
  7139. if ( snippet !== '' ) {
  7140. builder.addLineFlowCode( snippet, this );
  7141. }
  7142. } else {
  7143. const properties = builder.getNodeProperties( this );
  7144. const outputComputeNode = properties.outputComputeNode;
  7145. if ( outputComputeNode ) {
  7146. return outputComputeNode.build( builder, output );
  7147. }
  7148. }
  7149. }
  7150. }
  7151. /**
  7152. * TSL function for creating a compute kernel node.
  7153. *
  7154. * @tsl
  7155. * @function
  7156. * @param {Node} node - TODO
  7157. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7158. * @returns {AtomicFunctionNode}
  7159. */
  7160. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  7161. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  7162. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  7163. }
  7164. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  7165. const val = workgroupSize[ i ];
  7166. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  7167. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  7168. }
  7169. }
  7170. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  7171. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  7172. //
  7173. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  7174. };
  7175. /**
  7176. * TSL function for creating a compute node.
  7177. *
  7178. * @tsl
  7179. * @function
  7180. * @param {Node} node - TODO
  7181. * @param {number|Array<number>} count - TODO.
  7182. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  7183. * @returns {AtomicFunctionNode}
  7184. */
  7185. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  7186. addMethodChaining( 'compute', compute );
  7187. addMethodChaining( 'computeKernel', computeKernel );
  7188. /**
  7189. * This node can be used as a cache management component for another node.
  7190. * Caching is in general used by default in {@link NodeBuilder} but this node
  7191. * allows the usage of a shared parent cache during the build process.
  7192. *
  7193. * @augments Node
  7194. */
  7195. class IsolateNode extends Node {
  7196. static get type() {
  7197. return 'IsolateNode';
  7198. }
  7199. /**
  7200. * Constructs a new cache node.
  7201. *
  7202. * @param {Node} node - The node that should be cached.
  7203. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7204. */
  7205. constructor( node, parent = true ) {
  7206. super();
  7207. /**
  7208. * The node that should be cached.
  7209. *
  7210. * @type {Node}
  7211. */
  7212. this.node = node;
  7213. /**
  7214. * Whether this node refers to a shared parent cache or not.
  7215. *
  7216. * @type {boolean}
  7217. * @default true
  7218. */
  7219. this.parent = parent;
  7220. /**
  7221. * This flag can be used for type testing.
  7222. *
  7223. * @type {boolean}
  7224. * @readonly
  7225. * @default true
  7226. */
  7227. this.isIsolateNode = true;
  7228. }
  7229. getNodeType( builder ) {
  7230. const previousCache = builder.getCache();
  7231. const cache = builder.getCacheFromNode( this, this.parent );
  7232. builder.setCache( cache );
  7233. const nodeType = this.node.getNodeType( builder );
  7234. builder.setCache( previousCache );
  7235. return nodeType;
  7236. }
  7237. build( builder, ...params ) {
  7238. const previousCache = builder.getCache();
  7239. const cache = builder.getCacheFromNode( this, this.parent );
  7240. builder.setCache( cache );
  7241. const data = this.node.build( builder, ...params );
  7242. builder.setCache( previousCache );
  7243. return data;
  7244. }
  7245. setParent( parent ) {
  7246. this.parent = parent;
  7247. return this;
  7248. }
  7249. getParent() {
  7250. return this.parent;
  7251. }
  7252. }
  7253. /**
  7254. * TSL function for creating a cache node.
  7255. *
  7256. * @tsl
  7257. * @function
  7258. * @param {Node} node - The node that should be cached.
  7259. * @returns {IsolateNode}
  7260. */
  7261. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7262. /**
  7263. * TSL function for creating a cache node.
  7264. *
  7265. * @tsl
  7266. * @function
  7267. * @deprecated
  7268. * @param {Node} node - The node that should be cached.
  7269. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7270. * @returns {IsolateNode}
  7271. */
  7272. function cache( node, parent = true ) {
  7273. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7274. return isolate( node ).setParent( parent );
  7275. }
  7276. addMethodChaining( 'cache', cache );
  7277. addMethodChaining( 'isolate', isolate );
  7278. /**
  7279. * The class generates the code of a given node but returns another node in the output.
  7280. * This can be used to call a method or node that does not return a value, i.e.
  7281. * type `void` on an input where returning a value is required. Example:
  7282. *
  7283. * ```js
  7284. * material.colorNode = myColor.bypass( runVoidFn() )
  7285. *```
  7286. *
  7287. * @augments Node
  7288. */
  7289. class BypassNode extends Node {
  7290. static get type() {
  7291. return 'BypassNode';
  7292. }
  7293. /**
  7294. * Constructs a new bypass node.
  7295. *
  7296. * @param {Node} outputNode - The output node.
  7297. * @param {Node} callNode - The call node.
  7298. */
  7299. constructor( outputNode, callNode ) {
  7300. super();
  7301. /**
  7302. * This flag can be used for type testing.
  7303. *
  7304. * @type {boolean}
  7305. * @readonly
  7306. * @default true
  7307. */
  7308. this.isBypassNode = true;
  7309. /**
  7310. * The output node.
  7311. *
  7312. * @type {Node}
  7313. */
  7314. this.outputNode = outputNode;
  7315. /**
  7316. * The call node.
  7317. *
  7318. * @type {Node}
  7319. */
  7320. this.callNode = callNode;
  7321. }
  7322. getNodeType( builder ) {
  7323. return this.outputNode.getNodeType( builder );
  7324. }
  7325. generate( builder ) {
  7326. const snippet = this.callNode.build( builder, 'void' );
  7327. if ( snippet !== '' ) {
  7328. builder.addLineFlowCode( snippet, this );
  7329. }
  7330. return this.outputNode.build( builder );
  7331. }
  7332. }
  7333. /**
  7334. * TSL function for creating a bypass node.
  7335. *
  7336. * @tsl
  7337. * @function
  7338. * @param {Node} outputNode - The output node.
  7339. * @param {Node} callNode - The call node.
  7340. * @returns {BypassNode}
  7341. */
  7342. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7343. addMethodChaining( 'bypass', bypass );
  7344. /**
  7345. * This node allows to remap a node value from one range into another. E.g a value of
  7346. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7347. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7348. *
  7349. * @augments Node
  7350. */
  7351. class RemapNode extends Node {
  7352. static get type() {
  7353. return 'RemapNode';
  7354. }
  7355. /**
  7356. * Constructs a new remap node.
  7357. *
  7358. * @param {Node} node - The node that should be remapped.
  7359. * @param {Node} inLowNode - The source or current lower bound of the range.
  7360. * @param {Node} inHighNode - The source or current upper bound of the range.
  7361. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7362. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7363. */
  7364. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7365. super();
  7366. /**
  7367. * The node that should be remapped.
  7368. *
  7369. * @type {Node}
  7370. */
  7371. this.node = node;
  7372. /**
  7373. * The source or current lower bound of the range.
  7374. *
  7375. * @type {Node}
  7376. */
  7377. this.inLowNode = inLowNode;
  7378. /**
  7379. * The source or current upper bound of the range.
  7380. *
  7381. * @type {Node}
  7382. */
  7383. this.inHighNode = inHighNode;
  7384. /**
  7385. * The target lower bound of the range.
  7386. *
  7387. * @type {Node}
  7388. * @default float(0)
  7389. */
  7390. this.outLowNode = outLowNode;
  7391. /**
  7392. * The target upper bound of the range.
  7393. *
  7394. * @type {Node}
  7395. * @default float(1)
  7396. */
  7397. this.outHighNode = outHighNode;
  7398. /**
  7399. * Whether the node value should be clamped before
  7400. * remapping it to the target range.
  7401. *
  7402. * @type {boolean}
  7403. * @default true
  7404. */
  7405. this.doClamp = true;
  7406. }
  7407. setup() {
  7408. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7409. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7410. if ( doClamp === true ) t = t.clamp();
  7411. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7412. }
  7413. }
  7414. /**
  7415. * TSL function for creating a remap node.
  7416. *
  7417. * @tsl
  7418. * @function
  7419. * @param {Node} node - The node that should be remapped.
  7420. * @param {Node} inLowNode - The source or current lower bound of the range.
  7421. * @param {Node} inHighNode - The source or current upper bound of the range.
  7422. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7423. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7424. * @returns {RemapNode}
  7425. */
  7426. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7427. /**
  7428. * TSL function for creating a remap node, but with enabled clamping.
  7429. *
  7430. * @tsl
  7431. * @function
  7432. * @param {Node} node - The node that should be remapped.
  7433. * @param {Node} inLowNode - The source or current lower bound of the range.
  7434. * @param {Node} inHighNode - The source or current upper bound of the range.
  7435. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7436. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7437. * @returns {RemapNode}
  7438. */
  7439. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7440. addMethodChaining( 'remap', remap );
  7441. addMethodChaining( 'remapClamp', remapClamp );
  7442. /**
  7443. * This class can be used to implement basic expressions in shader code.
  7444. * Basic examples for that are `return`, `continue` or `discard` statements.
  7445. *
  7446. * @augments Node
  7447. */
  7448. class ExpressionNode extends Node {
  7449. static get type() {
  7450. return 'ExpressionNode';
  7451. }
  7452. /**
  7453. * Constructs a new expression node.
  7454. *
  7455. * @param {string} [snippet=''] - The native code snippet.
  7456. * @param {string} [nodeType='void'] - The node type.
  7457. */
  7458. constructor( snippet = '', nodeType = 'void' ) {
  7459. super( nodeType );
  7460. /**
  7461. * The native code snippet.
  7462. *
  7463. * @type {string}
  7464. * @default ''
  7465. */
  7466. this.snippet = snippet;
  7467. }
  7468. generate( builder, output ) {
  7469. const type = this.getNodeType( builder );
  7470. const snippet = this.snippet;
  7471. if ( type === 'void' ) {
  7472. builder.addLineFlowCode( snippet, this );
  7473. } else {
  7474. return builder.format( snippet, type, output );
  7475. }
  7476. }
  7477. }
  7478. /**
  7479. * TSL function for creating an expression node.
  7480. *
  7481. * @tsl
  7482. * @function
  7483. * @param {string} [snippet] - The native code snippet.
  7484. * @param {?string} [nodeType='void'] - The node type.
  7485. * @returns {ExpressionNode}
  7486. */
  7487. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7488. /**
  7489. * Represents a `discard` shader operation in TSL.
  7490. *
  7491. * @tsl
  7492. * @function
  7493. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7494. * @return {Node} The `discard` expression.
  7495. */
  7496. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7497. /**
  7498. * Represents a `return` shader operation in TSL.
  7499. *
  7500. * @tsl
  7501. * @function
  7502. * @return {ExpressionNode} The `return` expression.
  7503. */
  7504. const Return = () => expression( 'return' ).toStack();
  7505. addMethodChaining( 'discard', Discard );
  7506. /**
  7507. * Normally, tone mapping and color conversion happens automatically
  7508. * before outputting pixel too the default (screen) framebuffer. In certain
  7509. * post processing setups this happens to late because certain effects
  7510. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7511. * to apply tone mapping and color space conversion at an arbitrary point
  7512. * in the effect chain.
  7513. *
  7514. * When applying tone mapping and color space conversion manually with this node,
  7515. * you have to set {@link RenderPipeline#outputColorTransform} to `false`.
  7516. *
  7517. * ```js
  7518. * const postProcessing = new RenderPipeline( renderer );
  7519. * postProcessing.outputColorTransform = false;
  7520. *
  7521. * const scenePass = pass( scene, camera );
  7522. * const outputPass = renderOutput( scenePass );
  7523. *
  7524. * postProcessing.outputNode = outputPass;
  7525. * ```
  7526. *
  7527. * @augments TempNode
  7528. */
  7529. class RenderOutputNode extends TempNode {
  7530. static get type() {
  7531. return 'RenderOutputNode';
  7532. }
  7533. /**
  7534. * Constructs a new render output node.
  7535. *
  7536. * @param {Node} colorNode - The color node to process.
  7537. * @param {?number} toneMapping - The tone mapping type.
  7538. * @param {?string} outputColorSpace - The output color space.
  7539. */
  7540. constructor( colorNode, toneMapping, outputColorSpace ) {
  7541. super( 'vec4' );
  7542. /**
  7543. * The color node to process.
  7544. *
  7545. * @type {Node}
  7546. */
  7547. this.colorNode = colorNode;
  7548. /**
  7549. * The tone mapping type.
  7550. *
  7551. * @private
  7552. * @type {?number}
  7553. */
  7554. this._toneMapping = toneMapping;
  7555. /**
  7556. * The output color space.
  7557. *
  7558. * @type {?string}
  7559. */
  7560. this.outputColorSpace = outputColorSpace;
  7561. /**
  7562. * This flag can be used for type testing.
  7563. *
  7564. * @type {boolean}
  7565. * @readonly
  7566. * @default true
  7567. */
  7568. this.isRenderOutputNode = true;
  7569. }
  7570. /**
  7571. * Sets the tone mapping type.
  7572. *
  7573. * @param {number} value - The tone mapping type.
  7574. * @return {ToneMappingNode} A reference to this node.
  7575. */
  7576. setToneMapping( value ) {
  7577. this._toneMapping = value;
  7578. return this;
  7579. }
  7580. /**
  7581. * Gets the tone mapping type.
  7582. *
  7583. * @returns {number} The tone mapping type.
  7584. */
  7585. getToneMapping() {
  7586. return this._toneMapping;
  7587. }
  7588. setup( { context } ) {
  7589. let outputNode = this.colorNode || context.color;
  7590. // tone mapping
  7591. const toneMapping = ( this._toneMapping !== null ? this._toneMapping : context.toneMapping ) || NoToneMapping;
  7592. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7593. if ( toneMapping !== NoToneMapping ) {
  7594. outputNode = outputNode.toneMapping( toneMapping );
  7595. }
  7596. // working to output color space
  7597. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7598. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7599. }
  7600. return outputNode;
  7601. }
  7602. }
  7603. /**
  7604. * TSL function for creating a posterize node.
  7605. *
  7606. * @tsl
  7607. * @function
  7608. * @param {Node} color - The color node to process.
  7609. * @param {?number} [toneMapping=null] - The tone mapping type.
  7610. * @param {?string} [outputColorSpace=null] - The output color space.
  7611. * @returns {RenderOutputNode}
  7612. */
  7613. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7614. addMethodChaining( 'renderOutput', renderOutput );
  7615. class DebugNode extends TempNode {
  7616. static get type() {
  7617. return 'DebugNode';
  7618. }
  7619. constructor( node, callback = null ) {
  7620. super();
  7621. this.node = node;
  7622. this.callback = callback;
  7623. }
  7624. getNodeType( builder ) {
  7625. return this.node.getNodeType( builder );
  7626. }
  7627. setup( builder ) {
  7628. return this.node.build( builder );
  7629. }
  7630. analyze( builder ) {
  7631. return this.node.build( builder );
  7632. }
  7633. generate( builder ) {
  7634. const callback = this.callback;
  7635. const snippet = this.node.build( builder );
  7636. if ( callback !== null ) {
  7637. callback( builder, snippet );
  7638. } else {
  7639. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7640. const border = '-'.repeat( title.length );
  7641. let code = '';
  7642. code += '// #' + title + '#\n';
  7643. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7644. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7645. code += '// #' + border + '#\n';
  7646. log$1( code );
  7647. }
  7648. return snippet;
  7649. }
  7650. }
  7651. /**
  7652. * TSL function for creating a debug node.
  7653. *
  7654. * @tsl
  7655. * @function
  7656. * @param {Node} node - The node to debug.
  7657. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7658. * @returns {DebugNode}
  7659. */
  7660. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7661. addMethodChaining( 'debug', debug );
  7662. /**
  7663. * InspectorBase is the base class for all inspectors.
  7664. *
  7665. * @class InspectorBase
  7666. */
  7667. class InspectorBase {
  7668. /**
  7669. * Creates a new InspectorBase.
  7670. */
  7671. constructor() {
  7672. /**
  7673. * The renderer associated with this inspector.
  7674. *
  7675. * @type {WebGLRenderer}
  7676. * @private
  7677. */
  7678. this._renderer = null;
  7679. /**
  7680. * The current frame being processed.
  7681. *
  7682. * @type {Object}
  7683. */
  7684. this.currentFrame = null;
  7685. }
  7686. /**
  7687. * Returns the node frame for the current renderer.
  7688. *
  7689. * @return {Object} The node frame.
  7690. */
  7691. get nodeFrame() {
  7692. return this._renderer._nodes.nodeFrame;
  7693. }
  7694. /**
  7695. * Sets the renderer for this inspector.
  7696. *
  7697. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  7698. * @return {InspectorBase} This inspector instance.
  7699. */
  7700. setRenderer( renderer ) {
  7701. this._renderer = renderer;
  7702. return this;
  7703. }
  7704. /**
  7705. * Returns the renderer associated with this inspector.
  7706. *
  7707. * @return {WebGLRenderer} The associated renderer.
  7708. */
  7709. getRenderer() {
  7710. return this._renderer;
  7711. }
  7712. /**
  7713. * Initializes the inspector.
  7714. */
  7715. init() { }
  7716. /**
  7717. * Called when a frame begins.
  7718. */
  7719. begin() { }
  7720. /**
  7721. * Called when a frame ends.
  7722. */
  7723. finish() { }
  7724. /**
  7725. * Inspects a node.
  7726. *
  7727. * @param {Node} node - The node to inspect.
  7728. */
  7729. inspect( /*node*/ ) { }
  7730. /**
  7731. * When a compute operation is performed.
  7732. *
  7733. * @param {ComputeNode} computeNode - The compute node being executed.
  7734. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  7735. */
  7736. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  7737. /**
  7738. * Called when a compute operation begins.
  7739. *
  7740. * @param {string} uid - A unique identifier for the render context.
  7741. * @param {ComputeNode} computeNode - The compute node being executed.
  7742. */
  7743. beginCompute( /*uid, computeNode*/ ) { }
  7744. /**
  7745. * Called when a compute operation ends.
  7746. *
  7747. * @param {string} uid - A unique identifier for the render context.
  7748. * @param {ComputeNode} computeNode - The compute node being executed.
  7749. */
  7750. finishCompute( /*uid*/ ) { }
  7751. /**
  7752. * Called when a render operation begins.
  7753. *
  7754. * @param {string} uid - A unique identifier for the render context.
  7755. * @param {Scene} scene - The scene being rendered.
  7756. * @param {Camera} camera - The camera being used for rendering.
  7757. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  7758. */
  7759. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  7760. /**
  7761. * Called when an animation loop ends.
  7762. *
  7763. * @param {string} uid - A unique identifier for the render context.
  7764. */
  7765. finishRender( /*uid*/ ) { }
  7766. /**
  7767. * Called when a texture copy operation is performed.
  7768. *
  7769. * @param {Texture} srcTexture - The source texture.
  7770. * @param {Texture} dstTexture - The destination texture.
  7771. */
  7772. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  7773. /**
  7774. * Called when a framebuffer copy operation is performed.
  7775. *
  7776. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  7777. */
  7778. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  7779. }
  7780. /**
  7781. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7782. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7783. *
  7784. * @augments Node
  7785. */
  7786. class InspectorNode extends Node {
  7787. /**
  7788. * Returns the type of the node.
  7789. *
  7790. * @returns {string}
  7791. */
  7792. static get type() {
  7793. return 'InspectorNode';
  7794. }
  7795. /**
  7796. * Creates an InspectorNode.
  7797. *
  7798. * @param {Node} node - The node to inspect.
  7799. * @param {string} [name=''] - Optional name for the inspector node.
  7800. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7801. */
  7802. constructor( node, name = '', callback = null ) {
  7803. super();
  7804. this.node = node;
  7805. this.name = name;
  7806. this.callback = callback;
  7807. this.updateType = NodeUpdateType.FRAME;
  7808. this.isInspectorNode = true;
  7809. }
  7810. /**
  7811. * Returns the name of the inspector node.
  7812. *
  7813. * @returns {string}
  7814. */
  7815. getName() {
  7816. return this.name || this.node.name;
  7817. }
  7818. /**
  7819. * Updates the inspector node, allowing inspection of the wrapped node.
  7820. *
  7821. * @param {NodeFrame} frame - A reference to the current node frame.
  7822. */
  7823. update( frame ) {
  7824. frame.renderer.inspector.inspect( this );
  7825. }
  7826. /**
  7827. * Returns the type of the wrapped node.
  7828. *
  7829. * @param {NodeBuilder} builder - The node builder.
  7830. * @returns {string}
  7831. */
  7832. getNodeType( builder ) {
  7833. return this.node.getNodeType( builder );
  7834. }
  7835. /**
  7836. * Sets up the inspector node.
  7837. *
  7838. * @param {NodeBuilder} builder - The node builder.
  7839. * @returns {Node} The setup node.
  7840. */
  7841. setup( builder ) {
  7842. let node = this.node;
  7843. if ( builder.context.inspector === true && this.callback !== null ) {
  7844. node = this.callback( node );
  7845. }
  7846. if ( builder.renderer.backend.isWebGPUBackend !== true && builder.renderer.inspector.constructor !== InspectorBase ) {
  7847. warnOnce( 'TSL: ".toInspector()" is only available with WebGPU.' );
  7848. }
  7849. return node;
  7850. }
  7851. }
  7852. /**
  7853. * Creates an inspector node to wrap around a given node for inspection purposes.
  7854. *
  7855. * @tsl
  7856. * @param {Node} node - The node to inspect.
  7857. * @param {string} [name=''] - Optional name for the inspector node.
  7858. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7859. * @returns {Node} The inspector node.
  7860. */
  7861. function inspector( node, name = '', callback = null ) {
  7862. node = nodeObject( node );
  7863. return node.before( new InspectorNode( node, name, callback ) );
  7864. }
  7865. addMethodChaining( 'toInspector', inspector );
  7866. function addNodeElement( name/*, nodeElement*/ ) {
  7867. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7868. }
  7869. /**
  7870. * Base class for representing shader attributes as nodes.
  7871. *
  7872. * @augments Node
  7873. */
  7874. class AttributeNode extends Node {
  7875. static get type() {
  7876. return 'AttributeNode';
  7877. }
  7878. /**
  7879. * Constructs a new attribute node.
  7880. *
  7881. * @param {string} attributeName - The name of the attribute.
  7882. * @param {?string} nodeType - The node type.
  7883. */
  7884. constructor( attributeName, nodeType = null ) {
  7885. super( nodeType );
  7886. /**
  7887. * `AttributeNode` sets this property to `true` by default.
  7888. *
  7889. * @type {boolean}
  7890. * @default true
  7891. */
  7892. this.global = true;
  7893. this._attributeName = attributeName;
  7894. }
  7895. getHash( builder ) {
  7896. return this.getAttributeName( builder );
  7897. }
  7898. getNodeType( builder ) {
  7899. let nodeType = this.nodeType;
  7900. if ( nodeType === null ) {
  7901. const attributeName = this.getAttributeName( builder );
  7902. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7903. const attribute = builder.geometry.getAttribute( attributeName );
  7904. nodeType = builder.getTypeFromAttribute( attribute );
  7905. } else {
  7906. nodeType = 'float';
  7907. }
  7908. }
  7909. return nodeType;
  7910. }
  7911. /**
  7912. * Sets the attribute name to the given value. The method can be
  7913. * overwritten in derived classes if the final name must be computed
  7914. * analytically.
  7915. *
  7916. * @param {string} attributeName - The name of the attribute.
  7917. * @return {AttributeNode} A reference to this node.
  7918. */
  7919. setAttributeName( attributeName ) {
  7920. this._attributeName = attributeName;
  7921. return this;
  7922. }
  7923. /**
  7924. * Returns the attribute name of this node. The method can be
  7925. * overwritten in derived classes if the final name must be computed
  7926. * analytically.
  7927. *
  7928. * @param {NodeBuilder} builder - The current node builder.
  7929. * @return {string} The attribute name.
  7930. */
  7931. getAttributeName( /*builder*/ ) {
  7932. return this._attributeName;
  7933. }
  7934. generate( builder ) {
  7935. const attributeName = this.getAttributeName( builder );
  7936. const nodeType = this.getNodeType( builder );
  7937. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7938. if ( geometryAttribute === true ) {
  7939. const attribute = builder.geometry.getAttribute( attributeName );
  7940. const attributeType = builder.getTypeFromAttribute( attribute );
  7941. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7942. if ( builder.shaderStage === 'vertex' ) {
  7943. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7944. } else {
  7945. const nodeVarying = varying( this );
  7946. return nodeVarying.build( builder, nodeType );
  7947. }
  7948. } else {
  7949. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7950. return builder.generateConst( nodeType );
  7951. }
  7952. }
  7953. serialize( data ) {
  7954. super.serialize( data );
  7955. data.global = this.global;
  7956. data._attributeName = this._attributeName;
  7957. }
  7958. deserialize( data ) {
  7959. super.deserialize( data );
  7960. this.global = data.global;
  7961. this._attributeName = data._attributeName;
  7962. }
  7963. }
  7964. /**
  7965. * TSL function for creating an attribute node.
  7966. *
  7967. * @tsl
  7968. * @function
  7969. * @param {string} name - The name of the attribute.
  7970. * @param {?string} [nodeType=null] - The node type.
  7971. * @returns {AttributeNode}
  7972. */
  7973. const attribute = ( name, nodeType = null ) => new AttributeNode( name, nodeType );
  7974. /**
  7975. * TSL function for creating an uv attribute node with the given index.
  7976. *
  7977. * @tsl
  7978. * @function
  7979. * @param {number} [index=0] - The uv index.
  7980. * @return {AttributeNode<vec2>} The uv attribute node.
  7981. */
  7982. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7983. /**
  7984. * A node that represents the dimensions of a texture. The texture size is
  7985. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7986. * or `textureSize()`.
  7987. *
  7988. * @augments Node
  7989. */
  7990. class TextureSizeNode extends Node {
  7991. static get type() {
  7992. return 'TextureSizeNode';
  7993. }
  7994. /**
  7995. * Constructs a new texture size node.
  7996. *
  7997. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7998. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7999. */
  8000. constructor( textureNode, levelNode = null ) {
  8001. super( 'uvec2' );
  8002. /**
  8003. * This flag can be used for type testing.
  8004. *
  8005. * @type {boolean}
  8006. * @readonly
  8007. * @default true
  8008. */
  8009. this.isTextureSizeNode = true;
  8010. /**
  8011. * A texture node which size should be retrieved.
  8012. *
  8013. * @type {TextureNode}
  8014. */
  8015. this.textureNode = textureNode;
  8016. /**
  8017. * A level node which defines the requested mip.
  8018. *
  8019. * @type {Node<int>}
  8020. * @default null
  8021. */
  8022. this.levelNode = levelNode;
  8023. }
  8024. generate( builder, output ) {
  8025. const textureProperty = this.textureNode.build( builder, 'property' );
  8026. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  8027. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  8028. }
  8029. }
  8030. /**
  8031. * TSL function for creating a texture size node.
  8032. *
  8033. * @tsl
  8034. * @function
  8035. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  8036. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  8037. * @returns {TextureSizeNode}
  8038. */
  8039. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  8040. /**
  8041. * A special type of uniform node that computes the
  8042. * maximum mipmap level for a given texture node.
  8043. *
  8044. * ```js
  8045. * const level = maxMipLevel( textureNode );
  8046. * ```
  8047. *
  8048. * @augments UniformNode
  8049. */
  8050. class MaxMipLevelNode extends UniformNode {
  8051. static get type() {
  8052. return 'MaxMipLevelNode';
  8053. }
  8054. /**
  8055. * Constructs a new max mip level node.
  8056. *
  8057. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8058. */
  8059. constructor( textureNode ) {
  8060. super( 0 );
  8061. /**
  8062. * The texture node to compute the max mip level for.
  8063. *
  8064. * @private
  8065. * @type {TextureNode}
  8066. */
  8067. this._textureNode = textureNode;
  8068. /**
  8069. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  8070. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  8071. *
  8072. * @type {string}
  8073. * @default 'frame'
  8074. */
  8075. this.updateType = NodeUpdateType.FRAME;
  8076. }
  8077. /**
  8078. * The texture node to compute the max mip level for.
  8079. *
  8080. * @readonly
  8081. * @type {TextureNode}
  8082. */
  8083. get textureNode() {
  8084. return this._textureNode;
  8085. }
  8086. /**
  8087. * The texture.
  8088. *
  8089. * @readonly
  8090. * @type {Texture}
  8091. */
  8092. get texture() {
  8093. return this._textureNode.value;
  8094. }
  8095. update() {
  8096. const texture = this.texture;
  8097. const images = texture.images;
  8098. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  8099. if ( image && image.width !== undefined ) {
  8100. const { width, height } = image;
  8101. this.value = Math.log2( Math.max( width, height ) );
  8102. }
  8103. }
  8104. }
  8105. /**
  8106. * TSL function for creating a max mip level node.
  8107. *
  8108. * @tsl
  8109. * @function
  8110. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  8111. * @returns {MaxMipLevelNode}
  8112. */
  8113. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  8114. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  8115. /**
  8116. * This type of uniform node represents a 2D texture.
  8117. *
  8118. * @augments UniformNode
  8119. */
  8120. class TextureNode extends UniformNode {
  8121. static get type() {
  8122. return 'TextureNode';
  8123. }
  8124. /**
  8125. * Constructs a new texture node.
  8126. *
  8127. * @param {Texture} [value=EmptyTexture] - The texture.
  8128. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8129. * @param {?Node<int>} [levelNode=null] - The level node.
  8130. * @param {?Node<float>} [biasNode=null] - The bias node.
  8131. */
  8132. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  8133. super( value );
  8134. /**
  8135. * This flag can be used for type testing.
  8136. *
  8137. * @type {boolean}
  8138. * @readonly
  8139. * @default true
  8140. */
  8141. this.isTextureNode = true;
  8142. /**
  8143. * Represents the texture coordinates.
  8144. *
  8145. * @type {?Node<vec2|vec3>}
  8146. * @default null
  8147. */
  8148. this.uvNode = uvNode;
  8149. /**
  8150. * Represents the mip level that should be selected.
  8151. *
  8152. * @type {?Node<int>}
  8153. * @default null
  8154. */
  8155. this.levelNode = levelNode;
  8156. /**
  8157. * Represents the bias to be applied during level-of-detail computation.
  8158. *
  8159. * @type {?Node<float>}
  8160. * @default null
  8161. */
  8162. this.biasNode = biasNode;
  8163. /**
  8164. * Represents a reference value a texture sample is compared to.
  8165. *
  8166. * @type {?Node<float>}
  8167. * @default null
  8168. */
  8169. this.compareNode = null;
  8170. /**
  8171. * When using texture arrays, the depth node defines the layer to select.
  8172. *
  8173. * @type {?Node<int>}
  8174. * @default null
  8175. */
  8176. this.depthNode = null;
  8177. /**
  8178. * When defined, a texture is sampled using explicit gradients.
  8179. *
  8180. * @type {?Array<Node<vec2>>}
  8181. * @default null
  8182. */
  8183. this.gradNode = null;
  8184. /**
  8185. * Represents the optional texel offset applied to the unnormalized texture
  8186. * coordinate before sampling the texture.
  8187. *
  8188. * @type {?Node<ivec2|ivec3>}
  8189. * @default null
  8190. */
  8191. this.offsetNode = null;
  8192. /**
  8193. * Whether texture values should be sampled or fetched.
  8194. *
  8195. * @type {boolean}
  8196. * @default true
  8197. */
  8198. this.sampler = true;
  8199. /**
  8200. * Whether the uv transformation matrix should be
  8201. * automatically updated or not. Use `setUpdateMatrix()`
  8202. * if you want to change the value of the property.
  8203. *
  8204. * @type {boolean}
  8205. * @default false
  8206. */
  8207. this.updateMatrix = false;
  8208. /**
  8209. * By default the `update()` method is not executed. Depending on
  8210. * whether a uv transformation matrix and/or flipY is applied, `update()`
  8211. * is executed per object.
  8212. *
  8213. * @type {string}
  8214. * @default 'none'
  8215. */
  8216. this.updateType = NodeUpdateType.NONE;
  8217. /**
  8218. * The reference node.
  8219. *
  8220. * @type {?Node}
  8221. * @default null
  8222. */
  8223. this.referenceNode = null;
  8224. /**
  8225. * The texture value is stored in a private property.
  8226. *
  8227. * @private
  8228. * @type {Texture}
  8229. */
  8230. this._value = value;
  8231. /**
  8232. * The uniform node that represents the uv transformation matrix.
  8233. *
  8234. * @private
  8235. * @type {?UniformNode<mat3>}
  8236. * @default null
  8237. */
  8238. this._matrixUniform = null;
  8239. /**
  8240. * The uniform node that represents the y-flip. Only required for WebGL.
  8241. *
  8242. * @private
  8243. * @type {?UniformNode<bool>}
  8244. * @default null
  8245. */
  8246. this._flipYUniform = null;
  8247. this.setUpdateMatrix( uvNode === null );
  8248. }
  8249. set value( value ) {
  8250. if ( this.referenceNode ) {
  8251. this.referenceNode.value = value;
  8252. } else {
  8253. this._value = value;
  8254. }
  8255. }
  8256. /**
  8257. * The texture value.
  8258. *
  8259. * @type {Texture}
  8260. */
  8261. get value() {
  8262. return this.referenceNode ? this.referenceNode.value : this._value;
  8263. }
  8264. /**
  8265. * Overwritten since the uniform hash is defined by the texture's UUID.
  8266. *
  8267. * @param {NodeBuilder} builder - The current node builder.
  8268. * @return {string} The uniform hash.
  8269. */
  8270. getUniformHash( /*builder*/ ) {
  8271. return this.value.uuid;
  8272. }
  8273. /**
  8274. * Overwritten since the node type is inferred from the texture type.
  8275. *
  8276. * @param {NodeBuilder} builder - The current node builder.
  8277. * @return {string} The node type.
  8278. */
  8279. getNodeType( /*builder*/ ) {
  8280. if ( this.value.isDepthTexture === true ) return 'float';
  8281. if ( this.value.type === UnsignedIntType ) {
  8282. return 'uvec4';
  8283. } else if ( this.value.type === IntType ) {
  8284. return 'ivec4';
  8285. }
  8286. return 'vec4';
  8287. }
  8288. /**
  8289. * Overwrites the default implementation to return a fixed value `'texture'`.
  8290. *
  8291. * @param {NodeBuilder} builder - The current node builder.
  8292. * @return {string} The input type.
  8293. */
  8294. getInputType( /*builder*/ ) {
  8295. return 'texture';
  8296. }
  8297. /**
  8298. * Returns a default uvs based on the current texture's channel.
  8299. *
  8300. * @return {AttributeNode<vec2>} The default uvs.
  8301. */
  8302. getDefaultUV() {
  8303. return uv$1( this.value.channel );
  8304. }
  8305. /**
  8306. * Overwritten to always return the texture reference of the node.
  8307. *
  8308. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  8309. * @return {Texture} The texture reference.
  8310. */
  8311. updateReference( /*state*/ ) {
  8312. return this.value;
  8313. }
  8314. /**
  8315. * Transforms the given uv node with the texture transformation matrix.
  8316. *
  8317. * @param {Node} uvNode - The uv node to transform.
  8318. * @return {Node} The transformed uv node.
  8319. */
  8320. getTransformedUV( uvNode ) {
  8321. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  8322. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  8323. }
  8324. /**
  8325. * Defines whether the uv transformation matrix should automatically be updated or not.
  8326. *
  8327. * @param {boolean} value - The update toggle.
  8328. * @return {TextureNode} A reference to this node.
  8329. */
  8330. setUpdateMatrix( value ) {
  8331. this.updateMatrix = value;
  8332. return this;
  8333. }
  8334. /**
  8335. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  8336. * to modify the uv node for correct sampling.
  8337. *
  8338. * @param {NodeBuilder} builder - The current node builder.
  8339. * @param {Node} uvNode - The uv node to setup.
  8340. * @return {Node} The updated uv node.
  8341. */
  8342. setupUV( builder, uvNode ) {
  8343. if ( builder.isFlipY() ) {
  8344. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  8345. uvNode = uvNode.toVar();
  8346. if ( this.sampler ) {
  8347. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  8348. } else {
  8349. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  8350. }
  8351. }
  8352. return uvNode;
  8353. }
  8354. /**
  8355. * Setups texture node by preparing the internal nodes for code generation.
  8356. *
  8357. * @param {NodeBuilder} builder - The current node builder.
  8358. */
  8359. setup( builder ) {
  8360. const properties = builder.getNodeProperties( this );
  8361. properties.referenceNode = this.referenceNode;
  8362. //
  8363. const texture = this.value;
  8364. if ( ! texture || texture.isTexture !== true ) {
  8365. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8366. }
  8367. //
  8368. const uvNode = Fn( () => {
  8369. let uvNode = this.uvNode;
  8370. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8371. uvNode = builder.context.getUV( this, builder );
  8372. }
  8373. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8374. if ( this.updateMatrix === true ) {
  8375. uvNode = this.getTransformedUV( uvNode );
  8376. }
  8377. uvNode = this.setupUV( builder, uvNode );
  8378. //
  8379. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8380. //
  8381. return uvNode;
  8382. } )();
  8383. //
  8384. let levelNode = this.levelNode;
  8385. if ( levelNode === null && builder.context.getTextureLevel ) {
  8386. levelNode = builder.context.getTextureLevel( this );
  8387. }
  8388. //
  8389. let compareNode = null;
  8390. let compareStepNode = null;
  8391. if ( this.compareNode !== null ) {
  8392. if ( builder.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  8393. compareNode = this.compareNode;
  8394. } else {
  8395. if ( this.value.compareFunction !== null && this.value.compareFunction !== LessCompare ) {
  8396. warnOnce( 'TSL: Only "LessCompare" is supported for depth texture comparison fallback.' );
  8397. }
  8398. compareStepNode = this.compareNode;
  8399. }
  8400. }
  8401. properties.uvNode = uvNode;
  8402. properties.levelNode = levelNode;
  8403. properties.biasNode = this.biasNode;
  8404. properties.compareNode = compareNode;
  8405. properties.compareStepNode = compareStepNode;
  8406. properties.gradNode = this.gradNode;
  8407. properties.depthNode = this.depthNode;
  8408. properties.offsetNode = this.offsetNode;
  8409. }
  8410. /**
  8411. * Generates the uv code snippet.
  8412. *
  8413. * @param {NodeBuilder} builder - The current node builder.
  8414. * @param {Node} uvNode - The uv node to generate code for.
  8415. * @return {string} The generated code snippet.
  8416. */
  8417. generateUV( builder, uvNode ) {
  8418. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8419. }
  8420. /**
  8421. * Generates the offset code snippet.
  8422. *
  8423. * @param {NodeBuilder} builder - The current node builder.
  8424. * @param {Node} offsetNode - The offset node to generate code for.
  8425. * @return {string} The generated code snippet.
  8426. */
  8427. generateOffset( builder, offsetNode ) {
  8428. return offsetNode.build( builder, 'ivec2' );
  8429. }
  8430. /**
  8431. * Generates the snippet for the texture sampling.
  8432. *
  8433. * @param {NodeBuilder} builder - The current node builder.
  8434. * @param {string} textureProperty - The texture property.
  8435. * @param {string} uvSnippet - The uv snippet.
  8436. * @param {?string} levelSnippet - The level snippet.
  8437. * @param {?string} biasSnippet - The bias snippet.
  8438. * @param {?string} depthSnippet - The depth snippet.
  8439. * @param {?string} compareSnippet - The compare snippet.
  8440. * @param {?Array<string>} gradSnippet - The grad snippet.
  8441. * @param {?string} offsetSnippet - The offset snippet.
  8442. * @return {string} The generated code snippet.
  8443. */
  8444. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8445. const texture = this.value;
  8446. let snippet;
  8447. if ( biasSnippet ) {
  8448. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8449. } else if ( gradSnippet ) {
  8450. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8451. } else if ( compareSnippet ) {
  8452. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8453. } else if ( this.sampler === false ) {
  8454. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8455. } else if ( levelSnippet ) {
  8456. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8457. } else {
  8458. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8459. }
  8460. return snippet;
  8461. }
  8462. /**
  8463. * Generates the code snippet of the texture node.
  8464. *
  8465. * @param {NodeBuilder} builder - The current node builder.
  8466. * @param {string} output - The current output.
  8467. * @return {string} The generated code snippet.
  8468. */
  8469. generate( builder, output ) {
  8470. const texture = this.value;
  8471. const properties = builder.getNodeProperties( this );
  8472. const textureProperty = super.generate( builder, 'property' );
  8473. if ( /^sampler/.test( output ) ) {
  8474. return textureProperty + '_sampler';
  8475. } else if ( builder.isReference( output ) ) {
  8476. return textureProperty;
  8477. } else {
  8478. const nodeData = builder.getDataFromNode( this );
  8479. const nodeType = this.getNodeType( builder );
  8480. let propertyName = nodeData.propertyName;
  8481. if ( propertyName === undefined ) {
  8482. const { uvNode, levelNode, biasNode, compareNode, compareStepNode, depthNode, gradNode, offsetNode } = properties;
  8483. const uvSnippet = this.generateUV( builder, uvNode );
  8484. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8485. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8486. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8487. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8488. const compareStepSnippet = compareStepNode ? compareStepNode.build( builder, 'float' ) : null;
  8489. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8490. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8491. const nodeVar = builder.getVarFromNode( this );
  8492. propertyName = builder.getPropertyName( nodeVar );
  8493. let snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8494. if ( compareStepSnippet !== null ) {
  8495. snippet = step( expression( compareStepSnippet, 'float' ), expression( snippet, nodeType ) ).build( builder, nodeType );
  8496. }
  8497. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8498. nodeData.snippet = snippet;
  8499. nodeData.propertyName = propertyName;
  8500. }
  8501. let snippet = propertyName;
  8502. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8503. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8504. }
  8505. return builder.format( snippet, nodeType, output );
  8506. }
  8507. }
  8508. /**
  8509. * Sets the sampler value.
  8510. *
  8511. * @param {boolean} value - The sampler value to set.
  8512. * @return {TextureNode} A reference to this texture node.
  8513. */
  8514. setSampler( value ) {
  8515. this.sampler = value;
  8516. return this;
  8517. }
  8518. /**
  8519. * Returns the sampler value.
  8520. *
  8521. * @return {boolean} The sampler value.
  8522. */
  8523. getSampler() {
  8524. return this.sampler;
  8525. }
  8526. // @TODO: Move to TSL
  8527. /**
  8528. * Samples the texture with the given uv node.
  8529. *
  8530. * @param {Node} uvNode - The uv node.
  8531. * @return {TextureNode} A texture node representing the texture sample.
  8532. */
  8533. sample( uvNode ) {
  8534. const textureNode = this.clone();
  8535. textureNode.uvNode = nodeObject( uvNode );
  8536. textureNode.referenceNode = this.getBase();
  8537. return nodeObject( textureNode );
  8538. }
  8539. /**
  8540. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8541. *
  8542. * @param {Node<uvec2>} uvNode - The uv node.
  8543. * @returns {TextureNode} A texture node representing the texture load.
  8544. */
  8545. load( uvNode ) {
  8546. return this.sample( uvNode ).setSampler( false );
  8547. }
  8548. /**
  8549. * Samples a blurred version of the texture by defining an internal bias.
  8550. *
  8551. * @param {Node<float>} amountNode - How blurred the texture should be.
  8552. * @return {TextureNode} A texture node representing the texture sample.
  8553. */
  8554. blur( amountNode ) {
  8555. const textureNode = this.clone();
  8556. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8557. textureNode.referenceNode = this.getBase();
  8558. const map = textureNode.value;
  8559. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8560. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8561. textureNode.biasNode = null;
  8562. }
  8563. return nodeObject( textureNode );
  8564. }
  8565. /**
  8566. * Samples a specific mip of the texture.
  8567. *
  8568. * @param {Node<int>} levelNode - The mip level to sample.
  8569. * @return {TextureNode} A texture node representing the texture sample.
  8570. */
  8571. level( levelNode ) {
  8572. const textureNode = this.clone();
  8573. textureNode.levelNode = nodeObject( levelNode );
  8574. textureNode.referenceNode = this.getBase();
  8575. return nodeObject( textureNode );
  8576. }
  8577. /**
  8578. * Returns the texture size of the requested level.
  8579. *
  8580. * @param {Node<int>} levelNode - The level to compute the size for.
  8581. * @return {TextureSizeNode} The texture size.
  8582. */
  8583. size( levelNode ) {
  8584. return textureSize( this, levelNode );
  8585. }
  8586. /**
  8587. * Samples the texture with the given bias.
  8588. *
  8589. * @param {Node<float>} biasNode - The bias node.
  8590. * @return {TextureNode} A texture node representing the texture sample.
  8591. */
  8592. bias( biasNode ) {
  8593. const textureNode = this.clone();
  8594. textureNode.biasNode = nodeObject( biasNode );
  8595. textureNode.referenceNode = this.getBase();
  8596. return nodeObject( textureNode );
  8597. }
  8598. /**
  8599. * Returns the base texture of this node.
  8600. * @return {TextureNode} The base texture node.
  8601. */
  8602. getBase() {
  8603. return this.referenceNode ? this.referenceNode.getBase() : this;
  8604. }
  8605. /**
  8606. * Samples the texture by executing a compare operation.
  8607. *
  8608. * @param {Node<float>} compareNode - The node that defines the compare value.
  8609. * @return {TextureNode} A texture node representing the texture sample.
  8610. */
  8611. compare( compareNode ) {
  8612. const textureNode = this.clone();
  8613. textureNode.compareNode = nodeObject( compareNode );
  8614. textureNode.referenceNode = this.getBase();
  8615. return nodeObject( textureNode );
  8616. }
  8617. /**
  8618. * Samples the texture using an explicit gradient.
  8619. *
  8620. * @param {Node<vec2>} gradNodeX - The gradX node.
  8621. * @param {Node<vec2>} gradNodeY - The gradY node.
  8622. * @return {TextureNode} A texture node representing the texture sample.
  8623. */
  8624. grad( gradNodeX, gradNodeY ) {
  8625. const textureNode = this.clone();
  8626. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8627. textureNode.referenceNode = this.getBase();
  8628. return nodeObject( textureNode );
  8629. }
  8630. /**
  8631. * Samples the texture by defining a depth node.
  8632. *
  8633. * @param {Node<int>} depthNode - The depth node.
  8634. * @return {TextureNode} A texture node representing the texture sample.
  8635. */
  8636. depth( depthNode ) {
  8637. const textureNode = this.clone();
  8638. textureNode.depthNode = nodeObject( depthNode );
  8639. textureNode.referenceNode = this.getBase();
  8640. return nodeObject( textureNode );
  8641. }
  8642. /**
  8643. * Samples the texture by defining an offset node.
  8644. *
  8645. * @param {Node<ivec2>} offsetNode - The offset node.
  8646. * @return {TextureNode} A texture node representing the texture sample.
  8647. */
  8648. offset( offsetNode ) {
  8649. const textureNode = this.clone();
  8650. textureNode.offsetNode = nodeObject( offsetNode );
  8651. textureNode.referenceNode = this.getBase();
  8652. return nodeObject( textureNode );
  8653. }
  8654. // --
  8655. serialize( data ) {
  8656. super.serialize( data );
  8657. data.value = this.value.toJSON( data.meta ).uuid;
  8658. data.sampler = this.sampler;
  8659. data.updateMatrix = this.updateMatrix;
  8660. data.updateType = this.updateType;
  8661. }
  8662. deserialize( data ) {
  8663. super.deserialize( data );
  8664. this.value = data.meta.textures[ data.value ];
  8665. this.sampler = data.sampler;
  8666. this.updateMatrix = data.updateMatrix;
  8667. this.updateType = data.updateType;
  8668. }
  8669. /**
  8670. * The update is used to implement the update of the uv transformation matrix.
  8671. */
  8672. update() {
  8673. const texture = this.value;
  8674. const matrixUniform = this._matrixUniform;
  8675. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8676. if ( texture.matrixAutoUpdate === true ) {
  8677. texture.updateMatrix();
  8678. }
  8679. //
  8680. const flipYUniform = this._flipYUniform;
  8681. if ( flipYUniform !== null ) {
  8682. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8683. }
  8684. }
  8685. /**
  8686. * Clones the texture node.
  8687. *
  8688. * @return {TextureNode} The cloned texture node.
  8689. */
  8690. clone() {
  8691. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8692. newNode.sampler = this.sampler;
  8693. newNode.depthNode = this.depthNode;
  8694. newNode.compareNode = this.compareNode;
  8695. newNode.gradNode = this.gradNode;
  8696. newNode.offsetNode = this.offsetNode;
  8697. return newNode;
  8698. }
  8699. }
  8700. /**
  8701. * TSL function for creating a texture node.
  8702. *
  8703. * @tsl
  8704. * @function
  8705. * @param {?Texture} value - The texture.
  8706. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8707. * @param {?Node<int>} [levelNode=null] - The level node.
  8708. * @param {?Node<float>} [biasNode=null] - The bias node.
  8709. * @returns {TextureNode}
  8710. */
  8711. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8712. /**
  8713. * TSL function for creating a texture node or sample a texture node already existing.
  8714. *
  8715. * @tsl
  8716. * @function
  8717. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8718. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8719. * @param {?Node<int>} [levelNode=null] - The level node.
  8720. * @param {?Node<float>} [biasNode=null] - The bias node.
  8721. * @returns {TextureNode}
  8722. */
  8723. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8724. let textureNode;
  8725. if ( value && value.isTextureNode === true ) {
  8726. textureNode = nodeObject( value.clone() );
  8727. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8728. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8729. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8730. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8731. } else {
  8732. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8733. }
  8734. return textureNode;
  8735. };
  8736. /**
  8737. * TSL function for creating a uniform texture node.
  8738. *
  8739. * @tsl
  8740. * @function
  8741. * @param {?Texture} value - The texture.
  8742. * @returns {TextureNode}
  8743. */
  8744. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8745. /**
  8746. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8747. *
  8748. * @tsl
  8749. * @function
  8750. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8751. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8752. * @param {?Node<int>} [levelNode=null] - The level node.
  8753. * @param {?Node<float>} [biasNode=null] - The bias node.
  8754. * @returns {TextureNode}
  8755. */
  8756. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8757. const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8758. /**
  8759. * Converts a texture or texture node to a sampler.
  8760. *
  8761. * @tsl
  8762. * @function
  8763. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8764. * @returns {Node}
  8765. */
  8766. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8767. /**
  8768. * Converts a texture or texture node to a sampler comparison.
  8769. *
  8770. * @tsl
  8771. * @function
  8772. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8773. * @returns {Node}
  8774. */
  8775. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8776. /**
  8777. * A special type of uniform node which represents array-like data
  8778. * as uniform buffers. The access usually happens via `element()`
  8779. * which returns an instance of {@link ArrayElementNode}. For example:
  8780. *
  8781. * ```js
  8782. * const bufferNode = buffer( array, 'mat4', count );
  8783. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8784. * ```
  8785. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8786. * since it handles more input types and automatically cares about buffer paddings.
  8787. *
  8788. * @augments UniformNode
  8789. */
  8790. class BufferNode extends UniformNode {
  8791. static get type() {
  8792. return 'BufferNode';
  8793. }
  8794. /**
  8795. * Constructs a new buffer node.
  8796. *
  8797. * @param {Array<number>} value - Array-like buffer data.
  8798. * @param {string} bufferType - The data type of the buffer.
  8799. * @param {number} [bufferCount=0] - The count of buffer elements.
  8800. */
  8801. constructor( value, bufferType, bufferCount = 0 ) {
  8802. super( value, bufferType );
  8803. /**
  8804. * This flag can be used for type testing.
  8805. *
  8806. * @type {boolean}
  8807. * @readonly
  8808. * @default true
  8809. */
  8810. this.isBufferNode = true;
  8811. /**
  8812. * The data type of the buffer.
  8813. *
  8814. * @type {string}
  8815. */
  8816. this.bufferType = bufferType;
  8817. /**
  8818. * The uniform node that holds the value of the reference node.
  8819. *
  8820. * @type {number}
  8821. * @default 0
  8822. */
  8823. this.bufferCount = bufferCount;
  8824. /**
  8825. * An array of update ranges.
  8826. *
  8827. * @type {Array<{start: number, count: number}>}
  8828. */
  8829. this.updateRanges = [];
  8830. }
  8831. /**
  8832. * Adds a range of data in the data array to be updated on the GPU.
  8833. *
  8834. * @param {number} start - Position at which to start update.
  8835. * @param {number} count - The number of components to update.
  8836. */
  8837. addUpdateRange( start, count ) {
  8838. this.updateRanges.push( { start, count } );
  8839. }
  8840. /**
  8841. * Clears the update ranges.
  8842. */
  8843. clearUpdateRanges() {
  8844. this.updateRanges.length = 0;
  8845. }
  8846. /**
  8847. * The data type of the buffer elements.
  8848. *
  8849. * @param {NodeBuilder} builder - The current node builder.
  8850. * @return {string} The element type.
  8851. */
  8852. getElementType( builder ) {
  8853. return this.getNodeType( builder );
  8854. }
  8855. /**
  8856. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8857. *
  8858. * @param {NodeBuilder} builder - The current node builder.
  8859. * @return {string} The input type.
  8860. */
  8861. getInputType( /*builder*/ ) {
  8862. return 'buffer';
  8863. }
  8864. }
  8865. /**
  8866. * TSL function for creating a buffer node.
  8867. *
  8868. * @tsl
  8869. * @function
  8870. * @param {Array<number>} value - Array-like buffer data.
  8871. * @param {string} type - The data type of a buffer element.
  8872. * @param {number} count - The count of buffer elements.
  8873. * @returns {BufferNode}
  8874. */
  8875. const buffer = ( value, type, count ) => new BufferNode( value, type, count );
  8876. /**
  8877. * Represents the element access on uniform array nodes.
  8878. *
  8879. * @augments ArrayElementNode
  8880. */
  8881. class UniformArrayElementNode extends ArrayElementNode {
  8882. static get type() {
  8883. return 'UniformArrayElementNode';
  8884. }
  8885. /**
  8886. * Constructs a new buffer node.
  8887. *
  8888. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8889. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8890. */
  8891. constructor( uniformArrayNode, indexNode ) {
  8892. super( uniformArrayNode, indexNode );
  8893. /**
  8894. * This flag can be used for type testing.
  8895. *
  8896. * @type {boolean}
  8897. * @readonly
  8898. * @default true
  8899. */
  8900. this.isArrayBufferElementNode = true;
  8901. }
  8902. generate( builder ) {
  8903. const snippet = super.generate( builder );
  8904. const type = this.getNodeType();
  8905. const paddedType = this.node.getPaddedType();
  8906. return builder.format( snippet, paddedType, type );
  8907. }
  8908. }
  8909. /**
  8910. * Similar to {@link BufferNode} this module represents array-like data as
  8911. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8912. * data types in the array (e.g `three.js` primitives) and automatically
  8913. * manage buffer padding. It should be the first choice when working with
  8914. * uniforms buffers.
  8915. * ```js
  8916. * const tintColors = uniformArray( [
  8917. * new Color( 1, 0, 0 ),
  8918. * new Color( 0, 1, 0 ),
  8919. * new Color( 0, 0, 1 )
  8920. * ], 'color' );
  8921. *
  8922. * const redColor = tintColors.element( 0 );
  8923. *
  8924. * @augments BufferNode
  8925. */
  8926. class UniformArrayNode extends BufferNode {
  8927. static get type() {
  8928. return 'UniformArrayNode';
  8929. }
  8930. /**
  8931. * Constructs a new uniform array node.
  8932. *
  8933. * @param {Array<any>} value - Array holding the buffer data.
  8934. * @param {?string} [elementType=null] - The data type of a buffer element.
  8935. */
  8936. constructor( value, elementType = null ) {
  8937. super( null );
  8938. /**
  8939. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8940. * hold number primitives as well as three.js objects like vectors, matrices
  8941. * or colors.
  8942. *
  8943. * @type {Array<any>}
  8944. */
  8945. this.array = value;
  8946. /**
  8947. * The data type of an array element.
  8948. *
  8949. * @type {string}
  8950. */
  8951. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8952. /**
  8953. * The padded type. Uniform buffers must conform to a certain buffer layout
  8954. * so a separate type is computed to ensure correct buffer size.
  8955. *
  8956. * @type {string}
  8957. */
  8958. this.paddedType = this.getPaddedType();
  8959. /**
  8960. * Overwritten since uniform array nodes are updated per render.
  8961. *
  8962. * @type {string}
  8963. * @default 'render'
  8964. */
  8965. this.updateType = NodeUpdateType.RENDER;
  8966. /**
  8967. * This flag can be used for type testing.
  8968. *
  8969. * @type {boolean}
  8970. * @readonly
  8971. * @default true
  8972. */
  8973. this.isArrayBufferNode = true;
  8974. }
  8975. /**
  8976. * This method is overwritten since the node type is inferred from the
  8977. * {@link UniformArrayNode#paddedType}.
  8978. *
  8979. * @param {NodeBuilder} builder - The current node builder.
  8980. * @return {string} The node type.
  8981. */
  8982. getNodeType( /*builder*/ ) {
  8983. return this.paddedType;
  8984. }
  8985. /**
  8986. * The data type of the array elements.
  8987. *
  8988. * @param {NodeBuilder} builder - The current node builder.
  8989. * @return {string} The element type.
  8990. */
  8991. getElementType() {
  8992. return this.elementType;
  8993. }
  8994. /**
  8995. * Returns the padded type based on the element type.
  8996. *
  8997. * @return {string} The padded type.
  8998. */
  8999. getPaddedType() {
  9000. const elementType = this.elementType;
  9001. let paddedType = 'vec4';
  9002. if ( elementType === 'mat2' ) {
  9003. paddedType = 'mat2';
  9004. } else if ( /mat/.test( elementType ) === true ) {
  9005. paddedType = 'mat4';
  9006. } else if ( elementType.charAt( 0 ) === 'i' ) {
  9007. paddedType = 'ivec4';
  9008. } else if ( elementType.charAt( 0 ) === 'u' ) {
  9009. paddedType = 'uvec4';
  9010. }
  9011. return paddedType;
  9012. }
  9013. /**
  9014. * The update makes sure to correctly transfer the data from the (complex) objects
  9015. * in the array to the internal, correctly padded value buffer.
  9016. *
  9017. * @param {NodeFrame} frame - A reference to the current node frame.
  9018. */
  9019. update( /*frame*/ ) {
  9020. const { array, value } = this;
  9021. const elementType = this.elementType;
  9022. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  9023. for ( let i = 0; i < array.length; i ++ ) {
  9024. const index = i * 4;
  9025. value[ index ] = array[ i ];
  9026. }
  9027. } else if ( elementType === 'color' ) {
  9028. for ( let i = 0; i < array.length; i ++ ) {
  9029. const index = i * 4;
  9030. const vector = array[ i ];
  9031. value[ index ] = vector.r;
  9032. value[ index + 1 ] = vector.g;
  9033. value[ index + 2 ] = vector.b || 0;
  9034. //value[ index + 3 ] = vector.a || 0;
  9035. }
  9036. } else if ( elementType === 'mat2' ) {
  9037. for ( let i = 0; i < array.length; i ++ ) {
  9038. const index = i * 4;
  9039. const matrix = array[ i ];
  9040. value[ index ] = matrix.elements[ 0 ];
  9041. value[ index + 1 ] = matrix.elements[ 1 ];
  9042. value[ index + 2 ] = matrix.elements[ 2 ];
  9043. value[ index + 3 ] = matrix.elements[ 3 ];
  9044. }
  9045. } else if ( elementType === 'mat3' ) {
  9046. for ( let i = 0; i < array.length; i ++ ) {
  9047. const index = i * 16;
  9048. const matrix = array[ i ];
  9049. value[ index ] = matrix.elements[ 0 ];
  9050. value[ index + 1 ] = matrix.elements[ 1 ];
  9051. value[ index + 2 ] = matrix.elements[ 2 ];
  9052. value[ index + 4 ] = matrix.elements[ 3 ];
  9053. value[ index + 5 ] = matrix.elements[ 4 ];
  9054. value[ index + 6 ] = matrix.elements[ 5 ];
  9055. value[ index + 8 ] = matrix.elements[ 6 ];
  9056. value[ index + 9 ] = matrix.elements[ 7 ];
  9057. value[ index + 10 ] = matrix.elements[ 8 ];
  9058. value[ index + 15 ] = 1;
  9059. }
  9060. } else if ( elementType === 'mat4' ) {
  9061. for ( let i = 0; i < array.length; i ++ ) {
  9062. const index = i * 16;
  9063. const matrix = array[ i ];
  9064. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  9065. value[ index + i ] = matrix.elements[ i ];
  9066. }
  9067. }
  9068. } else {
  9069. for ( let i = 0; i < array.length; i ++ ) {
  9070. const index = i * 4;
  9071. const vector = array[ i ];
  9072. value[ index ] = vector.x;
  9073. value[ index + 1 ] = vector.y;
  9074. value[ index + 2 ] = vector.z || 0;
  9075. value[ index + 3 ] = vector.w || 0;
  9076. }
  9077. }
  9078. }
  9079. /**
  9080. * Implement the value buffer creation based on the array data.
  9081. *
  9082. * @param {NodeBuilder} builder - A reference to the current node builder.
  9083. * @return {null}
  9084. */
  9085. setup( builder ) {
  9086. const length = this.array.length;
  9087. const elementType = this.elementType;
  9088. let arrayType = Float32Array;
  9089. const paddedType = this.paddedType;
  9090. const paddedElementLength = builder.getTypeLength( paddedType );
  9091. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  9092. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  9093. this.value = new arrayType( length * paddedElementLength );
  9094. this.bufferCount = length;
  9095. this.bufferType = paddedType;
  9096. return super.setup( builder );
  9097. }
  9098. /**
  9099. * Overwrites the default `element()` method to provide element access
  9100. * based on {@link UniformArrayNode}.
  9101. *
  9102. * @param {IndexNode} indexNode - The index node.
  9103. * @return {UniformArrayElementNode}
  9104. */
  9105. element( indexNode ) {
  9106. return new UniformArrayElementNode( this, nodeObject( indexNode ) );
  9107. }
  9108. }
  9109. /**
  9110. * TSL function for creating an uniform array node.
  9111. *
  9112. * @tsl
  9113. * @function
  9114. * @param {Array<any>} values - Array-like data.
  9115. * @param {?string} [nodeType] - The data type of the array elements.
  9116. * @returns {UniformArrayNode}
  9117. */
  9118. const uniformArray = ( values, nodeType ) => new UniformArrayNode( values, nodeType );
  9119. /**
  9120. * The node allows to set values for built-in shader variables. That is
  9121. * required for features like hardware-accelerated vertex clipping.
  9122. *
  9123. * @augments Node
  9124. */
  9125. class BuiltinNode extends Node {
  9126. /**
  9127. * Constructs a new builtin node.
  9128. *
  9129. * @param {string} name - The name of the built-in shader variable.
  9130. */
  9131. constructor( name ) {
  9132. super( 'float' );
  9133. /**
  9134. * The name of the built-in shader variable.
  9135. *
  9136. * @type {string}
  9137. */
  9138. this.name = name;
  9139. /**
  9140. * This flag can be used for type testing.
  9141. *
  9142. * @type {boolean}
  9143. * @readonly
  9144. * @default true
  9145. */
  9146. this.isBuiltinNode = true;
  9147. }
  9148. /**
  9149. * Generates the code snippet of the builtin node.
  9150. *
  9151. * @param {NodeBuilder} builder - The current node builder.
  9152. * @return {string} The generated code snippet.
  9153. */
  9154. generate( /* builder */ ) {
  9155. return this.name;
  9156. }
  9157. }
  9158. /**
  9159. * TSL function for creating a builtin node.
  9160. *
  9161. * @tsl
  9162. * @function
  9163. * @param {string} name - The name of the built-in shader variable.
  9164. * @returns {BuiltinNode}
  9165. */
  9166. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  9167. let _screenSizeVec, _viewportVec;
  9168. /**
  9169. * This node provides a collection of screen related metrics.
  9170. * Depending on {@link ScreenNode#scope}, the nodes can represent
  9171. * resolution or viewport data as well as fragment or uv coordinates.
  9172. *
  9173. * @augments Node
  9174. */
  9175. class ScreenNode extends Node {
  9176. static get type() {
  9177. return 'ScreenNode';
  9178. }
  9179. /**
  9180. * Constructs a new screen node.
  9181. *
  9182. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  9183. */
  9184. constructor( scope ) {
  9185. super();
  9186. /**
  9187. * The node represents different metric depending on which scope is selected.
  9188. *
  9189. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  9190. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  9191. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  9192. * - `ScreenNode.UV`: Normalized coordinates.
  9193. * - `ScreenNode.DPR`: Device pixel ratio.
  9194. *
  9195. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  9196. */
  9197. this.scope = scope;
  9198. /**
  9199. * This output node.
  9200. *
  9201. * @private
  9202. * @type {?Node}
  9203. * @default null
  9204. */
  9205. this._output = null;
  9206. /**
  9207. * This flag can be used for type testing.
  9208. *
  9209. * @type {boolean}
  9210. * @readonly
  9211. * @default true
  9212. */
  9213. this.isViewportNode = true;
  9214. }
  9215. /**
  9216. * This method is overwritten since the node type depends on the selected scope.
  9217. *
  9218. * @return {('float'|'vec2'|'vec4')} The node type.
  9219. */
  9220. getNodeType() {
  9221. if ( this.scope === ScreenNode.DPR ) return 'float';
  9222. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  9223. else return 'vec2';
  9224. }
  9225. /**
  9226. * This method is overwritten since the node's update type depends on the selected scope.
  9227. *
  9228. * @return {NodeUpdateType} The update type.
  9229. */
  9230. getUpdateType() {
  9231. let updateType = NodeUpdateType.NONE;
  9232. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  9233. updateType = NodeUpdateType.RENDER;
  9234. }
  9235. this.updateType = updateType;
  9236. return updateType;
  9237. }
  9238. /**
  9239. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  9240. * from the current renderer.
  9241. *
  9242. * @param {NodeFrame} frame - A reference to the current node frame.
  9243. */
  9244. update( { renderer } ) {
  9245. const renderTarget = renderer.getRenderTarget();
  9246. if ( this.scope === ScreenNode.VIEWPORT ) {
  9247. if ( renderTarget !== null ) {
  9248. _viewportVec.copy( renderTarget.viewport );
  9249. } else {
  9250. renderer.getViewport( _viewportVec );
  9251. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  9252. }
  9253. } else if ( this.scope === ScreenNode.DPR ) {
  9254. this._output.value = renderer.getPixelRatio();
  9255. } else {
  9256. if ( renderTarget !== null ) {
  9257. _screenSizeVec.width = renderTarget.width;
  9258. _screenSizeVec.height = renderTarget.height;
  9259. } else {
  9260. renderer.getDrawingBufferSize( _screenSizeVec );
  9261. }
  9262. }
  9263. }
  9264. setup( /*builder*/ ) {
  9265. const scope = this.scope;
  9266. let output = null;
  9267. if ( scope === ScreenNode.SIZE ) {
  9268. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  9269. } else if ( scope === ScreenNode.VIEWPORT ) {
  9270. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  9271. } else if ( scope === ScreenNode.DPR ) {
  9272. output = uniform( 1 );
  9273. } else {
  9274. output = vec2( screenCoordinate.div( screenSize ) );
  9275. }
  9276. this._output = output;
  9277. return output;
  9278. }
  9279. generate( builder ) {
  9280. if ( this.scope === ScreenNode.COORDINATE ) {
  9281. let coord = builder.getFragCoord();
  9282. if ( builder.isFlipY() ) {
  9283. // follow webgpu standards
  9284. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  9285. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  9286. }
  9287. return coord;
  9288. }
  9289. return super.generate( builder );
  9290. }
  9291. }
  9292. ScreenNode.COORDINATE = 'coordinate';
  9293. ScreenNode.VIEWPORT = 'viewport';
  9294. ScreenNode.SIZE = 'size';
  9295. ScreenNode.UV = 'uv';
  9296. ScreenNode.DPR = 'dpr';
  9297. // Screen
  9298. /**
  9299. * TSL object that represents the current DPR.
  9300. *
  9301. * @tsl
  9302. * @type {ScreenNode<float>}
  9303. */
  9304. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  9305. /**
  9306. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  9307. *
  9308. * @tsl
  9309. * @type {ScreenNode<vec2>}
  9310. */
  9311. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  9312. /**
  9313. * TSL object that represents the screen resolution in physical pixel units.
  9314. *
  9315. * @tsl
  9316. * @type {ScreenNode<vec2>}
  9317. */
  9318. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  9319. /**
  9320. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  9321. *
  9322. * @tsl
  9323. * @type {ScreenNode<vec2>}
  9324. */
  9325. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  9326. // Viewport
  9327. /**
  9328. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  9329. *
  9330. * @tsl
  9331. * @type {ScreenNode<vec4>}
  9332. */
  9333. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  9334. /**
  9335. * TSL object that represents the viewport resolution in physical pixel units.
  9336. *
  9337. * @tsl
  9338. * @type {ScreenNode<vec2>}
  9339. */
  9340. const viewportSize = viewport.zw;
  9341. /**
  9342. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  9343. *
  9344. * @tsl
  9345. * @type {ScreenNode<vec2>}
  9346. */
  9347. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  9348. /**
  9349. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  9350. *
  9351. * @tsl
  9352. * @type {ScreenNode<vec2>}
  9353. */
  9354. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  9355. // Deprecated
  9356. /**
  9357. * @deprecated since r169. Use {@link screenSize} instead.
  9358. */
  9359. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  9360. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  9361. return screenSize;
  9362. }, 'vec2' ).once() )();
  9363. /**
  9364. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  9365. *
  9366. * @tsl
  9367. * @type {UniformNode<uint>}
  9368. */
  9369. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  9370. /**
  9371. * TSL object that represents the `near` value of the camera used for the current render.
  9372. *
  9373. * @tsl
  9374. * @type {UniformNode<float>}
  9375. */
  9376. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  9377. /**
  9378. * TSL object that represents the `far` value of the camera used for the current render.
  9379. *
  9380. * @tsl
  9381. * @type {UniformNode<float>}
  9382. */
  9383. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  9384. /**
  9385. * TSL object that represents the projection matrix of the camera used for the current render.
  9386. *
  9387. * @tsl
  9388. * @type {UniformNode<mat4>}
  9389. */
  9390. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9391. let cameraProjectionMatrix;
  9392. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9393. const matrices = [];
  9394. for ( const subCamera of camera.cameras ) {
  9395. matrices.push( subCamera.projectionMatrix );
  9396. }
  9397. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9398. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9399. } else {
  9400. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9401. }
  9402. return cameraProjectionMatrix;
  9403. } ).once() )();
  9404. /**
  9405. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9406. *
  9407. * @tsl
  9408. * @type {UniformNode<mat4>}
  9409. */
  9410. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9411. let cameraProjectionMatrixInverse;
  9412. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9413. const matrices = [];
  9414. for ( const subCamera of camera.cameras ) {
  9415. matrices.push( subCamera.projectionMatrixInverse );
  9416. }
  9417. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9418. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9419. } else {
  9420. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9421. }
  9422. return cameraProjectionMatrixInverse;
  9423. } ).once() )();
  9424. /**
  9425. * TSL object that represents the view matrix of the camera used for the current render.
  9426. *
  9427. * @tsl
  9428. * @type {UniformNode<mat4>}
  9429. */
  9430. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9431. let cameraViewMatrix;
  9432. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9433. const matrices = [];
  9434. for ( const subCamera of camera.cameras ) {
  9435. matrices.push( subCamera.matrixWorldInverse );
  9436. }
  9437. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9438. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9439. } else {
  9440. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9441. }
  9442. return cameraViewMatrix;
  9443. } ).once() )();
  9444. /**
  9445. * TSL object that represents the world matrix of the camera used for the current render.
  9446. *
  9447. * @tsl
  9448. * @type {UniformNode<mat4>}
  9449. */
  9450. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9451. let cameraWorldMatrix;
  9452. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9453. const matrices = [];
  9454. for ( const subCamera of camera.cameras ) {
  9455. matrices.push( subCamera.matrixWorld );
  9456. }
  9457. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9458. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9459. } else {
  9460. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9461. }
  9462. return cameraWorldMatrix;
  9463. } ).once() )();
  9464. /**
  9465. * TSL object that represents the normal matrix of the camera used for the current render.
  9466. *
  9467. * @tsl
  9468. * @type {UniformNode<mat3>}
  9469. */
  9470. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9471. let cameraNormalMatrix;
  9472. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9473. const matrices = [];
  9474. for ( const subCamera of camera.cameras ) {
  9475. matrices.push( subCamera.normalMatrix );
  9476. }
  9477. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9478. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9479. } else {
  9480. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9481. }
  9482. return cameraNormalMatrix;
  9483. } ).once() )();
  9484. /**
  9485. * TSL object that represents the position in world space of the camera used for the current render.
  9486. *
  9487. * @tsl
  9488. * @type {UniformNode<vec3>}
  9489. */
  9490. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9491. let cameraPosition;
  9492. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9493. const positions = [];
  9494. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9495. positions.push( new Vector3() );
  9496. }
  9497. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9498. const subCameras = camera.cameras;
  9499. const array = self.array;
  9500. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9501. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9502. }
  9503. } );
  9504. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9505. } else {
  9506. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9507. }
  9508. return cameraPosition;
  9509. } ).once() )();
  9510. /**
  9511. * TSL object that represents the viewport of the camera used for the current render.
  9512. *
  9513. * @tsl
  9514. * @type {UniformNode<vec4>}
  9515. */
  9516. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9517. let cameraViewport;
  9518. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9519. const viewports = [];
  9520. for ( const subCamera of camera.cameras ) {
  9521. viewports.push( subCamera.viewport );
  9522. }
  9523. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9524. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9525. } else {
  9526. // Fallback for single camera
  9527. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9528. }
  9529. return cameraViewport;
  9530. } ).once() )();
  9531. const _sphere = /*@__PURE__*/ new Sphere();
  9532. /**
  9533. * This node can be used to access transformation related metrics of 3D objects.
  9534. * Depending on the selected scope, a different metric is represented as a uniform
  9535. * in the shader. The following scopes are supported:
  9536. *
  9537. * - `POSITION`: The object's position in world space.
  9538. * - `VIEW_POSITION`: The object's position in view/camera space.
  9539. * - `DIRECTION`: The object's direction in world space.
  9540. * - `SCALE`: The object's scale in world space.
  9541. * - `WORLD_MATRIX`: The object's matrix in world space.
  9542. *
  9543. * @augments Node
  9544. */
  9545. class Object3DNode extends Node {
  9546. static get type() {
  9547. return 'Object3DNode';
  9548. }
  9549. /**
  9550. * Constructs a new object 3D node.
  9551. *
  9552. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9553. * @param {?Object3D} [object3d=null] - The 3D object.
  9554. */
  9555. constructor( scope, object3d = null ) {
  9556. super();
  9557. /**
  9558. * The node reports a different type of transformation depending on the scope.
  9559. *
  9560. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9561. */
  9562. this.scope = scope;
  9563. /**
  9564. * The 3D object.
  9565. *
  9566. * @type {?Object3D}
  9567. * @default null
  9568. */
  9569. this.object3d = object3d;
  9570. /**
  9571. * Overwritten since this type of node is updated per object.
  9572. *
  9573. * @type {string}
  9574. * @default 'object'
  9575. */
  9576. this.updateType = NodeUpdateType.OBJECT;
  9577. /**
  9578. * Holds the value of the node as a uniform.
  9579. *
  9580. * @type {UniformNode}
  9581. */
  9582. this.uniformNode = new UniformNode( null );
  9583. }
  9584. /**
  9585. * Overwritten since the node type is inferred from the scope.
  9586. *
  9587. * @return {('mat4'|'vec3'|'float')} The node type.
  9588. */
  9589. getNodeType() {
  9590. const scope = this.scope;
  9591. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9592. return 'mat4';
  9593. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9594. return 'vec3';
  9595. } else if ( scope === Object3DNode.RADIUS ) {
  9596. return 'float';
  9597. }
  9598. }
  9599. /**
  9600. * Updates the uniform value depending on the scope.
  9601. *
  9602. * @param {NodeFrame} frame - The current node frame.
  9603. */
  9604. update( frame ) {
  9605. const object = this.object3d;
  9606. const uniformNode = this.uniformNode;
  9607. const scope = this.scope;
  9608. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9609. uniformNode.value = object.matrixWorld;
  9610. } else if ( scope === Object3DNode.POSITION ) {
  9611. uniformNode.value = uniformNode.value || new Vector3();
  9612. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9613. } else if ( scope === Object3DNode.SCALE ) {
  9614. uniformNode.value = uniformNode.value || new Vector3();
  9615. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9616. } else if ( scope === Object3DNode.DIRECTION ) {
  9617. uniformNode.value = uniformNode.value || new Vector3();
  9618. object.getWorldDirection( uniformNode.value );
  9619. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9620. const camera = frame.camera;
  9621. uniformNode.value = uniformNode.value || new Vector3();
  9622. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9623. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9624. } else if ( scope === Object3DNode.RADIUS ) {
  9625. const geometry = frame.object.geometry;
  9626. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9627. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9628. uniformNode.value = _sphere.radius;
  9629. }
  9630. }
  9631. /**
  9632. * Generates the code snippet of the uniform node. The node type of the uniform
  9633. * node also depends on the selected scope.
  9634. *
  9635. * @param {NodeBuilder} builder - The current node builder.
  9636. * @return {string} The generated code snippet.
  9637. */
  9638. generate( builder ) {
  9639. const scope = this.scope;
  9640. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9641. this.uniformNode.nodeType = 'mat4';
  9642. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9643. this.uniformNode.nodeType = 'vec3';
  9644. } else if ( scope === Object3DNode.RADIUS ) {
  9645. this.uniformNode.nodeType = 'float';
  9646. }
  9647. return this.uniformNode.build( builder );
  9648. }
  9649. serialize( data ) {
  9650. super.serialize( data );
  9651. data.scope = this.scope;
  9652. }
  9653. deserialize( data ) {
  9654. super.deserialize( data );
  9655. this.scope = data.scope;
  9656. }
  9657. }
  9658. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9659. Object3DNode.POSITION = 'position';
  9660. Object3DNode.SCALE = 'scale';
  9661. Object3DNode.VIEW_POSITION = 'viewPosition';
  9662. Object3DNode.DIRECTION = 'direction';
  9663. Object3DNode.RADIUS = 'radius';
  9664. /**
  9665. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9666. *
  9667. * @tsl
  9668. * @function
  9669. * @param {?Object3D} [object3d] - The 3D object.
  9670. * @returns {Object3DNode<vec3>}
  9671. */
  9672. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9673. /**
  9674. * TSL function for creating an object 3D node that represents the object's world matrix.
  9675. *
  9676. * @tsl
  9677. * @function
  9678. * @param {?Object3D} [object3d] - The 3D object.
  9679. * @returns {Object3DNode<mat4>}
  9680. */
  9681. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9682. /**
  9683. * TSL function for creating an object 3D node that represents the object's position in world space.
  9684. *
  9685. * @tsl
  9686. * @function
  9687. * @param {?Object3D} [object3d] - The 3D object.
  9688. * @returns {Object3DNode<vec3>}
  9689. */
  9690. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9691. /**
  9692. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9693. *
  9694. * @tsl
  9695. * @function
  9696. * @param {?Object3D} [object3d] - The 3D object.
  9697. * @returns {Object3DNode<vec3>}
  9698. */
  9699. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9700. /**
  9701. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9702. *
  9703. * @tsl
  9704. * @function
  9705. * @param {?Object3D} [object3d] - The 3D object.
  9706. * @returns {Object3DNode<vec3>}
  9707. */
  9708. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9709. /**
  9710. * TSL function for creating an object 3D node that represents the object's radius.
  9711. *
  9712. * @tsl
  9713. * @function
  9714. * @param {?Object3D} [object3d] - The 3D object.
  9715. * @returns {Object3DNode<float>}
  9716. */
  9717. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9718. /**
  9719. * This type of node is a specialized version of `Object3DNode`
  9720. * with larger set of model related metrics. Unlike `Object3DNode`,
  9721. * `ModelNode` extracts the reference to the 3D object from the
  9722. * current node frame state.
  9723. *
  9724. * @augments Object3DNode
  9725. */
  9726. class ModelNode extends Object3DNode {
  9727. static get type() {
  9728. return 'ModelNode';
  9729. }
  9730. /**
  9731. * Constructs a new object model node.
  9732. *
  9733. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9734. */
  9735. constructor( scope ) {
  9736. super( scope );
  9737. }
  9738. /**
  9739. * Extracts the model reference from the frame state and then
  9740. * updates the uniform value depending on the scope.
  9741. *
  9742. * @param {NodeFrame} frame - The current node frame.
  9743. */
  9744. update( frame ) {
  9745. this.object3d = frame.object;
  9746. super.update( frame );
  9747. }
  9748. }
  9749. /**
  9750. * TSL object that represents the object's direction in world space.
  9751. *
  9752. * @tsl
  9753. * @type {ModelNode<vec3>}
  9754. */
  9755. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9756. /**
  9757. * TSL object that represents the object's world matrix.
  9758. *
  9759. * @tsl
  9760. * @type {ModelNode<mat4>}
  9761. */
  9762. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9763. /**
  9764. * TSL object that represents the object's position in world space.
  9765. *
  9766. * @tsl
  9767. * @type {ModelNode<vec3>}
  9768. */
  9769. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9770. /**
  9771. * TSL object that represents the object's scale in world space.
  9772. *
  9773. * @tsl
  9774. * @type {ModelNode<vec3>}
  9775. */
  9776. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9777. /**
  9778. * TSL object that represents the object's position in view/camera space.
  9779. *
  9780. * @tsl
  9781. * @type {ModelNode<vec3>}
  9782. */
  9783. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9784. /**
  9785. * TSL object that represents the object's radius.
  9786. *
  9787. * @tsl
  9788. * @type {ModelNode<float>}
  9789. */
  9790. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9791. /**
  9792. * TSL object that represents the object's normal matrix.
  9793. *
  9794. * @tsl
  9795. * @type {UniformNode<mat3>}
  9796. */
  9797. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9798. /**
  9799. * TSL object that represents the object's inverse world matrix.
  9800. *
  9801. * @tsl
  9802. * @type {UniformNode<mat4>}
  9803. */
  9804. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9805. /**
  9806. * TSL object that represents the object's model view matrix.
  9807. *
  9808. * @tsl
  9809. * @type {Node<mat4>}
  9810. */
  9811. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9812. return builder.context.modelViewMatrix || mediumpModelViewMatrix;
  9813. } ).once() )().toVar( 'modelViewMatrix' );
  9814. // GPU Precision
  9815. /**
  9816. * TSL object that represents the object's model view in `mediump` precision.
  9817. *
  9818. * @tsl
  9819. * @type {Node<mat4>}
  9820. */
  9821. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9822. // CPU Precision
  9823. /**
  9824. * TSL object that represents the object's model view in `highp` precision
  9825. * which is achieved by computing the matrix in JS and not in the shader.
  9826. *
  9827. * @tsl
  9828. * @type {Node<mat4>}
  9829. */
  9830. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9831. builder.context.isHighPrecisionModelViewMatrix = true;
  9832. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9833. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9834. } );
  9835. } ).once() )().toVar( 'highpModelViewMatrix' );
  9836. /**
  9837. * TSL object that represents the object's model normal view in `highp` precision
  9838. * which is achieved by computing the matrix in JS and not in the shader.
  9839. *
  9840. * @tsl
  9841. * @type {Node<mat3>}
  9842. */
  9843. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9844. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9845. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9846. if ( isHighPrecisionModelViewMatrix !== true ) {
  9847. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9848. }
  9849. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9850. } );
  9851. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9852. /**
  9853. * TSL object that represents the clip space position of the current rendered object.
  9854. *
  9855. * @tsl
  9856. * @type {VaryingNode<vec4>}
  9857. */
  9858. const clipSpace = /*@__PURE__*/ ( Fn( ( builder ) => {
  9859. if ( builder.shaderStage !== 'fragment' ) {
  9860. warnOnce( 'TSL: `clipSpace` is only available in fragment stage.' );
  9861. return vec4();
  9862. }
  9863. return builder.context.clipSpace.toVarying( 'v_clipSpace' );
  9864. } ).once() )();
  9865. /**
  9866. * TSL object that represents the position attribute of the current rendered object.
  9867. *
  9868. * @tsl
  9869. * @type {AttributeNode<vec3>}
  9870. */
  9871. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9872. /**
  9873. * TSL object that represents the vertex position in local space of the current rendered object.
  9874. *
  9875. * @tsl
  9876. * @type {AttributeNode<vec3>}
  9877. */
  9878. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9879. /**
  9880. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9881. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9882. *
  9883. * @tsl
  9884. * @type {AttributeNode<vec3>}
  9885. */
  9886. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9887. /**
  9888. * TSL object that represents the vertex position in world space of the current rendered object.
  9889. *
  9890. * @tsl
  9891. * @type {VaryingNode<vec3>}
  9892. */
  9893. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9894. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9895. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9896. /**
  9897. * TSL object that represents the position world direction of the current rendered object.
  9898. *
  9899. * @tsl
  9900. * @type {Node<vec3>}
  9901. */
  9902. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9903. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9904. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9905. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9906. /**
  9907. * TSL object that represents the vertex position in view space of the current rendered object.
  9908. *
  9909. * @tsl
  9910. * @type {VaryingNode<vec3>}
  9911. */
  9912. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9913. if ( builder.shaderStage === 'fragment' && builder.material.vertexNode ) {
  9914. // reconstruct view position from clip space
  9915. const viewPos = cameraProjectionMatrixInverse.mul( clipSpace );
  9916. return viewPos.xyz.div( viewPos.w ).toVar( 'positionView' );
  9917. }
  9918. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9919. }, 'vec3' ).once( [ 'POSITION', 'VERTEX' ] ) )();
  9920. /**
  9921. * TSL object that represents the position view direction of the current rendered object.
  9922. *
  9923. * @tsl
  9924. * @type {VaryingNode<vec3>}
  9925. */
  9926. const positionViewDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9927. let output;
  9928. if ( builder.camera.isOrthographicCamera ) {
  9929. output = vec3( 0, 0, 1 );
  9930. } else {
  9931. output = positionView.negate().toVarying( 'v_positionViewDirection' ).normalize();
  9932. }
  9933. return output.toVar( 'positionViewDirection' );
  9934. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9935. /**
  9936. * This node can be used to evaluate whether a primitive is front or back facing.
  9937. *
  9938. * @augments Node
  9939. */
  9940. class FrontFacingNode extends Node {
  9941. static get type() {
  9942. return 'FrontFacingNode';
  9943. }
  9944. /**
  9945. * Constructs a new front facing node.
  9946. */
  9947. constructor() {
  9948. super( 'bool' );
  9949. /**
  9950. * This flag can be used for type testing.
  9951. *
  9952. * @type {boolean}
  9953. * @readonly
  9954. * @default true
  9955. */
  9956. this.isFrontFacingNode = true;
  9957. }
  9958. generate( builder ) {
  9959. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9960. //
  9961. const { material } = builder;
  9962. if ( material.side === BackSide ) {
  9963. return 'false';
  9964. }
  9965. return builder.getFrontFacing();
  9966. }
  9967. }
  9968. /**
  9969. * TSL object that represents whether a primitive is front or back facing
  9970. *
  9971. * @tsl
  9972. * @type {FrontFacingNode<bool>}
  9973. */
  9974. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9975. /**
  9976. * TSL object that represents the front facing status as a number instead of a bool.
  9977. * `1` means front facing, `-1` means back facing.
  9978. *
  9979. * @tsl
  9980. * @type {Node<float>}
  9981. */
  9982. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9983. /**
  9984. * Converts a direction vector to a face direction vector based on the material's side.
  9985. *
  9986. * If the material is set to `BackSide`, the direction is inverted.
  9987. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9988. *
  9989. * @tsl
  9990. * @param {Node<vec3>} direction - The direction vector to convert.
  9991. * @returns {Node<vec3>} The converted direction vector.
  9992. */
  9993. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9994. const side = material.side;
  9995. if ( side === BackSide ) {
  9996. direction = direction.mul( -1 );
  9997. } else if ( side === DoubleSide ) {
  9998. direction = direction.mul( faceDirection );
  9999. }
  10000. return direction;
  10001. } );
  10002. /**
  10003. * TSL object that represents the normal attribute of the current rendered object in local space.
  10004. *
  10005. * @tsl
  10006. * @type {Node<vec3>}
  10007. */
  10008. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  10009. /**
  10010. * TSL object that represents the vertex normal of the current rendered object in local space.
  10011. *
  10012. * @tsl
  10013. * @type {Node<vec3>}
  10014. */
  10015. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  10016. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  10017. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  10018. return vec3( 0, 1, 0 );
  10019. }
  10020. return normalGeometry;
  10021. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  10022. /**
  10023. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  10024. *
  10025. * @tsl
  10026. * @type {Node<vec3>}
  10027. */
  10028. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  10029. /**
  10030. * TSL object that represents the vertex normal of the current rendered object in view space.
  10031. *
  10032. * @tsl
  10033. * @type {Node<vec3>}
  10034. */
  10035. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10036. let node;
  10037. if ( builder.isFlatShading() ) {
  10038. node = normalFlat;
  10039. } else {
  10040. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  10041. }
  10042. return node;
  10043. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  10044. /**
  10045. * TSL object that represents the vertex normal of the current rendered object in world space.
  10046. *
  10047. * @tsl
  10048. * @type {Node<vec3>}
  10049. */
  10050. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  10051. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  10052. if ( builder.isFlatShading() !== true ) {
  10053. normal = normal.toVarying( 'v_normalWorldGeometry' );
  10054. }
  10055. return normal.normalize().toVar( 'normalWorldGeometry' );
  10056. }, 'vec3' ).once() )();
  10057. /**
  10058. * TSL object that represents the vertex normal of the current rendered object in view space.
  10059. *
  10060. * @tsl
  10061. * @type {Node<vec3>}
  10062. */
  10063. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10064. let node;
  10065. if ( builder.subBuildFn === 'NORMAL' || builder.subBuildFn === 'VERTEX' ) {
  10066. node = normalViewGeometry;
  10067. if ( builder.isFlatShading() !== true ) {
  10068. node = directionToFaceDirection( node );
  10069. }
  10070. } else {
  10071. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10072. node = builder.context.setupNormal().context( { getUV: null } );
  10073. }
  10074. return node;
  10075. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  10076. /**
  10077. * TSL object that represents the vertex normal of the current rendered object in world space.
  10078. *
  10079. * @tsl
  10080. * @type {Node<vec3>}
  10081. */
  10082. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  10083. /**
  10084. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  10085. *
  10086. * @tsl
  10087. * @type {Node<vec3>}
  10088. */
  10089. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  10090. let node;
  10091. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  10092. node = normalView;
  10093. } else {
  10094. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  10095. node = context.setupClearcoatNormal().context( { getUV: null } );
  10096. }
  10097. return node;
  10098. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  10099. /**
  10100. * Transforms the normal with the given matrix.
  10101. *
  10102. * @tsl
  10103. * @function
  10104. * @param {Node<vec3>} normal - The normal.
  10105. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  10106. * @return {Node<vec3>} The transformed normal.
  10107. */
  10108. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  10109. const m = mat3( matrix );
  10110. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  10111. return m.mul( transformedNormal ).xyz;
  10112. } );
  10113. /**
  10114. * Transforms the given normal from local to view space.
  10115. *
  10116. * @tsl
  10117. * @function
  10118. * @param {Node<vec3>} normal - The normal.
  10119. * @param {NodeBuilder} builder - The current node builder.
  10120. * @return {Node<vec3>} The transformed normal.
  10121. */
  10122. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  10123. const modelNormalViewMatrix = builder.context.modelNormalViewMatrix;
  10124. if ( modelNormalViewMatrix ) {
  10125. return modelNormalViewMatrix.transformDirection( normal );
  10126. }
  10127. //
  10128. const transformedNormal = modelNormalMatrix.mul( normal );
  10129. return cameraViewMatrix.transformDirection( transformedNormal );
  10130. } );
  10131. // Deprecated
  10132. /**
  10133. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  10134. *
  10135. * @tsl
  10136. * @type {Node<vec3>}
  10137. * @deprecated since r178. Use `normalView` instead.
  10138. */
  10139. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  10140. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  10141. return normalView;
  10142. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10143. /**
  10144. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  10145. *
  10146. * @tsl
  10147. * @type {Node<vec3>}
  10148. * @deprecated since r178. Use `normalWorld` instead.
  10149. */
  10150. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  10151. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  10152. return normalWorld;
  10153. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10154. /**
  10155. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  10156. *
  10157. * @tsl
  10158. * @type {Node<vec3>}
  10159. * @deprecated since r178. Use `clearcoatNormalView` instead.
  10160. */
  10161. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  10162. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  10163. return clearcoatNormalView;
  10164. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  10165. const _e1$1 = /*@__PURE__*/ new Euler();
  10166. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10167. /**
  10168. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  10169. *
  10170. * @tsl
  10171. * @type {UniformNode<float>}
  10172. */
  10173. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  10174. /**
  10175. * TSL object that represents the intensity of environment maps of PBR materials.
  10176. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  10177. *
  10178. * @tsl
  10179. * @type {Node<float>}
  10180. */
  10181. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  10182. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  10183. } );
  10184. /**
  10185. * TSL object that represents the rotation of environment maps.
  10186. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  10187. * rotation of `scene.environment` instead.
  10188. *
  10189. * @tsl
  10190. * @type {Node<mat4>}
  10191. */
  10192. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  10193. return frame.material;
  10194. } ).onObjectUpdate( function ( { material, scene } ) {
  10195. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  10196. if ( rotation ) {
  10197. _e1$1.copy( rotation );
  10198. _m1$1.makeRotationFromEuler( _e1$1 );
  10199. } else {
  10200. _m1$1.identity();
  10201. }
  10202. return _m1$1;
  10203. } );
  10204. /**
  10205. * The reflect vector in view space.
  10206. *
  10207. * @tsl
  10208. * @type {Node<vec3>}
  10209. */
  10210. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  10211. /**
  10212. * The refract vector in view space.
  10213. *
  10214. * @tsl
  10215. * @type {Node<vec3>}
  10216. */
  10217. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  10218. /**
  10219. * Used for sampling cube maps when using cube reflection mapping.
  10220. *
  10221. * @tsl
  10222. * @type {Node<vec3>}
  10223. */
  10224. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10225. /**
  10226. * Used for sampling cube maps when using cube refraction mapping.
  10227. *
  10228. * @tsl
  10229. * @type {Node<vec3>}
  10230. */
  10231. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  10232. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  10233. /**
  10234. * This type of uniform node represents a cube texture.
  10235. *
  10236. * @augments TextureNode
  10237. */
  10238. class CubeTextureNode extends TextureNode {
  10239. static get type() {
  10240. return 'CubeTextureNode';
  10241. }
  10242. /**
  10243. * Constructs a new cube texture node.
  10244. *
  10245. * @param {CubeTexture} value - The cube texture.
  10246. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10247. * @param {?Node<int>} [levelNode=null] - The level node.
  10248. * @param {?Node<float>} [biasNode=null] - The bias node.
  10249. */
  10250. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  10251. super( value, uvNode, levelNode, biasNode );
  10252. /**
  10253. * This flag can be used for type testing.
  10254. *
  10255. * @type {boolean}
  10256. * @readonly
  10257. * @default true
  10258. */
  10259. this.isCubeTextureNode = true;
  10260. }
  10261. /**
  10262. * Overwrites the default implementation to return the appropriate cube texture type.
  10263. *
  10264. * @param {NodeBuilder} builder - The current node builder.
  10265. * @return {string} The input type.
  10266. */
  10267. getInputType( /*builder*/ ) {
  10268. if ( this.value.isDepthTexture === true ) {
  10269. return 'cubeDepthTexture';
  10270. }
  10271. return 'cubeTexture';
  10272. }
  10273. /**
  10274. * Returns a default uvs based on the mapping type of the cube texture.
  10275. *
  10276. * @return {Node<vec3>} The default uv attribute.
  10277. */
  10278. getDefaultUV() {
  10279. const texture = this.value;
  10280. if ( texture.mapping === CubeReflectionMapping ) {
  10281. return reflectVector;
  10282. } else if ( texture.mapping === CubeRefractionMapping ) {
  10283. return refractVector;
  10284. } else {
  10285. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  10286. return vec3( 0, 0, 0 );
  10287. }
  10288. }
  10289. /**
  10290. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  10291. * for cube textures. The uv transformation matrix is not applied to cube textures.
  10292. *
  10293. * @param {boolean} value - The update toggle.
  10294. */
  10295. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  10296. /**
  10297. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  10298. * to modify the uv node for correct sampling.
  10299. *
  10300. * @param {NodeBuilder} builder - The current node builder.
  10301. * @param {Node} uvNode - The uv node to setup.
  10302. * @return {Node} The updated uv node.
  10303. */
  10304. setupUV( builder, uvNode ) {
  10305. const texture = this.value;
  10306. // Depth textures (shadow maps) - no environment rotation, Y flip for WebGPU
  10307. if ( texture.isDepthTexture === true ) {
  10308. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  10309. return vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  10310. }
  10311. return uvNode;
  10312. }
  10313. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  10314. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  10315. }
  10316. return materialEnvRotation.mul( uvNode );
  10317. }
  10318. /**
  10319. * Generates the uv code snippet.
  10320. *
  10321. * @param {NodeBuilder} builder - The current node builder.
  10322. * @param {Node} cubeUV - The uv node to generate code for.
  10323. * @return {string} The generated code snippet.
  10324. */
  10325. generateUV( builder, cubeUV ) {
  10326. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  10327. }
  10328. }
  10329. /**
  10330. * TSL function for creating a cube texture node.
  10331. *
  10332. * @tsl
  10333. * @function
  10334. * @param {CubeTexture} value - The cube texture.
  10335. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10336. * @param {?Node<int>} [levelNode=null] - The level node.
  10337. * @param {?Node<float>} [biasNode=null] - The bias node.
  10338. * @returns {CubeTextureNode}
  10339. */
  10340. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  10341. /**
  10342. * TSL function for creating a cube texture uniform node.
  10343. *
  10344. * @tsl
  10345. * @function
  10346. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  10347. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  10348. * @param {?Node<int>} [levelNode=null] - The level node.
  10349. * @param {?Node<float>} [biasNode=null] - The bias node.
  10350. * @returns {CubeTextureNode}
  10351. */
  10352. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  10353. let textureNode;
  10354. if ( value && value.isCubeTextureNode === true ) {
  10355. textureNode = nodeObject( value.clone() );
  10356. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  10357. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  10358. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  10359. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  10360. } else {
  10361. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  10362. }
  10363. return textureNode;
  10364. };
  10365. /**
  10366. * TSL function for creating a uniform cube texture node.
  10367. *
  10368. * @tsl
  10369. * @function
  10370. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  10371. * @returns {CubeTextureNode}
  10372. */
  10373. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  10374. // TODO: Avoid duplicated code and use only ReferenceBaseNode or ReferenceNode
  10375. /**
  10376. * This class is only relevant if the referenced property is array-like.
  10377. * In this case, `ReferenceElementNode` allows to refer to a specific
  10378. * element inside the data structure via an index.
  10379. *
  10380. * @augments ArrayElementNode
  10381. */
  10382. class ReferenceElementNode extends ArrayElementNode {
  10383. static get type() {
  10384. return 'ReferenceElementNode';
  10385. }
  10386. /**
  10387. * Constructs a new reference element node.
  10388. *
  10389. * @param {?ReferenceNode} referenceNode - The reference node.
  10390. * @param {Node} indexNode - The index node that defines the element access.
  10391. */
  10392. constructor( referenceNode, indexNode ) {
  10393. super( referenceNode, indexNode );
  10394. /**
  10395. * Similar to {@link ReferenceNode#reference}, an additional
  10396. * property references to the current node.
  10397. *
  10398. * @type {?ReferenceNode}
  10399. * @default null
  10400. */
  10401. this.referenceNode = referenceNode;
  10402. /**
  10403. * This flag can be used for type testing.
  10404. *
  10405. * @type {boolean}
  10406. * @readonly
  10407. * @default true
  10408. */
  10409. this.isReferenceElementNode = true;
  10410. }
  10411. /**
  10412. * This method is overwritten since the node type is inferred from
  10413. * the uniform type of the reference node.
  10414. *
  10415. * @return {string} The node type.
  10416. */
  10417. getNodeType() {
  10418. return this.referenceNode.uniformType;
  10419. }
  10420. generate( builder ) {
  10421. const snippet = super.generate( builder );
  10422. const arrayType = this.referenceNode.getNodeType();
  10423. const elementType = this.getNodeType();
  10424. return builder.format( snippet, arrayType, elementType );
  10425. }
  10426. }
  10427. /**
  10428. * This type of node establishes a reference to a property of another object.
  10429. * In this way, the value of the node is automatically linked to the value of
  10430. * referenced object. Reference nodes internally represent the linked value
  10431. * as a uniform.
  10432. *
  10433. * @augments Node
  10434. */
  10435. class ReferenceNode extends Node {
  10436. static get type() {
  10437. return 'ReferenceNode';
  10438. }
  10439. /**
  10440. * Constructs a new reference node.
  10441. *
  10442. * @param {string} property - The name of the property the node refers to.
  10443. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10444. * @param {?Object} [object=null] - The object the property belongs to.
  10445. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10446. */
  10447. constructor( property, uniformType, object = null, count = null ) {
  10448. super();
  10449. /**
  10450. * The name of the property the node refers to.
  10451. *
  10452. * @type {string}
  10453. */
  10454. this.property = property;
  10455. /**
  10456. * The uniform type that should be used to represent the property value.
  10457. *
  10458. * @type {string}
  10459. */
  10460. this.uniformType = uniformType;
  10461. /**
  10462. * The object the property belongs to.
  10463. *
  10464. * @type {?Object}
  10465. * @default null
  10466. */
  10467. this.object = object;
  10468. /**
  10469. * When the linked property is an array, this parameter defines its length.
  10470. *
  10471. * @type {?number}
  10472. * @default null
  10473. */
  10474. this.count = count;
  10475. /**
  10476. * The property name might have dots so nested properties can be referred.
  10477. * The hierarchy of the names is stored inside this array.
  10478. *
  10479. * @type {Array<string>}
  10480. */
  10481. this.properties = property.split( '.' );
  10482. /**
  10483. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10484. * since the final reference might be updated from calling code.
  10485. *
  10486. * @type {?Object}
  10487. * @default null
  10488. */
  10489. this.reference = object;
  10490. /**
  10491. * The uniform node that holds the value of the reference node.
  10492. *
  10493. * @type {UniformNode}
  10494. * @default null
  10495. */
  10496. this.node = null;
  10497. /**
  10498. * The uniform group of the internal uniform.
  10499. *
  10500. * @type {UniformGroupNode}
  10501. * @default null
  10502. */
  10503. this.group = null;
  10504. /**
  10505. * An optional label of the internal uniform node.
  10506. *
  10507. * @type {?string}
  10508. * @default null
  10509. */
  10510. this.name = null;
  10511. /**
  10512. * Overwritten since reference nodes are updated per object.
  10513. *
  10514. * @type {string}
  10515. * @default 'object'
  10516. */
  10517. this.updateType = NodeUpdateType.OBJECT;
  10518. }
  10519. /**
  10520. * When the referred property is array-like, this method can be used
  10521. * to access elements via an index node.
  10522. *
  10523. * @param {IndexNode} indexNode - indexNode.
  10524. * @return {ReferenceElementNode} A reference to an element.
  10525. */
  10526. element( indexNode ) {
  10527. return new ReferenceElementNode( this, nodeObject( indexNode ) );
  10528. }
  10529. /**
  10530. * Sets the uniform group for this reference node.
  10531. *
  10532. * @param {UniformGroupNode} group - The uniform group to set.
  10533. * @return {ReferenceNode} A reference to this node.
  10534. */
  10535. setGroup( group ) {
  10536. this.group = group;
  10537. return this;
  10538. }
  10539. /**
  10540. * Sets the name for the internal uniform.
  10541. *
  10542. * @param {string} name - The label to set.
  10543. * @return {ReferenceNode} A reference to this node.
  10544. */
  10545. setName( name ) {
  10546. this.name = name;
  10547. return this;
  10548. }
  10549. /**
  10550. * Sets the label for the internal uniform.
  10551. *
  10552. * @deprecated
  10553. * @param {string} name - The label to set.
  10554. * @return {ReferenceNode} A reference to this node.
  10555. */
  10556. label( name ) {
  10557. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10558. return this.setName( name );
  10559. }
  10560. /**
  10561. * Sets the node type which automatically defines the internal
  10562. * uniform type.
  10563. *
  10564. * @param {string} uniformType - The type to set.
  10565. */
  10566. setNodeType( uniformType ) {
  10567. let node = null;
  10568. if ( this.count !== null ) {
  10569. node = buffer( null, uniformType, this.count );
  10570. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10571. node = uniformArray( null, uniformType );
  10572. } else if ( uniformType === 'texture' ) {
  10573. node = texture( null );
  10574. } else if ( uniformType === 'cubeTexture' ) {
  10575. node = cubeTexture( null );
  10576. } else {
  10577. node = uniform( null, uniformType );
  10578. }
  10579. if ( this.group !== null ) {
  10580. node.setGroup( this.group );
  10581. }
  10582. if ( this.name !== null ) node.setName( this.name );
  10583. this.node = node;
  10584. }
  10585. /**
  10586. * This method is overwritten since the node type is inferred from
  10587. * the type of the reference node.
  10588. *
  10589. * @param {NodeBuilder} builder - The current node builder.
  10590. * @return {string} The node type.
  10591. */
  10592. getNodeType( builder ) {
  10593. if ( this.node === null ) {
  10594. this.updateReference( builder );
  10595. this.updateValue();
  10596. }
  10597. return this.node.getNodeType( builder );
  10598. }
  10599. /**
  10600. * Returns the property value from the given referred object.
  10601. *
  10602. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10603. * @return {any} The value.
  10604. */
  10605. getValueFromReference( object = this.reference ) {
  10606. const { properties } = this;
  10607. let value = object[ properties[ 0 ] ];
  10608. for ( let i = 1; i < properties.length; i ++ ) {
  10609. value = value[ properties[ i ] ];
  10610. }
  10611. return value;
  10612. }
  10613. /**
  10614. * Allows to update the reference based on the given state. The state is only
  10615. * evaluated {@link ReferenceNode#object} is not set.
  10616. *
  10617. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10618. * @return {Object} The updated reference.
  10619. */
  10620. updateReference( state ) {
  10621. this.reference = this.object !== null ? this.object : state.object;
  10622. return this.reference;
  10623. }
  10624. /**
  10625. * The output of the reference node is the internal uniform node.
  10626. *
  10627. * @param {NodeBuilder} builder - The current node builder.
  10628. * @return {UniformNode} The output node.
  10629. */
  10630. setup( /* builder */ ) {
  10631. this.updateValue();
  10632. return this.node;
  10633. }
  10634. /**
  10635. * Overwritten to update the internal uniform value.
  10636. *
  10637. * @param {NodeFrame} frame - A reference to the current node frame.
  10638. */
  10639. update( /*frame*/ ) {
  10640. this.updateValue();
  10641. }
  10642. /**
  10643. * Retrieves the value from the referred object property and uses it
  10644. * to updated the internal uniform.
  10645. */
  10646. updateValue() {
  10647. if ( this.node === null ) this.setNodeType( this.uniformType );
  10648. const value = this.getValueFromReference();
  10649. if ( Array.isArray( value ) ) {
  10650. this.node.array = value;
  10651. } else {
  10652. this.node.value = value;
  10653. }
  10654. }
  10655. }
  10656. /**
  10657. * TSL function for creating a reference node.
  10658. *
  10659. * @tsl
  10660. * @function
  10661. * @param {string} name - The name of the property the node refers to.
  10662. * @param {string} type - The uniform type that should be used to represent the property value.
  10663. * @param {?Object} [object] - The object the property belongs to.
  10664. * @returns {ReferenceNode}
  10665. */
  10666. const reference = ( name, type, object ) => new ReferenceNode( name, type, object );
  10667. /**
  10668. * TSL function for creating a reference node. Use this function if you want need a reference
  10669. * to an array-like property that should be represented as a uniform buffer.
  10670. *
  10671. * @tsl
  10672. * @function
  10673. * @param {string} name - The name of the property the node refers to.
  10674. * @param {string} type - The uniform type that should be used to represent the property value.
  10675. * @param {number} count - The number of value inside the array-like object.
  10676. * @param {Object} object - An array-like object the property belongs to.
  10677. * @returns {ReferenceNode}
  10678. */
  10679. const referenceBuffer = ( name, type, count, object ) => new ReferenceNode( name, type, object, count );
  10680. /**
  10681. * This node is a special type of reference node which is intended
  10682. * for linking material properties with node values.
  10683. * ```js
  10684. * const opacityNode = materialReference( 'opacity', 'float', material );
  10685. * ```
  10686. * When changing `material.opacity`, the node value of `opacityNode` will
  10687. * automatically be updated.
  10688. *
  10689. * @augments ReferenceNode
  10690. */
  10691. class MaterialReferenceNode extends ReferenceNode {
  10692. static get type() {
  10693. return 'MaterialReferenceNode';
  10694. }
  10695. /**
  10696. * Constructs a new material reference node.
  10697. *
  10698. * @param {string} property - The name of the property the node refers to.
  10699. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10700. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10701. * the node refers to the material of the current rendered object.
  10702. */
  10703. constructor( property, inputType, material = null ) {
  10704. super( property, inputType, material );
  10705. /**
  10706. * The material the property belongs to. When no material is set,
  10707. * the node refers to the material of the current rendered object.
  10708. *
  10709. * @type {?Material}
  10710. * @default null
  10711. */
  10712. this.material = material;
  10713. /**
  10714. * This flag can be used for type testing.
  10715. *
  10716. * @type {boolean}
  10717. * @readonly
  10718. * @default true
  10719. */
  10720. this.isMaterialReferenceNode = true;
  10721. }
  10722. /**
  10723. * Updates the reference based on the given state. The state is only evaluated
  10724. * {@link MaterialReferenceNode#material} is not set.
  10725. *
  10726. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10727. * @return {Object} The updated reference.
  10728. */
  10729. updateReference( state ) {
  10730. this.reference = this.material !== null ? this.material : state.material;
  10731. return this.reference;
  10732. }
  10733. }
  10734. /**
  10735. * TSL function for creating a material reference node.
  10736. *
  10737. * @tsl
  10738. * @function
  10739. * @param {string} name - The name of the property the node refers to.
  10740. * @param {string} type - The uniform type that should be used to represent the property value.
  10741. * @param {?Material} [material=null] - The material the property belongs to.
  10742. * When no material is set, the node refers to the material of the current rendered object.
  10743. * @returns {MaterialReferenceNode}
  10744. */
  10745. const materialReference = ( name, type, material = null ) => new MaterialReferenceNode( name, type, material );
  10746. // Normal Mapping Without Precomputed Tangents
  10747. // http://www.thetenthplanet.de/archives/1180
  10748. const uv = uv$1();
  10749. const q0 = positionView.dFdx();
  10750. const q1 = positionView.dFdy();
  10751. const st0 = uv.dFdx();
  10752. const st1 = uv.dFdy();
  10753. const N = normalView;
  10754. const q1perp = q1.cross( N );
  10755. const q0perp = N.cross( q0 );
  10756. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10757. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10758. const det = T.dot( T ).max( B.dot( B ) );
  10759. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10760. /**
  10761. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10762. * Useful for normal mapping without precomputed tangents.
  10763. *
  10764. * Reference: http://www.thetenthplanet.de/archives/1180
  10765. *
  10766. * @tsl
  10767. * @type {Node<vec3>}
  10768. */
  10769. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10770. /**
  10771. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10772. * Complements the tangentViewFrame for constructing the tangent space basis.
  10773. *
  10774. * Reference: http://www.thetenthplanet.de/archives/1180
  10775. *
  10776. * @tsl
  10777. * @type {Node<vec3>}
  10778. */
  10779. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10780. /**
  10781. * TSL object that represents the tangent attribute of the current rendered object.
  10782. *
  10783. * @tsl
  10784. * @type {Node<vec4>}
  10785. */
  10786. const tangentGeometry = /*@__PURE__*/ attribute( 'tangent', 'vec4' );
  10787. /**
  10788. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10789. *
  10790. * @tsl
  10791. * @type {Node<vec3>}
  10792. */
  10793. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10794. /**
  10795. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10796. *
  10797. * @tsl
  10798. * @type {Node<vec3>}
  10799. */
  10800. const tangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10801. let node;
  10802. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  10803. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10804. } else {
  10805. node = tangentViewFrame;
  10806. }
  10807. if ( builder.isFlatShading() !== true ) {
  10808. node = directionToFaceDirection( node );
  10809. }
  10810. return node;
  10811. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10812. /**
  10813. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10814. *
  10815. * @tsl
  10816. * @type {Node<vec3>}
  10817. */
  10818. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10819. /**
  10820. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10821. *
  10822. * @tsl
  10823. * @private
  10824. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10825. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10826. * @returns {Node<vec3>} The bitangent node.
  10827. */
  10828. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  10829. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10830. if ( builder.subBuildFn === 'NORMAL' && builder.isFlatShading() !== true ) {
  10831. bitangent = bitangent.toVarying( varyingName );
  10832. }
  10833. return bitangent;
  10834. } ).once( [ 'NORMAL' ] );
  10835. /**
  10836. * TSL object that represents the bitangent attribute of the current rendered object.
  10837. *
  10838. * @tsl
  10839. * @type {Node<vec3>}
  10840. */
  10841. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10842. /**
  10843. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10844. *
  10845. * @tsl
  10846. * @type {Node<vec3>}
  10847. */
  10848. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10849. /**
  10850. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10851. *
  10852. * @tsl
  10853. * @type {Node<vec3>}
  10854. */
  10855. const bitangentView = /*@__PURE__*/ ( Fn( ( builder ) => {
  10856. let node;
  10857. if ( builder.subBuildFn === 'VERTEX' || builder.geometry.hasAttribute( 'tangent' ) ) {
  10858. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10859. } else {
  10860. node = bitangentViewFrame;
  10861. }
  10862. if ( builder.isFlatShading() !== true ) {
  10863. node = directionToFaceDirection( node );
  10864. }
  10865. return node;
  10866. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10867. /**
  10868. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10869. *
  10870. * @tsl
  10871. * @type {Node<vec3>}
  10872. */
  10873. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10874. /**
  10875. * TSL object that represents the TBN matrix in view space.
  10876. *
  10877. * @tsl
  10878. * @type {Node<mat3>}
  10879. */
  10880. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10881. /**
  10882. * TSL object that represents the parallax direction.
  10883. *
  10884. * @tsl
  10885. * @type {Node<mat3>}
  10886. */
  10887. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10888. /**
  10889. * TSL function for computing parallax uv coordinates.
  10890. *
  10891. * @tsl
  10892. * @function
  10893. * @param {Node<vec2>} uv - A uv node.
  10894. * @param {Node<vec2>} scale - A scale node.
  10895. * @returns {Node<vec2>} Parallax uv coordinates.
  10896. */
  10897. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10898. /**
  10899. * TSL function for computing bent normals.
  10900. *
  10901. * @tsl
  10902. * @function
  10903. * @returns {Node<vec3>} Bent normals.
  10904. */
  10905. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10906. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10907. let bentNormal = anisotropyB.cross( positionViewDirection );
  10908. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10909. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10910. return bentNormal;
  10911. } ).once() )();
  10912. /**
  10913. * Packs a direction vector into a color value.
  10914. *
  10915. * @tsl
  10916. * @function
  10917. * @param {Node<vec3>} node - The direction to pack.
  10918. * @return {Node<vec3>} The color.
  10919. */
  10920. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  10921. /**
  10922. * Unpacks a color value into a direction vector.
  10923. *
  10924. * @tsl
  10925. * @function
  10926. * @param {Node<vec3>} node - The color to unpack.
  10927. * @return {Node<vec3>} The direction.
  10928. */
  10929. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  10930. /**
  10931. * Unpacks a tangent space normal, reconstructing the Z component by projecting the X,Y coordinates onto the hemisphere.
  10932. * The X,Y coordinates are expected to be in the [-1, 1] range.
  10933. *
  10934. * @tsl
  10935. * @function
  10936. * @param {Node<vec2>} xy - The X,Y coordinates of the normal.
  10937. * @return {Node<vec3>} The resulting normal.
  10938. */
  10939. const unpackNormal = ( xy ) => vec3( xy, sqrt( saturate( float( 1.0 ).sub( dot( xy, xy ) ) ) ) );
  10940. /**
  10941. * This class can be used for applying normals maps to materials.
  10942. *
  10943. * ```js
  10944. * material.normalNode = normalMap( texture( normalTex ) );
  10945. * ```
  10946. *
  10947. * @augments TempNode
  10948. */
  10949. class NormalMapNode extends TempNode {
  10950. static get type() {
  10951. return 'NormalMapNode';
  10952. }
  10953. /**
  10954. * Constructs a new normal map node.
  10955. *
  10956. * @param {Node<vec3>} node - Represents the normal map data.
  10957. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10958. */
  10959. constructor( node, scaleNode = null ) {
  10960. super( 'vec3' );
  10961. /**
  10962. * Represents the normal map data.
  10963. *
  10964. * @type {Node<vec3>}
  10965. */
  10966. this.node = node;
  10967. /**
  10968. * Controls the intensity of the effect.
  10969. *
  10970. * @type {?Node<vec2>}
  10971. * @default null
  10972. */
  10973. this.scaleNode = scaleNode;
  10974. /**
  10975. * The normal map type.
  10976. *
  10977. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10978. * @default TangentSpaceNormalMap
  10979. */
  10980. this.normalMapType = TangentSpaceNormalMap;
  10981. /**
  10982. * Controls how to unpack the sampled normal map values.
  10983. *
  10984. * @type {string}
  10985. * @default NoNormalPacking
  10986. */
  10987. this.unpackNormalMode = NoNormalPacking;
  10988. }
  10989. setup( builder ) {
  10990. const { normalMapType, scaleNode, unpackNormalMode } = this;
  10991. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10992. if ( normalMapType === TangentSpaceNormalMap ) {
  10993. if ( unpackNormalMode === NormalRGPacking ) {
  10994. normalMap = unpackNormal( normalMap.xy );
  10995. } else if ( unpackNormalMode === NormalGAPacking ) {
  10996. normalMap = unpackNormal( normalMap.yw );
  10997. } else if ( unpackNormalMode !== NoNormalPacking ) {
  10998. console.error( `THREE.NodeMaterial: Unexpected unpack normal mode: ${ unpackNormalMode }` );
  10999. }
  11000. } else {
  11001. if ( unpackNormalMode !== NoNormalPacking ) {
  11002. console.error( `THREE.NodeMaterial: Normal map type '${ normalMapType }' is not compatible with unpack normal mode '${ unpackNormalMode }'` );
  11003. }
  11004. }
  11005. if ( scaleNode !== null ) {
  11006. let scale = scaleNode;
  11007. if ( builder.isFlatShading() === true ) {
  11008. scale = directionToFaceDirection( scale );
  11009. }
  11010. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  11011. }
  11012. let output = null;
  11013. if ( normalMapType === ObjectSpaceNormalMap ) {
  11014. output = transformNormalToView( normalMap );
  11015. } else if ( normalMapType === TangentSpaceNormalMap ) {
  11016. output = TBNViewMatrix.mul( normalMap ).normalize();
  11017. } else {
  11018. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  11019. output = normalView; // Fallback to default normal view
  11020. }
  11021. return output;
  11022. }
  11023. }
  11024. /**
  11025. * TSL function for creating a normal map node.
  11026. *
  11027. * @tsl
  11028. * @function
  11029. * @param {Node<vec3>} node - Represents the normal map data.
  11030. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  11031. * @returns {NormalMapNode}
  11032. */
  11033. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  11034. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  11035. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  11036. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  11037. // It's used to preserve the same TextureNode instance
  11038. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  11039. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  11040. return vec2(
  11041. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  11042. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  11043. ).mul( bumpScale );
  11044. } );
  11045. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  11046. const perturbNormalArb = Fn( ( inputs ) => {
  11047. const { surf_pos, surf_norm, dHdxy } = inputs;
  11048. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  11049. const vSigmaX = surf_pos.dFdx().normalize();
  11050. const vSigmaY = surf_pos.dFdy().normalize();
  11051. const vN = surf_norm; // normalized
  11052. const R1 = vSigmaY.cross( vN );
  11053. const R2 = vN.cross( vSigmaX );
  11054. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  11055. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  11056. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  11057. } );
  11058. /**
  11059. * This class can be used for applying bump maps to materials.
  11060. *
  11061. * ```js
  11062. * material.normalNode = bumpMap( texture( bumpTex ) );
  11063. * ```
  11064. *
  11065. * @augments TempNode
  11066. */
  11067. class BumpMapNode extends TempNode {
  11068. static get type() {
  11069. return 'BumpMapNode';
  11070. }
  11071. /**
  11072. * Constructs a new bump map node.
  11073. *
  11074. * @param {Node<float>} textureNode - Represents the bump map data.
  11075. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11076. */
  11077. constructor( textureNode, scaleNode = null ) {
  11078. super( 'vec3' );
  11079. /**
  11080. * Represents the bump map data.
  11081. *
  11082. * @type {Node<float>}
  11083. */
  11084. this.textureNode = textureNode;
  11085. /**
  11086. * Controls the intensity of the bump effect.
  11087. *
  11088. * @type {?Node<float>}
  11089. * @default null
  11090. */
  11091. this.scaleNode = scaleNode;
  11092. }
  11093. setup() {
  11094. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  11095. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  11096. return perturbNormalArb( {
  11097. surf_pos: positionView,
  11098. surf_norm: normalView,
  11099. dHdxy
  11100. } );
  11101. }
  11102. }
  11103. /**
  11104. * TSL function for creating a bump map node.
  11105. *
  11106. * @tsl
  11107. * @function
  11108. * @param {Node<float>} textureNode - Represents the bump map data.
  11109. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  11110. * @returns {BumpMapNode}
  11111. */
  11112. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  11113. const _propertyCache = new Map();
  11114. /**
  11115. * This class should simplify the node access to material properties.
  11116. * It internal uses reference nodes to make sure changes to material
  11117. * properties are automatically reflected to predefined TSL objects
  11118. * like e.g. `materialColor`.
  11119. *
  11120. * @augments Node
  11121. */
  11122. class MaterialNode extends Node {
  11123. static get type() {
  11124. return 'MaterialNode';
  11125. }
  11126. /**
  11127. * Constructs a new material node.
  11128. *
  11129. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  11130. */
  11131. constructor( scope ) {
  11132. super();
  11133. /**
  11134. * The scope defines what material property is referred by the node.
  11135. *
  11136. * @type {string}
  11137. */
  11138. this.scope = scope;
  11139. }
  11140. /**
  11141. * Returns a cached reference node for the given property and type.
  11142. *
  11143. * @param {string} property - The name of the material property.
  11144. * @param {string} type - The uniform type of the property.
  11145. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11146. */
  11147. getCache( property, type ) {
  11148. let node = _propertyCache.get( property );
  11149. if ( node === undefined ) {
  11150. node = materialReference( property, type );
  11151. _propertyCache.set( property, node );
  11152. }
  11153. return node;
  11154. }
  11155. /**
  11156. * Returns a float-typed material reference node for the given property name.
  11157. *
  11158. * @param {string} property - The name of the material property.
  11159. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  11160. */
  11161. getFloat( property ) {
  11162. return this.getCache( property, 'float' );
  11163. }
  11164. /**
  11165. * Returns a color-typed material reference node for the given property name.
  11166. *
  11167. * @param {string} property - The name of the material property.
  11168. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  11169. */
  11170. getColor( property ) {
  11171. return this.getCache( property, 'color' );
  11172. }
  11173. /**
  11174. * Returns a texture-typed material reference node for the given property name.
  11175. *
  11176. * @param {string} property - The name of the material property.
  11177. * @return {MaterialReferenceNode} A material reference node representing the property access.
  11178. */
  11179. getTexture( property ) {
  11180. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  11181. }
  11182. /**
  11183. * The node setup is done depending on the selected scope. Multiple material properties
  11184. * might be grouped into a single node composition if they logically belong together.
  11185. *
  11186. * @param {NodeBuilder} builder - The current node builder.
  11187. * @return {Node} The node representing the selected scope.
  11188. */
  11189. setup( builder ) {
  11190. const material = builder.context.material;
  11191. const scope = this.scope;
  11192. let node = null;
  11193. if ( scope === MaterialNode.COLOR ) {
  11194. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  11195. if ( material.map && material.map.isTexture === true ) {
  11196. node = colorNode.mul( this.getTexture( 'map' ) );
  11197. } else {
  11198. node = colorNode;
  11199. }
  11200. } else if ( scope === MaterialNode.OPACITY ) {
  11201. const opacityNode = this.getFloat( scope );
  11202. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  11203. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  11204. } else {
  11205. node = opacityNode;
  11206. }
  11207. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  11208. if ( material.specularMap && material.specularMap.isTexture === true ) {
  11209. node = this.getTexture( 'specular' ).r;
  11210. } else {
  11211. node = float( 1 );
  11212. }
  11213. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  11214. const specularIntensityNode = this.getFloat( scope );
  11215. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  11216. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  11217. } else {
  11218. node = specularIntensityNode;
  11219. }
  11220. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  11221. const specularColorNode = this.getColor( scope );
  11222. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  11223. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  11224. } else {
  11225. node = specularColorNode;
  11226. }
  11227. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  11228. const roughnessNode = this.getFloat( scope );
  11229. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  11230. node = roughnessNode.mul( this.getTexture( scope ).g );
  11231. } else {
  11232. node = roughnessNode;
  11233. }
  11234. } else if ( scope === MaterialNode.METALNESS ) {
  11235. const metalnessNode = this.getFloat( scope );
  11236. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  11237. node = metalnessNode.mul( this.getTexture( scope ).b );
  11238. } else {
  11239. node = metalnessNode;
  11240. }
  11241. } else if ( scope === MaterialNode.EMISSIVE ) {
  11242. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  11243. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  11244. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  11245. node = emissiveNode.mul( this.getTexture( scope ) );
  11246. } else {
  11247. node = emissiveNode;
  11248. }
  11249. } else if ( scope === MaterialNode.NORMAL ) {
  11250. if ( material.normalMap ) {
  11251. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  11252. node.normalMapType = material.normalMapType;
  11253. if ( material.normalMap.format == RGFormat || material.normalMap.format == RED_GREEN_RGTC2_Format || material.normalMap.format == RG11_EAC_Format ) {
  11254. node.unpackNormalMode = NormalRGPacking;
  11255. }
  11256. } else if ( material.bumpMap ) {
  11257. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  11258. } else {
  11259. node = normalView;
  11260. }
  11261. } else if ( scope === MaterialNode.CLEARCOAT ) {
  11262. const clearcoatNode = this.getFloat( scope );
  11263. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  11264. node = clearcoatNode.mul( this.getTexture( scope ).r );
  11265. } else {
  11266. node = clearcoatNode;
  11267. }
  11268. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  11269. const clearcoatRoughnessNode = this.getFloat( scope );
  11270. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  11271. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  11272. } else {
  11273. node = clearcoatRoughnessNode;
  11274. }
  11275. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  11276. if ( material.clearcoatNormalMap ) {
  11277. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  11278. } else {
  11279. node = normalView;
  11280. }
  11281. } else if ( scope === MaterialNode.SHEEN ) {
  11282. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  11283. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  11284. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  11285. } else {
  11286. node = sheenNode;
  11287. }
  11288. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  11289. const sheenRoughnessNode = this.getFloat( scope );
  11290. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  11291. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  11292. } else {
  11293. node = sheenRoughnessNode;
  11294. }
  11295. node = node.clamp( 0.0001, 1.0 );
  11296. } else if ( scope === MaterialNode.ANISOTROPY ) {
  11297. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  11298. const anisotropyPolar = this.getTexture( scope );
  11299. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  11300. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  11301. } else {
  11302. node = materialAnisotropyVector;
  11303. }
  11304. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  11305. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  11306. if ( material.iridescenceThicknessMap ) {
  11307. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  11308. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  11309. } else {
  11310. node = iridescenceThicknessMaximum;
  11311. }
  11312. } else if ( scope === MaterialNode.TRANSMISSION ) {
  11313. const transmissionNode = this.getFloat( scope );
  11314. if ( material.transmissionMap ) {
  11315. node = transmissionNode.mul( this.getTexture( scope ).r );
  11316. } else {
  11317. node = transmissionNode;
  11318. }
  11319. } else if ( scope === MaterialNode.THICKNESS ) {
  11320. const thicknessNode = this.getFloat( scope );
  11321. if ( material.thicknessMap ) {
  11322. node = thicknessNode.mul( this.getTexture( scope ).g );
  11323. } else {
  11324. node = thicknessNode;
  11325. }
  11326. } else if ( scope === MaterialNode.IOR ) {
  11327. node = this.getFloat( scope );
  11328. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  11329. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  11330. } else if ( scope === MaterialNode.AO ) {
  11331. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  11332. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  11333. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  11334. } else {
  11335. const outputType = this.getNodeType( builder );
  11336. node = this.getCache( scope, outputType );
  11337. }
  11338. return node;
  11339. }
  11340. }
  11341. MaterialNode.ALPHA_TEST = 'alphaTest';
  11342. MaterialNode.COLOR = 'color';
  11343. MaterialNode.OPACITY = 'opacity';
  11344. MaterialNode.SHININESS = 'shininess';
  11345. MaterialNode.SPECULAR = 'specular';
  11346. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  11347. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  11348. MaterialNode.SPECULAR_COLOR = 'specularColor';
  11349. MaterialNode.REFLECTIVITY = 'reflectivity';
  11350. MaterialNode.ROUGHNESS = 'roughness';
  11351. MaterialNode.METALNESS = 'metalness';
  11352. MaterialNode.NORMAL = 'normal';
  11353. MaterialNode.CLEARCOAT = 'clearcoat';
  11354. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  11355. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  11356. MaterialNode.EMISSIVE = 'emissive';
  11357. MaterialNode.ROTATION = 'rotation';
  11358. MaterialNode.SHEEN = 'sheen';
  11359. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  11360. MaterialNode.ANISOTROPY = 'anisotropy';
  11361. MaterialNode.IRIDESCENCE = 'iridescence';
  11362. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  11363. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  11364. MaterialNode.IOR = 'ior';
  11365. MaterialNode.TRANSMISSION = 'transmission';
  11366. MaterialNode.THICKNESS = 'thickness';
  11367. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  11368. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  11369. MaterialNode.LINE_SCALE = 'scale';
  11370. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  11371. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  11372. MaterialNode.LINE_WIDTH = 'linewidth';
  11373. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  11374. MaterialNode.POINT_SIZE = 'size';
  11375. MaterialNode.DISPERSION = 'dispersion';
  11376. MaterialNode.LIGHT_MAP = 'light';
  11377. MaterialNode.AO = 'ao';
  11378. /**
  11379. * TSL object that represents alpha test of the current material.
  11380. *
  11381. * @tsl
  11382. * @type {Node<float>}
  11383. */
  11384. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  11385. /**
  11386. * TSL object that represents the diffuse color of the current material.
  11387. * The value is composed via `color` * `map`.
  11388. *
  11389. * @tsl
  11390. * @type {Node<vec3>}
  11391. */
  11392. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  11393. /**
  11394. * TSL object that represents the shininess of the current material.
  11395. *
  11396. * @tsl
  11397. * @type {Node<float>}
  11398. */
  11399. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  11400. /**
  11401. * TSL object that represents the emissive color of the current material.
  11402. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  11403. *
  11404. * @tsl
  11405. * @type {Node<vec3>}
  11406. */
  11407. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  11408. /**
  11409. * TSL object that represents the opacity of the current material.
  11410. * The value is composed via `opacity` * `alphaMap`.
  11411. *
  11412. * @tsl
  11413. * @type {Node<float>}
  11414. */
  11415. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  11416. /**
  11417. * TSL object that represents the specular of the current material.
  11418. *
  11419. * @tsl
  11420. * @type {Node<vec3>}
  11421. */
  11422. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  11423. /**
  11424. * TSL object that represents the specular intensity of the current material.
  11425. * The value is composed via `specularIntensity` * `specularMap.a`.
  11426. *
  11427. * @tsl
  11428. * @type {Node<float>}
  11429. */
  11430. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  11431. /**
  11432. * TSL object that represents the specular color of the current material.
  11433. * The value is composed via `specularColor` * `specularMap.rgb`.
  11434. *
  11435. * @tsl
  11436. * @type {Node<vec3>}
  11437. */
  11438. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  11439. /**
  11440. * TSL object that represents the specular strength of the current material.
  11441. * The value is composed via `specularMap.r`.
  11442. *
  11443. * @tsl
  11444. * @type {Node<float>}
  11445. */
  11446. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  11447. /**
  11448. * TSL object that represents the reflectivity of the current material.
  11449. *
  11450. * @tsl
  11451. * @type {Node<float>}
  11452. */
  11453. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  11454. /**
  11455. * TSL object that represents the roughness of the current material.
  11456. * The value is composed via `roughness` * `roughnessMap.g`.
  11457. *
  11458. * @tsl
  11459. * @type {Node<float>}
  11460. */
  11461. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  11462. /**
  11463. * TSL object that represents the metalness of the current material.
  11464. * The value is composed via `metalness` * `metalnessMap.b`.
  11465. *
  11466. * @tsl
  11467. * @type {Node<float>}
  11468. */
  11469. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  11470. /**
  11471. * TSL object that represents the normal of the current material.
  11472. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  11473. *
  11474. * @tsl
  11475. * @type {Node<vec3>}
  11476. */
  11477. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11478. /**
  11479. * TSL object that represents the clearcoat of the current material.
  11480. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11481. *
  11482. * @tsl
  11483. * @type {Node<float>}
  11484. */
  11485. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11486. /**
  11487. * TSL object that represents the clearcoat roughness of the current material.
  11488. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11489. *
  11490. * @tsl
  11491. * @type {Node<float>}
  11492. */
  11493. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11494. /**
  11495. * TSL object that represents the clearcoat normal of the current material.
  11496. * The value will be either `clearcoatNormalMap` or `normalView`.
  11497. *
  11498. * @tsl
  11499. * @type {Node<vec3>}
  11500. */
  11501. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11502. /**
  11503. * TSL object that represents the rotation of the current sprite material.
  11504. *
  11505. * @tsl
  11506. * @type {Node<float>}
  11507. */
  11508. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11509. /**
  11510. * TSL object that represents the sheen color of the current material.
  11511. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11512. *
  11513. * @tsl
  11514. * @type {Node<vec3>}
  11515. */
  11516. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11517. /**
  11518. * TSL object that represents the sheen roughness of the current material.
  11519. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11520. *
  11521. * @tsl
  11522. * @type {Node<float>}
  11523. */
  11524. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11525. /**
  11526. * TSL object that represents the anisotropy of the current material.
  11527. *
  11528. * @tsl
  11529. * @type {Node<vec2>}
  11530. */
  11531. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11532. /**
  11533. * TSL object that represents the iridescence of the current material.
  11534. *
  11535. * @tsl
  11536. * @type {Node<float>}
  11537. */
  11538. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11539. /**
  11540. * TSL object that represents the iridescence IOR of the current material.
  11541. *
  11542. * @tsl
  11543. * @type {Node<float>}
  11544. */
  11545. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11546. /**
  11547. * TSL object that represents the iridescence thickness of the current material.
  11548. *
  11549. * @tsl
  11550. * @type {Node<float>}
  11551. */
  11552. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11553. /**
  11554. * TSL object that represents the transmission of the current material.
  11555. * The value is composed via `transmission` * `transmissionMap.r`.
  11556. *
  11557. * @tsl
  11558. * @type {Node<float>}
  11559. */
  11560. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11561. /**
  11562. * TSL object that represents the thickness of the current material.
  11563. * The value is composed via `thickness` * `thicknessMap.g`.
  11564. *
  11565. * @tsl
  11566. * @type {Node<float>}
  11567. */
  11568. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11569. /**
  11570. * TSL object that represents the IOR of the current material.
  11571. *
  11572. * @tsl
  11573. * @type {Node<float>}
  11574. */
  11575. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11576. /**
  11577. * TSL object that represents the attenuation distance of the current material.
  11578. *
  11579. * @tsl
  11580. * @type {Node<float>}
  11581. */
  11582. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11583. /**
  11584. * TSL object that represents the attenuation color of the current material.
  11585. *
  11586. * @tsl
  11587. * @type {Node<vec3>}
  11588. */
  11589. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11590. /**
  11591. * TSL object that represents the scale of the current dashed line material.
  11592. *
  11593. * @tsl
  11594. * @type {Node<float>}
  11595. */
  11596. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11597. /**
  11598. * TSL object that represents the dash size of the current dashed line material.
  11599. *
  11600. * @tsl
  11601. * @type {Node<float>}
  11602. */
  11603. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11604. /**
  11605. * TSL object that represents the gap size of the current dashed line material.
  11606. *
  11607. * @tsl
  11608. * @type {Node<float>}
  11609. */
  11610. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11611. /**
  11612. * TSL object that represents the line width of the current line material.
  11613. *
  11614. * @tsl
  11615. * @type {Node<float>}
  11616. */
  11617. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11618. /**
  11619. * TSL object that represents the dash offset of the current line material.
  11620. *
  11621. * @tsl
  11622. * @type {Node<float>}
  11623. */
  11624. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11625. /**
  11626. * TSL object that represents the point size of the current points material.
  11627. *
  11628. * @tsl
  11629. * @type {Node<float>}
  11630. */
  11631. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11632. /**
  11633. * TSL object that represents the dispersion of the current material.
  11634. *
  11635. * @tsl
  11636. * @type {Node<float>}
  11637. */
  11638. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11639. /**
  11640. * TSL object that represents the light map of the current material.
  11641. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11642. *
  11643. * @tsl
  11644. * @type {Node<vec3>}
  11645. */
  11646. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11647. /**
  11648. * TSL object that represents the ambient occlusion map of the current material.
  11649. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11650. *
  11651. * @tsl
  11652. * @type {Node<float>}
  11653. */
  11654. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11655. /**
  11656. * TSL object that represents the anisotropy vector of the current material.
  11657. *
  11658. * @tsl
  11659. * @type {Node<vec2>}
  11660. */
  11661. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11662. return frame.material;
  11663. } ).onRenderUpdate( function ( { material } ) {
  11664. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11665. } );
  11666. /**
  11667. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11668. *
  11669. * @tsl
  11670. * @type {VaryingNode<vec4>}
  11671. */
  11672. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11673. return builder.context.setupModelViewProjection();
  11674. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11675. /**
  11676. * This class enables element access on instances of {@link StorageBufferNode}.
  11677. * In most cases, it is indirectly used when accessing elements with the
  11678. * {@link StorageBufferNode#element} method.
  11679. *
  11680. * ```js
  11681. * const position = positionStorage.element( instanceIndex );
  11682. * ```
  11683. *
  11684. * @augments ArrayElementNode
  11685. */
  11686. class StorageArrayElementNode extends ArrayElementNode {
  11687. static get type() {
  11688. return 'StorageArrayElementNode';
  11689. }
  11690. /**
  11691. * Constructs storage buffer element node.
  11692. *
  11693. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11694. * @param {Node} indexNode - The index node that defines the element access.
  11695. */
  11696. constructor( storageBufferNode, indexNode ) {
  11697. super( storageBufferNode, indexNode );
  11698. /**
  11699. * This flag can be used for type testing.
  11700. *
  11701. * @type {boolean}
  11702. * @readonly
  11703. * @default true
  11704. */
  11705. this.isStorageArrayElementNode = true;
  11706. }
  11707. /**
  11708. * The storage buffer node.
  11709. *
  11710. * @param {Node} value
  11711. * @type {StorageBufferNode}
  11712. */
  11713. set storageBufferNode( value ) {
  11714. this.node = value;
  11715. }
  11716. get storageBufferNode() {
  11717. return this.node;
  11718. }
  11719. getMemberType( builder, name ) {
  11720. const structTypeNode = this.storageBufferNode.structTypeNode;
  11721. if ( structTypeNode ) {
  11722. return structTypeNode.getMemberType( builder, name );
  11723. }
  11724. return 'void';
  11725. }
  11726. setup( builder ) {
  11727. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11728. if ( this.node.isPBO === true ) {
  11729. builder.setupPBO( this.node );
  11730. }
  11731. }
  11732. return super.setup( builder );
  11733. }
  11734. generate( builder, output ) {
  11735. let snippet;
  11736. const isAssignContext = builder.context.assign;
  11737. //
  11738. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11739. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11740. snippet = builder.generatePBO( this );
  11741. } else {
  11742. snippet = this.node.build( builder );
  11743. }
  11744. } else {
  11745. snippet = super.generate( builder );
  11746. }
  11747. if ( isAssignContext !== true ) {
  11748. const type = this.getNodeType( builder );
  11749. snippet = builder.format( snippet, type, output );
  11750. }
  11751. return snippet;
  11752. }
  11753. }
  11754. /**
  11755. * TSL function for creating a storage element node.
  11756. *
  11757. * @tsl
  11758. * @function
  11759. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11760. * @param {Node} indexNode - The index node that defines the element access.
  11761. * @returns {StorageArrayElementNode}
  11762. */
  11763. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11764. /**
  11765. * This node is used in context of compute shaders and allows to define a
  11766. * storage buffer for data. A typical workflow is to create instances of
  11767. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11768. * setup up a compute shader that writes into the buffers and then convert
  11769. * the storage buffers to attribute nodes for rendering.
  11770. *
  11771. * ```js
  11772. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11773. *
  11774. * const computeInit = Fn( () => { // the compute shader
  11775. *
  11776. * const position = positionBuffer.element( instanceIndex );
  11777. *
  11778. * // compute position data
  11779. *
  11780. * position.x = 1;
  11781. * position.y = 1;
  11782. * position.z = 1;
  11783. *
  11784. * } )().compute( particleCount );
  11785. *
  11786. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11787. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11788. *
  11789. * renderer.computeAsync( computeInit );
  11790. *
  11791. * ```
  11792. *
  11793. * @augments BufferNode
  11794. */
  11795. class StorageBufferNode extends BufferNode {
  11796. static get type() {
  11797. return 'StorageBufferNode';
  11798. }
  11799. /**
  11800. * Constructs a new storage buffer node.
  11801. *
  11802. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11803. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11804. * @param {number} [bufferCount=0] - The buffer count.
  11805. */
  11806. constructor( value, bufferType = null, bufferCount = 0 ) {
  11807. let nodeType, structTypeNode = null;
  11808. if ( bufferType && bufferType.isStruct ) {
  11809. nodeType = 'struct';
  11810. structTypeNode = bufferType.layout;
  11811. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11812. bufferCount = value.count;
  11813. }
  11814. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11815. nodeType = getTypeFromLength( value.itemSize );
  11816. bufferCount = value.count;
  11817. } else {
  11818. nodeType = bufferType;
  11819. }
  11820. super( value, nodeType, bufferCount );
  11821. /**
  11822. * This flag can be used for type testing.
  11823. *
  11824. * @type {boolean}
  11825. * @readonly
  11826. * @default true
  11827. */
  11828. this.isStorageBufferNode = true;
  11829. /**
  11830. * The buffer struct type.
  11831. *
  11832. * @type {?StructTypeNode}
  11833. * @default null
  11834. */
  11835. this.structTypeNode = structTypeNode;
  11836. /**
  11837. * The access type of the texture node.
  11838. *
  11839. * @type {string}
  11840. * @default 'readWrite'
  11841. */
  11842. this.access = NodeAccess.READ_WRITE;
  11843. /**
  11844. * Whether the node is atomic or not.
  11845. *
  11846. * @type {boolean}
  11847. * @default false
  11848. */
  11849. this.isAtomic = false;
  11850. /**
  11851. * Whether the node represents a PBO or not.
  11852. * Only relevant for WebGL.
  11853. *
  11854. * @type {boolean}
  11855. * @default false
  11856. */
  11857. this.isPBO = false;
  11858. /**
  11859. * A reference to the internal buffer attribute node.
  11860. *
  11861. * @private
  11862. * @type {?BufferAttributeNode}
  11863. * @default null
  11864. */
  11865. this._attribute = null;
  11866. /**
  11867. * A reference to the internal varying node.
  11868. *
  11869. * @private
  11870. * @type {?VaryingNode}
  11871. * @default null
  11872. */
  11873. this._varying = null;
  11874. /**
  11875. * `StorageBufferNode` sets this property to `true` by default.
  11876. *
  11877. * @type {boolean}
  11878. * @default true
  11879. */
  11880. this.global = true;
  11881. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11882. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11883. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11884. else value.isStorageBufferAttribute = true;
  11885. }
  11886. }
  11887. /**
  11888. * This method is overwritten since the buffer data might be shared
  11889. * and thus the hash should be shared as well.
  11890. *
  11891. * @param {NodeBuilder} builder - The current node builder.
  11892. * @return {string} The hash.
  11893. */
  11894. getHash( builder ) {
  11895. if ( this.bufferCount === 0 ) {
  11896. let bufferData = builder.globalCache.getData( this.value );
  11897. if ( bufferData === undefined ) {
  11898. bufferData = {
  11899. node: this
  11900. };
  11901. builder.globalCache.setData( this.value, bufferData );
  11902. }
  11903. return bufferData.node.uuid;
  11904. }
  11905. return this.uuid;
  11906. }
  11907. /**
  11908. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11909. *
  11910. * @param {NodeBuilder} builder - The current node builder.
  11911. * @return {string} The input type.
  11912. */
  11913. getInputType( /*builder*/ ) {
  11914. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11915. }
  11916. /**
  11917. * Enables element access with the given index node.
  11918. *
  11919. * @param {IndexNode} indexNode - The index node.
  11920. * @return {StorageArrayElementNode} A node representing the element access.
  11921. */
  11922. element( indexNode ) {
  11923. return storageElement( this, indexNode );
  11924. }
  11925. /**
  11926. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11927. *
  11928. * @param {boolean} value - The value so set.
  11929. * @return {StorageBufferNode} A reference to this node.
  11930. */
  11931. setPBO( value ) {
  11932. this.isPBO = value;
  11933. return this;
  11934. }
  11935. /**
  11936. * Returns the `isPBO` value.
  11937. *
  11938. * @return {boolean} Whether the node represents a PBO or not.
  11939. */
  11940. getPBO() {
  11941. return this.isPBO;
  11942. }
  11943. /**
  11944. * Defines the node access.
  11945. *
  11946. * @param {string} value - The node access.
  11947. * @return {StorageBufferNode} A reference to this node.
  11948. */
  11949. setAccess( value ) {
  11950. this.access = value;
  11951. return this;
  11952. }
  11953. /**
  11954. * Convenience method for configuring a read-only node access.
  11955. *
  11956. * @return {StorageBufferNode} A reference to this node.
  11957. */
  11958. toReadOnly() {
  11959. return this.setAccess( NodeAccess.READ_ONLY );
  11960. }
  11961. /**
  11962. * Defines whether the node is atomic or not.
  11963. *
  11964. * @param {boolean} value - The atomic flag.
  11965. * @return {StorageBufferNode} A reference to this node.
  11966. */
  11967. setAtomic( value ) {
  11968. this.isAtomic = value;
  11969. return this;
  11970. }
  11971. /**
  11972. * Convenience method for making this node atomic.
  11973. *
  11974. * @return {StorageBufferNode} A reference to this node.
  11975. */
  11976. toAtomic() {
  11977. return this.setAtomic( true );
  11978. }
  11979. /**
  11980. * Returns attribute data for this storage buffer node.
  11981. *
  11982. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11983. */
  11984. getAttributeData() {
  11985. if ( this._attribute === null ) {
  11986. this._attribute = bufferAttribute( this.value );
  11987. this._varying = varying( this._attribute );
  11988. }
  11989. return {
  11990. attribute: this._attribute,
  11991. varying: this._varying
  11992. };
  11993. }
  11994. /**
  11995. * This method is overwritten since the node type from the availability of storage buffers
  11996. * and the attribute data.
  11997. *
  11998. * @param {NodeBuilder} builder - The current node builder.
  11999. * @return {string} The node type.
  12000. */
  12001. getNodeType( builder ) {
  12002. if ( this.structTypeNode !== null ) {
  12003. return this.structTypeNode.getNodeType( builder );
  12004. }
  12005. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12006. return super.getNodeType( builder );
  12007. }
  12008. const { attribute } = this.getAttributeData();
  12009. return attribute.getNodeType( builder );
  12010. }
  12011. /**
  12012. * Returns the type of a member of the struct.
  12013. *
  12014. * @param {NodeBuilder} builder - The current node builder.
  12015. * @param {string} name - The name of the member.
  12016. * @return {string} The type of the member.
  12017. */
  12018. getMemberType( builder, name ) {
  12019. if ( this.structTypeNode !== null ) {
  12020. return this.structTypeNode.getMemberType( builder, name );
  12021. }
  12022. return 'void';
  12023. }
  12024. /**
  12025. * Generates the code snippet of the storage buffer node.
  12026. *
  12027. * @param {NodeBuilder} builder - The current node builder.
  12028. * @return {string} The generated code snippet.
  12029. */
  12030. generate( builder ) {
  12031. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  12032. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  12033. return super.generate( builder );
  12034. }
  12035. const { attribute, varying } = this.getAttributeData();
  12036. const output = varying.build( builder );
  12037. builder.registerTransform( output, attribute );
  12038. return output;
  12039. }
  12040. }
  12041. /**
  12042. * TSL function for creating a storage buffer node.
  12043. *
  12044. * @tsl
  12045. * @function
  12046. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  12047. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  12048. * @param {number} [count=0] - The buffer count.
  12049. * @returns {StorageBufferNode}
  12050. */
  12051. const storage = ( value, type = null, count = 0 ) => new StorageBufferNode( value, type, count );
  12052. /**
  12053. * This class represents shader indices of different types. The following predefined node
  12054. * objects cover frequent use cases:
  12055. *
  12056. * - `vertexIndex`: The index of a vertex within a mesh.
  12057. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  12058. * - `drawIndex`: The index of a draw call.
  12059. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  12060. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  12061. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  12062. *
  12063. * @augments Node
  12064. */
  12065. class IndexNode extends Node {
  12066. static get type() {
  12067. return 'IndexNode';
  12068. }
  12069. /**
  12070. * Constructs a new index node.
  12071. *
  12072. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  12073. */
  12074. constructor( scope ) {
  12075. super( 'uint' );
  12076. /**
  12077. * The scope of the index node.
  12078. *
  12079. * @type {string}
  12080. */
  12081. this.scope = scope;
  12082. /**
  12083. * This flag can be used for type testing.
  12084. *
  12085. * @type {boolean}
  12086. * @readonly
  12087. * @default true
  12088. */
  12089. this.isIndexNode = true;
  12090. }
  12091. generate( builder ) {
  12092. const nodeType = this.getNodeType( builder );
  12093. const scope = this.scope;
  12094. let propertyName;
  12095. if ( scope === IndexNode.VERTEX ) {
  12096. propertyName = builder.getVertexIndex();
  12097. } else if ( scope === IndexNode.INSTANCE ) {
  12098. propertyName = builder.getInstanceIndex();
  12099. } else if ( scope === IndexNode.DRAW ) {
  12100. propertyName = builder.getDrawIndex();
  12101. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  12102. propertyName = builder.getInvocationLocalIndex();
  12103. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  12104. propertyName = builder.getInvocationSubgroupIndex();
  12105. } else if ( scope === IndexNode.SUBGROUP ) {
  12106. propertyName = builder.getSubgroupIndex();
  12107. } else {
  12108. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  12109. }
  12110. let output;
  12111. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  12112. output = propertyName;
  12113. } else {
  12114. const nodeVarying = varying( this );
  12115. output = nodeVarying.build( builder, nodeType );
  12116. }
  12117. return output;
  12118. }
  12119. }
  12120. IndexNode.VERTEX = 'vertex';
  12121. IndexNode.INSTANCE = 'instance';
  12122. IndexNode.SUBGROUP = 'subgroup';
  12123. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  12124. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  12125. IndexNode.DRAW = 'draw';
  12126. /**
  12127. * TSL object that represents the index of a vertex within a mesh.
  12128. *
  12129. * @tsl
  12130. * @type {IndexNode}
  12131. */
  12132. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  12133. /**
  12134. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  12135. *
  12136. * @tsl
  12137. * @type {IndexNode}
  12138. */
  12139. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  12140. /**
  12141. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  12142. *
  12143. * @tsl
  12144. * @type {IndexNode}
  12145. */
  12146. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  12147. /**
  12148. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  12149. *
  12150. * @tsl
  12151. * @type {IndexNode}
  12152. */
  12153. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  12154. /**
  12155. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  12156. *
  12157. * @tsl
  12158. * @type {IndexNode}
  12159. */
  12160. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  12161. /**
  12162. * TSL object that represents the index of a draw call.
  12163. *
  12164. * @tsl
  12165. * @type {IndexNode}
  12166. */
  12167. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  12168. /**
  12169. * This node implements the vertex shader logic which is required
  12170. * when rendering 3D objects via instancing. The code makes sure
  12171. * vertex positions, normals and colors can be modified via instanced
  12172. * data.
  12173. *
  12174. * @augments Node
  12175. */
  12176. class InstanceNode extends Node {
  12177. static get type() {
  12178. return 'InstanceNode';
  12179. }
  12180. /**
  12181. * Constructs a new instance node.
  12182. *
  12183. * @param {number} count - The number of instances.
  12184. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12185. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12186. */
  12187. constructor( count, instanceMatrix, instanceColor = null ) {
  12188. super( 'void' );
  12189. /**
  12190. * The number of instances.
  12191. *
  12192. * @type {number}
  12193. */
  12194. this.count = count;
  12195. /**
  12196. * Instanced buffer attribute representing the transformation of instances.
  12197. *
  12198. * @type {InstancedBufferAttribute}
  12199. */
  12200. this.instanceMatrix = instanceMatrix;
  12201. /**
  12202. * Instanced buffer attribute representing the color of instances.
  12203. *
  12204. * @type {InstancedBufferAttribute}
  12205. */
  12206. this.instanceColor = instanceColor;
  12207. /**
  12208. * The node that represents the instance matrix data.
  12209. *
  12210. * @type {?Node}
  12211. */
  12212. this.instanceMatrixNode = null;
  12213. /**
  12214. * The node that represents the instance color data.
  12215. *
  12216. * @type {?Node}
  12217. * @default null
  12218. */
  12219. this.instanceColorNode = null;
  12220. /**
  12221. * The update type is set to `frame` since an update
  12222. * of instanced buffer data must be checked per frame.
  12223. *
  12224. * @type {string}
  12225. * @default 'frame'
  12226. */
  12227. this.updateType = NodeUpdateType.FRAME;
  12228. /**
  12229. * A reference to a buffer that is used by `instanceMatrixNode`.
  12230. *
  12231. * @type {?InstancedInterleavedBuffer}
  12232. */
  12233. this.buffer = null;
  12234. /**
  12235. * A reference to a buffer that is used by `instanceColorNode`.
  12236. *
  12237. * @type {?InstancedBufferAttribute}
  12238. */
  12239. this.bufferColor = null;
  12240. /**
  12241. * The previous instance matrices. Required for computing motion vectors.
  12242. *
  12243. * @type {?Node}
  12244. * @default null
  12245. */
  12246. this.previousInstanceMatrixNode = null;
  12247. }
  12248. /**
  12249. * Tracks whether the matrix data is provided via a storage buffer.
  12250. *
  12251. * @type {boolean}
  12252. */
  12253. get isStorageMatrix() {
  12254. const { instanceMatrix } = this;
  12255. return instanceMatrix && instanceMatrix.isStorageInstancedBufferAttribute === true;
  12256. }
  12257. /**
  12258. * Tracks whether the color data is provided via a storage buffer.
  12259. *
  12260. * @type {boolean}
  12261. */
  12262. get isStorageColor() {
  12263. const { instanceColor } = this;
  12264. return instanceColor && instanceColor.isStorageInstancedBufferAttribute === true;
  12265. }
  12266. /**
  12267. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12268. * to predefined node variables for accumulation. That follows the same patterns
  12269. * like with morph and skinning nodes.
  12270. *
  12271. * @param {NodeBuilder} builder - The current node builder.
  12272. */
  12273. setup( builder ) {
  12274. let { instanceMatrixNode, instanceColorNode } = this;
  12275. // instance matrix
  12276. if ( instanceMatrixNode === null ) {
  12277. instanceMatrixNode = this._createInstanceMatrixNode( true, builder );
  12278. this.instanceMatrixNode = instanceMatrixNode;
  12279. }
  12280. // instance color
  12281. const { instanceColor, isStorageColor } = this;
  12282. if ( instanceColor && instanceColorNode === null ) {
  12283. if ( isStorageColor ) {
  12284. instanceColorNode = storage( instanceColor, 'vec3', Math.max( instanceColor.count, 1 ) ).element( instanceIndex );
  12285. } else {
  12286. const bufferAttribute = new InstancedBufferAttribute( instanceColor.array, 3 );
  12287. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12288. this.bufferColor = bufferAttribute;
  12289. instanceColorNode = vec3( bufferFn( bufferAttribute, 'vec3', 3, 0 ) );
  12290. }
  12291. this.instanceColorNode = instanceColorNode;
  12292. }
  12293. // POSITION
  12294. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  12295. positionLocal.assign( instancePosition );
  12296. if ( builder.needsPreviousData() ) {
  12297. positionPrevious.assign( this.getPreviousInstancedPosition( builder ) );
  12298. }
  12299. // NORMAL
  12300. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12301. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  12302. // ASSIGNS
  12303. normalLocal.assign( instanceNormal );
  12304. }
  12305. // COLOR
  12306. if ( this.instanceColorNode !== null ) {
  12307. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  12308. }
  12309. }
  12310. /**
  12311. * Checks if the internal buffers require an update.
  12312. *
  12313. * @param {NodeFrame} frame - The current node frame.
  12314. */
  12315. update( frame ) {
  12316. if ( this.buffer !== null && this.isStorageMatrix !== true ) {
  12317. this.buffer.clearUpdateRanges();
  12318. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  12319. // update version if necessary
  12320. if ( this.instanceMatrix.version !== this.buffer.version ) {
  12321. this.buffer.version = this.instanceMatrix.version;
  12322. }
  12323. }
  12324. if ( this.instanceColor && this.bufferColor !== null && this.isStorageColor !== true ) {
  12325. this.bufferColor.clearUpdateRanges();
  12326. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  12327. if ( this.instanceColor.version !== this.bufferColor.version ) {
  12328. this.bufferColor.version = this.instanceColor.version;
  12329. }
  12330. }
  12331. if ( this.previousInstanceMatrixNode !== null ) {
  12332. frame.object.previousInstanceMatrix.array.set( this.instanceMatrix.array );
  12333. }
  12334. }
  12335. /**
  12336. * Computes the transformed/instanced vertex position of the previous frame.
  12337. *
  12338. * @param {NodeBuilder} builder - The current node builder.
  12339. * @return {Node<vec3>} The instanced position from the previous frame.
  12340. */
  12341. getPreviousInstancedPosition( builder ) {
  12342. const instancedMesh = builder.object;
  12343. if ( this.previousInstanceMatrixNode === null ) {
  12344. instancedMesh.previousInstanceMatrix = this.instanceMatrix.clone();
  12345. this.previousInstanceMatrixNode = this._createInstanceMatrixNode( false, builder );
  12346. }
  12347. return this.previousInstanceMatrixNode.mul( positionPrevious ).xyz;
  12348. }
  12349. /**
  12350. * Creates a node representing the instance matrix data.
  12351. *
  12352. * @private
  12353. * @param {boolean} assignBuffer - Whether the created interleaved buffer should be assigned to the `buffer` member or not.
  12354. * @param {NodeBuilder} builder - A reference to the current node builder.
  12355. * @return {Node} The instance matrix node.
  12356. */
  12357. _createInstanceMatrixNode( assignBuffer, builder ) {
  12358. let instanceMatrixNode;
  12359. const { instanceMatrix } = this;
  12360. const { count } = instanceMatrix;
  12361. if ( this.isStorageMatrix ) {
  12362. instanceMatrixNode = storage( instanceMatrix, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12363. } else {
  12364. // WebGPU has a 64kb UBO limit, WebGL 2 ensures only 16KB; fallback to attributes if a certain count is exceeded
  12365. const limit = ( builder.renderer.backend.isWebGPUBackend === true ) ? 1000 : 250;
  12366. if ( count <= limit ) {
  12367. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  12368. } else {
  12369. const interleaved = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  12370. if ( assignBuffer === true ) this.buffer = interleaved;
  12371. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  12372. const instanceBuffers = [
  12373. bufferFn( interleaved, 'vec4', 16, 0 ),
  12374. bufferFn( interleaved, 'vec4', 16, 4 ),
  12375. bufferFn( interleaved, 'vec4', 16, 8 ),
  12376. bufferFn( interleaved, 'vec4', 16, 12 )
  12377. ];
  12378. instanceMatrixNode = mat4( ...instanceBuffers );
  12379. }
  12380. }
  12381. return instanceMatrixNode;
  12382. }
  12383. }
  12384. /**
  12385. * TSL function for creating an instance node.
  12386. *
  12387. * @tsl
  12388. * @function
  12389. * @param {number} count - The number of instances.
  12390. * @param {InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  12391. * @param {?InstancedBufferAttribute|StorageInstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  12392. * @returns {InstanceNode}
  12393. */
  12394. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  12395. /**
  12396. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  12397. * It allows an easier setup of the instance node.
  12398. *
  12399. * @augments InstanceNode
  12400. */
  12401. class InstancedMeshNode extends InstanceNode {
  12402. static get type() {
  12403. return 'InstancedMeshNode';
  12404. }
  12405. /**
  12406. * Constructs a new instanced mesh node.
  12407. *
  12408. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  12409. */
  12410. constructor( instancedMesh ) {
  12411. const { count, instanceMatrix, instanceColor } = instancedMesh;
  12412. super( count, instanceMatrix, instanceColor );
  12413. /**
  12414. * A reference to the instanced mesh.
  12415. *
  12416. * @type {InstancedMesh}
  12417. */
  12418. this.instancedMesh = instancedMesh;
  12419. }
  12420. }
  12421. /**
  12422. * TSL function for creating an instanced mesh node.
  12423. *
  12424. * @tsl
  12425. * @function
  12426. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  12427. * @returns {InstancedMeshNode}
  12428. */
  12429. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  12430. /**
  12431. * This node implements the vertex shader logic which is required
  12432. * when rendering 3D objects via batching. `BatchNode` must be used
  12433. * with instances of {@link BatchedMesh}.
  12434. *
  12435. * @augments Node
  12436. */
  12437. class BatchNode extends Node {
  12438. static get type() {
  12439. return 'BatchNode';
  12440. }
  12441. /**
  12442. * Constructs a new batch node.
  12443. *
  12444. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12445. */
  12446. constructor( batchMesh ) {
  12447. super( 'void' );
  12448. /**
  12449. * A reference to batched mesh.
  12450. *
  12451. * @type {BatchedMesh}
  12452. */
  12453. this.batchMesh = batchMesh;
  12454. /**
  12455. * The batching index node.
  12456. *
  12457. * @type {?IndexNode}
  12458. * @default null
  12459. */
  12460. this.batchingIdNode = null;
  12461. }
  12462. /**
  12463. * Setups the internal buffers and nodes and assigns the transformed vertex data
  12464. * to predefined node variables for accumulation. That follows the same patterns
  12465. * like with morph and skinning nodes.
  12466. *
  12467. * @param {NodeBuilder} builder - The current node builder.
  12468. */
  12469. setup( builder ) {
  12470. if ( this.batchingIdNode === null ) {
  12471. if ( builder.getDrawIndex() === null ) {
  12472. this.batchingIdNode = instanceIndex;
  12473. } else {
  12474. this.batchingIdNode = drawIndex;
  12475. }
  12476. }
  12477. const getIndirectIndex = Fn( ( [ id ] ) => {
  12478. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x ).toConst();
  12479. const x = int( id ).mod( size ).toConst();
  12480. const y = int( id ).div( size ).toConst();
  12481. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  12482. } ).setLayout( {
  12483. name: 'getIndirectIndex',
  12484. type: 'uint',
  12485. inputs: [
  12486. { name: 'id', type: 'int' }
  12487. ]
  12488. } );
  12489. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  12490. const matricesTexture = this.batchMesh._matricesTexture;
  12491. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x ).toConst();
  12492. const j = float( indirectId ).mul( 4 ).toInt().toConst();
  12493. const x = j.mod( size ).toConst();
  12494. const y = j.div( size ).toConst();
  12495. const batchingMatrix = mat4(
  12496. textureLoad( matricesTexture, ivec2( x, y ) ),
  12497. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  12498. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  12499. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  12500. );
  12501. const colorsTexture = this.batchMesh._colorsTexture;
  12502. if ( colorsTexture !== null ) {
  12503. const getBatchingColor = Fn( ( [ id ] ) => {
  12504. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x ).toConst();
  12505. const j = id;
  12506. const x = j.mod( size ).toConst();
  12507. const y = j.div( size ).toConst();
  12508. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  12509. } ).setLayout( {
  12510. name: 'getBatchingColor',
  12511. type: 'vec3',
  12512. inputs: [
  12513. { name: 'id', type: 'int' }
  12514. ]
  12515. } );
  12516. const color = getBatchingColor( indirectId );
  12517. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  12518. }
  12519. const bm = mat3( batchingMatrix );
  12520. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  12521. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  12522. const batchingNormal = bm.mul( transformedNormal ).xyz;
  12523. normalLocal.assign( batchingNormal );
  12524. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12525. tangentLocal.mulAssign( bm );
  12526. }
  12527. }
  12528. }
  12529. /**
  12530. * TSL function for creating a batch node.
  12531. *
  12532. * @tsl
  12533. * @function
  12534. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  12535. * @returns {BatchNode}
  12536. */
  12537. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  12538. const _frameId = new WeakMap();
  12539. /**
  12540. * This node implements the vertex transformation shader logic which is required
  12541. * for skinning/skeletal animation.
  12542. *
  12543. * @augments Node
  12544. */
  12545. class SkinningNode extends Node {
  12546. static get type() {
  12547. return 'SkinningNode';
  12548. }
  12549. /**
  12550. * Constructs a new skinning node.
  12551. *
  12552. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12553. */
  12554. constructor( skinnedMesh ) {
  12555. super( 'void' );
  12556. /**
  12557. * The skinned mesh.
  12558. *
  12559. * @type {SkinnedMesh}
  12560. */
  12561. this.skinnedMesh = skinnedMesh;
  12562. /**
  12563. * The update type overwritten since skinning nodes are updated per object.
  12564. *
  12565. * @type {string}
  12566. */
  12567. this.updateType = NodeUpdateType.OBJECT;
  12568. //
  12569. /**
  12570. * The skin index attribute.
  12571. *
  12572. * @type {AttributeNode}
  12573. */
  12574. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12575. /**
  12576. * The skin weight attribute.
  12577. *
  12578. * @type {AttributeNode}
  12579. */
  12580. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12581. /**
  12582. * The bind matrix node.
  12583. *
  12584. * @type {Node<mat4>}
  12585. */
  12586. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12587. /**
  12588. * The bind matrix inverse node.
  12589. *
  12590. * @type {Node<mat4>}
  12591. */
  12592. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12593. /**
  12594. * The bind matrices as a uniform buffer node.
  12595. *
  12596. * @type {Node}
  12597. */
  12598. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12599. /**
  12600. * The current vertex position in local space.
  12601. *
  12602. * @type {Node<vec3>}
  12603. */
  12604. this.positionNode = positionLocal;
  12605. /**
  12606. * The result of vertex position in local space.
  12607. *
  12608. * @type {Node<vec3>}
  12609. */
  12610. this.toPositionNode = positionLocal;
  12611. /**
  12612. * The previous bind matrices as a uniform buffer node.
  12613. * Required for computing motion vectors.
  12614. *
  12615. * @type {?Node}
  12616. * @default null
  12617. */
  12618. this.previousBoneMatricesNode = null;
  12619. }
  12620. /**
  12621. * Transforms the given vertex position via skinning.
  12622. *
  12623. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12624. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12625. * @return {Node<vec3>} The transformed vertex position.
  12626. */
  12627. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12628. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12629. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12630. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12631. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12632. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12633. // POSITION
  12634. const skinVertex = bindMatrixNode.mul( position );
  12635. const skinned = add(
  12636. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12637. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12638. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12639. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12640. );
  12641. return bindMatrixInverseNode.mul( skinned ).xyz;
  12642. }
  12643. /**
  12644. * Transforms the given vertex normal and tangent via skinning.
  12645. *
  12646. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12647. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12648. * @param {Node<vec3>} [tangent=tangentLocal] - The vertex tangent in local space.
  12649. * @return {{skinNormal: Node<vec3>, skinTangent:Node<vec3>}} The transformed vertex normal and tangent.
  12650. */
  12651. getSkinnedNormalAndTangent( boneMatrices = this.boneMatricesNode, normal = normalLocal, tangent = tangentLocal ) {
  12652. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12653. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12654. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12655. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12656. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12657. // NORMAL and TANGENT
  12658. let skinMatrix = add(
  12659. skinWeightNode.x.mul( boneMatX ),
  12660. skinWeightNode.y.mul( boneMatY ),
  12661. skinWeightNode.z.mul( boneMatZ ),
  12662. skinWeightNode.w.mul( boneMatW )
  12663. );
  12664. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12665. const skinNormal = skinMatrix.transformDirection( normal ).xyz;
  12666. const skinTangent = skinMatrix.transformDirection( tangent ).xyz;
  12667. return { skinNormal, skinTangent };
  12668. }
  12669. /**
  12670. * Computes the transformed/skinned vertex position of the previous frame.
  12671. *
  12672. * @param {NodeBuilder} builder - The current node builder.
  12673. * @return {Node<vec3>} The skinned position from the previous frame.
  12674. */
  12675. getPreviousSkinnedPosition( builder ) {
  12676. const skinnedMesh = builder.object;
  12677. if ( this.previousBoneMatricesNode === null ) {
  12678. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12679. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12680. }
  12681. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12682. }
  12683. /**
  12684. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12685. *
  12686. * @param {NodeBuilder} builder - The current node builder.
  12687. * @return {Node<vec3>} The transformed vertex position.
  12688. */
  12689. setup( builder ) {
  12690. if ( builder.needsPreviousData() ) {
  12691. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12692. }
  12693. const skinPosition = this.getSkinnedPosition();
  12694. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12695. //
  12696. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12697. const { skinNormal, skinTangent } = this.getSkinnedNormalAndTangent();
  12698. normalLocal.assign( skinNormal );
  12699. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12700. tangentLocal.assign( skinTangent );
  12701. }
  12702. }
  12703. return skinPosition;
  12704. }
  12705. /**
  12706. * Generates the code snippet of the skinning node.
  12707. *
  12708. * @param {NodeBuilder} builder - The current node builder.
  12709. * @param {string} output - The current output.
  12710. * @return {string} The generated code snippet.
  12711. */
  12712. generate( builder, output ) {
  12713. if ( output !== 'void' ) {
  12714. return super.generate( builder, output );
  12715. }
  12716. }
  12717. /**
  12718. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12719. *
  12720. * @param {NodeFrame} frame - The current node frame.
  12721. */
  12722. update( frame ) {
  12723. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12724. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12725. _frameId.set( skeleton, frame.frameId );
  12726. if ( this.previousBoneMatricesNode !== null ) {
  12727. if ( skeleton.previousBoneMatrices === null ) {
  12728. // cloned skeletons miss "previousBoneMatrices" in their first updated
  12729. skeleton.previousBoneMatrices = new Float32Array( skeleton.boneMatrices );
  12730. }
  12731. skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12732. }
  12733. skeleton.update();
  12734. }
  12735. }
  12736. /**
  12737. * TSL function for creating a skinning node.
  12738. *
  12739. * @tsl
  12740. * @function
  12741. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12742. * @returns {SkinningNode}
  12743. */
  12744. const skinning = ( skinnedMesh ) => new SkinningNode( skinnedMesh );
  12745. /**
  12746. * TSL function for computing skinning.
  12747. *
  12748. * @tsl
  12749. * @function
  12750. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12751. * @param {Node<vec3>} [toPosition=null] - The target position.
  12752. * @returns {SkinningNode}
  12753. */
  12754. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12755. const node = new SkinningNode( skinnedMesh );
  12756. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12757. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12758. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12759. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12760. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12761. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12762. node.toPositionNode = toPosition;
  12763. return nodeObject( node );
  12764. };
  12765. /**
  12766. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12767. * ```js
  12768. * Loop( count, ( { i } ) => {
  12769. *
  12770. * } );
  12771. * ```
  12772. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12773. * ```js
  12774. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12775. *
  12776. * } );
  12777. *```
  12778. * Nested loops can be defined in a compacted form:
  12779. * ```js
  12780. * Loop( 10, 5, ( { i, j } ) => {
  12781. *
  12782. * } );
  12783. * ```
  12784. * Loops that should run backwards can be defined like so:
  12785. * ```js
  12786. * Loop( { start: 10 }, () => {} );
  12787. * ```
  12788. * It is possible to execute with boolean values, similar to the `while` syntax.
  12789. * ```js
  12790. * const value = float( 0 ).toVar();
  12791. *
  12792. * Loop( value.lessThan( 10 ), () => {
  12793. *
  12794. * value.addAssign( 1 );
  12795. *
  12796. * } );
  12797. * ```
  12798. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12799. * @augments Node
  12800. */
  12801. class LoopNode extends Node {
  12802. static get type() {
  12803. return 'LoopNode';
  12804. }
  12805. /**
  12806. * Constructs a new loop node.
  12807. *
  12808. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12809. */
  12810. constructor( params = [] ) {
  12811. super( 'void' );
  12812. this.params = params;
  12813. }
  12814. /**
  12815. * Returns a loop variable name based on an index. The pattern is
  12816. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12817. *
  12818. * @param {number} index - The index.
  12819. * @return {string} The loop variable name.
  12820. */
  12821. getVarName( index ) {
  12822. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12823. }
  12824. /**
  12825. * Returns properties about this node.
  12826. *
  12827. * @param {NodeBuilder} builder - The current node builder.
  12828. * @return {Object} The node properties.
  12829. */
  12830. getProperties( builder ) {
  12831. const properties = builder.getNodeProperties( this );
  12832. if ( properties.stackNode !== undefined ) return properties;
  12833. //
  12834. const inputs = {};
  12835. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12836. const param = this.params[ i ];
  12837. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12838. const type = ( param.isNode !== true && param.type ) || 'int';
  12839. inputs[ name ] = expression( name, type );
  12840. }
  12841. const stack = builder.addStack();
  12842. const fnCall = this.params[ this.params.length - 1 ]( inputs );
  12843. properties.returnsNode = fnCall.context( { nodeLoop: fnCall } );
  12844. properties.stackNode = stack;
  12845. const baseParam = this.params[ 0 ];
  12846. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12847. const fnUpdateCall = Fn( this.params[ 0 ].update )( inputs );
  12848. properties.updateNode = fnUpdateCall.context( { nodeLoop: fnUpdateCall } );
  12849. }
  12850. builder.removeStack();
  12851. return properties;
  12852. }
  12853. setup( builder ) {
  12854. // setup properties
  12855. this.getProperties( builder );
  12856. if ( builder.fnCall ) {
  12857. const shaderNodeData = builder.getDataFromNode( builder.fnCall.shaderNode );
  12858. shaderNodeData.hasLoop = true;
  12859. }
  12860. }
  12861. generate( builder ) {
  12862. const properties = this.getProperties( builder );
  12863. const params = this.params;
  12864. const stackNode = properties.stackNode;
  12865. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12866. const param = params[ i ];
  12867. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12868. if ( param.isNode ) {
  12869. if ( param.getNodeType( builder ) === 'bool' ) {
  12870. isWhile = true;
  12871. type = 'bool';
  12872. end = param.build( builder, type );
  12873. } else {
  12874. type = 'int';
  12875. name = this.getVarName( i );
  12876. start = '0';
  12877. end = param.build( builder, type );
  12878. condition = '<';
  12879. }
  12880. } else {
  12881. type = param.type || 'int';
  12882. name = param.name || this.getVarName( i );
  12883. start = param.start;
  12884. end = param.end;
  12885. condition = param.condition;
  12886. update = param.update;
  12887. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12888. else if ( start && start.isNode ) start = start.build( builder, type );
  12889. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12890. else if ( end && end.isNode ) end = end.build( builder, type );
  12891. if ( start !== undefined && end === undefined ) {
  12892. start = start + ' - 1';
  12893. end = '0';
  12894. condition = '>=';
  12895. } else if ( end !== undefined && start === undefined ) {
  12896. start = '0';
  12897. condition = '<';
  12898. }
  12899. if ( condition === undefined ) {
  12900. if ( Number( start ) > Number( end ) ) {
  12901. condition = '>=';
  12902. } else {
  12903. condition = '<';
  12904. }
  12905. }
  12906. }
  12907. let loopSnippet;
  12908. if ( isWhile ) {
  12909. loopSnippet = `while ( ${ end } )`;
  12910. } else {
  12911. const internalParam = { start, end};
  12912. //
  12913. const startSnippet = internalParam.start;
  12914. const endSnippet = internalParam.end;
  12915. let updateSnippet;
  12916. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12917. if ( update !== undefined && update !== null ) {
  12918. switch ( typeof update ) {
  12919. case 'function':
  12920. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12921. const snippet = flow.code.replace( /\t|;/g, '' );
  12922. updateSnippet = snippet;
  12923. break;
  12924. case 'number':
  12925. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12926. break;
  12927. case 'string':
  12928. updateSnippet = name + ' ' + update;
  12929. break;
  12930. default:
  12931. if ( update.isNode ) {
  12932. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12933. } else {
  12934. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12935. updateSnippet = 'break /* invalid update */';
  12936. }
  12937. }
  12938. } else {
  12939. if ( type === 'int' || type === 'uint' ) {
  12940. update = condition.includes( '<' ) ? '++' : '--';
  12941. } else {
  12942. update = deltaOperator() + ' 1.';
  12943. }
  12944. updateSnippet = name + ' ' + update;
  12945. }
  12946. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12947. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12948. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12949. }
  12950. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12951. }
  12952. const stackSnippet = stackNode.build( builder, 'void' );
  12953. properties.returnsNode.build( builder, 'void' );
  12954. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12955. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12956. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12957. }
  12958. builder.addFlowTab();
  12959. }
  12960. }
  12961. /**
  12962. * TSL function for creating a loop node.
  12963. *
  12964. * @tsl
  12965. * @function
  12966. * @param {...any} params - A list of parameters.
  12967. * @returns {LoopNode}
  12968. */
  12969. const Loop = ( ...params ) => new LoopNode( nodeArray( params, 'int' ) ).toStack();
  12970. /**
  12971. * TSL function for creating a `Continue()` expression.
  12972. *
  12973. * @tsl
  12974. * @function
  12975. * @returns {ExpressionNode}
  12976. */
  12977. const Continue = () => expression( 'continue' ).toStack();
  12978. /**
  12979. * TSL function for creating a `Break()` expression.
  12980. *
  12981. * @tsl
  12982. * @function
  12983. * @returns {ExpressionNode}
  12984. */
  12985. const Break = () => expression( 'break' ).toStack();
  12986. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12987. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12988. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12989. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12990. const y = texelIndex.div( width );
  12991. const x = texelIndex.sub( y.mul( width ) );
  12992. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12993. return bufferAttrib.mul( influence );
  12994. } );
  12995. function getEntry( geometry ) {
  12996. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12997. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12998. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12999. // instead of using attributes, the WebGL 2 code path encodes morph targets
  13000. // into an array of data textures. Each layer represents a single morph target.
  13001. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13002. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13003. let entry = _morphTextures.get( geometry );
  13004. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  13005. if ( entry !== undefined ) entry.texture.dispose();
  13006. const morphTargets = geometry.morphAttributes.position || [];
  13007. const morphNormals = geometry.morphAttributes.normal || [];
  13008. const morphColors = geometry.morphAttributes.color || [];
  13009. let vertexDataCount = 0;
  13010. if ( hasMorphPosition === true ) vertexDataCount = 1;
  13011. if ( hasMorphNormals === true ) vertexDataCount = 2;
  13012. if ( hasMorphColors === true ) vertexDataCount = 3;
  13013. let width = geometry.attributes.position.count * vertexDataCount;
  13014. let height = 1;
  13015. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  13016. if ( width > maxTextureSize ) {
  13017. height = Math.ceil( width / maxTextureSize );
  13018. width = maxTextureSize;
  13019. }
  13020. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  13021. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  13022. bufferTexture.type = FloatType;
  13023. bufferTexture.needsUpdate = true;
  13024. // fill buffer
  13025. const vertexDataStride = vertexDataCount * 4;
  13026. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  13027. const morphTarget = morphTargets[ i ];
  13028. const morphNormal = morphNormals[ i ];
  13029. const morphColor = morphColors[ i ];
  13030. const offset = width * height * 4 * i;
  13031. for ( let j = 0; j < morphTarget.count; j ++ ) {
  13032. const stride = j * vertexDataStride;
  13033. if ( hasMorphPosition === true ) {
  13034. _morphVec4.fromBufferAttribute( morphTarget, j );
  13035. buffer[ offset + stride + 0 ] = _morphVec4.x;
  13036. buffer[ offset + stride + 1 ] = _morphVec4.y;
  13037. buffer[ offset + stride + 2 ] = _morphVec4.z;
  13038. buffer[ offset + stride + 3 ] = 0;
  13039. }
  13040. if ( hasMorphNormals === true ) {
  13041. _morphVec4.fromBufferAttribute( morphNormal, j );
  13042. buffer[ offset + stride + 4 ] = _morphVec4.x;
  13043. buffer[ offset + stride + 5 ] = _morphVec4.y;
  13044. buffer[ offset + stride + 6 ] = _morphVec4.z;
  13045. buffer[ offset + stride + 7 ] = 0;
  13046. }
  13047. if ( hasMorphColors === true ) {
  13048. _morphVec4.fromBufferAttribute( morphColor, j );
  13049. buffer[ offset + stride + 8 ] = _morphVec4.x;
  13050. buffer[ offset + stride + 9 ] = _morphVec4.y;
  13051. buffer[ offset + stride + 10 ] = _morphVec4.z;
  13052. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  13053. }
  13054. }
  13055. }
  13056. entry = {
  13057. count: morphTargetsCount,
  13058. texture: bufferTexture,
  13059. stride: vertexDataCount,
  13060. size: new Vector2( width, height )
  13061. };
  13062. _morphTextures.set( geometry, entry );
  13063. function disposeTexture() {
  13064. bufferTexture.dispose();
  13065. _morphTextures.delete( geometry );
  13066. geometry.removeEventListener( 'dispose', disposeTexture );
  13067. }
  13068. geometry.addEventListener( 'dispose', disposeTexture );
  13069. }
  13070. return entry;
  13071. }
  13072. /**
  13073. * This node implements the vertex transformation shader logic which is required
  13074. * for morph target animation.
  13075. *
  13076. * @augments Node
  13077. */
  13078. class MorphNode extends Node {
  13079. static get type() {
  13080. return 'MorphNode';
  13081. }
  13082. /**
  13083. * Constructs a new morph node.
  13084. *
  13085. * @param {Mesh} mesh - The mesh holding the morph targets.
  13086. */
  13087. constructor( mesh ) {
  13088. super( 'void' );
  13089. /**
  13090. * The mesh holding the morph targets.
  13091. *
  13092. * @type {Mesh}
  13093. */
  13094. this.mesh = mesh;
  13095. /**
  13096. * A uniform node which represents the morph base influence value.
  13097. *
  13098. * @type {UniformNode<float>}
  13099. */
  13100. this.morphBaseInfluence = uniform( 1 );
  13101. /**
  13102. * The update type overwritten since morph nodes are updated per object.
  13103. *
  13104. * @type {string}
  13105. */
  13106. this.updateType = NodeUpdateType.OBJECT;
  13107. }
  13108. /**
  13109. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  13110. *
  13111. * @param {NodeBuilder} builder - The current node builder.
  13112. */
  13113. setup( builder ) {
  13114. const { geometry } = builder;
  13115. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  13116. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  13117. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  13118. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  13119. // nodes
  13120. const { texture: bufferMap, stride, size } = getEntry( geometry );
  13121. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  13122. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  13123. const width = int( size.width );
  13124. Loop( morphTargetsCount, ( { i } ) => {
  13125. const influence = float( 0 ).toVar();
  13126. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  13127. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  13128. } else {
  13129. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  13130. }
  13131. If( influence.notEqual( 0 ), () => {
  13132. if ( hasMorphPosition === true ) {
  13133. positionLocal.addAssign( getMorph( {
  13134. bufferMap,
  13135. influence,
  13136. stride,
  13137. width,
  13138. depth: i,
  13139. offset: int( 0 )
  13140. } ) );
  13141. }
  13142. if ( hasMorphNormals === true ) {
  13143. normalLocal.addAssign( getMorph( {
  13144. bufferMap,
  13145. influence,
  13146. stride,
  13147. width,
  13148. depth: i,
  13149. offset: int( 1 )
  13150. } ) );
  13151. }
  13152. } );
  13153. } );
  13154. }
  13155. /**
  13156. * Updates the state of the morphed mesh by updating the base influence.
  13157. *
  13158. * @param {NodeFrame} frame - The current node frame.
  13159. */
  13160. update( /*frame*/ ) {
  13161. const morphBaseInfluence = this.morphBaseInfluence;
  13162. if ( this.mesh.geometry.morphTargetsRelative ) {
  13163. morphBaseInfluence.value = 1;
  13164. } else {
  13165. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  13166. }
  13167. }
  13168. }
  13169. /**
  13170. * TSL function for creating a morph node.
  13171. *
  13172. * @tsl
  13173. * @function
  13174. * @param {Mesh} mesh - The mesh holding the morph targets.
  13175. * @returns {MorphNode}
  13176. */
  13177. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  13178. /**
  13179. * Base class for lighting nodes.
  13180. *
  13181. * @augments Node
  13182. */
  13183. class LightingNode extends Node {
  13184. static get type() {
  13185. return 'LightingNode';
  13186. }
  13187. /**
  13188. * Constructs a new lighting node.
  13189. */
  13190. constructor() {
  13191. super( 'vec3' );
  13192. /**
  13193. * This flag can be used for type testing.
  13194. *
  13195. * @type {boolean}
  13196. * @readonly
  13197. * @default true
  13198. */
  13199. this.isLightingNode = true;
  13200. }
  13201. }
  13202. /**
  13203. * A generic class that can be used by nodes which contribute
  13204. * ambient occlusion to the scene. E.g. an ambient occlusion map
  13205. * node can be used as input for this module. Used in {@link NodeMaterial}.
  13206. *
  13207. * @augments LightingNode
  13208. */
  13209. class AONode extends LightingNode {
  13210. static get type() {
  13211. return 'AONode';
  13212. }
  13213. /**
  13214. * Constructs a new AO node.
  13215. *
  13216. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  13217. */
  13218. constructor( aoNode = null ) {
  13219. super();
  13220. /**
  13221. * The ambient occlusion node.
  13222. *
  13223. * @type {?Node<float>}
  13224. * @default null
  13225. */
  13226. this.aoNode = aoNode;
  13227. }
  13228. setup( builder ) {
  13229. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  13230. }
  13231. }
  13232. /**
  13233. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  13234. * by adding lighting specific context data. It represents the runtime context of
  13235. * {@link LightsNode}.
  13236. *
  13237. * @augments ContextNode
  13238. */
  13239. class LightingContextNode extends ContextNode {
  13240. static get type() {
  13241. return 'LightingContextNode';
  13242. }
  13243. /**
  13244. * Constructs a new lighting context node.
  13245. *
  13246. * @param {LightsNode} lightsNode - The lights node.
  13247. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  13248. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  13249. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  13250. */
  13251. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  13252. super( lightsNode );
  13253. /**
  13254. * The current lighting model.
  13255. *
  13256. * @type {?LightingModel}
  13257. * @default null
  13258. */
  13259. this.lightingModel = lightingModel;
  13260. /**
  13261. * A backdrop node.
  13262. *
  13263. * @type {?Node<vec3>}
  13264. * @default null
  13265. */
  13266. this.backdropNode = backdropNode;
  13267. /**
  13268. * A backdrop alpha node.
  13269. *
  13270. * @type {?Node<float>}
  13271. * @default null
  13272. */
  13273. this.backdropAlphaNode = backdropAlphaNode;
  13274. this._value = null;
  13275. }
  13276. /**
  13277. * Returns a lighting context object.
  13278. *
  13279. * @return {{
  13280. * radiance: Node<vec3>,
  13281. * irradiance: Node<vec3>,
  13282. * iblIrradiance: Node<vec3>,
  13283. * ambientOcclusion: Node<float>,
  13284. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  13285. * backdrop: Node<vec3>,
  13286. * backdropAlpha: Node<float>
  13287. * }} The lighting context object.
  13288. */
  13289. getContext() {
  13290. const { backdropNode, backdropAlphaNode } = this;
  13291. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  13292. directSpecular = vec3().toVar( 'directSpecular' ),
  13293. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  13294. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  13295. const reflectedLight = {
  13296. directDiffuse,
  13297. directSpecular,
  13298. indirectDiffuse,
  13299. indirectSpecular
  13300. };
  13301. const context = {
  13302. radiance: vec3().toVar( 'radiance' ),
  13303. irradiance: vec3().toVar( 'irradiance' ),
  13304. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  13305. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  13306. reflectedLight,
  13307. backdrop: backdropNode,
  13308. backdropAlpha: backdropAlphaNode
  13309. };
  13310. return context;
  13311. }
  13312. setup( builder ) {
  13313. this.value = this._value || ( this._value = this.getContext() );
  13314. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  13315. return super.setup( builder );
  13316. }
  13317. }
  13318. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  13319. /**
  13320. * A generic class that can be used by nodes which contribute
  13321. * irradiance to the scene. E.g. a light map node can be used
  13322. * as input for this module. Used in {@link NodeMaterial}.
  13323. *
  13324. * @augments LightingNode
  13325. */
  13326. class IrradianceNode extends LightingNode {
  13327. static get type() {
  13328. return 'IrradianceNode';
  13329. }
  13330. /**
  13331. * Constructs a new irradiance node.
  13332. *
  13333. * @param {Node<vec3>} node - A node contributing irradiance.
  13334. */
  13335. constructor( node ) {
  13336. super();
  13337. /**
  13338. * A node contributing irradiance.
  13339. *
  13340. * @type {Node<vec3>}
  13341. */
  13342. this.node = node;
  13343. }
  13344. setup( builder ) {
  13345. builder.context.irradiance.addAssign( this.node );
  13346. }
  13347. }
  13348. const _size$5 = /*@__PURE__*/ new Vector2();
  13349. /**
  13350. * A special type of texture node which represents the data of the current viewport
  13351. * as a texture. The module extracts data from the current bound framebuffer with
  13352. * a copy operation so no extra render pass is required to produce the texture data
  13353. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  13354. * variety of effects like refractive or transmissive materials.
  13355. *
  13356. * @augments TextureNode
  13357. */
  13358. class ViewportTextureNode extends TextureNode {
  13359. static get type() {
  13360. return 'ViewportTextureNode';
  13361. }
  13362. /**
  13363. * Constructs a new viewport texture node.
  13364. *
  13365. * @param {Node} [uvNode=screenUV] - The uv node.
  13366. * @param {?Node} [levelNode=null] - The level node.
  13367. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13368. */
  13369. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  13370. let defaultFramebuffer = null;
  13371. if ( framebufferTexture === null ) {
  13372. defaultFramebuffer = new FramebufferTexture();
  13373. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  13374. framebufferTexture = defaultFramebuffer;
  13375. } else {
  13376. defaultFramebuffer = framebufferTexture;
  13377. }
  13378. super( framebufferTexture, uvNode, levelNode );
  13379. /**
  13380. * Whether to generate mipmaps or not.
  13381. *
  13382. * @type {boolean}
  13383. * @default false
  13384. */
  13385. this.generateMipmaps = false;
  13386. /**
  13387. * The reference framebuffer texture. This is used to store the framebuffer texture
  13388. * for the current render target. If the render target changes, a new framebuffer texture
  13389. * is created automatically.
  13390. *
  13391. * @type {FramebufferTexture}
  13392. * @default null
  13393. */
  13394. this.defaultFramebuffer = defaultFramebuffer;
  13395. /**
  13396. * This flag can be used for type testing.
  13397. *
  13398. * @type {boolean}
  13399. * @readonly
  13400. * @default true
  13401. */
  13402. this.isOutputTextureNode = true;
  13403. /**
  13404. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node should extract
  13405. * the current contents of the bound framebuffer for each render call.
  13406. *
  13407. * @type {string}
  13408. * @default 'render'
  13409. */
  13410. this.updateBeforeType = NodeUpdateType.RENDER;
  13411. /**
  13412. * The framebuffer texture for the current renderer context.
  13413. *
  13414. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  13415. * @private
  13416. */
  13417. this._cacheTextures = new WeakMap();
  13418. }
  13419. /**
  13420. * This methods returns a texture for the given render target reference.
  13421. *
  13422. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  13423. * for different render contexts.
  13424. *
  13425. * @param {?RenderTarget} [reference=null] - The render target reference.
  13426. * @return {Texture} The framebuffer texture.
  13427. */
  13428. getTextureForReference( reference = null ) {
  13429. let defaultFramebuffer;
  13430. let cacheTextures;
  13431. if ( this.referenceNode ) {
  13432. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  13433. cacheTextures = this.referenceNode._cacheTextures;
  13434. } else {
  13435. defaultFramebuffer = this.defaultFramebuffer;
  13436. cacheTextures = this._cacheTextures;
  13437. }
  13438. if ( reference === null ) {
  13439. return defaultFramebuffer;
  13440. }
  13441. if ( cacheTextures.has( reference ) === false ) {
  13442. const framebufferTexture = defaultFramebuffer.clone();
  13443. cacheTextures.set( reference, framebufferTexture );
  13444. }
  13445. return cacheTextures.get( reference );
  13446. }
  13447. updateReference( frame ) {
  13448. const renderTarget = frame.renderer.getRenderTarget();
  13449. this.value = this.getTextureForReference( renderTarget );
  13450. return this.value;
  13451. }
  13452. updateBefore( frame ) {
  13453. const renderer = frame.renderer;
  13454. const renderTarget = renderer.getRenderTarget();
  13455. if ( renderTarget === null ) {
  13456. renderer.getDrawingBufferSize( _size$5 );
  13457. } else {
  13458. _size$5.set( renderTarget.width, renderTarget.height );
  13459. }
  13460. //
  13461. const framebufferTexture = this.getTextureForReference( renderTarget );
  13462. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  13463. framebufferTexture.image.width = _size$5.width;
  13464. framebufferTexture.image.height = _size$5.height;
  13465. framebufferTexture.needsUpdate = true;
  13466. }
  13467. //
  13468. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  13469. framebufferTexture.generateMipmaps = this.generateMipmaps;
  13470. renderer.copyFramebufferToTexture( framebufferTexture );
  13471. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  13472. }
  13473. clone() {
  13474. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  13475. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  13476. return viewportTextureNode;
  13477. }
  13478. }
  13479. /**
  13480. * TSL function for creating a viewport texture node.
  13481. *
  13482. * @tsl
  13483. * @function
  13484. * @param {?Node} [uvNode=screenUV] - The uv node.
  13485. * @param {?Node} [levelNode=null] - The level node.
  13486. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13487. * @returns {ViewportTextureNode}
  13488. */
  13489. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  13490. /**
  13491. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13492. *
  13493. * @tsl
  13494. * @function
  13495. * @param {?Node} [uvNode=screenUV] - The uv node.
  13496. * @param {?Node} [levelNode=null] - The level node.
  13497. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  13498. * @returns {ViewportTextureNode}
  13499. */
  13500. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  13501. // Singleton instances for common usage
  13502. const _singletonOpaqueViewportTextureNode = /*@__PURE__*/ viewportMipTexture();
  13503. /**
  13504. * TSL function for creating a viewport texture node with enabled mipmap generation.
  13505. * The texture should only contain the opaque rendering objects.
  13506. *
  13507. * This should be used just in transparent or transmissive materials.
  13508. *
  13509. * @tsl
  13510. * @function
  13511. * @param {?Node} [uv=screenUV] - The uv node.
  13512. * @param {?Node} [level=null] - The level node.
  13513. * @returns {ViewportTextureNode}
  13514. */
  13515. const viewportOpaqueMipTexture = ( uv = screenUV, level = null ) => _singletonOpaqueViewportTextureNode.sample( uv, level ); // TODO: Use once() when sample() supports it
  13516. let _sharedDepthbuffer = null;
  13517. /**
  13518. * Represents the depth of the current viewport as a texture. This module
  13519. * can be used in combination with viewport texture to achieve effects
  13520. * that require depth evaluation.
  13521. *
  13522. * @augments ViewportTextureNode
  13523. */
  13524. class ViewportDepthTextureNode extends ViewportTextureNode {
  13525. static get type() {
  13526. return 'ViewportDepthTextureNode';
  13527. }
  13528. /**
  13529. * Constructs a new viewport depth texture node.
  13530. *
  13531. * @param {Node} [uvNode=screenUV] - The uv node.
  13532. * @param {?Node} [levelNode=null] - The level node.
  13533. */
  13534. constructor( uvNode = screenUV, levelNode = null ) {
  13535. if ( _sharedDepthbuffer === null ) {
  13536. _sharedDepthbuffer = new DepthTexture();
  13537. }
  13538. super( uvNode, levelNode, _sharedDepthbuffer );
  13539. }
  13540. /**
  13541. * Overwritten so the method always returns the unique shared
  13542. * depth texture.
  13543. *
  13544. * @return {DepthTexture} The shared depth texture.
  13545. */
  13546. getTextureForReference() {
  13547. return _sharedDepthbuffer;
  13548. }
  13549. }
  13550. /**
  13551. * TSL function for a viewport depth texture node.
  13552. *
  13553. * @tsl
  13554. * @function
  13555. * @param {?Node} [uvNode=screenUV] - The uv node.
  13556. * @param {?Node} [levelNode=null] - The level node.
  13557. * @returns {ViewportDepthTextureNode}
  13558. */
  13559. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13560. /**
  13561. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13562. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13563. * fragment or for depth evaluation purposes.
  13564. *
  13565. * @augments Node
  13566. */
  13567. class ViewportDepthNode extends Node {
  13568. static get type() {
  13569. return 'ViewportDepthNode';
  13570. }
  13571. /**
  13572. * Constructs a new viewport depth node.
  13573. *
  13574. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13575. * @param {?Node} [valueNode=null] - The value node.
  13576. */
  13577. constructor( scope, valueNode = null ) {
  13578. super( 'float' );
  13579. /**
  13580. * The node behaves differently depending on which scope is selected.
  13581. *
  13582. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13583. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13584. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13585. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13586. *
  13587. * @type {('depth'|'depthBase'|'linearDepth')}
  13588. */
  13589. this.scope = scope;
  13590. /**
  13591. * Can be used to define a custom depth value.
  13592. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13593. *
  13594. * @type {?Node}
  13595. * @default null
  13596. */
  13597. this.valueNode = valueNode;
  13598. /**
  13599. * This flag can be used for type testing.
  13600. *
  13601. * @type {boolean}
  13602. * @readonly
  13603. * @default true
  13604. */
  13605. this.isViewportDepthNode = true;
  13606. }
  13607. generate( builder ) {
  13608. const { scope } = this;
  13609. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13610. return builder.getFragDepth();
  13611. }
  13612. return super.generate( builder );
  13613. }
  13614. setup( { camera } ) {
  13615. const { scope } = this;
  13616. const value = this.valueNode;
  13617. let node = null;
  13618. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13619. if ( value !== null ) {
  13620. node = depthBase().assign( value );
  13621. }
  13622. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13623. if ( camera.isPerspectiveCamera ) {
  13624. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13625. } else {
  13626. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13627. }
  13628. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13629. if ( value !== null ) {
  13630. if ( camera.isPerspectiveCamera ) {
  13631. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13632. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13633. } else {
  13634. node = value;
  13635. }
  13636. } else {
  13637. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13638. }
  13639. }
  13640. return node;
  13641. }
  13642. }
  13643. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13644. ViewportDepthNode.DEPTH = 'depth';
  13645. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13646. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13647. /**
  13648. * TSL function for converting a viewZ value to an orthographic depth value.
  13649. *
  13650. * @tsl
  13651. * @function
  13652. * @param {Node<float>} viewZ - The viewZ node.
  13653. * @param {Node<float>} near - The camera's near value.
  13654. * @param {Node<float>} far - The camera's far value.
  13655. * @returns {Node<float>}
  13656. */
  13657. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13658. /**
  13659. * TSL function for converting an orthographic depth value to a viewZ value.
  13660. *
  13661. * @tsl
  13662. * @function
  13663. * @param {Node<float>} depth - The orthographic depth.
  13664. * @param {Node<float>} near - The camera's near value.
  13665. * @param {Node<float>} far - The camera's far value.
  13666. * @returns {Node<float>}
  13667. */
  13668. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13669. /**
  13670. * TSL function for converting a viewZ value to a perspective depth value.
  13671. *
  13672. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13673. *
  13674. * @tsl
  13675. * @function
  13676. * @param {Node<float>} viewZ - The viewZ node.
  13677. * @param {Node<float>} near - The camera's near value.
  13678. * @param {Node<float>} far - The camera's far value.
  13679. * @returns {Node<float>}
  13680. */
  13681. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13682. /**
  13683. * TSL function for converting a perspective depth value to a viewZ value.
  13684. *
  13685. * @tsl
  13686. * @function
  13687. * @param {Node<float>} depth - The perspective depth.
  13688. * @param {Node<float>} near - The camera's near value.
  13689. * @param {Node<float>} far - The camera's far value.
  13690. * @returns {Node<float>}
  13691. */
  13692. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13693. /**
  13694. * TSL function for converting a viewZ value to a logarithmic depth value.
  13695. *
  13696. * @tsl
  13697. * @function
  13698. * @param {Node<float>} viewZ - The viewZ node.
  13699. * @param {Node<float>} near - The camera's near value.
  13700. * @param {Node<float>} far - The camera's far value.
  13701. * @returns {Node<float>}
  13702. */
  13703. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13704. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13705. // The final logarithmic depth formula used here is adapted from one described in an
  13706. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13707. // which was an improvement upon an earlier formula one described in an
  13708. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13709. // Ulrich's formula is the following:
  13710. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13711. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13712. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13713. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13714. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13715. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13716. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13717. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13718. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13719. // Outerra eventually made another improvement to their original "C-constant" variant,
  13720. // but it still does not incorporate the camera near plane (for this version,
  13721. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13722. // Here we make 4 changes to Ulrich's formula:
  13723. // 1. Clamp the camera near plane so we don't divide by 0.
  13724. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13725. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13726. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13727. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13728. // so we do the same here, hence the 'viewZ.negate()' call.
  13729. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13730. near = near.max( 1e-6 ).toVar();
  13731. const numerator = log2( viewZ.negate().div( near ) );
  13732. const denominator = log2( far.div( near ) );
  13733. return numerator.div( denominator );
  13734. };
  13735. /**
  13736. * TSL function for converting a logarithmic depth value to a viewZ value.
  13737. *
  13738. * @tsl
  13739. * @function
  13740. * @param {Node<float>} depth - The logarithmic depth.
  13741. * @param {Node<float>} near - The camera's near value.
  13742. * @param {Node<float>} far - The camera's far value.
  13743. * @returns {Node<float>}
  13744. */
  13745. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13746. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13747. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13748. // a negative viewZ).
  13749. const exponent = depth.mul( log( far.div( near ) ) );
  13750. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13751. };
  13752. /**
  13753. * TSL function for defining a value for the current fragment's depth.
  13754. *
  13755. * @tsl
  13756. * @function
  13757. * @param {Node<float>} value - The depth value to set.
  13758. * @returns {ViewportDepthNode<float>}
  13759. */
  13760. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13761. /**
  13762. * TSL object that represents the depth value for the current fragment.
  13763. *
  13764. * @tsl
  13765. * @type {ViewportDepthNode}
  13766. */
  13767. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13768. /**
  13769. * TSL function for converting a perspective depth value to linear depth.
  13770. *
  13771. * @tsl
  13772. * @function
  13773. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13774. * @returns {ViewportDepthNode<float>}
  13775. */
  13776. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13777. /**
  13778. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13779. *
  13780. * @tsl
  13781. * @type {ViewportDepthNode}
  13782. */
  13783. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13784. depth.assign = ( value ) => depthBase( value );
  13785. /**
  13786. * This node is used in {@link NodeMaterial} to setup the clipping
  13787. * which can happen hardware-accelerated (if supported) and optionally
  13788. * use alpha-to-coverage for anti-aliasing clipped edges.
  13789. *
  13790. * @augments Node
  13791. */
  13792. class ClippingNode extends Node {
  13793. static get type() {
  13794. return 'ClippingNode';
  13795. }
  13796. /**
  13797. * Constructs a new clipping node.
  13798. *
  13799. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13800. * the selected scope influences the behavior of the node and what type of code is generated.
  13801. */
  13802. constructor( scope = ClippingNode.DEFAULT ) {
  13803. super();
  13804. /**
  13805. * The node's scope. Similar to other nodes, the selected scope influences
  13806. * the behavior of the node and what type of code is generated.
  13807. *
  13808. * @type {('default'|'hardware'|'alphaToCoverage')}
  13809. */
  13810. this.scope = scope;
  13811. }
  13812. /**
  13813. * Setups the node depending on the selected scope.
  13814. *
  13815. * @param {NodeBuilder} builder - The current node builder.
  13816. * @return {Node} The result node.
  13817. */
  13818. setup( builder ) {
  13819. super.setup( builder );
  13820. const clippingContext = builder.clippingContext;
  13821. const { intersectionPlanes, unionPlanes } = clippingContext;
  13822. this.hardwareClipping = builder.material.hardwareClipping;
  13823. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13824. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13825. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13826. return this.setupHardwareClipping( unionPlanes, builder );
  13827. } else {
  13828. return this.setupDefault( intersectionPlanes, unionPlanes );
  13829. }
  13830. }
  13831. /**
  13832. * Setups alpha to coverage.
  13833. *
  13834. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13835. * @param {Array<Vector4>} unionPlanes - The union planes.
  13836. * @return {Node} The result node.
  13837. */
  13838. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13839. return Fn( () => {
  13840. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13841. const distanceGradient = float().toVar( 'distanceToGradient' );
  13842. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13843. const numUnionPlanes = unionPlanes.length;
  13844. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13845. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13846. Loop( numUnionPlanes, ( { i } ) => {
  13847. const plane = clippingPlanes.element( i );
  13848. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13849. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13850. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13851. } );
  13852. }
  13853. const numIntersectionPlanes = intersectionPlanes.length;
  13854. if ( numIntersectionPlanes > 0 ) {
  13855. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13856. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13857. Loop( numIntersectionPlanes, ( { i } ) => {
  13858. const plane = clippingPlanes.element( i );
  13859. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13860. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13861. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13862. } );
  13863. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13864. }
  13865. diffuseColor.a.mulAssign( clipOpacity );
  13866. diffuseColor.a.equal( 0.0 ).discard();
  13867. } )();
  13868. }
  13869. /**
  13870. * Setups the default clipping.
  13871. *
  13872. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13873. * @param {Array<Vector4>} unionPlanes - The union planes.
  13874. * @return {Node} The result node.
  13875. */
  13876. setupDefault( intersectionPlanes, unionPlanes ) {
  13877. return Fn( () => {
  13878. const numUnionPlanes = unionPlanes.length;
  13879. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13880. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13881. Loop( numUnionPlanes, ( { i } ) => {
  13882. const plane = clippingPlanes.element( i );
  13883. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13884. } );
  13885. }
  13886. const numIntersectionPlanes = intersectionPlanes.length;
  13887. if ( numIntersectionPlanes > 0 ) {
  13888. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13889. const clipped = bool( true ).toVar( 'clipped' );
  13890. Loop( numIntersectionPlanes, ( { i } ) => {
  13891. const plane = clippingPlanes.element( i );
  13892. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13893. } );
  13894. clipped.discard();
  13895. }
  13896. } )();
  13897. }
  13898. /**
  13899. * Setups hardware clipping.
  13900. *
  13901. * @param {Array<Vector4>} unionPlanes - The union planes.
  13902. * @param {NodeBuilder} builder - The current node builder.
  13903. * @return {Node} The result node.
  13904. */
  13905. setupHardwareClipping( unionPlanes, builder ) {
  13906. const numUnionPlanes = unionPlanes.length;
  13907. builder.enableHardwareClipping( numUnionPlanes );
  13908. return Fn( () => {
  13909. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13910. const hw_clip_distances = builtin( builder.getClipDistance() );
  13911. Loop( numUnionPlanes, ( { i } ) => {
  13912. const plane = clippingPlanes.element( i );
  13913. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13914. hw_clip_distances.element( i ).assign( distance );
  13915. } );
  13916. } )();
  13917. }
  13918. }
  13919. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13920. ClippingNode.DEFAULT = 'default';
  13921. ClippingNode.HARDWARE = 'hardware';
  13922. /**
  13923. * TSL function for setting up the default clipping logic.
  13924. *
  13925. * @tsl
  13926. * @function
  13927. * @returns {ClippingNode}
  13928. */
  13929. const clipping = () => new ClippingNode();
  13930. /**
  13931. * TSL function for setting up alpha to coverage.
  13932. *
  13933. * @tsl
  13934. * @function
  13935. * @returns {ClippingNode}
  13936. */
  13937. const clippingAlpha = () => new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE );
  13938. /**
  13939. * TSL function for setting up hardware-based clipping.
  13940. *
  13941. * @tsl
  13942. * @function
  13943. * @returns {ClippingNode}
  13944. */
  13945. const hardwareClipping = () => new ClippingNode( ClippingNode.HARDWARE );
  13946. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13947. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13948. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13949. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  13950. } );
  13951. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13952. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13953. } );
  13954. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13955. // Find the discretized derivatives of our coordinates
  13956. const maxDeriv = max$1(
  13957. length( dFdx( position.xyz ) ),
  13958. length( dFdy( position.xyz ) )
  13959. );
  13960. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13961. // Find two nearest log-discretized noise scales
  13962. const pixScales = vec2(
  13963. exp2( floor( log2( pixScale ) ) ),
  13964. exp2( ceil( log2( pixScale ) ) )
  13965. );
  13966. // Compute alpha thresholds at our two noise scales
  13967. const alpha = vec2(
  13968. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13969. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13970. );
  13971. // Factor to interpolate lerp with
  13972. const lerpFactor = fract( log2( pixScale ) );
  13973. // Interpolate alpha threshold from noise at two scales
  13974. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13975. // Pass into CDF to compute uniformly distrib threshold
  13976. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13977. const cases = vec3(
  13978. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13979. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13980. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13981. // Find our final, uniformly distributed alpha threshold (ατ)
  13982. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13983. // Avoids ατ == 0. Could also do ατ =1-ατ
  13984. return clamp( threshold, 1.0e-6, 1.0 );
  13985. } ).setLayout( {
  13986. name: 'getAlphaHashThreshold',
  13987. type: 'float',
  13988. inputs: [
  13989. { name: 'position', type: 'vec3' }
  13990. ]
  13991. } );
  13992. /**
  13993. * An attribute node for representing vertex colors.
  13994. *
  13995. * @augments AttributeNode
  13996. */
  13997. class VertexColorNode extends AttributeNode {
  13998. static get type() {
  13999. return 'VertexColorNode';
  14000. }
  14001. /**
  14002. * Constructs a new vertex color node.
  14003. *
  14004. * @param {number} index - The attribute index.
  14005. */
  14006. constructor( index ) {
  14007. super( null, 'vec4' );
  14008. /**
  14009. * This flag can be used for type testing.
  14010. *
  14011. * @type {boolean}
  14012. * @readonly
  14013. * @default true
  14014. */
  14015. this.isVertexColorNode = true;
  14016. /**
  14017. * The attribute index to enable more than one sets of vertex colors.
  14018. *
  14019. * @type {number}
  14020. * @default 0
  14021. */
  14022. this.index = index;
  14023. }
  14024. /**
  14025. * Overwrites the default implementation by honoring the attribute index.
  14026. *
  14027. * @param {NodeBuilder} builder - The current node builder.
  14028. * @return {string} The attribute name.
  14029. */
  14030. getAttributeName( /*builder*/ ) {
  14031. const index = this.index;
  14032. return 'color' + ( index > 0 ? index : '' );
  14033. }
  14034. generate( builder ) {
  14035. const attributeName = this.getAttributeName( builder );
  14036. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  14037. let result;
  14038. if ( geometryAttribute === true ) {
  14039. result = super.generate( builder );
  14040. } else {
  14041. // Vertex color fallback should be white
  14042. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  14043. }
  14044. return result;
  14045. }
  14046. serialize( data ) {
  14047. super.serialize( data );
  14048. data.index = this.index;
  14049. }
  14050. deserialize( data ) {
  14051. super.deserialize( data );
  14052. this.index = data.index;
  14053. }
  14054. }
  14055. /**
  14056. * TSL function for creating a reference node.
  14057. *
  14058. * @tsl
  14059. * @function
  14060. * @param {number} [index=0] - The attribute index.
  14061. * @returns {VertexColorNode}
  14062. */
  14063. const vertexColor = ( index = 0 ) => new VertexColorNode( index );
  14064. /**
  14065. * Represents a "Color Burn" blend mode.
  14066. *
  14067. * It's designed to darken the base layer's colors based on the color of the blend layer.
  14068. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  14069. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  14070. *
  14071. * @tsl
  14072. * @function
  14073. * @param {Node<vec3>} base - The base color.
  14074. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  14075. * @return {Node<vec3>} The result.
  14076. */
  14077. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14078. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  14079. } ).setLayout( {
  14080. name: 'blendBurn',
  14081. type: 'vec3',
  14082. inputs: [
  14083. { name: 'base', type: 'vec3' },
  14084. { name: 'blend', type: 'vec3' }
  14085. ]
  14086. } );
  14087. /**
  14088. * Represents a "Color Dodge" blend mode.
  14089. *
  14090. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  14091. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  14092. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  14093. *
  14094. * @tsl
  14095. * @function
  14096. * @param {Node<vec3>} base - The base color.
  14097. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14098. * @return {Node<vec3>} The result.
  14099. */
  14100. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14101. return min$1( base.div( blend.oneMinus() ), 1.0 );
  14102. } ).setLayout( {
  14103. name: 'blendDodge',
  14104. type: 'vec3',
  14105. inputs: [
  14106. { name: 'base', type: 'vec3' },
  14107. { name: 'blend', type: 'vec3' }
  14108. ]
  14109. } );
  14110. /**
  14111. * Represents a "Screen" blend mode.
  14112. *
  14113. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  14114. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  14115. * effects.
  14116. *
  14117. * @tsl
  14118. * @function
  14119. * @param {Node<vec3>} base - The base color.
  14120. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  14121. * @return {Node<vec3>} The result.
  14122. */
  14123. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14124. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  14125. } ).setLayout( {
  14126. name: 'blendScreen',
  14127. type: 'vec3',
  14128. inputs: [
  14129. { name: 'base', type: 'vec3' },
  14130. { name: 'blend', type: 'vec3' }
  14131. ]
  14132. } );
  14133. /**
  14134. * Represents a "Overlay" blend mode.
  14135. *
  14136. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  14137. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  14138. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  14139. *
  14140. * @tsl
  14141. * @function
  14142. * @param {Node<vec3>} base - The base color.
  14143. * @param {Node<vec3>} blend - The blend color
  14144. * @return {Node<vec3>} The result.
  14145. */
  14146. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14147. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  14148. } ).setLayout( {
  14149. name: 'blendOverlay',
  14150. type: 'vec3',
  14151. inputs: [
  14152. { name: 'base', type: 'vec3' },
  14153. { name: 'blend', type: 'vec3' }
  14154. ]
  14155. } );
  14156. /**
  14157. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  14158. * It assumes both input colors have non-premultiplied alpha.
  14159. *
  14160. * @tsl
  14161. * @function
  14162. * @param {Node<vec4>} base - The base color.
  14163. * @param {Node<vec4>} blend - The blend color
  14164. * @return {Node<vec4>} The result.
  14165. */
  14166. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  14167. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  14168. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  14169. } ).setLayout( {
  14170. name: 'blendColor',
  14171. type: 'vec4',
  14172. inputs: [
  14173. { name: 'base', type: 'vec4' },
  14174. { name: 'blend', type: 'vec4' }
  14175. ]
  14176. } );
  14177. /**
  14178. * Premultiplies the RGB channels of a color by its alpha channel.
  14179. *
  14180. * This function is useful for converting a non-premultiplied alpha color
  14181. * into a premultiplied alpha format, where the RGB values are scaled
  14182. * by the alpha value. Premultiplied alpha is often used in graphics
  14183. * rendering for certain operations, such as compositing and image processing.
  14184. *
  14185. * @tsl
  14186. * @function
  14187. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  14188. * @return {Node<vec4>} The color with premultiplied alpha.
  14189. */
  14190. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14191. return vec4( color.rgb.mul( color.a ), color.a );
  14192. }, { color: 'vec4', return: 'vec4' } );
  14193. /**
  14194. * Unpremultiplies the RGB channels of a color by its alpha channel.
  14195. *
  14196. * This function is useful for converting a premultiplied alpha color
  14197. * back into a non-premultiplied alpha format, where the RGB values are
  14198. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  14199. * rendering for certain operations, such as compositing and image processing.
  14200. *
  14201. * @tsl
  14202. * @function
  14203. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  14204. * @return {Node<vec4>} The color with non-premultiplied alpha.
  14205. */
  14206. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  14207. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  14208. return vec4( color.rgb.div( color.a ), color.a );
  14209. }, { color: 'vec4', return: 'vec4' } );
  14210. /**
  14211. * Base class for all node materials.
  14212. *
  14213. * @augments Material
  14214. */
  14215. class NodeMaterial extends Material {
  14216. static get type() {
  14217. return 'NodeMaterial';
  14218. }
  14219. /**
  14220. * Represents the type of the node material.
  14221. *
  14222. * @type {string}
  14223. */
  14224. get type() {
  14225. return this.constructor.type;
  14226. }
  14227. set type( _value ) { /* */ }
  14228. /**
  14229. * Constructs a new node material.
  14230. */
  14231. constructor() {
  14232. super();
  14233. /**
  14234. * This flag can be used for type testing.
  14235. *
  14236. * @type {boolean}
  14237. * @readonly
  14238. * @default true
  14239. */
  14240. this.isNodeMaterial = true;
  14241. /**
  14242. * Whether this material is affected by fog or not.
  14243. *
  14244. * @type {boolean}
  14245. * @default true
  14246. */
  14247. this.fog = true;
  14248. /**
  14249. * Whether this material is affected by lights or not.
  14250. *
  14251. * @type {boolean}
  14252. * @default false
  14253. */
  14254. this.lights = false;
  14255. /**
  14256. * Whether this material uses hardware clipping or not.
  14257. * This property is managed by the engine and should not be
  14258. * modified by apps.
  14259. *
  14260. * @type {boolean}
  14261. * @default false
  14262. */
  14263. this.hardwareClipping = false;
  14264. /**
  14265. * Node materials which set their `lights` property to `true`
  14266. * are affected by all lights of the scene. Sometimes selective
  14267. * lighting is wanted which means only _some_ lights in the scene
  14268. * affect a material. This can be achieved by creating an instance
  14269. * of {@link LightsNode} with a list of selective
  14270. * lights and assign the node to this property.
  14271. *
  14272. * ```js
  14273. * const customLightsNode = lights( [ light1, light2 ] );
  14274. * material.lightsNode = customLightsNode;
  14275. * ```
  14276. *
  14277. * @type {?LightsNode}
  14278. * @default null
  14279. */
  14280. this.lightsNode = null;
  14281. /**
  14282. * The environment of node materials can be defined by an environment
  14283. * map assigned to the `envMap` property or by `Scene.environment`
  14284. * if the node material is a PBR material. This node property allows to overwrite
  14285. * the default behavior and define the environment with a custom node.
  14286. *
  14287. * ```js
  14288. * material.envNode = pmremTexture( renderTarget.texture );
  14289. * ```
  14290. *
  14291. * @type {?Node<vec3>}
  14292. * @default null
  14293. */
  14294. this.envNode = null;
  14295. /**
  14296. * The lighting of node materials might be influenced by ambient occlusion.
  14297. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  14298. * and the respective `aoMapIntensity`. This node property allows to overwrite
  14299. * the default and define the ambient occlusion with a custom node instead.
  14300. *
  14301. * If you don't want to overwrite the diffuse color but modify the existing
  14302. * values instead, use {@link materialAO}.
  14303. *
  14304. * @type {?Node<float>}
  14305. * @default null
  14306. */
  14307. this.aoNode = null;
  14308. /**
  14309. * The diffuse color of node materials is by default inferred from the
  14310. * `color` and `map` properties. This node property allows to overwrite the default
  14311. * and define the diffuse color with a node instead.
  14312. *
  14313. * ```js
  14314. * material.colorNode = color( 0xff0000 ); // define red color
  14315. * ```
  14316. *
  14317. * If you don't want to overwrite the diffuse color but modify the existing
  14318. * values instead, use {@link materialColor}.
  14319. *
  14320. * ```js
  14321. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  14322. * ```
  14323. *
  14324. * @type {?Node<vec3>}
  14325. * @default null
  14326. */
  14327. this.colorNode = null;
  14328. /**
  14329. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  14330. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  14331. * and define the normals with a node instead.
  14332. *
  14333. * If you don't want to overwrite the normals but modify the existing values instead,
  14334. * use {@link materialNormal}.
  14335. *
  14336. * @type {?Node<vec3>}
  14337. * @default null
  14338. */
  14339. this.normalNode = null;
  14340. /**
  14341. * The opacity of node materials is by default inferred from the `opacity`
  14342. * and `alphaMap` properties. This node property allows to overwrite the default
  14343. * and define the opacity with a node instead.
  14344. *
  14345. * If you don't want to overwrite the opacity but modify the existing
  14346. * value instead, use {@link materialOpacity}.
  14347. *
  14348. * @type {?Node<float>}
  14349. * @default null
  14350. */
  14351. this.opacityNode = null;
  14352. /**
  14353. * This node can be used to implement a variety of filter-like effects. The idea is
  14354. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  14355. * to create an arbitrary effect and then assign the node composition to this property.
  14356. * Everything behind the object using this material will now be affected by a filter.
  14357. *
  14358. * ```js
  14359. * const material = new NodeMaterial()
  14360. * material.transparent = true;
  14361. *
  14362. * // everything behind the object will be monochromatic
  14363. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  14364. * ```
  14365. *
  14366. * Backdrop computations are part of the lighting so only lit materials can use this property.
  14367. *
  14368. * @type {?Node<vec3>}
  14369. * @default null
  14370. */
  14371. this.backdropNode = null;
  14372. /**
  14373. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  14374. *
  14375. * @type {?Node<float>}
  14376. * @default null
  14377. */
  14378. this.backdropAlphaNode = null;
  14379. /**
  14380. * The alpha test of node materials is by default inferred from the `alphaTest`
  14381. * property. This node property allows to overwrite the default and define the
  14382. * alpha test with a node instead.
  14383. *
  14384. * If you don't want to overwrite the alpha test but modify the existing
  14385. * value instead, use {@link materialAlphaTest}.
  14386. *
  14387. * @type {?Node<float>}
  14388. * @default null
  14389. */
  14390. this.alphaTestNode = null;
  14391. /**
  14392. * Discards the fragment if the mask value is `false`.
  14393. *
  14394. * @type {?Node<bool>}
  14395. * @default null
  14396. */
  14397. this.maskNode = null;
  14398. /**
  14399. * This node can be used to implement a shadow mask for the material.
  14400. *
  14401. * @type {?Node<bool>}
  14402. * @default null
  14403. */
  14404. this.maskShadowNode = null;
  14405. /**
  14406. * The local vertex positions are computed based on multiple factors like the
  14407. * attribute data, morphing or skinning. This node property allows to overwrite
  14408. * the default and define local vertex positions with nodes instead.
  14409. *
  14410. * If you don't want to overwrite the vertex positions but modify the existing
  14411. * values instead, use {@link positionLocal}.
  14412. *
  14413. *```js
  14414. * material.positionNode = positionLocal.add( displace );
  14415. * ```
  14416. *
  14417. * @type {?Node<vec3>}
  14418. * @default null
  14419. */
  14420. this.positionNode = null;
  14421. /**
  14422. * This node property is intended for logic which modifies geometry data once or per animation step.
  14423. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  14424. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  14425. * can be implemented.
  14426. *
  14427. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  14428. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  14429. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  14430. * eventually assigned to `geometryNode`.
  14431. *
  14432. * @type {?Function}
  14433. * @default null
  14434. */
  14435. this.geometryNode = null;
  14436. /**
  14437. * Allows to overwrite depth values in the fragment shader.
  14438. *
  14439. * @type {?Node<float>}
  14440. * @default null
  14441. */
  14442. this.depthNode = null;
  14443. /**
  14444. * Allows to overwrite the position used for shadow map rendering which
  14445. * is by default {@link positionWorld}, the vertex position
  14446. * in world space.
  14447. *
  14448. * @type {?Node<float>}
  14449. * @default null
  14450. */
  14451. this.receivedShadowPositionNode = null;
  14452. /**
  14453. * Allows to overwrite the geometry position used for shadow map projection which
  14454. * is by default {@link positionLocal}, the vertex position in local space.
  14455. *
  14456. * @type {?Node<float>}
  14457. * @default null
  14458. */
  14459. this.castShadowPositionNode = null;
  14460. /**
  14461. * This node can be used to influence how an object using this node material
  14462. * receive shadows.
  14463. *
  14464. * ```js
  14465. * const totalShadows = float( 1 ).toVar();
  14466. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  14467. * totalShadows.mulAssign( shadow );
  14468. * //return float( 1 ); // bypass received shadows
  14469. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  14470. * } );
  14471. *
  14472. * @type {?(Function|FunctionNode<vec4>)}
  14473. * @default null
  14474. */
  14475. this.receivedShadowNode = null;
  14476. /**
  14477. * This node can be used to influence how an object using this node material
  14478. * casts shadows. To apply a color to shadows, you can simply do:
  14479. *
  14480. * ```js
  14481. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  14482. * ```
  14483. *
  14484. * Which can be nice to fake colored shadows of semi-transparent objects. It
  14485. * is also common to use the property with `Fn` function so checks are performed
  14486. * per fragment.
  14487. *
  14488. * ```js
  14489. * materialCustomShadow.castShadowNode = Fn( () => {
  14490. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  14491. * return materialColor;
  14492. * } )();
  14493. * ```
  14494. *
  14495. * @type {?Node<vec4>}
  14496. * @default null
  14497. */
  14498. this.castShadowNode = null;
  14499. /**
  14500. * This node can be used to define the final output of the material.
  14501. *
  14502. * TODO: Explain the differences to `fragmentNode`.
  14503. *
  14504. * @type {?Node<vec4>}
  14505. * @default null
  14506. */
  14507. this.outputNode = null;
  14508. /**
  14509. * MRT configuration is done on renderer or pass level. This node allows to
  14510. * overwrite what values are written into MRT targets on material level. This
  14511. * can be useful for implementing selective FX features that should only affect
  14512. * specific objects.
  14513. *
  14514. * @type {?MRTNode}
  14515. * @default null
  14516. */
  14517. this.mrtNode = null;
  14518. /**
  14519. * This node property can be used if you need complete freedom in implementing
  14520. * the fragment shader. Assigning a node will replace the built-in material
  14521. * logic used in the fragment stage.
  14522. *
  14523. * @type {?Node<vec4>}
  14524. * @default null
  14525. */
  14526. this.fragmentNode = null;
  14527. /**
  14528. * This node property can be used if you need complete freedom in implementing
  14529. * the vertex shader. Assigning a node will replace the built-in material logic
  14530. * used in the vertex stage.
  14531. *
  14532. * @type {?Node<vec4>}
  14533. * @default null
  14534. */
  14535. this.vertexNode = null;
  14536. /**
  14537. * This node can be used as a global context management component for this material.
  14538. *
  14539. * @type {?ContextNode}
  14540. * @default null
  14541. */
  14542. this.contextNode = null;
  14543. }
  14544. /**
  14545. * Returns an array of child nodes for this material.
  14546. *
  14547. * @private
  14548. * @returns {Array<{property: string, childNode: Node}>}
  14549. */
  14550. _getNodeChildren() {
  14551. const children = [];
  14552. for ( const property of Object.getOwnPropertyNames( this ) ) {
  14553. if ( property.startsWith( '_' ) === true ) continue;
  14554. const object = this[ property ];
  14555. if ( object && object.isNode === true ) {
  14556. children.push( { property, childNode: object } );
  14557. }
  14558. }
  14559. return children;
  14560. }
  14561. /**
  14562. * Allows to define a custom cache key that influence the material key computation
  14563. * for render objects.
  14564. *
  14565. * @return {string} The custom cache key.
  14566. */
  14567. customProgramCacheKey() {
  14568. const values = [];
  14569. for ( const { property, childNode } of this._getNodeChildren() ) {
  14570. values.push( hashString( property.slice( 0, -4 ) ), childNode.getCacheKey() );
  14571. }
  14572. return this.type + hashArray( values );
  14573. }
  14574. /**
  14575. * Builds this material with the given node builder.
  14576. *
  14577. * @param {NodeBuilder} builder - The current node builder.
  14578. */
  14579. build( builder ) {
  14580. this.setup( builder );
  14581. }
  14582. /**
  14583. * Setups a node material observer with the given builder.
  14584. *
  14585. * @param {NodeBuilder} builder - The current node builder.
  14586. * @return {NodeMaterialObserver} The node material observer.
  14587. */
  14588. setupObserver( builder ) {
  14589. return new NodeMaterialObserver( builder );
  14590. }
  14591. /**
  14592. * Setups the vertex and fragment stage of this node material.
  14593. *
  14594. * @param {NodeBuilder} builder - The current node builder.
  14595. */
  14596. setup( builder ) {
  14597. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14598. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14599. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14600. const renderer = builder.renderer;
  14601. const renderTarget = renderer.getRenderTarget();
  14602. // < CONTEXT >
  14603. if ( renderer.contextNode.isContextNode === true ) {
  14604. builder.context = { ...builder.context, ...renderer.contextNode.getFlowContextData() };
  14605. } else {
  14606. error( 'NodeMaterial: "renderer.contextNode" must be an instance of `context()`.' );
  14607. }
  14608. if ( this.contextNode !== null ) {
  14609. if ( this.contextNode.isContextNode === true ) {
  14610. builder.context = { ...builder.context, ...this.contextNode.getFlowContextData() };
  14611. } else {
  14612. error( 'NodeMaterial: "material.contextNode" must be an instance of `context()`.' );
  14613. }
  14614. }
  14615. // < VERTEX STAGE >
  14616. builder.addStack();
  14617. const mvp = this.setupVertex( builder );
  14618. const vertexNode = subBuild( this.vertexNode || mvp, 'VERTEX' );
  14619. builder.context.clipSpace = vertexNode;
  14620. builder.stack.outputNode = vertexNode;
  14621. this.setupHardwareClipping( builder );
  14622. if ( this.geometryNode !== null ) {
  14623. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14624. }
  14625. builder.addFlow( 'vertex', builder.removeStack() );
  14626. // < FRAGMENT STAGE >
  14627. builder.addStack();
  14628. let resultNode;
  14629. const clippingNode = this.setupClipping( builder );
  14630. if ( this.depthWrite === true || this.depthTest === true ) {
  14631. // only write depth if depth buffer is configured
  14632. if ( renderTarget !== null ) {
  14633. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14634. } else {
  14635. if ( renderer.depth === true ) this.setupDepth( builder );
  14636. }
  14637. }
  14638. if ( this.fragmentNode === null ) {
  14639. this.setupDiffuseColor( builder );
  14640. this.setupVariants( builder );
  14641. const outgoingLightNode = this.setupLighting( builder );
  14642. if ( clippingNode !== null ) builder.stack.addToStack( clippingNode );
  14643. // force unsigned floats - useful for RenderTargets
  14644. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14645. resultNode = this.setupOutput( builder, basicOutput );
  14646. // OUTPUT NODE
  14647. output.assign( resultNode );
  14648. //
  14649. const isCustomOutput = this.outputNode !== null;
  14650. if ( isCustomOutput ) resultNode = this.outputNode;
  14651. //
  14652. if ( builder.context.getOutput ) {
  14653. resultNode = builder.context.getOutput( resultNode, builder );
  14654. }
  14655. // MRT
  14656. if ( renderTarget !== null ) {
  14657. const mrt = renderer.getMRT();
  14658. const materialMRT = this.mrtNode;
  14659. if ( mrt !== null ) {
  14660. if ( isCustomOutput ) output.assign( resultNode );
  14661. resultNode = mrt;
  14662. if ( materialMRT !== null ) {
  14663. resultNode = mrt.merge( materialMRT );
  14664. }
  14665. } else if ( materialMRT !== null ) {
  14666. resultNode = materialMRT;
  14667. }
  14668. }
  14669. } else {
  14670. let fragmentNode = this.fragmentNode;
  14671. if ( fragmentNode.isOutputStructNode !== true ) {
  14672. fragmentNode = vec4( fragmentNode );
  14673. }
  14674. resultNode = this.setupOutput( builder, fragmentNode );
  14675. }
  14676. builder.stack.outputNode = resultNode;
  14677. builder.addFlow( 'fragment', builder.removeStack() );
  14678. // < OBSERVER >
  14679. builder.observer = this.setupObserver( builder );
  14680. }
  14681. /**
  14682. * Setups the clipping node.
  14683. *
  14684. * @param {NodeBuilder} builder - The current node builder.
  14685. * @return {ClippingNode} The clipping node.
  14686. */
  14687. setupClipping( builder ) {
  14688. if ( builder.clippingContext === null ) return null;
  14689. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14690. let result = null;
  14691. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14692. const samples = builder.renderer.currentSamples;
  14693. if ( this.alphaToCoverage && samples > 1 ) {
  14694. // to be added to flow when the color/alpha value has been determined
  14695. result = clippingAlpha();
  14696. } else {
  14697. builder.stack.addToStack( clipping() );
  14698. }
  14699. }
  14700. return result;
  14701. }
  14702. /**
  14703. * Setups the hardware clipping if available on the current device.
  14704. *
  14705. * @param {NodeBuilder} builder - The current node builder.
  14706. */
  14707. setupHardwareClipping( builder ) {
  14708. this.hardwareClipping = false;
  14709. if ( builder.clippingContext === null ) return;
  14710. const candidateCount = builder.clippingContext.unionPlanes.length;
  14711. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14712. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14713. builder.stack.addToStack( hardwareClipping() );
  14714. this.hardwareClipping = true;
  14715. }
  14716. return;
  14717. }
  14718. /**
  14719. * Setups the depth of this material.
  14720. *
  14721. * @param {NodeBuilder} builder - The current node builder.
  14722. */
  14723. setupDepth( builder ) {
  14724. const { renderer, camera } = builder;
  14725. // Depth
  14726. let depthNode = this.depthNode;
  14727. if ( depthNode === null ) {
  14728. const mrt = renderer.getMRT();
  14729. if ( mrt && mrt.has( 'depth' ) ) {
  14730. depthNode = mrt.get( 'depth' );
  14731. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14732. if ( camera.isPerspectiveCamera ) {
  14733. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14734. } else {
  14735. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14736. }
  14737. }
  14738. }
  14739. if ( depthNode !== null ) {
  14740. depth.assign( depthNode ).toStack();
  14741. }
  14742. }
  14743. /**
  14744. * Setups the position node in view space. This method exists
  14745. * so derived node materials can modify the implementation e.g. sprite materials.
  14746. *
  14747. * @param {NodeBuilder} builder - The current node builder.
  14748. * @return {Node<vec3>} The position in view space.
  14749. */
  14750. setupPositionView( /*builder*/ ) {
  14751. return modelViewMatrix.mul( positionLocal ).xyz;
  14752. }
  14753. /**
  14754. * Setups the position in clip space.
  14755. *
  14756. * @param {NodeBuilder} builder - The current node builder.
  14757. * @return {Node<vec4>} The position in view space.
  14758. */
  14759. setupModelViewProjection( /*builder*/ ) {
  14760. return cameraProjectionMatrix.mul( positionView );
  14761. }
  14762. /**
  14763. * Setups the logic for the vertex stage.
  14764. *
  14765. * @param {NodeBuilder} builder - The current node builder.
  14766. * @return {Node<vec4>} The position in clip space.
  14767. */
  14768. setupVertex( builder ) {
  14769. builder.addStack();
  14770. this.setupPosition( builder );
  14771. builder.context.position = builder.removeStack();
  14772. return modelViewProjection;
  14773. }
  14774. /**
  14775. * Setups the computation of the position in local space.
  14776. *
  14777. * @param {NodeBuilder} builder - The current node builder.
  14778. * @return {Node<vec3>} The position in local space.
  14779. */
  14780. setupPosition( builder ) {
  14781. const { object, geometry } = builder;
  14782. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14783. morphReference( object ).toStack();
  14784. }
  14785. if ( object.isSkinnedMesh === true ) {
  14786. skinning( object ).toStack();
  14787. }
  14788. if ( this.displacementMap ) {
  14789. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14790. const displacementScale = materialReference( 'displacementScale', 'float' );
  14791. const displacementBias = materialReference( 'displacementBias', 'float' );
  14792. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14793. }
  14794. if ( object.isBatchedMesh ) {
  14795. batch( object ).toStack();
  14796. }
  14797. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14798. instancedMesh( object ).toStack();
  14799. }
  14800. if ( this.positionNode !== null ) {
  14801. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14802. }
  14803. return positionLocal;
  14804. }
  14805. /**
  14806. * Setups the computation of the material's diffuse color.
  14807. *
  14808. * @param {NodeBuilder} builder - The current node builder.
  14809. * @param {BufferGeometry} geometry - The geometry.
  14810. */
  14811. setupDiffuseColor( builder ) {
  14812. const { object, geometry } = builder;
  14813. // MASK
  14814. if ( this.maskNode !== null ) {
  14815. // Discard if the mask is `false`
  14816. bool( this.maskNode ).not().discard();
  14817. }
  14818. // COLOR
  14819. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14820. // VERTEX COLORS
  14821. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14822. colorNode = colorNode.mul( vertexColor() );
  14823. }
  14824. // INSTANCED COLORS
  14825. if ( object.instanceColor ) {
  14826. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14827. colorNode = instanceColor.mul( colorNode );
  14828. }
  14829. if ( object.isBatchedMesh && object._colorsTexture ) {
  14830. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14831. colorNode = batchColor.mul( colorNode );
  14832. }
  14833. // DIFFUSE COLOR
  14834. diffuseColor.assign( colorNode );
  14835. // OPACITY
  14836. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14837. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14838. // ALPHA TEST
  14839. let alphaTestNode = null;
  14840. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14841. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14842. if ( this.alphaToCoverage === true ) {
  14843. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14844. diffuseColor.a.lessThanEqual( 0 ).discard();
  14845. } else {
  14846. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14847. }
  14848. }
  14849. // ALPHA HASH
  14850. if ( this.alphaHash === true ) {
  14851. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14852. }
  14853. // OPAQUE
  14854. if ( builder.isOpaque() ) {
  14855. diffuseColor.a.assign( 1.0 );
  14856. }
  14857. }
  14858. /**
  14859. * Abstract interface method that can be implemented by derived materials
  14860. * to setup material-specific node variables.
  14861. *
  14862. * @abstract
  14863. * @param {NodeBuilder} builder - The current node builder.
  14864. */
  14865. setupVariants( /*builder*/ ) {
  14866. // Interface function.
  14867. }
  14868. /**
  14869. * Setups the outgoing light node variable
  14870. *
  14871. * @return {Node<vec3>} The outgoing light node.
  14872. */
  14873. setupOutgoingLight() {
  14874. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14875. }
  14876. /**
  14877. * Setups the normal node from the material.
  14878. *
  14879. * @return {Node<vec3>} The normal node.
  14880. */
  14881. setupNormal() {
  14882. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14883. }
  14884. /**
  14885. * Setups the environment node from the material.
  14886. *
  14887. * @param {NodeBuilder} builder - The current node builder.
  14888. * @return {Node<vec4>} The environment node.
  14889. */
  14890. setupEnvironment( /*builder*/ ) {
  14891. let node = null;
  14892. if ( this.envNode ) {
  14893. node = this.envNode;
  14894. } else if ( this.envMap ) {
  14895. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14896. }
  14897. return node;
  14898. }
  14899. /**
  14900. * Setups the light map node from the material.
  14901. *
  14902. * @param {NodeBuilder} builder - The current node builder.
  14903. * @return {Node<vec3>} The light map node.
  14904. */
  14905. setupLightMap( builder ) {
  14906. let node = null;
  14907. if ( builder.material.lightMap ) {
  14908. node = new IrradianceNode( materialLightMap );
  14909. }
  14910. return node;
  14911. }
  14912. /**
  14913. * Setups the lights node based on the scene, environment and material.
  14914. *
  14915. * @param {NodeBuilder} builder - The current node builder.
  14916. * @return {LightsNode} The lights node.
  14917. */
  14918. setupLights( builder ) {
  14919. const materialLightsNode = [];
  14920. //
  14921. const envNode = this.setupEnvironment( builder );
  14922. if ( envNode && envNode.isLightingNode ) {
  14923. materialLightsNode.push( envNode );
  14924. }
  14925. const lightMapNode = this.setupLightMap( builder );
  14926. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14927. materialLightsNode.push( lightMapNode );
  14928. }
  14929. let aoNode = this.aoNode;
  14930. if ( aoNode === null && builder.material.aoMap ) {
  14931. aoNode = materialAO;
  14932. }
  14933. if ( builder.context.getAO ) {
  14934. aoNode = builder.context.getAO( aoNode, builder );
  14935. }
  14936. if ( aoNode ) {
  14937. materialLightsNode.push( new AONode( aoNode ) );
  14938. }
  14939. let lightsN = this.lightsNode || builder.lightsNode;
  14940. if ( materialLightsNode.length > 0 ) {
  14941. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14942. }
  14943. return lightsN;
  14944. }
  14945. /**
  14946. * This method should be implemented by most derived materials
  14947. * since it defines the material's lighting model.
  14948. *
  14949. * @abstract
  14950. * @param {NodeBuilder} builder - The current node builder.
  14951. * @return {LightingModel} The lighting model.
  14952. */
  14953. setupLightingModel( /*builder*/ ) {
  14954. // Interface function.
  14955. }
  14956. /**
  14957. * Setups the outgoing light node.
  14958. *
  14959. * @param {NodeBuilder} builder - The current node builder.
  14960. * @return {Node<vec3>} The outgoing light node.
  14961. */
  14962. setupLighting( builder ) {
  14963. const { material } = builder;
  14964. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14965. // OUTGOING LIGHT
  14966. const lights = this.lights === true || this.lightsNode !== null;
  14967. const lightsNode = lights ? this.setupLights( builder ) : null;
  14968. let outgoingLightNode = this.setupOutgoingLight( builder );
  14969. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14970. const lightingModel = this.setupLightingModel( builder ) || null;
  14971. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14972. } else if ( backdropNode !== null ) {
  14973. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14974. }
  14975. // EMISSIVE
  14976. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14977. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14978. outgoingLightNode = outgoingLightNode.add( emissive );
  14979. }
  14980. return outgoingLightNode;
  14981. }
  14982. /**
  14983. * Setup the fog.
  14984. *
  14985. * @param {NodeBuilder} builder - The current node builder.
  14986. * @param {Node<vec4>} outputNode - The existing output node.
  14987. * @return {Node<vec4>} The output node.
  14988. */
  14989. setupFog( builder, outputNode ) {
  14990. const fogNode = builder.fogNode;
  14991. if ( fogNode ) {
  14992. output.assign( outputNode );
  14993. outputNode = vec4( fogNode.toVar() );
  14994. }
  14995. return outputNode;
  14996. }
  14997. /**
  14998. * Setups premultiplied alpha.
  14999. *
  15000. * @param {NodeBuilder} builder - The current node builder.
  15001. * @param {Node<vec4>} outputNode - The existing output node.
  15002. * @return {Node<vec4>} The output node.
  15003. */
  15004. setupPremultipliedAlpha( builder, outputNode ) {
  15005. return premultiplyAlpha( outputNode );
  15006. }
  15007. /**
  15008. * Setups the output node.
  15009. *
  15010. * @param {NodeBuilder} builder - The current node builder.
  15011. * @param {Node<vec4>} outputNode - The existing output node.
  15012. * @return {Node<vec4>} The output node.
  15013. */
  15014. setupOutput( builder, outputNode ) {
  15015. // FOG
  15016. if ( this.fog === true ) {
  15017. outputNode = this.setupFog( builder, outputNode );
  15018. }
  15019. // PREMULTIPLIED ALPHA
  15020. if ( this.premultipliedAlpha === true ) {
  15021. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  15022. }
  15023. return outputNode;
  15024. }
  15025. /**
  15026. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  15027. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  15028. * defining all material properties of the classic type in the node type.
  15029. *
  15030. * @param {Material} material - The material to copy properties with their values to this node material.
  15031. */
  15032. setDefaultValues( material ) {
  15033. // This approach is to reuse the native refreshUniforms*
  15034. // and turn available the use of features like transmission and environment in core
  15035. for ( const property in material ) {
  15036. const value = material[ property ];
  15037. if ( this[ property ] === undefined ) {
  15038. this[ property ] = value;
  15039. if ( value && value.clone ) this[ property ] = value.clone();
  15040. }
  15041. }
  15042. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  15043. for ( const key in descriptors ) {
  15044. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  15045. descriptors[ key ].get !== undefined ) {
  15046. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  15047. }
  15048. }
  15049. }
  15050. /**
  15051. * Serializes this material to JSON.
  15052. *
  15053. * @param {?(Object|string)} meta - The meta information for serialization.
  15054. * @return {Object} The serialized node.
  15055. */
  15056. toJSON( meta ) {
  15057. const isRoot = ( meta === undefined || typeof meta === 'string' );
  15058. if ( isRoot ) {
  15059. meta = {
  15060. textures: {},
  15061. images: {},
  15062. nodes: {}
  15063. };
  15064. }
  15065. const data = Material.prototype.toJSON.call( this, meta );
  15066. data.inputNodes = {};
  15067. for ( const { property, childNode } of this._getNodeChildren() ) {
  15068. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  15069. }
  15070. // TODO: Copied from Object3D.toJSON
  15071. function extractFromCache( cache ) {
  15072. const values = [];
  15073. for ( const key in cache ) {
  15074. const data = cache[ key ];
  15075. delete data.metadata;
  15076. values.push( data );
  15077. }
  15078. return values;
  15079. }
  15080. if ( isRoot ) {
  15081. const textures = extractFromCache( meta.textures );
  15082. const images = extractFromCache( meta.images );
  15083. const nodes = extractFromCache( meta.nodes );
  15084. if ( textures.length > 0 ) data.textures = textures;
  15085. if ( images.length > 0 ) data.images = images;
  15086. if ( nodes.length > 0 ) data.nodes = nodes;
  15087. }
  15088. return data;
  15089. }
  15090. /**
  15091. * Copies the properties of the given node material to this instance.
  15092. *
  15093. * @param {NodeMaterial} source - The material to copy.
  15094. * @return {NodeMaterial} A reference to this node material.
  15095. */
  15096. copy( source ) {
  15097. this.lightsNode = source.lightsNode;
  15098. this.envNode = source.envNode;
  15099. this.aoNode = source.aoNode;
  15100. this.colorNode = source.colorNode;
  15101. this.normalNode = source.normalNode;
  15102. this.opacityNode = source.opacityNode;
  15103. this.backdropNode = source.backdropNode;
  15104. this.backdropAlphaNode = source.backdropAlphaNode;
  15105. this.alphaTestNode = source.alphaTestNode;
  15106. this.maskNode = source.maskNode;
  15107. this.maskShadowNode = source.maskShadowNode;
  15108. this.positionNode = source.positionNode;
  15109. this.geometryNode = source.geometryNode;
  15110. this.depthNode = source.depthNode;
  15111. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  15112. this.castShadowPositionNode = source.castShadowPositionNode;
  15113. this.receivedShadowNode = source.receivedShadowNode;
  15114. this.castShadowNode = source.castShadowNode;
  15115. this.outputNode = source.outputNode;
  15116. this.mrtNode = source.mrtNode;
  15117. this.fragmentNode = source.fragmentNode;
  15118. this.vertexNode = source.vertexNode;
  15119. this.contextNode = source.contextNode;
  15120. return super.copy( source );
  15121. }
  15122. }
  15123. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  15124. /**
  15125. * Node material version of {@link LineBasicMaterial}.
  15126. *
  15127. * @augments NodeMaterial
  15128. */
  15129. class LineBasicNodeMaterial extends NodeMaterial {
  15130. static get type() {
  15131. return 'LineBasicNodeMaterial';
  15132. }
  15133. /**
  15134. * Constructs a new line basic node material.
  15135. *
  15136. * @param {Object} [parameters] - The configuration parameter.
  15137. */
  15138. constructor( parameters ) {
  15139. super();
  15140. /**
  15141. * This flag can be used for type testing.
  15142. *
  15143. * @type {boolean}
  15144. * @readonly
  15145. * @default true
  15146. */
  15147. this.isLineBasicNodeMaterial = true;
  15148. this.setDefaultValues( _defaultValues$d );
  15149. this.setValues( parameters );
  15150. }
  15151. }
  15152. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  15153. /**
  15154. * Node material version of {@link LineDashedMaterial}.
  15155. *
  15156. * @augments NodeMaterial
  15157. */
  15158. class LineDashedNodeMaterial extends NodeMaterial {
  15159. static get type() {
  15160. return 'LineDashedNodeMaterial';
  15161. }
  15162. /**
  15163. * Constructs a new line dashed node material.
  15164. *
  15165. * @param {Object} [parameters] - The configuration parameter.
  15166. */
  15167. constructor( parameters ) {
  15168. super();
  15169. /**
  15170. * This flag can be used for type testing.
  15171. *
  15172. * @type {boolean}
  15173. * @readonly
  15174. * @default true
  15175. */
  15176. this.isLineDashedNodeMaterial = true;
  15177. this.setDefaultValues( _defaultValues$c );
  15178. /**
  15179. * The dash offset.
  15180. *
  15181. * @type {number}
  15182. * @default 0
  15183. */
  15184. this.dashOffset = 0;
  15185. /**
  15186. * The offset of dash materials is by default inferred from the `dashOffset`
  15187. * property. This node property allows to overwrite the default
  15188. * and define the offset with a node instead.
  15189. *
  15190. * If you don't want to overwrite the offset but modify the existing
  15191. * value instead, use {@link materialLineDashOffset}.
  15192. *
  15193. * @type {?Node<float>}
  15194. * @default null
  15195. */
  15196. this.offsetNode = null;
  15197. /**
  15198. * The scale of dash materials is by default inferred from the `scale`
  15199. * property. This node property allows to overwrite the default
  15200. * and define the scale with a node instead.
  15201. *
  15202. * If you don't want to overwrite the scale but modify the existing
  15203. * value instead, use {@link materialLineScale}.
  15204. *
  15205. * @type {?Node<float>}
  15206. * @default null
  15207. */
  15208. this.dashScaleNode = null;
  15209. /**
  15210. * The dash size of dash materials is by default inferred from the `dashSize`
  15211. * property. This node property allows to overwrite the default
  15212. * and define the dash size with a node instead.
  15213. *
  15214. * If you don't want to overwrite the dash size but modify the existing
  15215. * value instead, use {@link materialLineDashSize}.
  15216. *
  15217. * @type {?Node<float>}
  15218. * @default null
  15219. */
  15220. this.dashSizeNode = null;
  15221. /**
  15222. * The gap size of dash materials is by default inferred from the `gapSize`
  15223. * property. This node property allows to overwrite the default
  15224. * and define the gap size with a node instead.
  15225. *
  15226. * If you don't want to overwrite the gap size but modify the existing
  15227. * value instead, use {@link materialLineGapSize}.
  15228. *
  15229. * @type {?Node<float>}
  15230. * @default null
  15231. */
  15232. this.gapSizeNode = null;
  15233. this.setValues( parameters );
  15234. }
  15235. /**
  15236. * Setups the dash specific node variables.
  15237. *
  15238. * @param {NodeBuilder} builder - The current node builder.
  15239. */
  15240. setupVariants( /* builder */ ) {
  15241. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15242. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15243. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15244. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15245. dashSize.assign( dashSizeNode );
  15246. gapSize.assign( gapSizeNode );
  15247. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  15248. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  15249. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  15250. }
  15251. }
  15252. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  15253. /**
  15254. * This node material can be used to render lines with a size larger than one
  15255. * by representing them as instanced meshes.
  15256. *
  15257. * @augments NodeMaterial
  15258. */
  15259. class Line2NodeMaterial extends NodeMaterial {
  15260. static get type() {
  15261. return 'Line2NodeMaterial';
  15262. }
  15263. /**
  15264. * Constructs a new node material for wide line rendering.
  15265. *
  15266. * @param {Object} [parameters={}] - The configuration parameter.
  15267. */
  15268. constructor( parameters = {} ) {
  15269. super();
  15270. /**
  15271. * This flag can be used for type testing.
  15272. *
  15273. * @type {boolean}
  15274. * @readonly
  15275. * @default true
  15276. */
  15277. this.isLine2NodeMaterial = true;
  15278. this.setDefaultValues( _defaultValues$b );
  15279. /**
  15280. * Whether vertex colors should be used or not.
  15281. *
  15282. * @type {boolean}
  15283. * @default false
  15284. */
  15285. this.vertexColors = parameters.vertexColors;
  15286. /**
  15287. * The dash offset.
  15288. *
  15289. * @type {number}
  15290. * @default 0
  15291. */
  15292. this.dashOffset = 0;
  15293. /**
  15294. * Defines the lines color.
  15295. *
  15296. * @type {?Node<vec3>}
  15297. * @default null
  15298. */
  15299. this.lineColorNode = null;
  15300. /**
  15301. * Defines the offset.
  15302. *
  15303. * @type {?Node<float>}
  15304. * @default null
  15305. */
  15306. this.offsetNode = null;
  15307. /**
  15308. * Defines the dash scale.
  15309. *
  15310. * @type {?Node<float>}
  15311. * @default null
  15312. */
  15313. this.dashScaleNode = null;
  15314. /**
  15315. * Defines the dash size.
  15316. *
  15317. * @type {?Node<float>}
  15318. * @default null
  15319. */
  15320. this.dashSizeNode = null;
  15321. /**
  15322. * Defines the gap size.
  15323. *
  15324. * @type {?Node<float>}
  15325. * @default null
  15326. */
  15327. this.gapSizeNode = null;
  15328. /**
  15329. * Blending is set to `NoBlending` since transparency
  15330. * is not supported, yet.
  15331. *
  15332. * @type {number}
  15333. * @default 0
  15334. */
  15335. this.blending = NoBlending;
  15336. this._useDash = parameters.dashed;
  15337. this._useAlphaToCoverage = true;
  15338. this._useWorldUnits = false;
  15339. this.setValues( parameters );
  15340. }
  15341. /**
  15342. * Setups the vertex and fragment stage of this node material.
  15343. *
  15344. * @param {NodeBuilder} builder - The current node builder.
  15345. */
  15346. setup( builder ) {
  15347. const { renderer } = builder;
  15348. const useAlphaToCoverage = this._useAlphaToCoverage;
  15349. const vertexColors = this.vertexColors;
  15350. const useDash = this._useDash;
  15351. const useWorldUnits = this._useWorldUnits;
  15352. const trimSegment = Fn( ( { start, end } ) => {
  15353. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  15354. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  15355. const nearEstimate = b.mul( -0.5 ).div( a );
  15356. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  15357. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  15358. } ).setLayout( {
  15359. name: 'trimSegment',
  15360. type: 'vec4',
  15361. inputs: [
  15362. { name: 'start', type: 'vec4' },
  15363. { name: 'end', type: 'vec4' }
  15364. ]
  15365. } );
  15366. this.vertexNode = Fn( () => {
  15367. const instanceStart = attribute( 'instanceStart' );
  15368. const instanceEnd = attribute( 'instanceEnd' );
  15369. // camera space
  15370. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  15371. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  15372. if ( useDash ) {
  15373. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  15374. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  15375. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  15376. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  15377. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  15378. lineDistance = lineDistance.add( offsetNode );
  15379. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  15380. }
  15381. if ( useWorldUnits ) {
  15382. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  15383. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  15384. }
  15385. const aspect = viewport.z.div( viewport.w );
  15386. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  15387. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  15388. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  15389. // perhaps there is a more elegant solution -- WestLangley
  15390. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  15391. If( perspective, () => {
  15392. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  15393. end.assign( trimSegment( { start: start, end: end } ) );
  15394. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  15395. start.assign( trimSegment( { start: end, end: start } ) );
  15396. } );
  15397. } );
  15398. // clip space
  15399. const clipStart = cameraProjectionMatrix.mul( start );
  15400. const clipEnd = cameraProjectionMatrix.mul( end );
  15401. // ndc space
  15402. const ndcStart = clipStart.xyz.div( clipStart.w );
  15403. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  15404. // direction
  15405. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  15406. // account for clip-space aspect ratio
  15407. dir.x.assign( dir.x.mul( aspect ) );
  15408. dir.assign( dir.normalize() );
  15409. const clip = vec4().toVar();
  15410. if ( useWorldUnits ) {
  15411. // get the offset direction as perpendicular to the view vector
  15412. const worldDir = end.xyz.sub( start.xyz ).normalize();
  15413. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  15414. const worldUp = worldDir.cross( tmpFwd ).normalize();
  15415. const worldFwd = worldDir.cross( worldUp );
  15416. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  15417. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  15418. // height offset
  15419. const hw = materialLineWidth.mul( 0.5 );
  15420. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  15421. // don't extend the line if we're rendering dashes because we
  15422. // won't be rendering the endcaps
  15423. if ( ! useDash ) {
  15424. // cap extension
  15425. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  15426. // add width to the box
  15427. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  15428. // endcaps
  15429. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  15430. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  15431. } );
  15432. }
  15433. // project the worldpos
  15434. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  15435. // shift the depth of the projected points so the line
  15436. // segments overlap neatly
  15437. const clipPose = vec3().toVar();
  15438. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  15439. clip.z.assign( clipPose.z.mul( clip.w ) );
  15440. } else {
  15441. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  15442. // undo aspect ratio adjustment
  15443. dir.x.assign( dir.x.div( aspect ) );
  15444. offset.x.assign( offset.x.div( aspect ) );
  15445. // sign flip
  15446. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  15447. // endcaps
  15448. If( positionGeometry.y.lessThan( 0.0 ), () => {
  15449. offset.assign( offset.sub( dir ) );
  15450. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  15451. offset.assign( offset.add( dir ) );
  15452. } );
  15453. // adjust for linewidth
  15454. offset.assign( offset.mul( materialLineWidth ) );
  15455. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  15456. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  15457. // select end
  15458. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  15459. // back to clip space
  15460. offset.assign( offset.mul( clip.w ) );
  15461. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  15462. }
  15463. return clip;
  15464. } )();
  15465. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  15466. const p13 = p1.sub( p3 );
  15467. const p43 = p4.sub( p3 );
  15468. const p21 = p2.sub( p1 );
  15469. const d1343 = p13.dot( p43 );
  15470. const d4321 = p43.dot( p21 );
  15471. const d1321 = p13.dot( p21 );
  15472. const d4343 = p43.dot( p43 );
  15473. const d2121 = p21.dot( p21 );
  15474. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  15475. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  15476. const mua = numer.div( denom ).clamp();
  15477. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  15478. return vec2( mua, mub );
  15479. } );
  15480. this.colorNode = Fn( () => {
  15481. const vUv = uv$1();
  15482. if ( useDash ) {
  15483. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  15484. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  15485. dashSize.assign( dashSizeNode );
  15486. gapSize.assign( gapSizeNode );
  15487. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  15488. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  15489. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  15490. }
  15491. const alpha = float( 1 ).toVar( 'alpha' );
  15492. if ( useWorldUnits ) {
  15493. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15494. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15495. // Find the closest points on the view ray and the line segment
  15496. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15497. const lineDir = worldEnd.sub( worldStart );
  15498. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15499. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15500. const p2 = rayEnd.mul( params.y );
  15501. const delta = p1.sub( p2 );
  15502. const len = delta.length();
  15503. const norm = len.div( materialLineWidth );
  15504. if ( ! useDash ) {
  15505. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15506. const dnorm = norm.fwidth();
  15507. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15508. } else {
  15509. norm.greaterThan( 0.5 ).discard();
  15510. }
  15511. }
  15512. } else {
  15513. // round endcaps
  15514. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15515. const a = vUv.x;
  15516. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15517. const len2 = a.mul( a ).add( b.mul( b ) );
  15518. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15519. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15520. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15521. } );
  15522. } else {
  15523. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15524. const a = vUv.x;
  15525. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15526. const len2 = a.mul( a ).add( b.mul( b ) );
  15527. len2.greaterThan( 1.0 ).discard();
  15528. } );
  15529. }
  15530. }
  15531. let lineColorNode;
  15532. if ( this.lineColorNode ) {
  15533. lineColorNode = this.lineColorNode;
  15534. } else {
  15535. if ( vertexColors ) {
  15536. const instanceColorStart = attribute( 'instanceColorStart' );
  15537. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15538. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15539. lineColorNode = instanceColor.mul( materialColor );
  15540. } else {
  15541. lineColorNode = materialColor;
  15542. }
  15543. }
  15544. return vec4( lineColorNode, alpha );
  15545. } )();
  15546. if ( this.transparent ) {
  15547. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15548. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportOpaqueMipTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15549. }
  15550. super.setup( builder );
  15551. }
  15552. /**
  15553. * Whether the lines should sized in world units or not.
  15554. * When set to `false` the unit is pixel.
  15555. *
  15556. * @type {boolean}
  15557. * @default false
  15558. */
  15559. get worldUnits() {
  15560. return this._useWorldUnits;
  15561. }
  15562. set worldUnits( value ) {
  15563. if ( this._useWorldUnits !== value ) {
  15564. this._useWorldUnits = value;
  15565. this.needsUpdate = true;
  15566. }
  15567. }
  15568. /**
  15569. * Whether the lines should be dashed or not.
  15570. *
  15571. * @type {boolean}
  15572. * @default false
  15573. */
  15574. get dashed() {
  15575. return this._useDash;
  15576. }
  15577. set dashed( value ) {
  15578. if ( this._useDash !== value ) {
  15579. this._useDash = value;
  15580. this.needsUpdate = true;
  15581. }
  15582. }
  15583. /**
  15584. * Whether alpha to coverage should be used or not.
  15585. *
  15586. * @type {boolean}
  15587. * @default true
  15588. */
  15589. get alphaToCoverage() {
  15590. return this._useAlphaToCoverage;
  15591. }
  15592. set alphaToCoverage( value ) {
  15593. if ( this._useAlphaToCoverage !== value ) {
  15594. this._useAlphaToCoverage = value;
  15595. this.needsUpdate = true;
  15596. }
  15597. }
  15598. }
  15599. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15600. /**
  15601. * Node material version of {@link MeshNormalMaterial}.
  15602. *
  15603. * @augments NodeMaterial
  15604. */
  15605. class MeshNormalNodeMaterial extends NodeMaterial {
  15606. static get type() {
  15607. return 'MeshNormalNodeMaterial';
  15608. }
  15609. /**
  15610. * Constructs a new mesh normal node material.
  15611. *
  15612. * @param {Object} [parameters] - The configuration parameter.
  15613. */
  15614. constructor( parameters ) {
  15615. super();
  15616. /**
  15617. * This flag can be used for type testing.
  15618. *
  15619. * @type {boolean}
  15620. * @readonly
  15621. * @default true
  15622. */
  15623. this.isMeshNormalNodeMaterial = true;
  15624. this.setDefaultValues( _defaultValues$a );
  15625. this.setValues( parameters );
  15626. }
  15627. /**
  15628. * Overwrites the default implementation by computing the diffuse color
  15629. * based on the normal data.
  15630. */
  15631. setupDiffuseColor() {
  15632. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15633. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15634. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15635. }
  15636. }
  15637. /**
  15638. * TSL function for creating an equirect uv node.
  15639. *
  15640. * Can be used to compute texture coordinates for projecting an
  15641. * equirectangular texture onto a mesh for using it as the scene's
  15642. * background.
  15643. *
  15644. * ```js
  15645. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15646. * ```
  15647. *
  15648. * @tsl
  15649. * @function
  15650. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15651. * @returns {Node<vec2>}
  15652. */
  15653. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15654. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15655. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15656. return vec2( u, v );
  15657. } );
  15658. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15659. /**
  15660. * This class represents a cube render target. It is a special version
  15661. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15662. *
  15663. * @augments WebGLCubeRenderTarget
  15664. */
  15665. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15666. /**
  15667. * Constructs a new cube render target.
  15668. *
  15669. * @param {number} [size=1] - The size of the render target.
  15670. * @param {RenderTarget~Options} [options] - The configuration object.
  15671. */
  15672. constructor( size = 1, options = {} ) {
  15673. super( size, options );
  15674. /**
  15675. * This flag can be used for type testing.
  15676. *
  15677. * @type {boolean}
  15678. * @readonly
  15679. * @default true
  15680. */
  15681. this.isCubeRenderTarget = true;
  15682. }
  15683. /**
  15684. * Converts the given equirectangular texture to a cube map.
  15685. *
  15686. * @param {Renderer} renderer - The renderer.
  15687. * @param {Texture} texture - The equirectangular texture.
  15688. * @return {CubeRenderTarget} A reference to this cube render target.
  15689. */
  15690. fromEquirectangularTexture( renderer, texture$1 ) {
  15691. const currentMinFilter = texture$1.minFilter;
  15692. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15693. texture$1.generateMipmaps = true;
  15694. this.texture.type = texture$1.type;
  15695. this.texture.colorSpace = texture$1.colorSpace;
  15696. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15697. this.texture.minFilter = texture$1.minFilter;
  15698. this.texture.magFilter = texture$1.magFilter;
  15699. const geometry = new BoxGeometry( 5, 5, 5 );
  15700. const uvNode = equirectUV( positionWorldDirection );
  15701. const material = new NodeMaterial();
  15702. material.colorNode = texture( texture$1, uvNode, 0 );
  15703. material.side = BackSide;
  15704. material.blending = NoBlending;
  15705. const mesh = new Mesh( geometry, material );
  15706. const scene = new Scene();
  15707. scene.add( mesh );
  15708. // Avoid blurred poles
  15709. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15710. const camera = new CubeCamera( 1, 10, this );
  15711. const currentMRT = renderer.getMRT();
  15712. renderer.setMRT( null );
  15713. camera.update( renderer, scene );
  15714. renderer.setMRT( currentMRT );
  15715. texture$1.minFilter = currentMinFilter;
  15716. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15717. mesh.geometry.dispose();
  15718. mesh.material.dispose();
  15719. return this;
  15720. }
  15721. }
  15722. const _cache$1 = new WeakMap();
  15723. /**
  15724. * This node can be used to automatically convert environment maps in the
  15725. * equirectangular format into the cube map format.
  15726. *
  15727. * @augments TempNode
  15728. */
  15729. class CubeMapNode extends TempNode {
  15730. static get type() {
  15731. return 'CubeMapNode';
  15732. }
  15733. /**
  15734. * Constructs a new cube map node.
  15735. *
  15736. * @param {Node} envNode - The node representing the environment map.
  15737. */
  15738. constructor( envNode ) {
  15739. super( 'vec3' );
  15740. /**
  15741. * The node representing the environment map.
  15742. *
  15743. * @type {Node}
  15744. */
  15745. this.envNode = envNode;
  15746. /**
  15747. * A reference to the internal cube texture.
  15748. *
  15749. * @private
  15750. * @type {?CubeTexture}
  15751. * @default null
  15752. */
  15753. this._cubeTexture = null;
  15754. /**
  15755. * A reference to the internal cube texture node.
  15756. *
  15757. * @private
  15758. * @type {CubeTextureNode}
  15759. */
  15760. this._cubeTextureNode = cubeTexture( null );
  15761. const defaultTexture = new CubeTexture();
  15762. defaultTexture.isRenderTargetTexture = true;
  15763. /**
  15764. * A default cube texture that acts as a placeholder.
  15765. * It is used when the conversion from equirectangular to cube
  15766. * map has not finished yet for a given texture.
  15767. *
  15768. * @private
  15769. * @type {CubeTexture}
  15770. */
  15771. this._defaultTexture = defaultTexture;
  15772. /**
  15773. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15774. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15775. *
  15776. * @type {string}
  15777. * @default 'render'
  15778. */
  15779. this.updateBeforeType = NodeUpdateType.RENDER;
  15780. }
  15781. updateBefore( frame ) {
  15782. const { renderer, material } = frame;
  15783. const envNode = this.envNode;
  15784. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15785. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15786. if ( texture && texture.isTexture ) {
  15787. const mapping = texture.mapping;
  15788. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15789. // check for converted cubemap map
  15790. if ( _cache$1.has( texture ) ) {
  15791. const cubeMap = _cache$1.get( texture );
  15792. mapTextureMapping( cubeMap, texture.mapping );
  15793. this._cubeTexture = cubeMap;
  15794. } else {
  15795. // create cube map from equirectangular map
  15796. const image = texture.image;
  15797. if ( isEquirectangularMapReady$1( image ) ) {
  15798. const renderTarget = new CubeRenderTarget( image.height );
  15799. renderTarget.fromEquirectangularTexture( renderer, texture );
  15800. mapTextureMapping( renderTarget.texture, texture.mapping );
  15801. this._cubeTexture = renderTarget.texture;
  15802. _cache$1.set( texture, renderTarget.texture );
  15803. texture.addEventListener( 'dispose', onTextureDispose );
  15804. } else {
  15805. // default cube texture as fallback when equirectangular texture is not yet loaded
  15806. this._cubeTexture = this._defaultTexture;
  15807. }
  15808. }
  15809. //
  15810. this._cubeTextureNode.value = this._cubeTexture;
  15811. } else {
  15812. // envNode already refers to a cube map
  15813. this._cubeTextureNode = this.envNode;
  15814. }
  15815. }
  15816. }
  15817. }
  15818. setup( builder ) {
  15819. this.updateBefore( builder );
  15820. return this._cubeTextureNode;
  15821. }
  15822. }
  15823. /**
  15824. * Returns true if the given equirectangular image has been fully loaded
  15825. * and is ready for further processing.
  15826. *
  15827. * @private
  15828. * @param {Image} image - The equirectangular image to check.
  15829. * @return {boolean} Whether the image is ready or not.
  15830. */
  15831. function isEquirectangularMapReady$1( image ) {
  15832. if ( image === null || image === undefined ) return false;
  15833. return image.height > 0;
  15834. }
  15835. /**
  15836. * This function is executed when `dispose()` is called on the equirectangular
  15837. * texture. In this case, the generated cube map with its render target
  15838. * is deleted as well.
  15839. *
  15840. * @private
  15841. * @param {Object} event - The event object.
  15842. */
  15843. function onTextureDispose( event ) {
  15844. const texture = event.target;
  15845. texture.removeEventListener( 'dispose', onTextureDispose );
  15846. const renderTarget = _cache$1.get( texture );
  15847. if ( renderTarget !== undefined ) {
  15848. _cache$1.delete( texture );
  15849. renderTarget.dispose();
  15850. }
  15851. }
  15852. /**
  15853. * This function makes sure the generated cube map uses the correct
  15854. * texture mapping that corresponds to the equirectangular original.
  15855. *
  15856. * @private
  15857. * @param {Texture} texture - The cube texture.
  15858. * @param {number} mapping - The original texture mapping.
  15859. */
  15860. function mapTextureMapping( texture, mapping ) {
  15861. if ( mapping === EquirectangularReflectionMapping ) {
  15862. texture.mapping = CubeReflectionMapping;
  15863. } else if ( mapping === EquirectangularRefractionMapping ) {
  15864. texture.mapping = CubeRefractionMapping;
  15865. }
  15866. }
  15867. /**
  15868. * TSL function for creating a cube map node.
  15869. *
  15870. * @tsl
  15871. * @function
  15872. * @param {Node} envNode - The node representing the environment map.
  15873. * @returns {CubeMapNode}
  15874. */
  15875. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15876. /**
  15877. * Represents a basic model for Image-based lighting (IBL). The environment
  15878. * is defined via environment maps in the equirectangular or cube map format.
  15879. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15880. * or {@link MeshPhongNodeMaterial}.
  15881. *
  15882. * @augments LightingNode
  15883. */
  15884. class BasicEnvironmentNode extends LightingNode {
  15885. static get type() {
  15886. return 'BasicEnvironmentNode';
  15887. }
  15888. /**
  15889. * Constructs a new basic environment node.
  15890. *
  15891. * @param {Node} [envNode=null] - A node representing the environment.
  15892. */
  15893. constructor( envNode = null ) {
  15894. super();
  15895. /**
  15896. * A node representing the environment.
  15897. *
  15898. * @type {Node}
  15899. * @default null
  15900. */
  15901. this.envNode = envNode;
  15902. }
  15903. setup( builder ) {
  15904. // environment property is used in the finish() method of BasicLightingModel
  15905. builder.context.environment = cubeMapNode( this.envNode );
  15906. }
  15907. }
  15908. /**
  15909. * A specific version of {@link IrradianceNode} that is only relevant
  15910. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15911. * requires a special scaling factor for the light map.
  15912. *
  15913. * @augments LightingNode
  15914. */
  15915. class BasicLightMapNode extends LightingNode {
  15916. static get type() {
  15917. return 'BasicLightMapNode';
  15918. }
  15919. /**
  15920. * Constructs a new basic light map node.
  15921. *
  15922. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15923. */
  15924. constructor( lightMapNode = null ) {
  15925. super();
  15926. /**
  15927. * The light map node.
  15928. *
  15929. * @type {?Node<vec3>}
  15930. */
  15931. this.lightMapNode = lightMapNode;
  15932. }
  15933. setup( builder ) {
  15934. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15935. const RECIPROCAL_PI = float( 1 / Math.PI );
  15936. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15937. }
  15938. }
  15939. /**
  15940. * Abstract class for implementing lighting models. The module defines
  15941. * multiple methods that concrete lighting models can implement. These
  15942. * methods are executed at different points during the light evaluation
  15943. * process.
  15944. */
  15945. class LightingModel {
  15946. /**
  15947. * This method is intended for setting up lighting model and context data
  15948. * which are later used in the evaluation process.
  15949. *
  15950. * @abstract
  15951. * @param {NodeBuilder} builder - The current node builder.
  15952. */
  15953. start( builder ) {
  15954. // lights ( direct )
  15955. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15956. // indirect
  15957. this.indirect( builder );
  15958. }
  15959. /**
  15960. * This method is intended for executing final tasks like final updates
  15961. * to the outgoing light.
  15962. *
  15963. * @abstract
  15964. * @param {NodeBuilder} builder - The current node builder.
  15965. */
  15966. finish( /*builder*/ ) { }
  15967. /**
  15968. * This method is intended for implementing the direct light term and
  15969. * executed during the build process of directional, point and spot light nodes.
  15970. *
  15971. * @abstract
  15972. * @param {Object} lightData - The light data.
  15973. * @param {NodeBuilder} builder - The current node builder.
  15974. */
  15975. direct( /*lightData, builder*/ ) { }
  15976. /**
  15977. * This method is intended for implementing the direct light term for
  15978. * rect area light nodes.
  15979. *
  15980. * @abstract
  15981. * @param {Object} lightData - The light data.
  15982. * @param {NodeBuilder} builder - The current node builder.
  15983. */
  15984. directRectArea( /*lightData, builder*/ ) {}
  15985. /**
  15986. * This method is intended for implementing the indirect light term.
  15987. *
  15988. * @abstract
  15989. * @param {NodeBuilder} builder - The current node builder.
  15990. */
  15991. indirect( /*builder*/ ) { }
  15992. /**
  15993. * This method is intended for implementing the ambient occlusion term.
  15994. * Unlike other methods, this method must be called manually by the lighting
  15995. * model in its indirect term.
  15996. *
  15997. * @abstract
  15998. * @param {NodeBuilder} builder - The current node builder.
  15999. */
  16000. ambientOcclusion( /*input, stack, builder*/ ) { }
  16001. }
  16002. /**
  16003. * Represents the lighting model for unlit materials. The only light contribution
  16004. * is baked indirect lighting modulated with ambient occlusion and the material's
  16005. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  16006. *
  16007. * @augments LightingModel
  16008. */
  16009. class BasicLightingModel extends LightingModel {
  16010. /**
  16011. * Constructs a new basic lighting model.
  16012. */
  16013. constructor() {
  16014. super();
  16015. }
  16016. /**
  16017. * Implements the baked indirect lighting with its modulation.
  16018. *
  16019. * @param {NodeBuilder} builder - The current node builder.
  16020. */
  16021. indirect( { context } ) {
  16022. const ambientOcclusion = context.ambientOcclusion;
  16023. const reflectedLight = context.reflectedLight;
  16024. const irradianceLightMap = context.irradianceLightMap;
  16025. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  16026. // accumulation (baked indirect lighting only)
  16027. if ( irradianceLightMap ) {
  16028. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  16029. } else {
  16030. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  16031. }
  16032. // modulation
  16033. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16034. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  16035. }
  16036. /**
  16037. * Implements the environment mapping.
  16038. *
  16039. * @param {NodeBuilder} builder - The current node builder.
  16040. */
  16041. finish( builder ) {
  16042. const { material, context } = builder;
  16043. const outgoingLight = context.outgoingLight;
  16044. const envNode = builder.context.environment;
  16045. if ( envNode ) {
  16046. switch ( material.combine ) {
  16047. case MultiplyOperation:
  16048. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  16049. break;
  16050. case MixOperation:
  16051. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  16052. break;
  16053. case AddOperation:
  16054. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  16055. break;
  16056. default:
  16057. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  16058. break;
  16059. }
  16060. }
  16061. }
  16062. }
  16063. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  16064. /**
  16065. * Node material version of {@link MeshBasicMaterial}.
  16066. *
  16067. * @augments NodeMaterial
  16068. */
  16069. class MeshBasicNodeMaterial extends NodeMaterial {
  16070. static get type() {
  16071. return 'MeshBasicNodeMaterial';
  16072. }
  16073. /**
  16074. * Constructs a new mesh basic node material.
  16075. *
  16076. * @param {Object} [parameters] - The configuration parameter.
  16077. */
  16078. constructor( parameters ) {
  16079. super();
  16080. /**
  16081. * This flag can be used for type testing.
  16082. *
  16083. * @type {boolean}
  16084. * @readonly
  16085. * @default true
  16086. */
  16087. this.isMeshBasicNodeMaterial = true;
  16088. /**
  16089. * Although the basic material is by definition unlit, we set
  16090. * this property to `true` since we use a lighting model to compute
  16091. * the outgoing light of the fragment shader.
  16092. *
  16093. * @type {boolean}
  16094. * @default true
  16095. */
  16096. this.lights = true;
  16097. this.setDefaultValues( _defaultValues$9 );
  16098. this.setValues( parameters );
  16099. }
  16100. /**
  16101. * Basic materials are not affected by normal and bump maps so we
  16102. * return by default {@link normalViewGeometry}.
  16103. *
  16104. * @return {Node<vec3>} The normal node.
  16105. */
  16106. setupNormal() {
  16107. return directionToFaceDirection( normalViewGeometry ); // see #28839
  16108. }
  16109. /**
  16110. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16111. * to implement the default environment mapping.
  16112. *
  16113. * @param {NodeBuilder} builder - The current node builder.
  16114. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16115. */
  16116. setupEnvironment( builder ) {
  16117. const envNode = super.setupEnvironment( builder );
  16118. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16119. }
  16120. /**
  16121. * This method must be overwritten since light maps are evaluated
  16122. * with a special scaling factor for basic materials.
  16123. *
  16124. * @param {NodeBuilder} builder - The current node builder.
  16125. * @return {?BasicLightMapNode<vec3>} The light map node.
  16126. */
  16127. setupLightMap( builder ) {
  16128. let node = null;
  16129. if ( builder.material.lightMap ) {
  16130. node = new BasicLightMapNode( materialLightMap );
  16131. }
  16132. return node;
  16133. }
  16134. /**
  16135. * The material overwrites this method because `lights` is set to `true` but
  16136. * we still want to return the diffuse color as the outgoing light.
  16137. *
  16138. * @return {Node<vec3>} The outgoing light node.
  16139. */
  16140. setupOutgoingLight() {
  16141. return diffuseColor.rgb;
  16142. }
  16143. /**
  16144. * Setups the lighting model.
  16145. *
  16146. * @return {BasicLightingModel} The lighting model.
  16147. */
  16148. setupLightingModel() {
  16149. return new BasicLightingModel();
  16150. }
  16151. }
  16152. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  16153. // Original approximation by Christophe Schlick '94
  16154. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  16155. // Optimized variant (presented by Epic at SIGGRAPH '13)
  16156. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  16157. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  16158. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  16159. } ); // validated
  16160. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  16161. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  16162. } ); // validated
  16163. const G_BlinnPhong_Implicit = () => float( 0.25 );
  16164. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  16165. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  16166. } );
  16167. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16168. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16169. const dotNH = normalView.dot( halfDir ).clamp();
  16170. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16171. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  16172. const G = G_BlinnPhong_Implicit();
  16173. const D = D_BlinnPhong( { dotNH } );
  16174. return F.mul( G ).mul( D );
  16175. } );
  16176. /**
  16177. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  16178. *
  16179. * @augments BasicLightingModel
  16180. */
  16181. class PhongLightingModel extends BasicLightingModel {
  16182. /**
  16183. * Constructs a new phong lighting model.
  16184. *
  16185. * @param {boolean} [specular=true] - Whether specular is supported or not.
  16186. */
  16187. constructor( specular = true ) {
  16188. super();
  16189. /**
  16190. * Whether specular is supported or not. Set this to `false` if you are
  16191. * looking for a Lambert-like material meaning a material for non-shiny
  16192. * surfaces, without specular highlights.
  16193. *
  16194. * @type {boolean}
  16195. * @default true
  16196. */
  16197. this.specular = specular;
  16198. }
  16199. /**
  16200. * Implements the direct lighting. The specular portion is optional an can be controlled
  16201. * with the {@link PhongLightingModel#specular} flag.
  16202. *
  16203. * @param {Object} lightData - The light data.
  16204. */
  16205. direct( { lightDirection, lightColor, reflectedLight } ) {
  16206. const dotNL = normalView.dot( lightDirection ).clamp();
  16207. const irradiance = dotNL.mul( lightColor );
  16208. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16209. if ( this.specular === true ) {
  16210. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  16211. }
  16212. }
  16213. /**
  16214. * Implements the indirect lighting.
  16215. *
  16216. * @param {NodeBuilder} builder - The current node builder.
  16217. */
  16218. indirect( builder ) {
  16219. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16220. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16221. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16222. }
  16223. }
  16224. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  16225. /**
  16226. * Node material version of {@link MeshLambertMaterial}.
  16227. *
  16228. * @augments NodeMaterial
  16229. */
  16230. class MeshLambertNodeMaterial extends NodeMaterial {
  16231. static get type() {
  16232. return 'MeshLambertNodeMaterial';
  16233. }
  16234. /**
  16235. * Constructs a new mesh lambert node material.
  16236. *
  16237. * @param {Object} [parameters] - The configuration parameter.
  16238. */
  16239. constructor( parameters ) {
  16240. super();
  16241. /**
  16242. * This flag can be used for type testing.
  16243. *
  16244. * @type {boolean}
  16245. * @readonly
  16246. * @default true
  16247. */
  16248. this.isMeshLambertNodeMaterial = true;
  16249. /**
  16250. * Set to `true` because lambert materials react on lights.
  16251. *
  16252. * @type {boolean}
  16253. * @default true
  16254. */
  16255. this.lights = true;
  16256. this.setDefaultValues( _defaultValues$8 );
  16257. this.setValues( parameters );
  16258. }
  16259. /**
  16260. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16261. * to implement the default environment mapping.
  16262. *
  16263. * @param {NodeBuilder} builder - The current node builder.
  16264. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16265. */
  16266. setupEnvironment( builder ) {
  16267. const envNode = super.setupEnvironment( builder );
  16268. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16269. }
  16270. /**
  16271. * Setups the lighting model.
  16272. *
  16273. * @return {PhongLightingModel} The lighting model.
  16274. */
  16275. setupLightingModel( /*builder*/ ) {
  16276. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  16277. }
  16278. }
  16279. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  16280. /**
  16281. * Node material version of {@link MeshPhongMaterial}.
  16282. *
  16283. * @augments NodeMaterial
  16284. */
  16285. class MeshPhongNodeMaterial extends NodeMaterial {
  16286. static get type() {
  16287. return 'MeshPhongNodeMaterial';
  16288. }
  16289. /**
  16290. * Constructs a new mesh lambert node material.
  16291. *
  16292. * @param {Object} [parameters] - The configuration parameter.
  16293. */
  16294. constructor( parameters ) {
  16295. super();
  16296. /**
  16297. * This flag can be used for type testing.
  16298. *
  16299. * @type {boolean}
  16300. * @readonly
  16301. * @default true
  16302. */
  16303. this.isMeshPhongNodeMaterial = true;
  16304. /**
  16305. * Set to `true` because phong materials react on lights.
  16306. *
  16307. * @type {boolean}
  16308. * @default true
  16309. */
  16310. this.lights = true;
  16311. /**
  16312. * The shininess of phong materials is by default inferred from the `shininess`
  16313. * property. This node property allows to overwrite the default
  16314. * and define the shininess with a node instead.
  16315. *
  16316. * If you don't want to overwrite the shininess but modify the existing
  16317. * value instead, use {@link materialShininess}.
  16318. *
  16319. * @type {?Node<float>}
  16320. * @default null
  16321. */
  16322. this.shininessNode = null;
  16323. /**
  16324. * The specular color of phong materials is by default inferred from the
  16325. * `specular` property. This node property allows to overwrite the default
  16326. * and define the specular color with a node instead.
  16327. *
  16328. * If you don't want to overwrite the specular color but modify the existing
  16329. * value instead, use {@link materialSpecular}.
  16330. *
  16331. * @type {?Node<vec3>}
  16332. * @default null
  16333. */
  16334. this.specularNode = null;
  16335. this.setDefaultValues( _defaultValues$7 );
  16336. this.setValues( parameters );
  16337. }
  16338. /**
  16339. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  16340. * to implement the default environment mapping.
  16341. *
  16342. * @param {NodeBuilder} builder - The current node builder.
  16343. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  16344. */
  16345. setupEnvironment( builder ) {
  16346. const envNode = super.setupEnvironment( builder );
  16347. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  16348. }
  16349. /**
  16350. * Setups the lighting model.
  16351. *
  16352. * @return {PhongLightingModel} The lighting model.
  16353. */
  16354. setupLightingModel( /*builder*/ ) {
  16355. return new PhongLightingModel();
  16356. }
  16357. /**
  16358. * Setups the phong specific node variables.
  16359. *
  16360. * @param {NodeBuilder} builder - The current node builder.
  16361. */
  16362. setupVariants( /*builder*/ ) {
  16363. // SHININESS
  16364. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16365. shininess.assign( shininessNode );
  16366. // SPECULAR COLOR
  16367. const specularNode = this.specularNode || materialSpecular;
  16368. specularColor.assign( specularNode );
  16369. }
  16370. copy( source ) {
  16371. this.shininessNode = source.shininessNode;
  16372. this.specularNode = source.specularNode;
  16373. return super.copy( source );
  16374. }
  16375. }
  16376. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  16377. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  16378. return float( 0 );
  16379. }
  16380. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  16381. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  16382. return geometryRoughness;
  16383. } );
  16384. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  16385. const { roughness } = inputs;
  16386. const geometryRoughness = getGeometryRoughness();
  16387. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  16388. roughnessFactor = roughnessFactor.add( geometryRoughness );
  16389. roughnessFactor = roughnessFactor.min( 1.0 );
  16390. return roughnessFactor;
  16391. } );
  16392. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  16393. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  16394. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  16395. const a2 = alpha.pow2();
  16396. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  16397. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  16398. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  16399. } ).setLayout( {
  16400. name: 'V_GGX_SmithCorrelated',
  16401. type: 'float',
  16402. inputs: [
  16403. { name: 'alpha', type: 'float' },
  16404. { name: 'dotNL', type: 'float' },
  16405. { name: 'dotNV', type: 'float' }
  16406. ]
  16407. } ); // validated
  16408. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16409. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  16410. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  16411. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  16412. const v = div( 0.5, gv.add( gl ) );
  16413. return v;
  16414. } ).setLayout( {
  16415. name: 'V_GGX_SmithCorrelated_Anisotropic',
  16416. type: 'float',
  16417. inputs: [
  16418. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16419. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16420. { name: 'dotTV', type: 'float', qualifier: 'in' },
  16421. { name: 'dotBV', type: 'float', qualifier: 'in' },
  16422. { name: 'dotTL', type: 'float', qualifier: 'in' },
  16423. { name: 'dotBL', type: 'float', qualifier: 'in' },
  16424. { name: 'dotNV', type: 'float', qualifier: 'in' },
  16425. { name: 'dotNL', type: 'float', qualifier: 'in' }
  16426. ]
  16427. } );
  16428. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  16429. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  16430. // alpha is "roughness squared" in Disney’s reparameterization
  16431. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  16432. const a2 = alpha.pow2();
  16433. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  16434. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  16435. } ).setLayout( {
  16436. name: 'D_GGX',
  16437. type: 'float',
  16438. inputs: [
  16439. { name: 'alpha', type: 'float' },
  16440. { name: 'dotNH', type: 'float' }
  16441. ]
  16442. } ); // validated
  16443. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  16444. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  16445. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  16446. const a2 = alphaT.mul( alphaB );
  16447. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  16448. const v2 = v.dot( v );
  16449. const w2 = a2.div( v2 );
  16450. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  16451. } ).setLayout( {
  16452. name: 'D_GGX_Anisotropic',
  16453. type: 'float',
  16454. inputs: [
  16455. { name: 'alphaT', type: 'float', qualifier: 'in' },
  16456. { name: 'alphaB', type: 'float', qualifier: 'in' },
  16457. { name: 'dotNH', type: 'float', qualifier: 'in' },
  16458. { name: 'dotTH', type: 'float', qualifier: 'in' },
  16459. { name: 'dotBH', type: 'float', qualifier: 'in' }
  16460. ]
  16461. } );
  16462. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  16463. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16464. const alpha = roughness.pow2(); // UE4's roughness
  16465. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16466. const dotNL = normalView$1.dot( lightDirection ).clamp();
  16467. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16468. const dotNH = normalView$1.dot( halfDir ).clamp();
  16469. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  16470. let F = F_Schlick( { f0, f90, dotVH } );
  16471. let V, D;
  16472. if ( defined( USE_IRIDESCENCE ) ) {
  16473. F = iridescence.mix( F, f );
  16474. }
  16475. if ( defined( USE_ANISOTROPY ) ) {
  16476. const dotTL = anisotropyT.dot( lightDirection );
  16477. const dotTV = anisotropyT.dot( positionViewDirection );
  16478. const dotTH = anisotropyT.dot( halfDir );
  16479. const dotBL = anisotropyB.dot( lightDirection );
  16480. const dotBV = anisotropyB.dot( positionViewDirection );
  16481. const dotBH = anisotropyB.dot( halfDir );
  16482. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16483. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16484. } else {
  16485. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16486. D = D_GGX( { alpha, dotNH } );
  16487. }
  16488. return F.mul( V ).mul( D );
  16489. } ); // validated
  16490. /**
  16491. * Precomputed DFG LUT for Image-Based Lighting
  16492. * Resolution: 16x16
  16493. * Samples: 4096 per texel
  16494. * Format: RG16F (2 half floats per texel: scale, bias)
  16495. */
  16496. const DATA = new Uint16Array( [
  16497. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  16498. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  16499. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  16500. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  16501. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  16502. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  16503. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  16504. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  16505. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  16506. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  16507. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  16508. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  16509. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  16510. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  16511. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  16512. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  16513. ] );
  16514. let lut = null;
  16515. const DFGLUT = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16516. if ( lut === null ) {
  16517. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  16518. lut.name = 'DFG_LUT';
  16519. lut.minFilter = LinearFilter;
  16520. lut.magFilter = LinearFilter;
  16521. lut.wrapS = ClampToEdgeWrapping;
  16522. lut.wrapT = ClampToEdgeWrapping;
  16523. lut.generateMipmaps = false;
  16524. lut.needsUpdate = true;
  16525. }
  16526. const uv = vec2( roughness, dotNV );
  16527. return texture( lut, uv ).rg;
  16528. } );
  16529. // GGX BRDF with multi-scattering energy compensation for direct lighting
  16530. // This provides more accurate energy conservation, especially for rough materials
  16531. // Based on "Practical Multiple Scattering Compensation for Microfacet Models"
  16532. // https://blog.selfshadow.com/publications/turquin/ms_comp_final.pdf
  16533. const BRDF_GGX_Multiscatter = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  16534. // Single-scattering BRDF (standard GGX)
  16535. const singleScatter = BRDF_GGX( { lightDirection, f0, f90, roughness: _roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } );
  16536. // Multi-scattering compensation
  16537. const dotNL = normalView.dot( lightDirection ).clamp();
  16538. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16539. // Precomputed DFG values for view and light directions
  16540. const dfgV = DFGLUT( { roughness: _roughness, dotNV } );
  16541. const dfgL = DFGLUT( { roughness: _roughness, dotNV: dotNL } );
  16542. // Single-scattering energy for view and light
  16543. const FssEss_V = f0.mul( dfgV.x ).add( f90.mul( dfgV.y ) );
  16544. const FssEss_L = f0.mul( dfgL.x ).add( f90.mul( dfgL.y ) );
  16545. const Ess_V = dfgV.x.add( dfgV.y );
  16546. const Ess_L = dfgL.x.add( dfgL.y );
  16547. // Energy lost to multiple scattering
  16548. const Ems_V = float( 1.0 ).sub( Ess_V );
  16549. const Ems_L = float( 1.0 ).sub( Ess_L );
  16550. // Average Fresnel reflectance
  16551. const Favg = f0.add( f0.oneMinus().mul( 0.047619 ) ); // 1/21
  16552. // Multiple scattering contribution
  16553. // Uses geometric mean of view and light contributions for better energy distribution
  16554. const Fms = FssEss_V.mul( FssEss_L ).mul( Favg ).div( float( 1.0 ).sub( Ems_V.mul( Ems_L ).mul( Favg ).mul( Favg ) ).add( EPSILON ) );
  16555. // Energy compensation factor
  16556. const compensationFactor = Ems_V.mul( Ems_L );
  16557. const multiScatter = Fms.mul( compensationFactor );
  16558. return singleScatter.add( multiScatter );
  16559. } );
  16560. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16561. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16562. const fab = DFGLUT( { dotNV, roughness } );
  16563. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16564. } );
  16565. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16566. const x = dotVH.oneMinus().saturate();
  16567. const x2 = x.mul( x );
  16568. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16569. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16570. } ).setLayout( {
  16571. name: 'Schlick_to_F0',
  16572. type: 'vec3',
  16573. inputs: [
  16574. { name: 'f', type: 'vec3' },
  16575. { name: 'f90', type: 'float' },
  16576. { name: 'dotVH', type: 'float' }
  16577. ]
  16578. } );
  16579. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16580. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16581. const alpha = roughness.pow2();
  16582. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16583. const invAlpha = float( 1.0 ).div( alpha );
  16584. const cos2h = dotNH.pow2();
  16585. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16586. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16587. } ).setLayout( {
  16588. name: 'D_Charlie',
  16589. type: 'float',
  16590. inputs: [
  16591. { name: 'roughness', type: 'float' },
  16592. { name: 'dotNH', type: 'float' }
  16593. ]
  16594. } );
  16595. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16596. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16597. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16598. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16599. } ).setLayout( {
  16600. name: 'V_Neubelt',
  16601. type: 'float',
  16602. inputs: [
  16603. { name: 'dotNV', type: 'float' },
  16604. { name: 'dotNL', type: 'float' }
  16605. ]
  16606. } );
  16607. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16608. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16609. const dotNL = normalView.dot( lightDirection ).clamp();
  16610. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16611. const dotNH = normalView.dot( halfDir ).clamp();
  16612. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16613. const V = V_Neubelt( { dotNV, dotNL } );
  16614. return sheen.mul( D ).mul( V );
  16615. } );
  16616. // Rect Area Light
  16617. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16618. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16619. // code: https://github.com/selfshadow/ltc_code/
  16620. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16621. const LUT_SIZE = 64.0;
  16622. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16623. const LUT_BIAS = 0.5 / LUT_SIZE;
  16624. const dotNV = N.dot( V ).saturate();
  16625. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16626. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16627. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16628. return uv;
  16629. } ).setLayout( {
  16630. name: 'LTC_Uv',
  16631. type: 'vec2',
  16632. inputs: [
  16633. { name: 'N', type: 'vec3' },
  16634. { name: 'V', type: 'vec3' },
  16635. { name: 'roughness', type: 'float' }
  16636. ]
  16637. } );
  16638. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16639. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16640. // An approximation of the form factor of a horizon-clipped rectangle.
  16641. const l = f.length();
  16642. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16643. } ).setLayout( {
  16644. name: 'LTC_ClippedSphereFormFactor',
  16645. type: 'float',
  16646. inputs: [
  16647. { name: 'f', type: 'vec3' }
  16648. ]
  16649. } );
  16650. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16651. const x = v1.dot( v2 );
  16652. const y = x.abs().toVar();
  16653. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16654. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16655. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16656. const v = a.div( b );
  16657. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16658. return v1.cross( v2 ).mul( theta_sintheta );
  16659. } ).setLayout( {
  16660. name: 'LTC_EdgeVectorFormFactor',
  16661. type: 'vec3',
  16662. inputs: [
  16663. { name: 'v1', type: 'vec3' },
  16664. { name: 'v2', type: 'vec3' }
  16665. ]
  16666. } );
  16667. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16668. // bail if point is on back side of plane of light
  16669. // assumes ccw winding order of light vertices
  16670. const v1 = p1.sub( p0 ).toVar();
  16671. const v2 = p3.sub( p0 ).toVar();
  16672. const lightNormal = v1.cross( v2 );
  16673. const result = vec3().toVar();
  16674. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16675. // construct orthonormal basis around N
  16676. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16677. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16678. // compute transform
  16679. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16680. // transform rect
  16681. // & project rect onto sphere
  16682. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16683. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16684. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16685. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16686. // calculate vector form factor
  16687. const vectorFormFactor = vec3( 0 ).toVar();
  16688. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16689. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16690. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16691. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16692. // adjust for horizon clipping
  16693. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16694. } );
  16695. return result;
  16696. } ).setLayout( {
  16697. name: 'LTC_Evaluate',
  16698. type: 'vec3',
  16699. inputs: [
  16700. { name: 'N', type: 'vec3' },
  16701. { name: 'V', type: 'vec3' },
  16702. { name: 'P', type: 'vec3' },
  16703. { name: 'mInv', type: 'mat3' },
  16704. { name: 'p0', type: 'vec3' },
  16705. { name: 'p1', type: 'vec3' },
  16706. { name: 'p2', type: 'vec3' },
  16707. { name: 'p3', type: 'vec3' }
  16708. ]
  16709. } );
  16710. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16711. // bail if point is on back side of plane of light
  16712. // assumes ccw winding order of light vertices
  16713. const v1 = p1.sub( p0 ).toVar();
  16714. const v2 = p3.sub( p0 ).toVar();
  16715. const lightNormal = v1.cross( v2 );
  16716. const result = vec3().toVar();
  16717. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16718. // transform rect
  16719. // & project rect onto sphere
  16720. const coords0 = p0.sub( P ).normalize().toVar();
  16721. const coords1 = p1.sub( P ).normalize().toVar();
  16722. const coords2 = p2.sub( P ).normalize().toVar();
  16723. const coords3 = p3.sub( P ).normalize().toVar();
  16724. // calculate vector form factor
  16725. const vectorFormFactor = vec3( 0 ).toVar();
  16726. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16727. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16728. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16729. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16730. // adjust for horizon clipping
  16731. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16732. } );
  16733. return result;
  16734. } ).setLayout( {
  16735. name: 'LTC_Evaluate',
  16736. type: 'vec3',
  16737. inputs: [
  16738. { name: 'P', type: 'vec3' },
  16739. { name: 'p0', type: 'vec3' },
  16740. { name: 'p1', type: 'vec3' },
  16741. { name: 'p2', type: 'vec3' },
  16742. { name: 'p3', type: 'vec3' }
  16743. ]
  16744. } );
  16745. // Mipped Bicubic Texture Filtering by N8
  16746. // https://www.shadertoy.com/view/Dl2SDW
  16747. const bC = 1.0 / 6.0;
  16748. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16749. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16750. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16751. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16752. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16753. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16754. // h0 and h1 are the two offset functions
  16755. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16756. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16757. const bicubic = ( textureNode, texelSize, lod ) => {
  16758. const uv = textureNode.uvNode;
  16759. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16760. const iuv = floor( uvScaled );
  16761. const fuv = fract( uvScaled );
  16762. const g0x = g0( fuv.x );
  16763. const g1x = g1( fuv.x );
  16764. const h0x = h0( fuv.x );
  16765. const h1x = h1( fuv.x );
  16766. const h0y = h0( fuv.y );
  16767. const h1y = h1( fuv.y );
  16768. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16769. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16770. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16771. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16772. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16773. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16774. return a.add( b );
  16775. };
  16776. /**
  16777. * Applies mipped bicubic texture filtering to the given texture node.
  16778. *
  16779. * @tsl
  16780. * @function
  16781. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16782. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16783. * @return {Node} The filtered texture sample.
  16784. */
  16785. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16786. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16787. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16788. const fLodSizeInv = div( 1.0, fLodSize );
  16789. const cLodSizeInv = div( 1.0, cLodSize );
  16790. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16791. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16792. return fract( lodNode ).mix( fSample, cSample );
  16793. } );
  16794. /**
  16795. * Applies mipped bicubic texture filtering to the given texture node.
  16796. *
  16797. * @tsl
  16798. * @function
  16799. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16800. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16801. * @return {Node} The filtered texture sample.
  16802. */
  16803. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16804. const lod = strength.mul( maxMipLevel( textureNode ) );
  16805. return textureBicubicLevel( textureNode, lod );
  16806. } );
  16807. //
  16808. // Transmission
  16809. //
  16810. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16811. // Direction of refracted light.
  16812. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16813. // Compute rotation-independent scaling of the model matrix.
  16814. const modelScale = vec3(
  16815. length( modelMatrix[ 0 ].xyz ),
  16816. length( modelMatrix[ 1 ].xyz ),
  16817. length( modelMatrix[ 2 ].xyz )
  16818. );
  16819. // The thickness is specified in local space.
  16820. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16821. } ).setLayout( {
  16822. name: 'getVolumeTransmissionRay',
  16823. type: 'vec3',
  16824. inputs: [
  16825. { name: 'n', type: 'vec3' },
  16826. { name: 'v', type: 'vec3' },
  16827. { name: 'thickness', type: 'float' },
  16828. { name: 'ior', type: 'float' },
  16829. { name: 'modelMatrix', type: 'mat4' }
  16830. ]
  16831. } );
  16832. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16833. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16834. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16835. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16836. } ).setLayout( {
  16837. name: 'applyIorToRoughness',
  16838. type: 'float',
  16839. inputs: [
  16840. { name: 'roughness', type: 'float' },
  16841. { name: 'ior', type: 'float' }
  16842. ]
  16843. } );
  16844. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16845. const viewportFrontSideTexture = /*@__PURE__*/ viewportOpaqueMipTexture();
  16846. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16847. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16848. const transmissionSample = vTexture.sample( fragCoord );
  16849. //const transmissionSample = viewportMipTexture( fragCoord );
  16850. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16851. return textureBicubicLevel( transmissionSample, lod );
  16852. } );
  16853. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16854. If( attenuationDistance.notEqual( 0 ), () => {
  16855. // Compute light attenuation using Beer's law.
  16856. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16857. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16858. return transmittance;
  16859. } );
  16860. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16861. return vec3( 1.0 );
  16862. } ).setLayout( {
  16863. name: 'volumeAttenuation',
  16864. type: 'vec3',
  16865. inputs: [
  16866. { name: 'transmissionDistance', type: 'float' },
  16867. { name: 'attenuationColor', type: 'vec3' },
  16868. { name: 'attenuationDistance', type: 'float' }
  16869. ]
  16870. } );
  16871. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16872. let transmittedLight, transmittance;
  16873. if ( dispersion ) {
  16874. transmittedLight = vec4().toVar();
  16875. transmittance = vec3().toVar();
  16876. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16877. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16878. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16879. const ior = iors.element( i );
  16880. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16881. const refractedRayExit = position.add( transmissionRay );
  16882. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16883. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16884. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16885. refractionCoords.addAssign( 1.0 );
  16886. refractionCoords.divAssign( 2.0 );
  16887. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16888. // Sample framebuffer to get pixel the refracted ray hits.
  16889. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16890. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16891. transmittedLight.a.addAssign( transmissionSample.a );
  16892. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16893. } );
  16894. transmittedLight.a.divAssign( 3.0 );
  16895. } else {
  16896. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16897. const refractedRayExit = position.add( transmissionRay );
  16898. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16899. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16900. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16901. refractionCoords.addAssign( 1.0 );
  16902. refractionCoords.divAssign( 2.0 );
  16903. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16904. // Sample framebuffer to get pixel the refracted ray hits.
  16905. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16906. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16907. }
  16908. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16909. const dotNV = n.dot( v ).clamp();
  16910. // Get the specular component.
  16911. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16912. dotNV,
  16913. specularColor,
  16914. specularF90,
  16915. roughness
  16916. } ) );
  16917. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16918. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16919. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16920. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16921. } );
  16922. //
  16923. // Iridescence
  16924. //
  16925. // XYZ to linear-sRGB color space
  16926. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16927. 3.2404542, -0.969266, 0.0556434,
  16928. -1.5371385, 1.8760108, -0.2040259,
  16929. -0.4985314, 0.0415560, 1.0572252
  16930. );
  16931. // Assume air interface for top
  16932. // Note: We don't handle the case fresnel0 == 1
  16933. const Fresnel0ToIor = ( fresnel0 ) => {
  16934. const sqrtF0 = fresnel0.sqrt();
  16935. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16936. };
  16937. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16938. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16939. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16940. };
  16941. // Fresnel equations for dielectric/dielectric interfaces.
  16942. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16943. // Evaluation XYZ sensitivity curves in Fourier space
  16944. const evalSensitivity = ( OPD, shift ) => {
  16945. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16946. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16947. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16948. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16949. 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( -45282e5 ).exp() );
  16950. 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() );
  16951. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16952. const rgb = XYZ_TO_REC709.mul( xyz );
  16953. return rgb;
  16954. };
  16955. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16956. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16957. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16958. // Evaluate the cosTheta on the base layer (Snell law)
  16959. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16960. // Handle TIR:
  16961. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16962. If( cosTheta2Sq.lessThan( 0 ), () => {
  16963. return vec3( 1.0 );
  16964. } );
  16965. const cosTheta2 = cosTheta2Sq.sqrt();
  16966. // First interface
  16967. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16968. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16969. //const R21 = R12;
  16970. const T121 = R12.oneMinus();
  16971. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16972. const phi21 = float( Math.PI ).sub( phi12 );
  16973. // Second interface
  16974. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16975. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16976. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16977. const phi23 = vec3(
  16978. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16979. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16980. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16981. );
  16982. // Phase shift
  16983. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16984. const phi = vec3( phi21 ).add( phi23 );
  16985. // Compound terms
  16986. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16987. const r123 = R123.sqrt();
  16988. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16989. // Reflectance term for m = 0 (DC term amplitude)
  16990. const C0 = R12.add( Rs );
  16991. const I = C0.toVar();
  16992. // Reflectance term for m > 0 (pairs of diracs)
  16993. const Cm = Rs.sub( T121 ).toVar();
  16994. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16995. Cm.mulAssign( r123 );
  16996. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16997. I.addAssign( Cm.mul( Sm ) );
  16998. } );
  16999. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  17000. return I.max( vec3( 0.0 ) );
  17001. } ).setLayout( {
  17002. name: 'evalIridescence',
  17003. type: 'vec3',
  17004. inputs: [
  17005. { name: 'outsideIOR', type: 'float' },
  17006. { name: 'eta2', type: 'float' },
  17007. { name: 'cosTheta1', type: 'float' },
  17008. { name: 'thinFilmThickness', type: 'float' },
  17009. { name: 'baseF0', type: 'vec3' }
  17010. ]
  17011. } );
  17012. //
  17013. // Sheen
  17014. //
  17015. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  17016. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF".
  17017. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  17018. const dotNV = normal.dot( viewDir ).saturate();
  17019. const r2 = roughness.mul( roughness );
  17020. const rInv = roughness.add( 0.1 ).reciprocal();
  17021. const a = float( -1.9362 ).add( roughness.mul( 1.0678 ) ).add( r2.mul( 0.4573 ) ).sub( rInv.mul( 0.8469 ) );
  17022. const b = float( -0.6014 ).add( roughness.mul( 0.5538 ) ).sub( r2.mul( 0.4670 ) ).sub( rInv.mul( 0.1255 ) );
  17023. const DG = a.mul( dotNV ).add( b ).exp();
  17024. return DG.saturate();
  17025. } );
  17026. const clearcoatF0 = vec3( 0.04 );
  17027. const clearcoatF90 = float( 1 );
  17028. /**
  17029. * Represents the lighting model for a PBR material.
  17030. *
  17031. * @augments LightingModel
  17032. */
  17033. class PhysicalLightingModel extends LightingModel {
  17034. /**
  17035. * Constructs a new physical lighting model.
  17036. *
  17037. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17038. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17039. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17040. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17041. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17042. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17043. */
  17044. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  17045. super();
  17046. /**
  17047. * Whether clearcoat is supported or not.
  17048. *
  17049. * @type {boolean}
  17050. * @default false
  17051. */
  17052. this.clearcoat = clearcoat;
  17053. /**
  17054. * Whether sheen is supported or not.
  17055. *
  17056. * @type {boolean}
  17057. * @default false
  17058. */
  17059. this.sheen = sheen;
  17060. /**
  17061. * Whether iridescence is supported or not.
  17062. *
  17063. * @type {boolean}
  17064. * @default false
  17065. */
  17066. this.iridescence = iridescence;
  17067. /**
  17068. * Whether anisotropy is supported or not.
  17069. *
  17070. * @type {boolean}
  17071. * @default false
  17072. */
  17073. this.anisotropy = anisotropy;
  17074. /**
  17075. * Whether transmission is supported or not.
  17076. *
  17077. * @type {boolean}
  17078. * @default false
  17079. */
  17080. this.transmission = transmission;
  17081. /**
  17082. * Whether dispersion is supported or not.
  17083. *
  17084. * @type {boolean}
  17085. * @default false
  17086. */
  17087. this.dispersion = dispersion;
  17088. /**
  17089. * The clear coat radiance.
  17090. *
  17091. * @type {?Node}
  17092. * @default null
  17093. */
  17094. this.clearcoatRadiance = null;
  17095. /**
  17096. * The clear coat specular direct.
  17097. *
  17098. * @type {?Node}
  17099. * @default null
  17100. */
  17101. this.clearcoatSpecularDirect = null;
  17102. /**
  17103. * The clear coat specular indirect.
  17104. *
  17105. * @type {?Node}
  17106. * @default null
  17107. */
  17108. this.clearcoatSpecularIndirect = null;
  17109. /**
  17110. * The sheen specular direct.
  17111. *
  17112. * @type {?Node}
  17113. * @default null
  17114. */
  17115. this.sheenSpecularDirect = null;
  17116. /**
  17117. * The sheen specular indirect.
  17118. *
  17119. * @type {?Node}
  17120. * @default null
  17121. */
  17122. this.sheenSpecularIndirect = null;
  17123. /**
  17124. * The iridescence Fresnel.
  17125. *
  17126. * @type {?Node}
  17127. * @default null
  17128. */
  17129. this.iridescenceFresnel = null;
  17130. /**
  17131. * The iridescence F0.
  17132. *
  17133. * @type {?Node}
  17134. * @default null
  17135. */
  17136. this.iridescenceF0 = null;
  17137. /**
  17138. * The iridescence F0 dielectric.
  17139. *
  17140. * @type {?Node}
  17141. * @default null
  17142. */
  17143. this.iridescenceF0Dielectric = null;
  17144. /**
  17145. * The iridescence F0 metallic.
  17146. *
  17147. * @type {?Node}
  17148. * @default null
  17149. */
  17150. this.iridescenceF0Metallic = null;
  17151. }
  17152. /**
  17153. * Depending on what features are requested, the method prepares certain node variables
  17154. * which are later used for lighting computations.
  17155. *
  17156. * @param {NodeBuilder} builder - The current node builder.
  17157. */
  17158. start( builder ) {
  17159. if ( this.clearcoat === true ) {
  17160. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  17161. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  17162. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  17163. }
  17164. if ( this.sheen === true ) {
  17165. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  17166. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  17167. }
  17168. if ( this.iridescence === true ) {
  17169. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  17170. const iridescenceFresnelDielectric = evalIridescence( {
  17171. outsideIOR: float( 1.0 ),
  17172. eta2: iridescenceIOR,
  17173. cosTheta1: dotNVi,
  17174. thinFilmThickness: iridescenceThickness,
  17175. baseF0: specularColor
  17176. } );
  17177. const iridescenceFresnelMetallic = evalIridescence( {
  17178. outsideIOR: float( 1.0 ),
  17179. eta2: iridescenceIOR,
  17180. cosTheta1: dotNVi,
  17181. thinFilmThickness: iridescenceThickness,
  17182. baseF0: diffuseColor.rgb
  17183. } );
  17184. this.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, metalness );
  17185. this.iridescenceF0Dielectric = Schlick_to_F0( { f: iridescenceFresnelDielectric, f90: 1.0, dotVH: dotNVi } );
  17186. this.iridescenceF0Metallic = Schlick_to_F0( { f: iridescenceFresnelMetallic, f90: 1.0, dotVH: dotNVi } );
  17187. this.iridescenceF0 = mix( this.iridescenceF0Dielectric, this.iridescenceF0Metallic, metalness );
  17188. }
  17189. if ( this.transmission === true ) {
  17190. const position = positionWorld;
  17191. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  17192. const n = normalWorld;
  17193. const context = builder.context;
  17194. context.backdrop = getIBLVolumeRefraction(
  17195. n,
  17196. v,
  17197. roughness,
  17198. diffuseContribution,
  17199. specularColorBlended,
  17200. specularF90, // specularF90
  17201. position, // positionWorld
  17202. modelWorldMatrix, // modelMatrix
  17203. cameraViewMatrix, // viewMatrix
  17204. cameraProjectionMatrix, // projMatrix
  17205. ior,
  17206. thickness,
  17207. attenuationColor,
  17208. attenuationDistance,
  17209. this.dispersion ? dispersion : null
  17210. );
  17211. context.backdropAlpha = transmission;
  17212. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  17213. }
  17214. super.start( builder );
  17215. }
  17216. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  17217. // Approximates multi-scattering in order to preserve energy.
  17218. // http://www.jcgt.org/published/0008/01/03/
  17219. computeMultiscattering( singleScatter, multiScatter, specularF90, f0, iridescenceF0 = null ) {
  17220. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17221. const fab = DFGLUT( { roughness, dotNV } );
  17222. const Fr = iridescenceF0 ? iridescence.mix( f0, iridescenceF0 ) : f0;
  17223. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  17224. const Ess = fab.x.add( fab.y );
  17225. const Ems = Ess.oneMinus();
  17226. const Favg = Fr.add( Fr.oneMinus().mul( 0.047619 ) ); // 1/21
  17227. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  17228. singleScatter.addAssign( FssEss );
  17229. multiScatter.addAssign( Fms.mul( Ems ) );
  17230. }
  17231. /**
  17232. * Implements the direct light.
  17233. *
  17234. * @param {Object} lightData - The light data.
  17235. * @param {NodeBuilder} builder - The current node builder.
  17236. */
  17237. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  17238. const dotNL = normalView.dot( lightDirection ).clamp();
  17239. const irradiance = dotNL.mul( lightColor ).toVar();
  17240. if ( this.sheen === true ) {
  17241. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  17242. const sheenAlbedoV = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17243. const sheenAlbedoL = IBLSheenBRDF( { normal: normalView, viewDir: lightDirection, roughness: sheenRoughness } );
  17244. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedoV.max( sheenAlbedoL ) ).oneMinus();
  17245. irradiance.mulAssign( sheenEnergyComp );
  17246. }
  17247. if ( this.clearcoat === true ) {
  17248. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  17249. const ccIrradiance = dotNLcc.mul( lightColor );
  17250. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  17251. }
  17252. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ) );
  17253. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX_Multiscatter( { lightDirection, f0: specularColorBlended, f90: 1, roughness, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  17254. }
  17255. /**
  17256. * This method is intended for implementing the direct light term for
  17257. * rect area light nodes.
  17258. *
  17259. * @param {Object} input - The input data.
  17260. * @param {NodeBuilder} builder - The current node builder.
  17261. */
  17262. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  17263. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17264. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17265. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17266. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17267. const N = normalView;
  17268. const V = positionViewDirection;
  17269. const P = positionView.toVar();
  17270. const uv = LTC_Uv( { N, V, roughness } );
  17271. const t1 = ltc_1.sample( uv ).toVar();
  17272. const t2 = ltc_2.sample( uv ).toVar();
  17273. const mInv = mat3(
  17274. vec3( t1.x, 0, t1.y ),
  17275. vec3( 0, 1, 0 ),
  17276. vec3( t1.z, 0, t1.w )
  17277. ).toVar();
  17278. // LTC Fresnel Approximation by Stephen Hill
  17279. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  17280. const fresnel = specularColorBlended.mul( t2.x ).add( specularF90.sub( specularColorBlended ).mul( t2.y ) ).toVar();
  17281. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  17282. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseContribution ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  17283. if ( this.clearcoat === true ) {
  17284. const Ncc = clearcoatNormalView;
  17285. const uvClearcoat = LTC_Uv( { N: Ncc, V, roughness: clearcoatRoughness } );
  17286. const t1Clearcoat = ltc_1.sample( uvClearcoat );
  17287. const t2Clearcoat = ltc_2.sample( uvClearcoat );
  17288. const mInvClearcoat = mat3(
  17289. vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
  17290. vec3( 0, 1, 0 ),
  17291. vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
  17292. );
  17293. // LTC Fresnel Approximation for clearcoat
  17294. const fresnelClearcoat = clearcoatF0.mul( t2Clearcoat.x ).add( clearcoatF90.sub( clearcoatF0 ).mul( t2Clearcoat.y ) );
  17295. this.clearcoatSpecularDirect.addAssign( lightColor.mul( fresnelClearcoat ).mul( LTC_Evaluate( { N: Ncc, V, P, mInv: mInvClearcoat, p0, p1, p2, p3 } ) ) );
  17296. }
  17297. }
  17298. /**
  17299. * Implements the indirect lighting.
  17300. *
  17301. * @param {NodeBuilder} builder - The current node builder.
  17302. */
  17303. indirect( builder ) {
  17304. this.indirectDiffuse( builder );
  17305. this.indirectSpecular( builder );
  17306. this.ambientOcclusion( builder );
  17307. }
  17308. /**
  17309. * Implements the indirect diffuse term.
  17310. *
  17311. * @param {NodeBuilder} builder - The current node builder.
  17312. */
  17313. indirectDiffuse( builder ) {
  17314. const { irradiance, reflectedLight } = builder.context;
  17315. const diffuse = irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseContribution } ) ).toVar();
  17316. if ( this.sheen === true ) {
  17317. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17318. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17319. diffuse.mulAssign( sheenEnergyComp );
  17320. }
  17321. reflectedLight.indirectDiffuse.addAssign( diffuse );
  17322. }
  17323. /**
  17324. * Implements the indirect specular term.
  17325. *
  17326. * @param {NodeBuilder} builder - The current node builder.
  17327. */
  17328. indirectSpecular( builder ) {
  17329. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  17330. if ( this.sheen === true ) {
  17331. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  17332. sheen,
  17333. IBLSheenBRDF( {
  17334. normal: normalView,
  17335. viewDir: positionViewDirection,
  17336. roughness: sheenRoughness
  17337. } )
  17338. ) );
  17339. }
  17340. if ( this.clearcoat === true ) {
  17341. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17342. const clearcoatEnv = EnvironmentBRDF( {
  17343. dotNV: dotNVcc,
  17344. specularColor: clearcoatF0,
  17345. specularF90: clearcoatF90,
  17346. roughness: clearcoatRoughness
  17347. } );
  17348. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  17349. }
  17350. // Both indirect specular and indirect diffuse light accumulate here
  17351. // Compute multiscattering separately for dielectric and metallic, then mix
  17352. const singleScatteringDielectric = vec3().toVar( 'singleScatteringDielectric' );
  17353. const multiScatteringDielectric = vec3().toVar( 'multiScatteringDielectric' );
  17354. const singleScatteringMetallic = vec3().toVar( 'singleScatteringMetallic' );
  17355. const multiScatteringMetallic = vec3().toVar( 'multiScatteringMetallic' );
  17356. this.computeMultiscattering( singleScatteringDielectric, multiScatteringDielectric, specularF90, specularColor, this.iridescenceF0Dielectric );
  17357. this.computeMultiscattering( singleScatteringMetallic, multiScatteringMetallic, specularF90, diffuseColor.rgb, this.iridescenceF0Metallic );
  17358. // Mix based on metalness
  17359. const singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, metalness );
  17360. const multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, metalness );
  17361. // Diffuse energy conservation uses dielectric path
  17362. const totalScatteringDielectric = singleScatteringDielectric.add( multiScatteringDielectric );
  17363. const diffuse = diffuseContribution.mul( totalScatteringDielectric.oneMinus() );
  17364. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  17365. const indirectSpecular = radiance.mul( singleScattering ).add( multiScattering.mul( cosineWeightedIrradiance ) ).toVar();
  17366. const indirectDiffuse = diffuse.mul( cosineWeightedIrradiance ).toVar();
  17367. if ( this.sheen === true ) {
  17368. const sheenAlbedo = IBLSheenBRDF( { normal: normalView, viewDir: positionViewDirection, roughness: sheenRoughness } );
  17369. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( sheenAlbedo ).oneMinus();
  17370. indirectSpecular.mulAssign( sheenEnergyComp );
  17371. indirectDiffuse.mulAssign( sheenEnergyComp );
  17372. }
  17373. reflectedLight.indirectSpecular.addAssign( indirectSpecular );
  17374. reflectedLight.indirectDiffuse.addAssign( indirectDiffuse );
  17375. }
  17376. /**
  17377. * Implements the ambient occlusion term.
  17378. *
  17379. * @param {NodeBuilder} builder - The current node builder.
  17380. */
  17381. ambientOcclusion( builder ) {
  17382. const { ambientOcclusion, reflectedLight } = builder.context;
  17383. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  17384. const aoNV = dotNV.add( ambientOcclusion );
  17385. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  17386. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  17387. if ( this.clearcoat === true ) {
  17388. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  17389. }
  17390. if ( this.sheen === true ) {
  17391. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  17392. }
  17393. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17394. reflectedLight.indirectSpecular.mulAssign( aoNode );
  17395. }
  17396. /**
  17397. * Used for final lighting accumulations depending on the requested features.
  17398. *
  17399. * @param {NodeBuilder} builder - The current node builder.
  17400. */
  17401. finish( { context } ) {
  17402. const { outgoingLight } = context;
  17403. if ( this.clearcoat === true ) {
  17404. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  17405. const Fcc = F_Schlick( {
  17406. dotVH: dotNVcc,
  17407. f0: clearcoatF0,
  17408. f90: clearcoatF90
  17409. } );
  17410. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  17411. outgoingLight.assign( clearcoatLight );
  17412. }
  17413. if ( this.sheen === true ) {
  17414. const sheenLight = outgoingLight.add( this.sheenSpecularDirect, this.sheenSpecularIndirect.mul( 1.0 / Math.PI ) );
  17415. outgoingLight.assign( sheenLight );
  17416. }
  17417. }
  17418. }
  17419. // These defines must match with PMREMGenerator
  17420. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  17421. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  17422. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  17423. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  17424. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  17425. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  17426. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  17427. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  17428. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  17429. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  17430. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  17431. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  17432. // These shader functions convert between the UV coordinates of a single face of
  17433. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  17434. // sampling a textureCube (not generally normalized ).
  17435. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  17436. const absDirection = vec3( abs( direction ) ).toVar();
  17437. const face = float( -1 ).toVar();
  17438. If( absDirection.x.greaterThan( absDirection.z ), () => {
  17439. If( absDirection.x.greaterThan( absDirection.y ), () => {
  17440. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  17441. } ).Else( () => {
  17442. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17443. } );
  17444. } ).Else( () => {
  17445. If( absDirection.z.greaterThan( absDirection.y ), () => {
  17446. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  17447. } ).Else( () => {
  17448. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  17449. } );
  17450. } );
  17451. return face;
  17452. } ).setLayout( {
  17453. name: 'getFace',
  17454. type: 'float',
  17455. inputs: [
  17456. { name: 'direction', type: 'vec3' }
  17457. ]
  17458. } );
  17459. // RH coordinate system; PMREM face-indexing convention
  17460. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  17461. const uv = vec2().toVar();
  17462. If( face.equal( 0.0 ), () => {
  17463. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  17464. } ).ElseIf( face.equal( 1.0 ), () => {
  17465. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  17466. } ).ElseIf( face.equal( 2.0 ), () => {
  17467. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  17468. } ).ElseIf( face.equal( 3.0 ), () => {
  17469. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  17470. } ).ElseIf( face.equal( 4.0 ), () => {
  17471. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  17472. } ).Else( () => {
  17473. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  17474. } );
  17475. return mul( 0.5, uv.add( 1.0 ) );
  17476. } ).setLayout( {
  17477. name: 'getUV',
  17478. type: 'vec2',
  17479. inputs: [
  17480. { name: 'direction', type: 'vec3' },
  17481. { name: 'face', type: 'float' }
  17482. ]
  17483. } );
  17484. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  17485. const mip = float( 0.0 ).toVar();
  17486. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  17487. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  17488. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  17489. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  17490. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  17491. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  17492. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  17493. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  17494. } ).Else( () => {
  17495. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  17496. } );
  17497. return mip;
  17498. } ).setLayout( {
  17499. name: 'roughnessToMip',
  17500. type: 'float',
  17501. inputs: [
  17502. { name: 'roughness', type: 'float' }
  17503. ]
  17504. } );
  17505. // RH coordinate system; PMREM face-indexing convention
  17506. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  17507. const uv = uv_immutable.toVar();
  17508. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  17509. const direction = vec3( uv, 1.0 ).toVar();
  17510. If( face.equal( 0.0 ), () => {
  17511. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  17512. } ).ElseIf( face.equal( 1.0 ), () => {
  17513. direction.assign( direction.xzy );
  17514. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  17515. } ).ElseIf( face.equal( 2.0 ), () => {
  17516. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  17517. } ).ElseIf( face.equal( 3.0 ), () => {
  17518. direction.assign( direction.zyx );
  17519. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  17520. } ).ElseIf( face.equal( 4.0 ), () => {
  17521. direction.assign( direction.xzy );
  17522. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  17523. } ).ElseIf( face.equal( 5.0 ), () => {
  17524. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  17525. } );
  17526. return direction;
  17527. } ).setLayout( {
  17528. name: 'getDirection',
  17529. type: 'vec3',
  17530. inputs: [
  17531. { name: 'uv', type: 'vec2' },
  17532. { name: 'face', type: 'float' }
  17533. ]
  17534. } );
  17535. //
  17536. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17537. const roughness = float( roughness_immutable );
  17538. const sampleDir = vec3( sampleDir_immutable );
  17539. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  17540. const mipF = fract( mip );
  17541. const mipInt = floor( mip );
  17542. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17543. If( mipF.notEqual( 0.0 ), () => {
  17544. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  17545. color0.assign( mix( color0, color1, mipF ) );
  17546. } );
  17547. return color0;
  17548. } );
  17549. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  17550. const mipInt = float( mipInt_immutable ).toVar();
  17551. const direction = vec3( direction_immutable );
  17552. const face = float( getFace( direction ) ).toVar();
  17553. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  17554. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  17555. const faceSize = float( exp2( mipInt ) ).toVar();
  17556. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  17557. If( face.greaterThan( 2.0 ), () => {
  17558. uv.y.addAssign( faceSize );
  17559. face.subAssign( 3.0 );
  17560. } );
  17561. uv.x.addAssign( face.mul( faceSize ) );
  17562. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  17563. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  17564. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  17565. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  17566. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  17567. } );
  17568. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17569. const cosTheta = cos( theta );
  17570. // Rodrigues' axis-angle rotation
  17571. const sampleDirection = outputDirection.mul( cosTheta )
  17572. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  17573. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  17574. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17575. } );
  17576. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17577. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  17578. If( axis.equal( vec3( 0.0 ) ), () => {
  17579. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  17580. } );
  17581. axis.assign( normalize( axis ) );
  17582. const gl_FragColor = vec3().toVar();
  17583. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17584. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17585. If( i.greaterThanEqual( samples ), () => {
  17586. Break();
  17587. } );
  17588. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17589. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17590. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17591. } );
  17592. return vec4( gl_FragColor, 1 );
  17593. } );
  17594. // GGX VNDF importance sampling functions
  17595. // Van der Corput radical inverse for generating quasi-random sequences
  17596. const radicalInverse_VdC = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  17597. const bits = uint( bits_immutable ).toVar();
  17598. bits.assign( bits.shiftLeft( uint( 16 ) ).bitOr( bits.shiftRight( uint( 16 ) ) ) );
  17599. bits.assign( bits.bitAnd( uint( 0x55555555 ) ).shiftLeft( uint( 1 ) ).bitOr( bits.bitAnd( uint( 0xAAAAAAAA ) ).shiftRight( uint( 1 ) ) ) );
  17600. bits.assign( bits.bitAnd( uint( 0x33333333 ) ).shiftLeft( uint( 2 ) ).bitOr( bits.bitAnd( uint( 0xCCCCCCCC ) ).shiftRight( uint( 2 ) ) ) );
  17601. bits.assign( bits.bitAnd( uint( 0x0F0F0F0F ) ).shiftLeft( uint( 4 ) ).bitOr( bits.bitAnd( uint( 0xF0F0F0F0 ) ).shiftRight( uint( 4 ) ) ) );
  17602. bits.assign( bits.bitAnd( uint( 0x00FF00FF ) ).shiftLeft( uint( 8 ) ).bitOr( bits.bitAnd( uint( 0xFF00FF00 ) ).shiftRight( uint( 8 ) ) ) );
  17603. return float( bits ).mul( 2.3283064365386963e-10 ); // / 0x100000000
  17604. } );
  17605. // Hammersley sequence for quasi-Monte Carlo sampling
  17606. const hammersley = /*@__PURE__*/ Fn( ( [ i, N ] ) => {
  17607. return vec2( float( i ).div( float( N ) ), radicalInverse_VdC( i ) );
  17608. } );
  17609. // GGX VNDF importance sampling (Eric Heitz 2018)
  17610. // "Sampling the GGX Distribution of Visible Normals"
  17611. // https://jcgt.org/published/0007/04/01/
  17612. const importanceSampleGGX_VNDF = /*@__PURE__*/ Fn( ( [ Xi, V, roughness ] ) => {
  17613. const alpha = roughness.mul( roughness ).toConst();
  17614. // Section 4.1: Orthonormal basis
  17615. const T1 = vec3( 1.0, 0.0, 0.0 ).toConst();
  17616. const T2 = cross( V, T1 ).toConst();
  17617. // Section 4.2: Parameterization of projected area
  17618. const r = sqrt( Xi.x ).toConst();
  17619. const phi = mul( 2.0, 3.14159265359 ).mul( Xi.y ).toConst();
  17620. const t1 = r.mul( cos( phi ) ).toConst();
  17621. const t2 = r.mul( sin( phi ) ).toVar();
  17622. const s = mul( 0.5, V.z.add( 1.0 ) ).toConst();
  17623. t2.assign( s.oneMinus().mul( sqrt( t1.mul( t1 ).oneMinus() ) ).add( s.mul( t2 ) ) );
  17624. // Section 4.3: Reprojection onto hemisphere
  17625. const Nh = T1.mul( t1 ).add( T2.mul( t2 ) ).add( V.mul( sqrt( max$1( 0.0, t1.mul( t1 ).add( t2.mul( t2 ) ).oneMinus() ) ) ) );
  17626. // Section 3.4: Transform back to ellipsoid configuration
  17627. return normalize( vec3( alpha.mul( Nh.x ), alpha.mul( Nh.y ), max$1( 0.0, Nh.z ) ) );
  17628. } );
  17629. // GGX convolution using VNDF importance sampling
  17630. const ggxConvolution = /*@__PURE__*/ Fn( ( { roughness, mipInt, envMap, N_immutable, GGX_SAMPLES, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  17631. const N = vec3( N_immutable ).toVar();
  17632. const prefilteredColor = vec3( 0.0 ).toVar();
  17633. const totalWeight = float( 0.0 ).toVar();
  17634. // For very low roughness, just sample the environment directly
  17635. If( roughness.lessThan( 0.001 ), () => {
  17636. prefilteredColor.assign( bilinearCubeUV( envMap, N, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) );
  17637. } ).Else( () => {
  17638. // Tangent space basis for VNDF sampling
  17639. const up = select( abs( N.z ).lessThan( 0.999 ), vec3( 0.0, 0.0, 1.0 ), vec3( 1.0, 0.0, 0.0 ) );
  17640. const tangent = normalize( cross( up, N ) ).toVar();
  17641. const bitangent = cross( N, tangent ).toVar();
  17642. Loop( { start: uint( 0 ), end: GGX_SAMPLES }, ( { i } ) => {
  17643. const Xi = hammersley( i, GGX_SAMPLES );
  17644. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  17645. const H_tangent = importanceSampleGGX_VNDF( Xi, vec3( 0.0, 0.0, 1.0 ), roughness );
  17646. // Transform H back to world space
  17647. const H = normalize( tangent.mul( H_tangent.x ).add( bitangent.mul( H_tangent.y ) ).add( N.mul( H_tangent.z ) ) );
  17648. const L = normalize( H.mul( dot( N, H ).mul( 2.0 ) ).sub( N ) );
  17649. const NdotL = max$1( dot( N, L ), 0.0 );
  17650. If( NdotL.greaterThan( 0.0 ), () => {
  17651. // Sample environment at fixed mip level
  17652. // VNDF importance sampling handles the distribution filtering
  17653. const sampleColor = bilinearCubeUV( envMap, L, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  17654. // Weight by NdotL for the split-sum approximation
  17655. // VNDF PDF naturally accounts for the visible microfacet distribution
  17656. prefilteredColor.addAssign( sampleColor.mul( NdotL ) );
  17657. totalWeight.addAssign( NdotL );
  17658. } );
  17659. } );
  17660. If( totalWeight.greaterThan( 0.0 ), () => {
  17661. prefilteredColor.assign( prefilteredColor.div( totalWeight ) );
  17662. } );
  17663. } );
  17664. return vec4( prefilteredColor, 1.0 );
  17665. } );
  17666. const LOD_MIN = 4;
  17667. // The standard deviations (radians) associated with the extra mips.
  17668. // Used for scene blur in fromScene() method.
  17669. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17670. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17671. // samples and exit early, but not recompile the shader.
  17672. // Used for scene blur in fromScene() method.
  17673. const MAX_SAMPLES = 20;
  17674. // GGX VNDF importance sampling configuration
  17675. const GGX_SAMPLES = 512;
  17676. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17677. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17678. const _clearColor$2 = /*@__PURE__*/ new Color();
  17679. let _oldTarget = null;
  17680. let _oldActiveCubeFace = 0;
  17681. let _oldActiveMipmapLevel = 0;
  17682. const _origin = /*@__PURE__*/ new Vector3();
  17683. // maps blur materials to their uniforms dictionary
  17684. const _uniformsMap = new WeakMap();
  17685. // WebGPU Face indices
  17686. const _faceLib = [
  17687. 3, 1, 5,
  17688. 0, 4, 2
  17689. ];
  17690. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17691. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17692. /**
  17693. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17694. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17695. * blur to be quickly accessed based on material roughness. It is packed into a
  17696. * special CubeUV format that allows us to perform custom interpolation so that
  17697. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17698. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17699. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17700. * higher roughness levels. In this way we maintain resolution to smoothly
  17701. * interpolate diffuse lighting while limiting sampling computation.
  17702. *
  17703. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  17704. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  17705. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  17706. * used in material rendering for physically-based image-based lighting.
  17707. */
  17708. class PMREMGenerator {
  17709. /**
  17710. * Constructs a new PMREM generator.
  17711. *
  17712. * @param {Renderer} renderer - The renderer.
  17713. */
  17714. constructor( renderer ) {
  17715. this._renderer = renderer;
  17716. this._pingPongRenderTarget = null;
  17717. this._lodMax = 0;
  17718. this._cubeSize = 0;
  17719. this._sizeLods = [];
  17720. this._sigmas = [];
  17721. this._lodMeshes = [];
  17722. this._blurMaterial = null;
  17723. this._ggxMaterial = null;
  17724. this._cubemapMaterial = null;
  17725. this._equirectMaterial = null;
  17726. this._backgroundBox = null;
  17727. }
  17728. get _hasInitialized() {
  17729. return this._renderer.hasInitialized();
  17730. }
  17731. /**
  17732. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17733. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17734. * in radians to be applied to the scene before PMREM generation. Optional near
  17735. * and far planes ensure the scene is rendered in its entirety.
  17736. *
  17737. * @param {Scene} scene - The scene to be captured.
  17738. * @param {number} [sigma=0] - The blur radius in radians.
  17739. * @param {number} [near=0.1] - The near plane distance.
  17740. * @param {number} [far=100] - The far plane distance.
  17741. * @param {Object} [options={}] - The configuration options.
  17742. * @param {number} [options.size=256] - The texture size of the PMREM.
  17743. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17744. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17745. * @return {RenderTarget} The resulting PMREM.
  17746. * @see {@link PMREMGenerator#fromScene}
  17747. */
  17748. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17749. const {
  17750. size = 256,
  17751. position = _origin,
  17752. renderTarget = null,
  17753. } = options;
  17754. this._setSize( size );
  17755. if ( this._hasInitialized === false ) {
  17756. warn( 'PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17757. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17758. options.renderTarget = cubeUVRenderTarget;
  17759. this.fromSceneAsync( scene, sigma, near, far, options );
  17760. return cubeUVRenderTarget;
  17761. }
  17762. _oldTarget = this._renderer.getRenderTarget();
  17763. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17764. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17765. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17766. cubeUVRenderTarget.depthBuffer = true;
  17767. this._init( cubeUVRenderTarget );
  17768. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17769. if ( sigma > 0 ) {
  17770. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17771. }
  17772. this._applyPMREM( cubeUVRenderTarget );
  17773. this._cleanup( cubeUVRenderTarget );
  17774. return cubeUVRenderTarget;
  17775. }
  17776. /**
  17777. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17778. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17779. * in radians to be applied to the scene before PMREM generation. Optional near
  17780. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17781. * is placed at the origin).
  17782. *
  17783. * @deprecated
  17784. * @param {Scene} scene - The scene to be captured.
  17785. * @param {number} [sigma=0] - The blur radius in radians.
  17786. * @param {number} [near=0.1] - The near plane distance.
  17787. * @param {number} [far=100] - The far plane distance.
  17788. * @param {Object} [options={}] - The configuration options.
  17789. * @param {number} [options.size=256] - The texture size of the PMREM.
  17790. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17791. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17792. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17793. * @see {@link PMREMGenerator#fromScene}
  17794. */
  17795. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17796. warnOnce( 'PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17797. await this._renderer.init();
  17798. return this.fromScene( scene, sigma, near, far, options );
  17799. }
  17800. /**
  17801. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17802. * or HDR. The ideal input image size is 1k (1024 x 512),
  17803. * as this matches best with the 256 x 256 cubemap output.
  17804. *
  17805. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17806. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17807. * @return {RenderTarget} The resulting PMREM.
  17808. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17809. */
  17810. fromEquirectangular( equirectangular, renderTarget = null ) {
  17811. if ( this._hasInitialized === false ) {
  17812. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.' );
  17813. this._setSizeFromTexture( equirectangular );
  17814. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17815. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17816. return cubeUVRenderTarget;
  17817. }
  17818. return this._fromTexture( equirectangular, renderTarget );
  17819. }
  17820. /**
  17821. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17822. * or HDR. The ideal input image size is 1k (1024 x 512),
  17823. * as this matches best with the 256 x 256 cubemap output.
  17824. *
  17825. * @deprecated
  17826. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17827. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17828. * @return {Promise<RenderTarget>} The resulting PMREM.
  17829. * @see {@link PMREMGenerator#fromEquirectangular}
  17830. */
  17831. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17832. warnOnce( 'PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17833. await this._renderer.init();
  17834. return this._fromTexture( equirectangular, renderTarget );
  17835. }
  17836. /**
  17837. * Generates a PMREM from an cubemap texture, which can be either LDR
  17838. * or HDR. The ideal input cube size is 256 x 256,
  17839. * as this matches best with the 256 x 256 cubemap output.
  17840. *
  17841. * @param {Texture} cubemap - The cubemap texture to be converted.
  17842. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17843. * @return {RenderTarget} The resulting PMREM.
  17844. * @see {@link PMREMGenerator#fromCubemapAsync}
  17845. */
  17846. fromCubemap( cubemap, renderTarget = null ) {
  17847. if ( this._hasInitialized === false ) {
  17848. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17849. this._setSizeFromTexture( cubemap );
  17850. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17851. this.fromCubemapAsync( cubemap, renderTarget );
  17852. return cubeUVRenderTarget;
  17853. }
  17854. return this._fromTexture( cubemap, renderTarget );
  17855. }
  17856. /**
  17857. * Generates a PMREM from an cubemap texture, which can be either LDR
  17858. * or HDR. The ideal input cube size is 256 x 256,
  17859. * with the 256 x 256 cubemap output.
  17860. *
  17861. * @deprecated
  17862. * @param {Texture} cubemap - The cubemap texture to be converted.
  17863. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17864. * @return {Promise<RenderTarget>} The resulting PMREM.
  17865. * @see {@link PMREMGenerator#fromCubemap}
  17866. */
  17867. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17868. warnOnce( 'PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.' ); // @deprecated r181
  17869. await this._renderer.init();
  17870. return this._fromTexture( cubemap, renderTarget );
  17871. }
  17872. /**
  17873. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17874. * your texture's network fetch for increased concurrency.
  17875. *
  17876. * @returns {Promise}
  17877. */
  17878. async compileCubemapShader() {
  17879. if ( this._cubemapMaterial === null ) {
  17880. this._cubemapMaterial = _getCubemapMaterial();
  17881. await this._compileMaterial( this._cubemapMaterial );
  17882. }
  17883. }
  17884. /**
  17885. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17886. * your texture's network fetch for increased concurrency.
  17887. *
  17888. * @returns {Promise}
  17889. */
  17890. async compileEquirectangularShader() {
  17891. if ( this._equirectMaterial === null ) {
  17892. this._equirectMaterial = _getEquirectMaterial();
  17893. await this._compileMaterial( this._equirectMaterial );
  17894. }
  17895. }
  17896. /**
  17897. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17898. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17899. * one of them will cause any others to also become unusable.
  17900. */
  17901. dispose() {
  17902. this._dispose();
  17903. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17904. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17905. if ( this._backgroundBox !== null ) {
  17906. this._backgroundBox.geometry.dispose();
  17907. this._backgroundBox.material.dispose();
  17908. }
  17909. }
  17910. // private interface
  17911. _setSizeFromTexture( texture ) {
  17912. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17913. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17914. } else { // Equirectangular
  17915. this._setSize( texture.image.width / 4 );
  17916. }
  17917. }
  17918. _setSize( cubeSize ) {
  17919. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17920. this._cubeSize = Math.pow( 2, this._lodMax );
  17921. }
  17922. _dispose() {
  17923. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17924. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  17925. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17926. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  17927. this._lodMeshes[ i ].geometry.dispose();
  17928. }
  17929. }
  17930. _cleanup( outputTarget ) {
  17931. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17932. outputTarget.scissorTest = false;
  17933. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17934. }
  17935. _fromTexture( texture, renderTarget ) {
  17936. this._setSizeFromTexture( texture );
  17937. _oldTarget = this._renderer.getRenderTarget();
  17938. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17939. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17940. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17941. this._init( cubeUVRenderTarget );
  17942. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17943. this._applyPMREM( cubeUVRenderTarget );
  17944. this._cleanup( cubeUVRenderTarget );
  17945. return cubeUVRenderTarget;
  17946. }
  17947. _allocateTarget() {
  17948. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17949. const height = 4 * this._cubeSize;
  17950. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17951. return cubeUVRenderTarget;
  17952. }
  17953. _init( renderTarget ) {
  17954. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17955. if ( this._pingPongRenderTarget !== null ) {
  17956. this._dispose();
  17957. }
  17958. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17959. const { _lodMax } = this;
  17960. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  17961. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17962. this._ggxMaterial = _getGGXShader( _lodMax, renderTarget.width, renderTarget.height );
  17963. }
  17964. }
  17965. async _compileMaterial( material ) {
  17966. const mesh = new Mesh( new BufferGeometry(), material );
  17967. await this._renderer.compile( mesh, _flatCamera );
  17968. }
  17969. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17970. const cubeCamera = _cubeCamera;
  17971. cubeCamera.near = near;
  17972. cubeCamera.far = far;
  17973. // px, py, pz, nx, ny, nz
  17974. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17975. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17976. const renderer = this._renderer;
  17977. const originalAutoClear = renderer.autoClear;
  17978. renderer.getClearColor( _clearColor$2 );
  17979. renderer.autoClear = false;
  17980. if ( this._backgroundBox === null ) {
  17981. this._backgroundBox = new Mesh(
  17982. new BoxGeometry(),
  17983. new MeshBasicMaterial( {
  17984. name: 'PMREM.Background',
  17985. side: BackSide,
  17986. depthWrite: false,
  17987. depthTest: false,
  17988. } )
  17989. );
  17990. }
  17991. const backgroundBox = this._backgroundBox;
  17992. const backgroundMaterial = backgroundBox.material;
  17993. let useSolidColor = false;
  17994. const background = scene.background;
  17995. if ( background ) {
  17996. if ( background.isColor ) {
  17997. backgroundMaterial.color.copy( background );
  17998. scene.background = null;
  17999. useSolidColor = true;
  18000. }
  18001. } else {
  18002. backgroundMaterial.color.copy( _clearColor$2 );
  18003. useSolidColor = true;
  18004. }
  18005. renderer.setRenderTarget( cubeUVRenderTarget );
  18006. renderer.clear();
  18007. if ( useSolidColor ) {
  18008. renderer.render( backgroundBox, cubeCamera );
  18009. }
  18010. for ( let i = 0; i < 6; i ++ ) {
  18011. const col = i % 3;
  18012. if ( col === 0 ) {
  18013. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18014. cubeCamera.position.set( position.x, position.y, position.z );
  18015. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  18016. } else if ( col === 1 ) {
  18017. cubeCamera.up.set( 0, 0, upSign[ i ] );
  18018. cubeCamera.position.set( position.x, position.y, position.z );
  18019. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  18020. } else {
  18021. cubeCamera.up.set( 0, upSign[ i ], 0 );
  18022. cubeCamera.position.set( position.x, position.y, position.z );
  18023. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  18024. }
  18025. const size = this._cubeSize;
  18026. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  18027. renderer.render( scene, cubeCamera );
  18028. }
  18029. renderer.autoClear = originalAutoClear;
  18030. scene.background = background;
  18031. }
  18032. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  18033. const renderer = this._renderer;
  18034. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  18035. if ( isCubeTexture ) {
  18036. if ( this._cubemapMaterial === null ) {
  18037. this._cubemapMaterial = _getCubemapMaterial( texture );
  18038. }
  18039. } else {
  18040. if ( this._equirectMaterial === null ) {
  18041. this._equirectMaterial = _getEquirectMaterial( texture );
  18042. }
  18043. }
  18044. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  18045. material.fragmentNode.value = texture;
  18046. const mesh = this._lodMeshes[ 0 ];
  18047. mesh.material = material;
  18048. const size = this._cubeSize;
  18049. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  18050. renderer.setRenderTarget( cubeUVRenderTarget );
  18051. renderer.render( mesh, _flatCamera );
  18052. }
  18053. _applyPMREM( cubeUVRenderTarget ) {
  18054. const renderer = this._renderer;
  18055. const autoClear = renderer.autoClear;
  18056. renderer.autoClear = false;
  18057. const n = this._lodMeshes.length;
  18058. // Use GGX VNDF importance sampling
  18059. for ( let i = 1; i < n; i ++ ) {
  18060. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  18061. }
  18062. renderer.autoClear = autoClear;
  18063. }
  18064. /**
  18065. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  18066. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  18067. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  18068. * applies incremental roughness filtering to avoid over-blurring.
  18069. *
  18070. * @private
  18071. * @param {RenderTarget} cubeUVRenderTarget
  18072. * @param {number} lodIn - Source LOD level to read from
  18073. * @param {number} lodOut - Target LOD level to write to
  18074. */
  18075. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  18076. const renderer = this._renderer;
  18077. const pingPongRenderTarget = this._pingPongRenderTarget;
  18078. const ggxMaterial = this._ggxMaterial;
  18079. const ggxMesh = this._lodMeshes[ lodOut ];
  18080. ggxMesh.material = ggxMaterial;
  18081. const ggxUniforms = _uniformsMap.get( ggxMaterial );
  18082. // Calculate incremental roughness between LOD levels
  18083. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  18084. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  18085. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  18086. // Apply blur strength mapping for better quality across the roughness range
  18087. const blurStrength = 0.0 + targetRoughness * 1.25;
  18088. const adjustedRoughness = incrementalRoughness * blurStrength;
  18089. // Calculate viewport position based on output LOD level
  18090. const { _lodMax } = this;
  18091. const outputSize = this._sizeLods[ lodOut ];
  18092. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18093. const y = 4 * ( this._cubeSize - outputSize );
  18094. // Read from previous LOD with incremental roughness
  18095. cubeUVRenderTarget.texture.frame = ( cubeUVRenderTarget.texture.frame || 0 ) + 1;
  18096. ggxUniforms.envMap.value = cubeUVRenderTarget.texture;
  18097. ggxUniforms.roughness.value = adjustedRoughness;
  18098. ggxUniforms.mipInt.value = _lodMax - lodIn; // Sample from input LOD
  18099. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18100. renderer.setRenderTarget( pingPongRenderTarget );
  18101. renderer.render( ggxMesh, _flatCamera );
  18102. // Copy from pingPong back to cubeUV (simple direct copy)
  18103. pingPongRenderTarget.texture.frame = ( pingPongRenderTarget.texture.frame || 0 ) + 1;
  18104. ggxUniforms.envMap.value = pingPongRenderTarget.texture;
  18105. ggxUniforms.roughness.value = 0.0; // Direct copy
  18106. ggxUniforms.mipInt.value = _lodMax - lodOut; // Read from the level we just wrote
  18107. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  18108. renderer.setRenderTarget( cubeUVRenderTarget );
  18109. renderer.render( ggxMesh, _flatCamera );
  18110. }
  18111. /**
  18112. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  18113. * vertically and horizontally, but this breaks down on a cube. Here we apply
  18114. * the blur latitudinally (around the poles), and then longitudinally (towards
  18115. * the poles) to approximate the orthogonally-separable blur. It is least
  18116. * accurate at the poles, but still does a decent job.
  18117. *
  18118. * Used for initial scene blur in fromScene() method when sigma > 0.
  18119. *
  18120. * @private
  18121. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  18122. * @param {number} lodIn - The input level-of-detail.
  18123. * @param {number} lodOut - The output level-of-detail.
  18124. * @param {number} sigma - The blur radius in radians.
  18125. * @param {Vector3} [poleAxis] - The pole axis.
  18126. */
  18127. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  18128. const pingPongRenderTarget = this._pingPongRenderTarget;
  18129. this._halfBlur(
  18130. cubeUVRenderTarget,
  18131. pingPongRenderTarget,
  18132. lodIn,
  18133. lodOut,
  18134. sigma,
  18135. 'latitudinal',
  18136. poleAxis );
  18137. this._halfBlur(
  18138. pingPongRenderTarget,
  18139. cubeUVRenderTarget,
  18140. lodOut,
  18141. lodOut,
  18142. sigma,
  18143. 'longitudinal',
  18144. poleAxis );
  18145. }
  18146. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  18147. const renderer = this._renderer;
  18148. const blurMaterial = this._blurMaterial;
  18149. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  18150. error( 'blur direction must be either latitudinal or longitudinal!' );
  18151. }
  18152. // Number of standard deviations at which to cut off the discrete approximation.
  18153. const STANDARD_DEVIATIONS = 3;
  18154. const blurMesh = this._lodMeshes[ lodOut ];
  18155. blurMesh.material = blurMaterial;
  18156. const blurUniforms = _uniformsMap.get( blurMaterial );
  18157. const pixels = this._sizeLods[ lodIn ] - 1;
  18158. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  18159. const sigmaPixels = sigmaRadians / radiansPerPixel;
  18160. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  18161. if ( samples > MAX_SAMPLES ) {
  18162. warn( `sigmaRadians, ${
  18163. sigmaRadians}, is too large and will clip, as it requested ${
  18164. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  18165. }
  18166. const weights = [];
  18167. let sum = 0;
  18168. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  18169. const x = i / sigmaPixels;
  18170. const weight = Math.exp( - x * x / 2 );
  18171. weights.push( weight );
  18172. if ( i === 0 ) {
  18173. sum += weight;
  18174. } else if ( i < samples ) {
  18175. sum += 2 * weight;
  18176. }
  18177. }
  18178. for ( let i = 0; i < weights.length; i ++ ) {
  18179. weights[ i ] = weights[ i ] / sum;
  18180. }
  18181. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  18182. blurUniforms.envMap.value = targetIn.texture;
  18183. blurUniforms.samples.value = samples;
  18184. blurUniforms.weights.array = weights;
  18185. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  18186. if ( poleAxis ) {
  18187. blurUniforms.poleAxis.value = poleAxis;
  18188. }
  18189. const { _lodMax } = this;
  18190. blurUniforms.dTheta.value = radiansPerPixel;
  18191. blurUniforms.mipInt.value = _lodMax - lodIn;
  18192. const outputSize = this._sizeLods[ lodOut ];
  18193. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  18194. const y = 4 * ( this._cubeSize - outputSize );
  18195. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  18196. renderer.setRenderTarget( targetOut );
  18197. renderer.render( blurMesh, _flatCamera );
  18198. }
  18199. }
  18200. function _createPlanes( lodMax ) {
  18201. const sizeLods = [];
  18202. const sigmas = [];
  18203. const lodMeshes = [];
  18204. let lod = lodMax;
  18205. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  18206. for ( let i = 0; i < totalLods; i ++ ) {
  18207. const sizeLod = Math.pow( 2, lod );
  18208. sizeLods.push( sizeLod );
  18209. let sigma = 1.0 / sizeLod;
  18210. if ( i > lodMax - LOD_MIN ) {
  18211. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  18212. } else if ( i === 0 ) {
  18213. sigma = 0;
  18214. }
  18215. sigmas.push( sigma );
  18216. const texelSize = 1.0 / ( sizeLod - 2 );
  18217. const min = - texelSize;
  18218. const max = 1 + texelSize;
  18219. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  18220. const cubeFaces = 6;
  18221. const vertices = 6;
  18222. const positionSize = 3;
  18223. const uvSize = 2;
  18224. const faceIndexSize = 1;
  18225. const position = new Float32Array( positionSize * vertices * cubeFaces );
  18226. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  18227. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  18228. for ( let face = 0; face < cubeFaces; face ++ ) {
  18229. const x = ( face % 3 ) * 2 / 3 - 1;
  18230. const y = face > 2 ? 0 : -1;
  18231. const coordinates = [
  18232. x, y, 0,
  18233. x + 2 / 3, y, 0,
  18234. x + 2 / 3, y + 1, 0,
  18235. x, y, 0,
  18236. x + 2 / 3, y + 1, 0,
  18237. x, y + 1, 0
  18238. ];
  18239. const faceIdx = _faceLib[ face ];
  18240. position.set( coordinates, positionSize * vertices * faceIdx );
  18241. uv.set( uv1, uvSize * vertices * faceIdx );
  18242. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  18243. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  18244. }
  18245. const planes = new BufferGeometry();
  18246. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  18247. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  18248. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  18249. lodMeshes.push( new Mesh( planes, null ) );
  18250. if ( lod > LOD_MIN ) {
  18251. lod --;
  18252. }
  18253. }
  18254. return { lodMeshes, sizeLods, sigmas };
  18255. }
  18256. function _createRenderTarget( width, height ) {
  18257. const params = {
  18258. magFilter: LinearFilter,
  18259. minFilter: LinearFilter,
  18260. generateMipmaps: false,
  18261. type: HalfFloatType,
  18262. format: RGBAFormat,
  18263. colorSpace: LinearSRGBColorSpace,
  18264. //depthBuffer: false
  18265. };
  18266. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  18267. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  18268. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  18269. cubeUVRenderTarget.texture.isPMREMTexture = true;
  18270. cubeUVRenderTarget.scissorTest = true;
  18271. return cubeUVRenderTarget;
  18272. }
  18273. function _setViewport( target, x, y, width, height ) {
  18274. target.viewport.set( x, y, width, height );
  18275. target.scissor.set( x, y, width, height );
  18276. }
  18277. function _getMaterial( type ) {
  18278. const material = new NodeMaterial();
  18279. material.depthTest = false;
  18280. material.depthWrite = false;
  18281. material.blending = NoBlending;
  18282. material.name = `PMREM_${ type }`;
  18283. return material;
  18284. }
  18285. function _getBlurShader( lodMax, width, height ) {
  18286. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  18287. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  18288. const dTheta = uniform( 0 );
  18289. const n = float( MAX_SAMPLES );
  18290. const latitudinal = uniform( 0 ); // false, bool
  18291. const samples = uniform( 1 ); // int
  18292. const envMap = texture();
  18293. const mipInt = uniform( 0 ); // int
  18294. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18295. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18296. const CUBEUV_MAX_MIP = float( lodMax );
  18297. const materialUniforms = {
  18298. n,
  18299. latitudinal,
  18300. weights,
  18301. poleAxis,
  18302. outputDirection: _outputDirection,
  18303. dTheta,
  18304. samples,
  18305. envMap,
  18306. mipInt,
  18307. CUBEUV_TEXEL_WIDTH,
  18308. CUBEUV_TEXEL_HEIGHT,
  18309. CUBEUV_MAX_MIP
  18310. };
  18311. const material = _getMaterial( 'blur' );
  18312. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  18313. _uniformsMap.set( material, materialUniforms );
  18314. return material;
  18315. }
  18316. function _getGGXShader( lodMax, width, height ) {
  18317. const envMap = texture();
  18318. const roughness = uniform( 0 );
  18319. const mipInt = uniform( 0 );
  18320. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  18321. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  18322. const CUBEUV_MAX_MIP = float( lodMax );
  18323. const materialUniforms = {
  18324. envMap,
  18325. roughness,
  18326. mipInt,
  18327. CUBEUV_TEXEL_WIDTH,
  18328. CUBEUV_TEXEL_HEIGHT,
  18329. CUBEUV_MAX_MIP
  18330. };
  18331. const material = _getMaterial( 'ggx' );
  18332. material.fragmentNode = ggxConvolution( {
  18333. ...materialUniforms,
  18334. N_immutable: _outputDirection,
  18335. GGX_SAMPLES: uint( GGX_SAMPLES )
  18336. } );
  18337. _uniformsMap.set( material, materialUniforms );
  18338. return material;
  18339. }
  18340. function _getCubemapMaterial( envTexture ) {
  18341. const material = _getMaterial( 'cubemap' );
  18342. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  18343. return material;
  18344. }
  18345. function _getEquirectMaterial( envTexture ) {
  18346. const material = _getMaterial( 'equirect' );
  18347. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  18348. return material;
  18349. }
  18350. const _cache = new WeakMap();
  18351. /**
  18352. * Generates the cubeUV size based on the given image height.
  18353. *
  18354. * @private
  18355. * @param {number} imageHeight - The image height.
  18356. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  18357. */
  18358. function _generateCubeUVSize( imageHeight ) {
  18359. const maxMip = Math.log2( imageHeight ) - 2;
  18360. const texelHeight = 1.0 / imageHeight;
  18361. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  18362. return { texelWidth, texelHeight, maxMip };
  18363. }
  18364. /**
  18365. * Generates a PMREM from the given texture.
  18366. *
  18367. * @private
  18368. * @param {Texture} texture - The texture to create the PMREM for.
  18369. * @param {Renderer} renderer - The renderer.
  18370. * @param {PMREMGenerator} generator - The PMREM generator.
  18371. * @return {?Texture} The PMREM.
  18372. */
  18373. function _getPMREMFromTexture( texture, renderer, generator ) {
  18374. const cache = _getCache( renderer );
  18375. let cacheTexture = cache.get( texture );
  18376. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  18377. if ( pmremVersion !== texture.pmremVersion ) {
  18378. const image = texture.image;
  18379. if ( texture.isCubeTexture ) {
  18380. if ( isCubeMapReady( image ) ) {
  18381. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  18382. } else {
  18383. return null;
  18384. }
  18385. } else {
  18386. if ( isEquirectangularMapReady( image ) ) {
  18387. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  18388. } else {
  18389. return null;
  18390. }
  18391. }
  18392. cacheTexture.pmremVersion = texture.pmremVersion;
  18393. cache.set( texture, cacheTexture );
  18394. }
  18395. return cacheTexture.texture;
  18396. }
  18397. /**
  18398. * Returns a cache that stores generated PMREMs for the respective textures.
  18399. * A cache must be maintained per renderer since PMREMs are render target textures
  18400. * which can't be shared across render contexts.
  18401. *
  18402. * @private
  18403. * @param {Renderer} renderer - The renderer.
  18404. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  18405. */
  18406. function _getCache( renderer ) {
  18407. let rendererCache = _cache.get( renderer );
  18408. if ( rendererCache === undefined ) {
  18409. rendererCache = new WeakMap();
  18410. _cache.set( renderer, rendererCache );
  18411. }
  18412. return rendererCache;
  18413. }
  18414. /**
  18415. * This node represents a PMREM which is a special type of preprocessed
  18416. * environment map intended for PBR materials.
  18417. *
  18418. * ```js
  18419. * const material = new MeshStandardNodeMaterial();
  18420. * material.envNode = pmremTexture( envMap );
  18421. * ```
  18422. *
  18423. * @augments TempNode
  18424. */
  18425. class PMREMNode extends TempNode {
  18426. static get type() {
  18427. return 'PMREMNode';
  18428. }
  18429. /**
  18430. * Constructs a new function overloading node.
  18431. *
  18432. * @param {Texture} value - The input texture.
  18433. * @param {Node<vec2>} [uvNode=null] - The uv node.
  18434. * @param {Node<float>} [levelNode=null] - The level node.
  18435. */
  18436. constructor( value, uvNode = null, levelNode = null ) {
  18437. super( 'vec3' );
  18438. /**
  18439. * Reference to the input texture.
  18440. *
  18441. * @private
  18442. * @type {Texture}
  18443. */
  18444. this._value = value;
  18445. /**
  18446. * Reference to the generated PMREM.
  18447. *
  18448. * @private
  18449. * @type {Texture | null}
  18450. * @default null
  18451. */
  18452. this._pmrem = null;
  18453. /**
  18454. * The uv node.
  18455. *
  18456. * @type {Node<vec2>}
  18457. */
  18458. this.uvNode = uvNode;
  18459. /**
  18460. * The level node.
  18461. *
  18462. * @type {Node<float>}
  18463. */
  18464. this.levelNode = levelNode;
  18465. /**
  18466. * Reference to a PMREM generator.
  18467. *
  18468. * @private
  18469. * @type {?PMREMGenerator}
  18470. * @default null
  18471. */
  18472. this._generator = null;
  18473. const defaultTexture = new Texture();
  18474. defaultTexture.isRenderTargetTexture = true;
  18475. /**
  18476. * The texture node holding the generated PMREM.
  18477. *
  18478. * @private
  18479. * @type {TextureNode}
  18480. */
  18481. this._texture = texture( defaultTexture );
  18482. /**
  18483. * A uniform representing the PMREM's width.
  18484. *
  18485. * @private
  18486. * @type {UniformNode<float>}
  18487. */
  18488. this._width = uniform( 0 );
  18489. /**
  18490. * A uniform representing the PMREM's height.
  18491. *
  18492. * @private
  18493. * @type {UniformNode<float>}
  18494. */
  18495. this._height = uniform( 0 );
  18496. /**
  18497. * A uniform representing the PMREM's max Mip.
  18498. *
  18499. * @private
  18500. * @type {UniformNode<float>}
  18501. */
  18502. this._maxMip = uniform( 0 );
  18503. /**
  18504. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  18505. *
  18506. * @type {string}
  18507. * @default 'render'
  18508. */
  18509. this.updateBeforeType = NodeUpdateType.RENDER;
  18510. }
  18511. set value( value ) {
  18512. this._value = value;
  18513. this._pmrem = null;
  18514. }
  18515. /**
  18516. * The node's texture value.
  18517. *
  18518. * @type {Texture}
  18519. */
  18520. get value() {
  18521. return this._value;
  18522. }
  18523. /**
  18524. * Uses the given PMREM texture to update internal values.
  18525. *
  18526. * @param {Texture} texture - The PMREM texture.
  18527. */
  18528. updateFromTexture( texture ) {
  18529. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  18530. this._texture.value = texture;
  18531. this._width.value = cubeUVSize.texelWidth;
  18532. this._height.value = cubeUVSize.texelHeight;
  18533. this._maxMip.value = cubeUVSize.maxMip;
  18534. }
  18535. updateBefore( frame ) {
  18536. let pmrem = this._pmrem;
  18537. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  18538. const texture = this._value;
  18539. if ( pmremVersion !== texture.pmremVersion ) {
  18540. if ( texture.isPMREMTexture === true ) {
  18541. pmrem = texture;
  18542. } else {
  18543. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  18544. }
  18545. if ( pmrem !== null ) {
  18546. this._pmrem = pmrem;
  18547. this.updateFromTexture( pmrem );
  18548. }
  18549. }
  18550. }
  18551. setup( builder ) {
  18552. if ( this._generator === null ) {
  18553. this._generator = new PMREMGenerator( builder.renderer );
  18554. }
  18555. this.updateBefore( builder );
  18556. //
  18557. let uvNode = this.uvNode;
  18558. if ( uvNode === null && builder.context.getUV ) {
  18559. uvNode = builder.context.getUV( this, builder );
  18560. }
  18561. //
  18562. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  18563. //
  18564. let levelNode = this.levelNode;
  18565. if ( levelNode === null && builder.context.getTextureLevel ) {
  18566. levelNode = builder.context.getTextureLevel( this );
  18567. }
  18568. //
  18569. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  18570. }
  18571. dispose() {
  18572. super.dispose();
  18573. if ( this._generator !== null ) this._generator.dispose();
  18574. }
  18575. }
  18576. /**
  18577. * Returns `true` if the given cube map image has been fully loaded.
  18578. *
  18579. * @private
  18580. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  18581. * @return {boolean} Whether the given cube map is ready or not.
  18582. */
  18583. function isCubeMapReady( image ) {
  18584. if ( image === null || image === undefined ) return false;
  18585. let count = 0;
  18586. const length = 6;
  18587. for ( let i = 0; i < length; i ++ ) {
  18588. if ( image[ i ] !== undefined ) count ++;
  18589. }
  18590. return count === length;
  18591. }
  18592. /**
  18593. * Returns `true` if the given equirectangular image has been fully loaded.
  18594. *
  18595. * @private
  18596. * @param {(Image|Object)} image - The equirectangular image.
  18597. * @return {boolean} Whether the given cube map is ready or not.
  18598. */
  18599. function isEquirectangularMapReady( image ) {
  18600. if ( image === null || image === undefined ) return false;
  18601. return image.height > 0;
  18602. }
  18603. /**
  18604. * TSL function for creating a PMREM node.
  18605. *
  18606. * @tsl
  18607. * @function
  18608. * @param {Texture} value - The input texture.
  18609. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  18610. * @param {?Node<float>} [levelNode=null] - The level node.
  18611. * @returns {PMREMNode}
  18612. */
  18613. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  18614. const _envNodeCache = new WeakMap();
  18615. /**
  18616. * Represents a physical model for Image-based lighting (IBL). The environment
  18617. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  18618. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  18619. *
  18620. * @augments LightingNode
  18621. */
  18622. class EnvironmentNode extends LightingNode {
  18623. static get type() {
  18624. return 'EnvironmentNode';
  18625. }
  18626. /**
  18627. * Constructs a new environment node.
  18628. *
  18629. * @param {Node} [envNode=null] - A node representing the environment.
  18630. */
  18631. constructor( envNode = null ) {
  18632. super();
  18633. /**
  18634. * A node representing the environment.
  18635. *
  18636. * @type {?Node}
  18637. * @default null
  18638. */
  18639. this.envNode = envNode;
  18640. }
  18641. setup( builder ) {
  18642. const { material } = builder;
  18643. let envNode = this.envNode;
  18644. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  18645. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  18646. let cacheEnvNode = _envNodeCache.get( value );
  18647. if ( cacheEnvNode === undefined ) {
  18648. cacheEnvNode = pmremTexture( value );
  18649. _envNodeCache.set( value, cacheEnvNode );
  18650. }
  18651. envNode = cacheEnvNode;
  18652. }
  18653. //
  18654. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  18655. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  18656. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  18657. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  18658. const isolateRadiance = isolate( radiance );
  18659. const isolateIrradiance = isolate( irradiance );
  18660. //
  18661. builder.context.radiance.addAssign( isolateRadiance );
  18662. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  18663. //
  18664. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  18665. if ( clearcoatRadiance ) {
  18666. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  18667. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  18668. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  18669. }
  18670. }
  18671. }
  18672. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  18673. let reflectVec = null;
  18674. return {
  18675. getUV: () => {
  18676. if ( reflectVec === null ) {
  18677. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  18678. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  18679. reflectVec = pow4( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  18680. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  18681. }
  18682. return reflectVec;
  18683. },
  18684. getTextureLevel: () => {
  18685. return roughnessNode;
  18686. }
  18687. };
  18688. };
  18689. const createIrradianceContext = ( normalWorldNode ) => {
  18690. return {
  18691. getUV: () => {
  18692. return normalWorldNode;
  18693. },
  18694. getTextureLevel: () => {
  18695. return float( 1.0 );
  18696. }
  18697. };
  18698. };
  18699. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  18700. /**
  18701. * Node material version of {@link MeshStandardMaterial}.
  18702. *
  18703. * @augments NodeMaterial
  18704. */
  18705. class MeshStandardNodeMaterial extends NodeMaterial {
  18706. static get type() {
  18707. return 'MeshStandardNodeMaterial';
  18708. }
  18709. /**
  18710. * Constructs a new mesh standard node material.
  18711. *
  18712. * @param {Object} [parameters] - The configuration parameter.
  18713. */
  18714. constructor( parameters ) {
  18715. super();
  18716. /**
  18717. * This flag can be used for type testing.
  18718. *
  18719. * @type {boolean}
  18720. * @readonly
  18721. * @default true
  18722. */
  18723. this.isMeshStandardNodeMaterial = true;
  18724. /**
  18725. * Set to `true` because standard materials react on lights.
  18726. *
  18727. * @type {boolean}
  18728. * @default true
  18729. */
  18730. this.lights = true;
  18731. /**
  18732. * The emissive color of standard materials is by default inferred from the `emissive`,
  18733. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18734. * overwrite the default and define the emissive color with a node instead.
  18735. *
  18736. * If you don't want to overwrite the emissive color but modify the existing
  18737. * value instead, use {@link materialEmissive}.
  18738. *
  18739. * @type {?Node<vec3>}
  18740. * @default null
  18741. */
  18742. this.emissiveNode = null;
  18743. /**
  18744. * The metalness of standard materials is by default inferred from the `metalness`,
  18745. * and `metalnessMap` properties. This node property allows to
  18746. * overwrite the default and define the metalness with a node instead.
  18747. *
  18748. * If you don't want to overwrite the metalness but modify the existing
  18749. * value instead, use {@link materialMetalness}.
  18750. *
  18751. * @type {?Node<float>}
  18752. * @default null
  18753. */
  18754. this.metalnessNode = null;
  18755. /**
  18756. * The roughness of standard materials is by default inferred from the `roughness`,
  18757. * and `roughnessMap` properties. This node property allows to
  18758. * overwrite the default and define the roughness with a node instead.
  18759. *
  18760. * If you don't want to overwrite the roughness but modify the existing
  18761. * value instead, use {@link materialRoughness}.
  18762. *
  18763. * @type {?Node<float>}
  18764. * @default null
  18765. */
  18766. this.roughnessNode = null;
  18767. this.setDefaultValues( _defaultValues$6 );
  18768. this.setValues( parameters );
  18769. }
  18770. /**
  18771. * Overwritten since this type of material uses {@link EnvironmentNode}
  18772. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18773. * method honors `Scene.environment`.
  18774. *
  18775. * @param {NodeBuilder} builder - The current node builder.
  18776. * @return {?EnvironmentNode<vec3>} The environment node.
  18777. */
  18778. setupEnvironment( builder ) {
  18779. let envNode = super.setupEnvironment( builder );
  18780. if ( envNode === null && builder.environmentNode ) {
  18781. envNode = builder.environmentNode;
  18782. }
  18783. return envNode ? new EnvironmentNode( envNode ) : null;
  18784. }
  18785. /**
  18786. * Setups the lighting model.
  18787. *
  18788. * @return {PhysicalLightingModel} The lighting model.
  18789. */
  18790. setupLightingModel( /*builder*/ ) {
  18791. return new PhysicalLightingModel();
  18792. }
  18793. /**
  18794. * Setups the specular related node variables.
  18795. */
  18796. setupSpecular() {
  18797. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18798. specularColor.assign( vec3( 0.04 ) );
  18799. specularColorBlended.assign( specularColorNode );
  18800. specularF90.assign( 1.0 );
  18801. }
  18802. /**
  18803. * Setups the standard specific node variables.
  18804. *
  18805. * @param {NodeBuilder} builder - The current node builder.
  18806. */
  18807. setupVariants() {
  18808. // METALNESS
  18809. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18810. metalness.assign( metalnessNode );
  18811. // ROUGHNESS
  18812. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18813. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18814. roughness.assign( roughnessNode );
  18815. // SPECULAR COLOR
  18816. this.setupSpecular();
  18817. // DIFFUSE COLOR
  18818. diffuseContribution.assign( diffuseColor.rgb.mul( metalnessNode.oneMinus() ) );
  18819. }
  18820. copy( source ) {
  18821. this.emissiveNode = source.emissiveNode;
  18822. this.metalnessNode = source.metalnessNode;
  18823. this.roughnessNode = source.roughnessNode;
  18824. return super.copy( source );
  18825. }
  18826. }
  18827. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18828. /**
  18829. * Node material version of {@link MeshPhysicalMaterial}.
  18830. *
  18831. * @augments MeshStandardNodeMaterial
  18832. */
  18833. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18834. static get type() {
  18835. return 'MeshPhysicalNodeMaterial';
  18836. }
  18837. /**
  18838. * Constructs a new mesh physical node material.
  18839. *
  18840. * @param {Object} [parameters] - The configuration parameter.
  18841. */
  18842. constructor( parameters ) {
  18843. super();
  18844. /**
  18845. * This flag can be used for type testing.
  18846. *
  18847. * @type {boolean}
  18848. * @readonly
  18849. * @default true
  18850. */
  18851. this.isMeshPhysicalNodeMaterial = true;
  18852. /**
  18853. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18854. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18855. * and define the clearcoat with a node instead.
  18856. *
  18857. * If you don't want to overwrite the clearcoat but modify the existing
  18858. * value instead, use {@link materialClearcoat}.
  18859. *
  18860. * @type {?Node<float>}
  18861. * @default null
  18862. */
  18863. this.clearcoatNode = null;
  18864. /**
  18865. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18866. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18867. * and define the clearcoat roughness with a node instead.
  18868. *
  18869. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18870. * value instead, use {@link materialClearcoatRoughness}.
  18871. *
  18872. * @type {?Node<float>}
  18873. * @default null
  18874. */
  18875. this.clearcoatRoughnessNode = null;
  18876. /**
  18877. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18878. * property. This node property allows to overwrite the default
  18879. * and define the clearcoat normal with a node instead.
  18880. *
  18881. * If you don't want to overwrite the clearcoat normal but modify the existing
  18882. * value instead, use {@link materialClearcoatNormal}.
  18883. *
  18884. * @type {?Node<vec3>}
  18885. * @default null
  18886. */
  18887. this.clearcoatNormalNode = null;
  18888. /**
  18889. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18890. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18891. * and define the sheen with a node instead.
  18892. *
  18893. * If you don't want to overwrite the sheen but modify the existing
  18894. * value instead, use {@link materialSheen}.
  18895. *
  18896. * @type {?Node<vec3>}
  18897. * @default null
  18898. */
  18899. this.sheenNode = null;
  18900. /**
  18901. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18902. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18903. * and define the sheen roughness with a node instead.
  18904. *
  18905. * If you don't want to overwrite the sheen roughness but modify the existing
  18906. * value instead, use {@link materialSheenRoughness}.
  18907. *
  18908. * @type {?Node<float>}
  18909. * @default null
  18910. */
  18911. this.sheenRoughnessNode = null;
  18912. /**
  18913. * The iridescence of physical materials is by default inferred from the `iridescence`
  18914. * property. This node property allows to overwrite the default
  18915. * and define the iridescence with a node instead.
  18916. *
  18917. * If you don't want to overwrite the iridescence but modify the existing
  18918. * value instead, use {@link materialIridescence}.
  18919. *
  18920. * @type {?Node<float>}
  18921. * @default null
  18922. */
  18923. this.iridescenceNode = null;
  18924. /**
  18925. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18926. * property. This node property allows to overwrite the default
  18927. * and define the iridescence IOR with a node instead.
  18928. *
  18929. * If you don't want to overwrite the iridescence IOR but modify the existing
  18930. * value instead, use {@link materialIridescenceIOR}.
  18931. *
  18932. * @type {?Node<float>}
  18933. * @default null
  18934. */
  18935. this.iridescenceIORNode = null;
  18936. /**
  18937. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18938. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18939. * and define the iridescence thickness with a node instead.
  18940. *
  18941. * If you don't want to overwrite the iridescence thickness but modify the existing
  18942. * value instead, use {@link materialIridescenceThickness}.
  18943. *
  18944. * @type {?Node<float>}
  18945. * @default null
  18946. */
  18947. this.iridescenceThicknessNode = null;
  18948. /**
  18949. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18950. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18951. * and define the specular intensity with a node instead.
  18952. *
  18953. * If you don't want to overwrite the specular intensity but modify the existing
  18954. * value instead, use {@link materialSpecularIntensity}.
  18955. *
  18956. * @type {?Node<float>}
  18957. * @default null
  18958. */
  18959. this.specularIntensityNode = null;
  18960. /**
  18961. * The specular color of physical materials is by default inferred from the `specularColor`
  18962. * and `specularColorMap` properties. This node property allows to overwrite the default
  18963. * and define the specular color with a node instead.
  18964. *
  18965. * If you don't want to overwrite the specular color but modify the existing
  18966. * value instead, use {@link materialSpecularColor}.
  18967. *
  18968. * @type {?Node<vec3>}
  18969. * @default null
  18970. */
  18971. this.specularColorNode = null;
  18972. /**
  18973. * The ior of physical materials is by default inferred from the `ior`
  18974. * property. This node property allows to overwrite the default
  18975. * and define the ior with a node instead.
  18976. *
  18977. * If you don't want to overwrite the ior but modify the existing
  18978. * value instead, use {@link materialIOR}.
  18979. *
  18980. * @type {?Node<float>}
  18981. * @default null
  18982. */
  18983. this.iorNode = null;
  18984. /**
  18985. * The transmission of physical materials is by default inferred from the `transmission` and
  18986. * `transmissionMap` properties. This node property allows to overwrite the default
  18987. * and define the transmission with a node instead.
  18988. *
  18989. * If you don't want to overwrite the transmission but modify the existing
  18990. * value instead, use {@link materialTransmission}.
  18991. *
  18992. * @type {?Node<float>}
  18993. * @default null
  18994. */
  18995. this.transmissionNode = null;
  18996. /**
  18997. * The thickness of physical materials is by default inferred from the `thickness` and
  18998. * `thicknessMap` properties. This node property allows to overwrite the default
  18999. * and define the thickness with a node instead.
  19000. *
  19001. * If you don't want to overwrite the thickness but modify the existing
  19002. * value instead, use {@link materialThickness}.
  19003. *
  19004. * @type {?Node<float>}
  19005. * @default null
  19006. */
  19007. this.thicknessNode = null;
  19008. /**
  19009. * The attenuation distance of physical materials is by default inferred from the
  19010. * `attenuationDistance` property. This node property allows to overwrite the default
  19011. * and define the attenuation distance with a node instead.
  19012. *
  19013. * If you don't want to overwrite the attenuation distance but modify the existing
  19014. * value instead, use {@link materialAttenuationDistance}.
  19015. *
  19016. * @type {?Node<float>}
  19017. * @default null
  19018. */
  19019. this.attenuationDistanceNode = null;
  19020. /**
  19021. * The attenuation color of physical materials is by default inferred from the
  19022. * `attenuationColor` property. This node property allows to overwrite the default
  19023. * and define the attenuation color with a node instead.
  19024. *
  19025. * If you don't want to overwrite the attenuation color but modify the existing
  19026. * value instead, use {@link materialAttenuationColor}.
  19027. *
  19028. * @type {?Node<vec3>}
  19029. * @default null
  19030. */
  19031. this.attenuationColorNode = null;
  19032. /**
  19033. * The dispersion of physical materials is by default inferred from the
  19034. * `dispersion` property. This node property allows to overwrite the default
  19035. * and define the dispersion with a node instead.
  19036. *
  19037. * If you don't want to overwrite the dispersion but modify the existing
  19038. * value instead, use {@link materialDispersion}.
  19039. *
  19040. * @type {?Node<float>}
  19041. * @default null
  19042. */
  19043. this.dispersionNode = null;
  19044. /**
  19045. * The anisotropy of physical materials is by default inferred from the
  19046. * `anisotropy` property. This node property allows to overwrite the default
  19047. * and define the anisotropy with a node instead.
  19048. *
  19049. * If you don't want to overwrite the anisotropy but modify the existing
  19050. * value instead, use {@link materialAnisotropy}.
  19051. *
  19052. * @type {?Node<float>}
  19053. * @default null
  19054. */
  19055. this.anisotropyNode = null;
  19056. this.setDefaultValues( _defaultValues$5 );
  19057. this.setValues( parameters );
  19058. }
  19059. /**
  19060. * Whether the lighting model should use clearcoat or not.
  19061. *
  19062. * @type {boolean}
  19063. * @default true
  19064. */
  19065. get useClearcoat() {
  19066. return this.clearcoat > 0 || this.clearcoatNode !== null;
  19067. }
  19068. /**
  19069. * Whether the lighting model should use iridescence or not.
  19070. *
  19071. * @type {boolean}
  19072. * @default true
  19073. */
  19074. get useIridescence() {
  19075. return this.iridescence > 0 || this.iridescenceNode !== null;
  19076. }
  19077. /**
  19078. * Whether the lighting model should use sheen or not.
  19079. *
  19080. * @type {boolean}
  19081. * @default true
  19082. */
  19083. get useSheen() {
  19084. return this.sheen > 0 || this.sheenNode !== null;
  19085. }
  19086. /**
  19087. * Whether the lighting model should use anisotropy or not.
  19088. *
  19089. * @type {boolean}
  19090. * @default true
  19091. */
  19092. get useAnisotropy() {
  19093. return this.anisotropy > 0 || this.anisotropyNode !== null;
  19094. }
  19095. /**
  19096. * Whether the lighting model should use transmission or not.
  19097. *
  19098. * @type {boolean}
  19099. * @default true
  19100. */
  19101. get useTransmission() {
  19102. return this.transmission > 0 || this.transmissionNode !== null;
  19103. }
  19104. /**
  19105. * Whether the lighting model should use dispersion or not.
  19106. *
  19107. * @type {boolean}
  19108. * @default true
  19109. */
  19110. get useDispersion() {
  19111. return this.dispersion > 0 || this.dispersionNode !== null;
  19112. }
  19113. /**
  19114. * Setups the specular related node variables.
  19115. */
  19116. setupSpecular() {
  19117. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  19118. ior.assign( iorNode );
  19119. specularColor.assign( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ) );
  19120. specularColorBlended.assign( mix( specularColor, diffuseColor.rgb, metalness ) );
  19121. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  19122. }
  19123. /**
  19124. * Setups the lighting model.
  19125. *
  19126. * @return {PhysicalLightingModel} The lighting model.
  19127. */
  19128. setupLightingModel( /*builder*/ ) {
  19129. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  19130. }
  19131. /**
  19132. * Setups the physical specific node variables.
  19133. *
  19134. * @param {NodeBuilder} builder - The current node builder.
  19135. */
  19136. setupVariants( builder ) {
  19137. super.setupVariants( builder );
  19138. // CLEARCOAT
  19139. if ( this.useClearcoat ) {
  19140. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  19141. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  19142. clearcoat.assign( clearcoatNode );
  19143. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  19144. }
  19145. // SHEEN
  19146. if ( this.useSheen ) {
  19147. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  19148. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  19149. sheen.assign( sheenNode );
  19150. sheenRoughness.assign( sheenRoughnessNode );
  19151. }
  19152. // IRIDESCENCE
  19153. if ( this.useIridescence ) {
  19154. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  19155. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  19156. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  19157. iridescence.assign( iridescenceNode );
  19158. iridescenceIOR.assign( iridescenceIORNode );
  19159. iridescenceThickness.assign( iridescenceThicknessNode );
  19160. }
  19161. // ANISOTROPY
  19162. if ( this.useAnisotropy ) {
  19163. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  19164. anisotropy.assign( anisotropyV.length() );
  19165. If( anisotropy.equal( 0.0 ), () => {
  19166. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  19167. } ).Else( () => {
  19168. anisotropyV.divAssign( vec2( anisotropy ) );
  19169. anisotropy.assign( anisotropy.saturate() );
  19170. } );
  19171. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  19172. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  19173. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  19174. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  19175. }
  19176. // TRANSMISSION
  19177. if ( this.useTransmission ) {
  19178. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  19179. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  19180. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  19181. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  19182. transmission.assign( transmissionNode );
  19183. thickness.assign( thicknessNode );
  19184. attenuationDistance.assign( attenuationDistanceNode );
  19185. attenuationColor.assign( attenuationColorNode );
  19186. if ( this.useDispersion ) {
  19187. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  19188. dispersion.assign( dispersionNode );
  19189. }
  19190. }
  19191. }
  19192. /**
  19193. * Setups the clearcoat normal node.
  19194. *
  19195. * @return {Node<vec3>} The clearcoat normal.
  19196. */
  19197. setupClearcoatNormal() {
  19198. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  19199. }
  19200. setup( builder ) {
  19201. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  19202. super.setup( builder );
  19203. }
  19204. copy( source ) {
  19205. this.clearcoatNode = source.clearcoatNode;
  19206. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  19207. this.clearcoatNormalNode = source.clearcoatNormalNode;
  19208. this.sheenNode = source.sheenNode;
  19209. this.sheenRoughnessNode = source.sheenRoughnessNode;
  19210. this.iridescenceNode = source.iridescenceNode;
  19211. this.iridescenceIORNode = source.iridescenceIORNode;
  19212. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  19213. this.specularIntensityNode = source.specularIntensityNode;
  19214. this.specularColorNode = source.specularColorNode;
  19215. this.iorNode = source.iorNode;
  19216. this.transmissionNode = source.transmissionNode;
  19217. this.thicknessNode = source.thicknessNode;
  19218. this.attenuationDistanceNode = source.attenuationDistanceNode;
  19219. this.attenuationColorNode = source.attenuationColorNode;
  19220. this.dispersionNode = source.dispersionNode;
  19221. this.anisotropyNode = source.anisotropyNode;
  19222. return super.copy( source );
  19223. }
  19224. }
  19225. /**
  19226. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  19227. *
  19228. * @augments PhysicalLightingModel
  19229. */
  19230. class SSSLightingModel extends PhysicalLightingModel {
  19231. /**
  19232. * Constructs a new physical lighting model.
  19233. *
  19234. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  19235. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  19236. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  19237. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  19238. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  19239. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  19240. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  19241. */
  19242. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  19243. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  19244. /**
  19245. * Whether the lighting model should use SSS or not.
  19246. *
  19247. * @type {boolean}
  19248. * @default false
  19249. */
  19250. this.useSSS = sss;
  19251. }
  19252. /**
  19253. * Extends the default implementation with a SSS term.
  19254. *
  19255. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look](https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/)
  19256. *
  19257. * @param {Object} input - The input data.
  19258. * @param {NodeBuilder} builder - The current node builder.
  19259. */
  19260. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19261. if ( this.useSSS === true ) {
  19262. const material = builder.material;
  19263. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  19264. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  19265. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  19266. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  19267. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  19268. }
  19269. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  19270. }
  19271. }
  19272. /**
  19273. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  19274. * that implements a Subsurface scattering (SSS) term.
  19275. *
  19276. * @augments MeshPhysicalNodeMaterial
  19277. */
  19278. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  19279. static get type() {
  19280. return 'MeshSSSNodeMaterial';
  19281. }
  19282. /**
  19283. * Constructs a new mesh SSS node material.
  19284. *
  19285. * @param {Object} [parameters] - The configuration parameter.
  19286. */
  19287. constructor( parameters ) {
  19288. super( parameters );
  19289. /**
  19290. * Represents the thickness color.
  19291. *
  19292. * @type {?Node<vec3>}
  19293. * @default null
  19294. */
  19295. this.thicknessColorNode = null;
  19296. /**
  19297. * Represents the distortion factor.
  19298. *
  19299. * @type {?Node<float>}
  19300. */
  19301. this.thicknessDistortionNode = float( 0.1 );
  19302. /**
  19303. * Represents the thickness ambient factor.
  19304. *
  19305. * @type {?Node<float>}
  19306. */
  19307. this.thicknessAmbientNode = float( 0.0 );
  19308. /**
  19309. * Represents the thickness attenuation.
  19310. *
  19311. * @type {?Node<float>}
  19312. */
  19313. this.thicknessAttenuationNode = float( .1 );
  19314. /**
  19315. * Represents the thickness power.
  19316. *
  19317. * @type {?Node<float>}
  19318. */
  19319. this.thicknessPowerNode = float( 2.0 );
  19320. /**
  19321. * Represents the thickness scale.
  19322. *
  19323. * @type {?Node<float>}
  19324. */
  19325. this.thicknessScaleNode = float( 10.0 );
  19326. }
  19327. /**
  19328. * Whether the lighting model should use SSS or not.
  19329. *
  19330. * @type {boolean}
  19331. * @default true
  19332. */
  19333. get useSSS() {
  19334. return this.thicknessColorNode !== null;
  19335. }
  19336. /**
  19337. * Setups the lighting model.
  19338. *
  19339. * @return {SSSLightingModel} The lighting model.
  19340. */
  19341. setupLightingModel( /*builder*/ ) {
  19342. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  19343. }
  19344. copy( source ) {
  19345. this.thicknessColorNode = source.thicknessColorNode;
  19346. this.thicknessDistortionNode = source.thicknessDistortionNode;
  19347. this.thicknessAmbientNode = source.thicknessAmbientNode;
  19348. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  19349. this.thicknessPowerNode = source.thicknessPowerNode;
  19350. this.thicknessScaleNode = source.thicknessScaleNode;
  19351. return super.copy( source );
  19352. }
  19353. }
  19354. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  19355. // dotNL will be from -1.0 to 1.0
  19356. const dotNL = normal.dot( lightDirection );
  19357. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  19358. if ( builder.material.gradientMap ) {
  19359. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  19360. return vec3( gradientMap.r );
  19361. } else {
  19362. const fw = coord.fwidth().mul( 0.5 );
  19363. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  19364. }
  19365. } );
  19366. /**
  19367. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  19368. *
  19369. * @augments LightingModel
  19370. */
  19371. class ToonLightingModel extends LightingModel {
  19372. /**
  19373. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  19374. * reduced to a small number of discrete shades to create a comic-like, flat look.
  19375. *
  19376. * @param {Object} lightData - The light data.
  19377. * @param {NodeBuilder} builder - The current node builder.
  19378. */
  19379. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  19380. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  19381. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  19382. }
  19383. /**
  19384. * Implements the indirect lighting.
  19385. *
  19386. * @param {NodeBuilder} builder - The current node builder.
  19387. */
  19388. indirect( builder ) {
  19389. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  19390. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  19391. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  19392. }
  19393. }
  19394. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  19395. /**
  19396. * Node material version of {@link MeshToonMaterial}.
  19397. *
  19398. * @augments NodeMaterial
  19399. */
  19400. class MeshToonNodeMaterial extends NodeMaterial {
  19401. static get type() {
  19402. return 'MeshToonNodeMaterial';
  19403. }
  19404. /**
  19405. * Constructs a new mesh toon node material.
  19406. *
  19407. * @param {Object} [parameters] - The configuration parameter.
  19408. */
  19409. constructor( parameters ) {
  19410. super();
  19411. /**
  19412. * This flag can be used for type testing.
  19413. *
  19414. * @type {boolean}
  19415. * @readonly
  19416. * @default true
  19417. */
  19418. this.isMeshToonNodeMaterial = true;
  19419. /**
  19420. * Set to `true` because toon materials react on lights.
  19421. *
  19422. * @type {boolean}
  19423. * @default true
  19424. */
  19425. this.lights = true;
  19426. this.setDefaultValues( _defaultValues$4 );
  19427. this.setValues( parameters );
  19428. }
  19429. /**
  19430. * Setups the lighting model.
  19431. *
  19432. * @return {ToonLightingModel} The lighting model.
  19433. */
  19434. setupLightingModel( /*builder*/ ) {
  19435. return new ToonLightingModel();
  19436. }
  19437. }
  19438. /**
  19439. * TSL function for creating a matcap uv node.
  19440. *
  19441. * Can be used to compute texture coordinates for projecting a
  19442. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  19443. *
  19444. * @tsl
  19445. * @function
  19446. * @returns {Node<vec2>} The matcap UV coordinates.
  19447. */
  19448. const matcapUV = /*@__PURE__*/ Fn( () => {
  19449. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  19450. const y = positionViewDirection.cross( x );
  19451. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  19452. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  19453. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  19454. /**
  19455. * Node material version of {@link MeshMatcapMaterial}.
  19456. *
  19457. * @augments NodeMaterial
  19458. */
  19459. class MeshMatcapNodeMaterial extends NodeMaterial {
  19460. static get type() {
  19461. return 'MeshMatcapNodeMaterial';
  19462. }
  19463. /**
  19464. * Constructs a new mesh normal node material.
  19465. *
  19466. * @param {Object} [parameters] - The configuration parameter.
  19467. */
  19468. constructor( parameters ) {
  19469. super();
  19470. /**
  19471. * This flag can be used for type testing.
  19472. *
  19473. * @type {boolean}
  19474. * @readonly
  19475. * @default true
  19476. */
  19477. this.isMeshMatcapNodeMaterial = true;
  19478. this.setDefaultValues( _defaultValues$3 );
  19479. this.setValues( parameters );
  19480. }
  19481. /**
  19482. * Setups the matcap specific node variables.
  19483. *
  19484. * @param {NodeBuilder} builder - The current node builder.
  19485. */
  19486. setupVariants( builder ) {
  19487. const uv = matcapUV;
  19488. let matcapColor;
  19489. if ( builder.material.matcap ) {
  19490. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  19491. } else {
  19492. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  19493. }
  19494. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  19495. }
  19496. }
  19497. /**
  19498. * Applies a rotation to the given position node.
  19499. *
  19500. * @augments TempNode
  19501. */
  19502. class RotateNode extends TempNode {
  19503. static get type() {
  19504. return 'RotateNode';
  19505. }
  19506. /**
  19507. * Constructs a new rotate node.
  19508. *
  19509. * @param {Node} positionNode - The position node.
  19510. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19511. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19512. */
  19513. constructor( positionNode, rotationNode ) {
  19514. super();
  19515. /**
  19516. * The position node.
  19517. *
  19518. * @type {Node}
  19519. */
  19520. this.positionNode = positionNode;
  19521. /**
  19522. * Represents the rotation that is applied to the position node.
  19523. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19524. *
  19525. * @type {Node}
  19526. */
  19527. this.rotationNode = rotationNode;
  19528. }
  19529. /**
  19530. * The type of the {@link RotateNode#positionNode} defines the node's type.
  19531. *
  19532. * @param {NodeBuilder} builder - The current node builder.
  19533. * @return {string} The node's type.
  19534. */
  19535. getNodeType( builder ) {
  19536. return this.positionNode.getNodeType( builder );
  19537. }
  19538. setup( builder ) {
  19539. const { rotationNode, positionNode } = this;
  19540. const nodeType = this.getNodeType( builder );
  19541. if ( nodeType === 'vec2' ) {
  19542. const cosAngle = rotationNode.cos();
  19543. const sinAngle = rotationNode.sin();
  19544. const rotationMatrix = mat2(
  19545. cosAngle, sinAngle,
  19546. sinAngle.negate(), cosAngle
  19547. );
  19548. return rotationMatrix.mul( positionNode );
  19549. } else {
  19550. const rotation = rotationNode;
  19551. 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 ) );
  19552. 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 ) );
  19553. 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 ) );
  19554. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  19555. }
  19556. }
  19557. }
  19558. /**
  19559. * TSL function for creating a rotate node.
  19560. *
  19561. * @tsl
  19562. * @function
  19563. * @param {Node} positionNode - The position node.
  19564. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  19565. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  19566. * @returns {RotateNode}
  19567. */
  19568. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  19569. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  19570. /**
  19571. * Node material version of {@link SpriteMaterial}.
  19572. *
  19573. * @augments NodeMaterial
  19574. */
  19575. class SpriteNodeMaterial extends NodeMaterial {
  19576. static get type() {
  19577. return 'SpriteNodeMaterial';
  19578. }
  19579. /**
  19580. * Constructs a new sprite node material.
  19581. *
  19582. * @param {Object} [parameters] - The configuration parameter.
  19583. */
  19584. constructor( parameters ) {
  19585. super();
  19586. /**
  19587. * This flag can be used for type testing.
  19588. *
  19589. * @type {boolean}
  19590. * @readonly
  19591. * @default true
  19592. */
  19593. this.isSpriteNodeMaterial = true;
  19594. this._useSizeAttenuation = true;
  19595. /**
  19596. * This property makes it possible to define the position of the sprite with a
  19597. * node. That can be useful when the material is used with instanced rendering
  19598. * and node data are defined with an instanced attribute node:
  19599. * ```js
  19600. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  19601. * material.positionNode = instancedBufferAttribute( positionAttribute );
  19602. * ```
  19603. * Another possibility is to compute the instanced data with a compute shader:
  19604. * ```js
  19605. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  19606. * particleMaterial.positionNode = positionBuffer.toAttribute();
  19607. * ```
  19608. *
  19609. * @type {?Node<vec2>}
  19610. * @default null
  19611. */
  19612. this.positionNode = null;
  19613. /**
  19614. * The rotation of sprite materials is by default inferred from the `rotation`,
  19615. * property. This node property allows to overwrite the default and define
  19616. * the rotation with a node instead.
  19617. *
  19618. * If you don't want to overwrite the rotation but modify the existing
  19619. * value instead, use {@link materialRotation}.
  19620. *
  19621. * @type {?Node<float>}
  19622. * @default null
  19623. */
  19624. this.rotationNode = null;
  19625. /**
  19626. * This node property provides an additional way to scale sprites next to
  19627. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  19628. * is multiplied with the scale value of this node in the vertex shader.
  19629. *
  19630. * @type {?Node<vec2>}
  19631. * @default null
  19632. */
  19633. this.scaleNode = null;
  19634. /**
  19635. * In Sprites, the transparent property is enabled by default.
  19636. *
  19637. * @type {boolean}
  19638. * @default true
  19639. */
  19640. this.transparent = true;
  19641. this.setDefaultValues( _defaultValues$2 );
  19642. this.setValues( parameters );
  19643. }
  19644. /**
  19645. * Setups the position node in view space. This method implements
  19646. * the sprite specific vertex shader.
  19647. *
  19648. * @param {NodeBuilder} builder - The current node builder.
  19649. * @return {Node<vec3>} The position in view space.
  19650. */
  19651. setupPositionView( builder ) {
  19652. const { object, camera } = builder;
  19653. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  19654. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  19655. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  19656. if ( scaleNode !== null ) {
  19657. scale = scale.mul( vec2( scaleNode ) );
  19658. }
  19659. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  19660. scale = scale.mul( mvPosition.z.negate() );
  19661. }
  19662. let alignedPosition = positionGeometry.xy;
  19663. if ( object.center && object.center.isVector2 === true ) {
  19664. const center = reference$1( 'center', 'vec2', object );
  19665. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  19666. }
  19667. alignedPosition = alignedPosition.mul( scale );
  19668. const rotation = float( rotationNode || materialRotation );
  19669. const rotatedPosition = rotate( alignedPosition, rotation );
  19670. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  19671. }
  19672. copy( source ) {
  19673. this.positionNode = source.positionNode;
  19674. this.rotationNode = source.rotationNode;
  19675. this.scaleNode = source.scaleNode;
  19676. return super.copy( source );
  19677. }
  19678. /**
  19679. * Whether to use size attenuation or not.
  19680. *
  19681. * @type {boolean}
  19682. * @default true
  19683. */
  19684. get sizeAttenuation() {
  19685. return this._useSizeAttenuation;
  19686. }
  19687. set sizeAttenuation( value ) {
  19688. if ( this._useSizeAttenuation !== value ) {
  19689. this._useSizeAttenuation = value;
  19690. this.needsUpdate = true;
  19691. }
  19692. }
  19693. }
  19694. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  19695. const _size$4 = /*@__PURE__*/ new Vector2();
  19696. /**
  19697. * Node material version of {@link PointsMaterial}.
  19698. *
  19699. * This material can be used in two ways:
  19700. *
  19701. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  19702. * with a pixel size of `1`, it's not possible to define a size.
  19703. *
  19704. * ```js
  19705. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  19706. * ```
  19707. *
  19708. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  19709. * see {@link PointsNodeMaterial#sizeNode}.
  19710. *
  19711. * ```js
  19712. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  19713. * ```
  19714. *
  19715. * @augments SpriteNodeMaterial
  19716. */
  19717. class PointsNodeMaterial extends SpriteNodeMaterial {
  19718. static get type() {
  19719. return 'PointsNodeMaterial';
  19720. }
  19721. /**
  19722. * Constructs a new points node material.
  19723. *
  19724. * @param {Object} [parameters] - The configuration parameter.
  19725. */
  19726. constructor( parameters ) {
  19727. super();
  19728. /**
  19729. * This node property provides an additional way to set the point size.
  19730. *
  19731. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19732. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19733. * backend. If an application wants to render points with a size larger than 1 pixel,
  19734. * the material should be used with {@link Sprite} and instancing.
  19735. *
  19736. * @type {?Node<vec2>}
  19737. * @default null
  19738. */
  19739. this.sizeNode = null;
  19740. /**
  19741. * This flag can be used for type testing.
  19742. *
  19743. * @type {boolean}
  19744. * @readonly
  19745. * @default true
  19746. */
  19747. this.isPointsNodeMaterial = true;
  19748. this.setDefaultValues( _defaultValues$1 );
  19749. this.setValues( parameters );
  19750. }
  19751. setupPositionView() {
  19752. const { positionNode } = this;
  19753. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19754. }
  19755. setupVertexSprite( builder ) {
  19756. const { material, camera } = builder;
  19757. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19758. let mvp = super.setupVertex( builder );
  19759. // skip further processing if the material is not a node material
  19760. if ( material.isNodeMaterial !== true ) {
  19761. return mvp;
  19762. }
  19763. // point size
  19764. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19765. pointSize = pointSize.mul( screenDPR );
  19766. // size attenuation
  19767. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19768. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19769. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19770. }
  19771. // scale
  19772. if ( scaleNode && scaleNode.isNode ) {
  19773. pointSize = pointSize.mul( vec2( scaleNode ) );
  19774. }
  19775. // compute offset
  19776. let offset = positionGeometry.xy;
  19777. // apply rotation
  19778. if ( rotationNode && rotationNode.isNode ) {
  19779. const rotation = float( rotationNode );
  19780. offset = rotate( offset, rotation );
  19781. }
  19782. // account for point size
  19783. offset = offset.mul( pointSize );
  19784. // scale by viewport size
  19785. offset = offset.div( viewportSize.div( 2 ) );
  19786. // compensate for the perspective divide
  19787. offset = offset.mul( mvp.w );
  19788. // add offset
  19789. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19790. return mvp;
  19791. }
  19792. setupVertex( builder ) {
  19793. if ( builder.object.isPoints ) {
  19794. return super.setupVertex( builder );
  19795. } else {
  19796. return this.setupVertexSprite( builder );
  19797. }
  19798. }
  19799. /**
  19800. * Whether alpha to coverage should be used or not.
  19801. *
  19802. * @type {boolean}
  19803. * @default true
  19804. */
  19805. get alphaToCoverage() {
  19806. return this._useAlphaToCoverage;
  19807. }
  19808. set alphaToCoverage( value ) {
  19809. if ( this._useAlphaToCoverage !== value ) {
  19810. this._useAlphaToCoverage = value;
  19811. this.needsUpdate = true;
  19812. }
  19813. }
  19814. }
  19815. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19816. const size = renderer.getSize( _size$4 ); // logical units
  19817. this.value = 0.5 * size.y;
  19818. } );
  19819. /**
  19820. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19821. *
  19822. * @augments LightingModel
  19823. */
  19824. class ShadowMaskModel extends LightingModel {
  19825. /**
  19826. * Constructs a new shadow mask model.
  19827. */
  19828. constructor() {
  19829. super();
  19830. /**
  19831. * The shadow mask node.
  19832. *
  19833. * @type {Node}
  19834. */
  19835. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19836. }
  19837. /**
  19838. * Only used to save the shadow mask.
  19839. *
  19840. * @param {Object} input - The input data.
  19841. */
  19842. direct( { lightNode } ) {
  19843. if ( lightNode.shadowNode !== null ) {
  19844. this.shadowNode.mulAssign( lightNode.shadowNode );
  19845. }
  19846. }
  19847. /**
  19848. * Uses the shadow mask to produce the final color.
  19849. *
  19850. * @param {NodeBuilder} builder - The current node builder.
  19851. */
  19852. finish( { context } ) {
  19853. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19854. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19855. }
  19856. }
  19857. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19858. /**
  19859. * Node material version of {@link ShadowMaterial}.
  19860. *
  19861. * @augments NodeMaterial
  19862. */
  19863. class ShadowNodeMaterial extends NodeMaterial {
  19864. static get type() {
  19865. return 'ShadowNodeMaterial';
  19866. }
  19867. /**
  19868. * Constructs a new shadow node material.
  19869. *
  19870. * @param {Object} [parameters] - The configuration parameter.
  19871. */
  19872. constructor( parameters ) {
  19873. super();
  19874. /**
  19875. * This flag can be used for type testing.
  19876. *
  19877. * @type {boolean}
  19878. * @readonly
  19879. * @default true
  19880. */
  19881. this.isShadowNodeMaterial = true;
  19882. /**
  19883. * Set to `true` because so it's possible to implement
  19884. * the shadow mask effect.
  19885. *
  19886. * @type {boolean}
  19887. * @default true
  19888. */
  19889. this.lights = true;
  19890. /**
  19891. * Overwritten since shadow materials are transparent
  19892. * by default.
  19893. *
  19894. * @type {boolean}
  19895. * @default true
  19896. */
  19897. this.transparent = true;
  19898. this.setDefaultValues( _defaultValues );
  19899. this.setValues( parameters );
  19900. }
  19901. /**
  19902. * Setups the lighting model.
  19903. *
  19904. * @return {ShadowMaskModel} The lighting model.
  19905. */
  19906. setupLightingModel( /*builder*/ ) {
  19907. return new ShadowMaskModel();
  19908. }
  19909. }
  19910. const scatteringDensity = property( 'vec3' );
  19911. const linearDepthRay = property( 'vec3' );
  19912. const outgoingRayLight = property( 'vec3' );
  19913. /**
  19914. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19915. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19916. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19917. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19918. *
  19919. * @augments LightingModel
  19920. */
  19921. class VolumetricLightingModel extends LightingModel {
  19922. constructor() {
  19923. super();
  19924. }
  19925. start( builder ) {
  19926. const { material } = builder;
  19927. const startPos = property( 'vec3' );
  19928. const endPos = property( 'vec3' );
  19929. // This approach dynamically changes the direction of the ray,
  19930. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  19931. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19932. startPos.assign( cameraPosition );
  19933. endPos.assign( positionWorld );
  19934. } ).Else( () => {
  19935. startPos.assign( positionWorld );
  19936. endPos.assign( cameraPosition );
  19937. } );
  19938. //
  19939. const viewVector = endPos.sub( startPos );
  19940. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19941. const stepSize = viewVector.length().div( steps ).toVar();
  19942. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19943. const distTravelled = float( 0.0 ).toVar();
  19944. const transmittance = vec3( 1 ).toVar();
  19945. if ( material.offsetNode ) {
  19946. // reduce banding
  19947. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19948. }
  19949. Loop( steps, () => {
  19950. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19951. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19952. if ( material.depthNode !== null ) {
  19953. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19954. builder.context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19955. }
  19956. builder.context.positionWorld = positionRay;
  19957. builder.context.shadowPositionWorld = positionRay;
  19958. builder.context.positionView = positionViewRay;
  19959. scatteringDensity.assign( 0 );
  19960. let scatteringNode;
  19961. if ( material.scatteringNode ) {
  19962. scatteringNode = material.scatteringNode( {
  19963. positionRay
  19964. } );
  19965. }
  19966. super.start( builder );
  19967. if ( scatteringNode ) {
  19968. scatteringDensity.mulAssign( scatteringNode );
  19969. }
  19970. // beer's law
  19971. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19972. transmittance.mulAssign( falloff );
  19973. // move along the ray
  19974. distTravelled.addAssign( stepSize );
  19975. } );
  19976. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19977. }
  19978. scatteringLight( lightColor, builder ) {
  19979. const sceneDepthNode = builder.context.sceneDepthNode;
  19980. if ( sceneDepthNode ) {
  19981. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19982. scatteringDensity.addAssign( lightColor );
  19983. } );
  19984. } else {
  19985. scatteringDensity.addAssign( lightColor );
  19986. }
  19987. }
  19988. direct( { lightNode, lightColor }, builder ) {
  19989. // Ignore lights with infinite distance
  19990. if ( lightNode.light.distance === undefined ) return;
  19991. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19992. const directLight = lightColor.xyz.toVar();
  19993. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19994. this.scatteringLight( directLight, builder );
  19995. }
  19996. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19997. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19998. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19999. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  20000. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  20001. const P = builder.context.positionView;
  20002. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  20003. this.scatteringLight( directLight, builder );
  20004. }
  20005. finish( builder ) {
  20006. builder.context.outgoingLight.assign( outgoingRayLight );
  20007. }
  20008. }
  20009. /**
  20010. * Volume node material.
  20011. *
  20012. * @augments NodeMaterial
  20013. */
  20014. class VolumeNodeMaterial extends NodeMaterial {
  20015. static get type() {
  20016. return 'VolumeNodeMaterial';
  20017. }
  20018. /**
  20019. * Constructs a new volume node material.
  20020. *
  20021. * @param {Object} [parameters] - The configuration parameter.
  20022. */
  20023. constructor( parameters ) {
  20024. super();
  20025. /**
  20026. * This flag can be used for type testing.
  20027. *
  20028. * @type {boolean}
  20029. * @readonly
  20030. * @default true
  20031. */
  20032. this.isVolumeNodeMaterial = true;
  20033. /**
  20034. * Number of steps used for raymarching.
  20035. *
  20036. * @type {number}
  20037. * @default 25
  20038. */
  20039. this.steps = 25;
  20040. /**
  20041. * Offsets the distance a ray has been traveled through a volume.
  20042. * Can be used to implement dithering to reduce banding.
  20043. *
  20044. * @type {Node<float>}
  20045. * @default null
  20046. */
  20047. this.offsetNode = null;
  20048. /**
  20049. * Node used for scattering calculations.
  20050. *
  20051. * @type {Function|FunctionNode<vec4>}
  20052. * @default null
  20053. */
  20054. this.scatteringNode = null;
  20055. this.lights = true;
  20056. this.transparent = true;
  20057. this.side = BackSide;
  20058. this.depthTest = false;
  20059. this.depthWrite = false;
  20060. this.setValues( parameters );
  20061. }
  20062. setupLightingModel() {
  20063. return new VolumetricLightingModel();
  20064. }
  20065. }
  20066. /**
  20067. * This module manages the internal animation loop of the renderer.
  20068. *
  20069. * @private
  20070. */
  20071. class Animation {
  20072. /**
  20073. * Constructs a new animation loop management component.
  20074. *
  20075. * @param {Renderer} renderer - A reference to the main renderer.
  20076. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20077. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20078. */
  20079. constructor( renderer, nodes, info ) {
  20080. /**
  20081. * A reference to the main renderer.
  20082. *
  20083. * @type {Renderer}
  20084. */
  20085. this.renderer = renderer;
  20086. /**
  20087. * Renderer component for managing nodes related logic.
  20088. *
  20089. * @type {Nodes}
  20090. */
  20091. this.nodes = nodes;
  20092. /**
  20093. * Renderer component for managing metrics and monitoring data.
  20094. *
  20095. * @type {Info}
  20096. */
  20097. this.info = info;
  20098. /**
  20099. * A reference to the context from `requestAnimationFrame()` can
  20100. * be called (usually `window`).
  20101. *
  20102. * @type {?(Window|XRSession)}
  20103. */
  20104. this._context = typeof self !== 'undefined' ? self : null;
  20105. /**
  20106. * The user-defined animation loop.
  20107. *
  20108. * @type {?Function}
  20109. * @default null
  20110. */
  20111. this._animationLoop = null;
  20112. /**
  20113. * The requestId which is returned from the `requestAnimationFrame()` call.
  20114. * Can be used to cancel the stop the animation loop.
  20115. *
  20116. * @type {?number}
  20117. * @default null
  20118. */
  20119. this._requestId = null;
  20120. }
  20121. /**
  20122. * Starts the internal animation loop.
  20123. */
  20124. start() {
  20125. const update = ( time, xrFrame ) => {
  20126. this._requestId = this._context.requestAnimationFrame( update );
  20127. if ( this.info.autoReset === true ) this.info.reset();
  20128. this.nodes.nodeFrame.update();
  20129. this.info.frame = this.nodes.nodeFrame.frameId;
  20130. this.renderer._inspector.begin();
  20131. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  20132. this.renderer._inspector.finish();
  20133. };
  20134. update();
  20135. }
  20136. /**
  20137. * Stops the internal animation loop.
  20138. */
  20139. stop() {
  20140. this._context.cancelAnimationFrame( this._requestId );
  20141. this._requestId = null;
  20142. }
  20143. /**
  20144. * Returns the user-level animation loop.
  20145. *
  20146. * @return {?Function} The animation loop.
  20147. */
  20148. getAnimationLoop() {
  20149. return this._animationLoop;
  20150. }
  20151. /**
  20152. * Defines the user-level animation loop.
  20153. *
  20154. * @param {?Function} callback - The animation loop.
  20155. */
  20156. setAnimationLoop( callback ) {
  20157. this._animationLoop = callback;
  20158. }
  20159. /**
  20160. * Returns the animation context.
  20161. *
  20162. * @return {Window|XRSession} The animation context.
  20163. */
  20164. getContext() {
  20165. return this._context;
  20166. }
  20167. /**
  20168. * Defines the context in which `requestAnimationFrame()` is executed.
  20169. *
  20170. * @param {Window|XRSession} context - The context to set.
  20171. */
  20172. setContext( context ) {
  20173. this._context = context;
  20174. }
  20175. /**
  20176. * Frees all internal resources and stops the animation loop.
  20177. */
  20178. dispose() {
  20179. this.stop();
  20180. }
  20181. }
  20182. /**
  20183. * Data structure for the renderer. It allows defining values
  20184. * with chained, hierarchical keys. Keys are meant to be
  20185. * objects since the module internally works with Weak Maps
  20186. * for performance reasons.
  20187. *
  20188. * @private
  20189. */
  20190. class ChainMap {
  20191. /**
  20192. * Constructs a new Chain Map.
  20193. */
  20194. constructor() {
  20195. /**
  20196. * A map of Weak Maps by their key length.
  20197. *
  20198. * @type {Object<number, WeakMap>}
  20199. */
  20200. this.weakMaps = {};
  20201. }
  20202. /**
  20203. * Returns the Weak Map for the given keys.
  20204. *
  20205. * @param {Array<Object>} keys - List of keys.
  20206. * @return {WeakMap} The weak map.
  20207. */
  20208. _getWeakMap( keys ) {
  20209. const length = keys.length;
  20210. let weakMap = this.weakMaps[ length ];
  20211. if ( weakMap === undefined ) {
  20212. weakMap = new WeakMap();
  20213. this.weakMaps[ length ] = weakMap;
  20214. }
  20215. return weakMap;
  20216. }
  20217. /**
  20218. * Returns the value for the given array of keys.
  20219. *
  20220. * @param {Array<Object>} keys - List of keys.
  20221. * @return {any} The value. Returns `undefined` if no value was found.
  20222. */
  20223. get( keys ) {
  20224. let map = this._getWeakMap( keys );
  20225. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20226. map = map.get( keys[ i ] );
  20227. if ( map === undefined ) return undefined;
  20228. }
  20229. return map.get( keys[ keys.length - 1 ] );
  20230. }
  20231. /**
  20232. * Sets the value for the given keys.
  20233. *
  20234. * @param {Array<Object>} keys - List of keys.
  20235. * @param {any} value - The value to set.
  20236. * @return {ChainMap} A reference to this Chain Map.
  20237. */
  20238. set( keys, value ) {
  20239. let map = this._getWeakMap( keys );
  20240. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20241. const key = keys[ i ];
  20242. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  20243. map = map.get( key );
  20244. }
  20245. map.set( keys[ keys.length - 1 ], value );
  20246. return this;
  20247. }
  20248. /**
  20249. * Deletes a value for the given keys.
  20250. *
  20251. * @param {Array<Object>} keys - The keys.
  20252. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  20253. */
  20254. delete( keys ) {
  20255. let map = this._getWeakMap( keys );
  20256. for ( let i = 0; i < keys.length - 1; i ++ ) {
  20257. map = map.get( keys[ i ] );
  20258. if ( map === undefined ) return false;
  20259. }
  20260. return map.delete( keys[ keys.length - 1 ] );
  20261. }
  20262. }
  20263. let _id$a = 0;
  20264. function getKeys( obj ) {
  20265. const keys = Object.keys( obj );
  20266. let proto = Object.getPrototypeOf( obj );
  20267. while ( proto ) {
  20268. const descriptors = Object.getOwnPropertyDescriptors( proto );
  20269. for ( const key in descriptors ) {
  20270. if ( descriptors[ key ] !== undefined ) {
  20271. const descriptor = descriptors[ key ];
  20272. if ( descriptor && typeof descriptor.get === 'function' ) {
  20273. keys.push( key );
  20274. }
  20275. }
  20276. }
  20277. proto = Object.getPrototypeOf( proto );
  20278. }
  20279. return keys;
  20280. }
  20281. /**
  20282. * A render object is the renderer's representation of single entity that gets drawn
  20283. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  20284. * scene since render objects also depend from the used material, the current render context
  20285. * and the current scene's lighting.
  20286. *
  20287. * In general, the basic process of the renderer is:
  20288. *
  20289. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  20290. * - Process the render lists by calling one or more render commands for each render item.
  20291. * - For each render command, request a render object and perform the draw.
  20292. *
  20293. * The module provides an interface to get data required for the draw command like the actual
  20294. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  20295. * creating render objects should only be done when necessary.
  20296. *
  20297. * @private
  20298. */
  20299. class RenderObject {
  20300. /**
  20301. * Constructs a new render object.
  20302. *
  20303. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20304. * @param {Geometries} geometries - Renderer component for managing geometries.
  20305. * @param {Renderer} renderer - The renderer.
  20306. * @param {Object3D} object - The 3D object.
  20307. * @param {Material} material - The 3D object's material.
  20308. * @param {Scene} scene - The scene the 3D object belongs to.
  20309. * @param {Camera} camera - The camera the object should be rendered with.
  20310. * @param {LightsNode} lightsNode - The lights node.
  20311. * @param {RenderContext} renderContext - The render context.
  20312. * @param {ClippingContext} clippingContext - The clipping context.
  20313. */
  20314. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  20315. this.id = _id$a ++;
  20316. /**
  20317. * Renderer component for managing nodes related logic.
  20318. *
  20319. * @type {Nodes}
  20320. * @private
  20321. */
  20322. this._nodes = nodes;
  20323. /**
  20324. * Renderer component for managing geometries.
  20325. *
  20326. * @type {Geometries}
  20327. * @private
  20328. */
  20329. this._geometries = geometries;
  20330. /**
  20331. * The renderer.
  20332. *
  20333. * @type {Renderer}
  20334. */
  20335. this.renderer = renderer;
  20336. /**
  20337. * The 3D object.
  20338. *
  20339. * @type {Object3D}
  20340. */
  20341. this.object = object;
  20342. /**
  20343. * The 3D object's material.
  20344. *
  20345. * @type {Material}
  20346. */
  20347. this.material = material;
  20348. /**
  20349. * The scene the 3D object belongs to.
  20350. *
  20351. * @type {Scene}
  20352. */
  20353. this.scene = scene;
  20354. /**
  20355. * The camera the 3D object should be rendered with.
  20356. *
  20357. * @type {Camera}
  20358. */
  20359. this.camera = camera;
  20360. /**
  20361. * The lights node.
  20362. *
  20363. * @type {LightsNode}
  20364. */
  20365. this.lightsNode = lightsNode;
  20366. /**
  20367. * The render context.
  20368. *
  20369. * @type {RenderContext}
  20370. */
  20371. this.context = renderContext;
  20372. /**
  20373. * The 3D object's geometry.
  20374. *
  20375. * @type {BufferGeometry}
  20376. */
  20377. this.geometry = object.geometry;
  20378. /**
  20379. * The render object's version.
  20380. *
  20381. * @type {number}
  20382. */
  20383. this.version = material.version;
  20384. /**
  20385. * The draw range of the geometry.
  20386. *
  20387. * @type {?Object}
  20388. * @default null
  20389. */
  20390. this.drawRange = null;
  20391. /**
  20392. * An array holding the buffer attributes
  20393. * of the render object. This entails attribute
  20394. * definitions on geometry and node level.
  20395. *
  20396. * @type {?Array<BufferAttribute>}
  20397. * @default null
  20398. */
  20399. this.attributes = null;
  20400. /**
  20401. * An object holding the version of the
  20402. * attributes. The keys are the attribute names
  20403. * and the values are the attribute versions.
  20404. *
  20405. * @type {?Object<string, number>}
  20406. * @default null
  20407. */
  20408. this.attributesId = null;
  20409. /**
  20410. * A reference to a render pipeline the render
  20411. * object is processed with.
  20412. *
  20413. * @type {RenderPipeline}
  20414. * @default null
  20415. */
  20416. this.pipeline = null;
  20417. /**
  20418. * Only relevant for objects using
  20419. * multiple materials. This represents a group entry
  20420. * from the respective `BufferGeometry`.
  20421. *
  20422. * @type {?{start: number, count: number}}
  20423. * @default null
  20424. */
  20425. this.group = null;
  20426. /**
  20427. * An array holding the vertex buffers which can
  20428. * be buffer attributes but also interleaved buffers.
  20429. *
  20430. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  20431. * @default null
  20432. */
  20433. this.vertexBuffers = null;
  20434. /**
  20435. * The parameters for the draw command.
  20436. *
  20437. * @type {?Object}
  20438. * @default null
  20439. */
  20440. this.drawParams = null;
  20441. /**
  20442. * If this render object is used inside a render bundle,
  20443. * this property points to the respective bundle group.
  20444. *
  20445. * @type {?BundleGroup}
  20446. * @default null
  20447. */
  20448. this.bundle = null;
  20449. /**
  20450. * The clipping context.
  20451. *
  20452. * @type {ClippingContext}
  20453. */
  20454. this.clippingContext = clippingContext;
  20455. /**
  20456. * The clipping context's cache key.
  20457. *
  20458. * @type {string}
  20459. */
  20460. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  20461. /**
  20462. * The initial node cache key.
  20463. *
  20464. * @type {number}
  20465. */
  20466. this.initialNodesCacheKey = this.getDynamicCacheKey();
  20467. /**
  20468. * The initial cache key.
  20469. *
  20470. * @type {number}
  20471. */
  20472. this.initialCacheKey = this.getCacheKey();
  20473. /**
  20474. * The node builder state.
  20475. *
  20476. * @type {?NodeBuilderState}
  20477. * @private
  20478. * @default null
  20479. */
  20480. this._nodeBuilderState = null;
  20481. /**
  20482. * An array of bindings.
  20483. *
  20484. * @type {?Array<BindGroup>}
  20485. * @private
  20486. * @default null
  20487. */
  20488. this._bindings = null;
  20489. /**
  20490. * Reference to the node material observer.
  20491. *
  20492. * @type {?NodeMaterialObserver}
  20493. * @private
  20494. * @default null
  20495. */
  20496. this._monitor = null;
  20497. /**
  20498. * An event listener which is defined by `RenderObjects`. It performs
  20499. * clean up tasks when `dispose()` on this render object.
  20500. *
  20501. * @method
  20502. */
  20503. this.onDispose = null;
  20504. /**
  20505. * This flag can be used for type testing.
  20506. *
  20507. * @type {boolean}
  20508. * @readonly
  20509. * @default true
  20510. */
  20511. this.isRenderObject = true;
  20512. /**
  20513. * An event listener which is executed when `dispose()` is called on
  20514. * the material of this render object.
  20515. *
  20516. * @method
  20517. */
  20518. this.onMaterialDispose = () => {
  20519. this.dispose();
  20520. };
  20521. /**
  20522. * An event listener which is executed when `dispose()` is called on
  20523. * the geometry of this render object.
  20524. *
  20525. * @method
  20526. */
  20527. this.onGeometryDispose = () => {
  20528. // clear geometry cache attributes
  20529. this.attributes = null;
  20530. this.attributesId = null;
  20531. };
  20532. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  20533. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  20534. }
  20535. /**
  20536. * Updates the clipping context.
  20537. *
  20538. * @param {ClippingContext} context - The clipping context to set.
  20539. */
  20540. updateClipping( context ) {
  20541. this.clippingContext = context;
  20542. }
  20543. /**
  20544. * Whether the clipping requires an update or not.
  20545. *
  20546. * @type {boolean}
  20547. * @readonly
  20548. */
  20549. get clippingNeedsUpdate() {
  20550. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  20551. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  20552. return true;
  20553. }
  20554. /**
  20555. * The number of clipping planes defined in context of hardware clipping.
  20556. *
  20557. * @type {number}
  20558. * @readonly
  20559. */
  20560. get hardwareClippingPlanes() {
  20561. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  20562. }
  20563. /**
  20564. * Returns the node builder state of this render object.
  20565. *
  20566. * @return {NodeBuilderState} The node builder state.
  20567. */
  20568. getNodeBuilderState() {
  20569. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  20570. }
  20571. /**
  20572. * Returns the node material observer of this render object.
  20573. *
  20574. * @return {NodeMaterialObserver} The node material observer.
  20575. */
  20576. getMonitor() {
  20577. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  20578. }
  20579. /**
  20580. * Returns an array of bind groups of this render object.
  20581. *
  20582. * @return {Array<BindGroup>} The bindings.
  20583. */
  20584. getBindings() {
  20585. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  20586. }
  20587. /**
  20588. * Returns a binding group by group name of this render object.
  20589. *
  20590. * @param {string} name - The name of the binding group.
  20591. * @return {?BindGroup} The bindings.
  20592. */
  20593. getBindingGroup( name ) {
  20594. for ( const bindingGroup of this.getBindings() ) {
  20595. if ( bindingGroup.name === name ) {
  20596. return bindingGroup;
  20597. }
  20598. }
  20599. }
  20600. /**
  20601. * Returns the index of the render object's geometry.
  20602. *
  20603. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20604. */
  20605. getIndex() {
  20606. return this._geometries.getIndex( this );
  20607. }
  20608. /**
  20609. * Returns the indirect buffer attribute.
  20610. *
  20611. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20612. */
  20613. getIndirect() {
  20614. return this._geometries.getIndirect( this );
  20615. }
  20616. /**
  20617. * Returns the byte offset into the indirect attribute buffer.
  20618. *
  20619. * @return {number|Array<number>} The byte offset into the indirect attribute buffer.
  20620. */
  20621. getIndirectOffset() {
  20622. return this._geometries.getIndirectOffset( this );
  20623. }
  20624. /**
  20625. * Returns an array that acts as a key for identifying the render object in a chain map.
  20626. *
  20627. * @return {Array<Object>} An array with object references.
  20628. */
  20629. getChainArray() {
  20630. return [ this.object, this.material, this.context, this.lightsNode ];
  20631. }
  20632. /**
  20633. * This method is used when the geometry of a 3D object has been exchanged and the
  20634. * respective render object now requires an update.
  20635. *
  20636. * @param {BufferGeometry} geometry - The geometry to set.
  20637. */
  20638. setGeometry( geometry ) {
  20639. this.geometry = geometry;
  20640. this.attributes = null;
  20641. this.attributesId = null;
  20642. }
  20643. /**
  20644. * Returns the buffer attributes of the render object. The returned array holds
  20645. * attribute definitions on geometry and node level.
  20646. *
  20647. * @return {Array<BufferAttribute>} An array with buffer attributes.
  20648. */
  20649. getAttributes() {
  20650. if ( this.attributes !== null ) return this.attributes;
  20651. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  20652. const geometry = this.geometry;
  20653. const attributes = [];
  20654. const vertexBuffers = new Set();
  20655. const attributesId = {};
  20656. for ( const nodeAttribute of nodeAttributes ) {
  20657. let attribute;
  20658. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  20659. // node attribute
  20660. attribute = nodeAttribute.node.attribute;
  20661. } else {
  20662. // geometry attribute
  20663. attribute = geometry.getAttribute( nodeAttribute.name );
  20664. attributesId[ nodeAttribute.name ] = attribute.id;
  20665. }
  20666. if ( attribute === undefined ) continue;
  20667. attributes.push( attribute );
  20668. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  20669. vertexBuffers.add( bufferAttribute );
  20670. }
  20671. this.attributes = attributes;
  20672. this.attributesId = attributesId;
  20673. this.vertexBuffers = Array.from( vertexBuffers.values() );
  20674. return attributes;
  20675. }
  20676. /**
  20677. * Returns the vertex buffers of the render object.
  20678. *
  20679. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  20680. */
  20681. getVertexBuffers() {
  20682. if ( this.vertexBuffers === null ) this.getAttributes();
  20683. return this.vertexBuffers;
  20684. }
  20685. /**
  20686. * Returns the draw parameters for the render object.
  20687. *
  20688. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  20689. */
  20690. getDrawParameters() {
  20691. const { object, material, geometry, group, drawRange } = this;
  20692. const drawParams = this.drawParams || ( this.drawParams = {
  20693. vertexCount: 0,
  20694. firstVertex: 0,
  20695. instanceCount: 0,
  20696. firstInstance: 0
  20697. } );
  20698. const index = this.getIndex();
  20699. const hasIndex = ( index !== null );
  20700. let instanceCount = 1;
  20701. if ( geometry.isInstancedBufferGeometry === true ) {
  20702. instanceCount = geometry.instanceCount;
  20703. } else if ( object.count !== undefined ) {
  20704. instanceCount = Math.max( 0, object.count );
  20705. }
  20706. if ( instanceCount === 0 ) return null;
  20707. drawParams.instanceCount = instanceCount;
  20708. if ( object.isBatchedMesh === true ) return drawParams;
  20709. let rangeFactor = 1;
  20710. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  20711. rangeFactor = 2;
  20712. }
  20713. let firstVertex = drawRange.start * rangeFactor;
  20714. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  20715. if ( group !== null ) {
  20716. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  20717. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  20718. }
  20719. const position = geometry.attributes.position;
  20720. let itemCount = Infinity;
  20721. if ( hasIndex ) {
  20722. itemCount = index.count;
  20723. } else if ( position !== undefined && position !== null ) {
  20724. itemCount = position.count;
  20725. }
  20726. firstVertex = Math.max( firstVertex, 0 );
  20727. lastVertex = Math.min( lastVertex, itemCount );
  20728. const count = lastVertex - firstVertex;
  20729. if ( count < 0 || count === Infinity ) return null;
  20730. drawParams.vertexCount = count;
  20731. drawParams.firstVertex = firstVertex;
  20732. return drawParams;
  20733. }
  20734. /**
  20735. * Returns the render object's geometry cache key.
  20736. *
  20737. * The geometry cache key is part of the material cache key.
  20738. *
  20739. * @return {string} The geometry cache key.
  20740. */
  20741. getGeometryCacheKey() {
  20742. const { geometry } = this;
  20743. let cacheKey = '';
  20744. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  20745. const attribute = geometry.attributes[ name ];
  20746. cacheKey += name + ',';
  20747. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20748. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20749. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20750. if ( attribute.normalized ) cacheKey += 'n,';
  20751. }
  20752. // structural equality isn't sufficient for morph targets since the
  20753. // data are maintained in textures. only if the targets are all equal
  20754. // the texture and thus the instance of `MorphNode` can be shared.
  20755. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20756. const targets = geometry.morphAttributes[ name ];
  20757. cacheKey += 'morph-' + name + ',';
  20758. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20759. const attribute = targets[ i ];
  20760. cacheKey += attribute.id + ',';
  20761. }
  20762. }
  20763. if ( geometry.index ) {
  20764. cacheKey += 'index,';
  20765. }
  20766. return cacheKey;
  20767. }
  20768. /**
  20769. * Returns the render object's material cache key.
  20770. *
  20771. * The material cache key is part of the render object cache key.
  20772. *
  20773. * @return {number} The material cache key.
  20774. */
  20775. getMaterialCacheKey() {
  20776. const { object, material, renderer } = this;
  20777. let cacheKey = material.customProgramCacheKey();
  20778. for ( const property of getKeys( material ) ) {
  20779. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20780. const value = material[ property ];
  20781. let valueKey;
  20782. if ( value !== null ) {
  20783. // some material values require a formatting
  20784. const type = typeof value;
  20785. if ( type === 'number' ) {
  20786. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20787. } else if ( type === 'object' ) {
  20788. valueKey = '{';
  20789. if ( value.isTexture ) {
  20790. valueKey += value.mapping;
  20791. // WebGPU must honor the sampler data because they are part of the bindings
  20792. if ( renderer.backend.isWebGPUBackend === true ) {
  20793. valueKey += value.magFilter;
  20794. valueKey += value.minFilter;
  20795. valueKey += value.wrapS;
  20796. valueKey += value.wrapT;
  20797. valueKey += value.wrapR;
  20798. }
  20799. }
  20800. valueKey += '}';
  20801. } else {
  20802. valueKey = String( value );
  20803. }
  20804. } else {
  20805. valueKey = String( value );
  20806. }
  20807. cacheKey += /*property + ':' +*/ valueKey + ',';
  20808. }
  20809. cacheKey += this.clippingContextCacheKey + ',';
  20810. if ( object.geometry ) {
  20811. cacheKey += this.getGeometryCacheKey();
  20812. }
  20813. if ( object.skeleton ) {
  20814. cacheKey += object.skeleton.bones.length + ',';
  20815. }
  20816. if ( object.isBatchedMesh ) {
  20817. cacheKey += object._matricesTexture.uuid + ',';
  20818. if ( object._colorsTexture !== null ) {
  20819. cacheKey += object._colorsTexture.uuid + ',';
  20820. }
  20821. }
  20822. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20823. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20824. cacheKey += object.uuid + ',';
  20825. }
  20826. cacheKey += this.context.id + ',';
  20827. cacheKey += object.receiveShadow + ',';
  20828. return hashString( cacheKey );
  20829. }
  20830. /**
  20831. * Whether the geometry requires an update or not.
  20832. *
  20833. * @type {boolean}
  20834. * @readonly
  20835. */
  20836. get needsGeometryUpdate() {
  20837. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20838. if ( this.attributes !== null ) {
  20839. const attributesId = this.attributesId;
  20840. for ( const name in attributesId ) {
  20841. const attribute = this.geometry.getAttribute( name );
  20842. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20843. return true;
  20844. }
  20845. }
  20846. }
  20847. return false;
  20848. }
  20849. /**
  20850. * Whether the render object requires an update or not.
  20851. *
  20852. * Note: There are two distinct places where render objects are checked for an update.
  20853. *
  20854. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20855. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20856. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20857. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20858. * a need for a refresh due to material, geometry or object related value changes.
  20859. *
  20860. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20861. * that performs the 'needsUpdate' check.
  20862. *
  20863. * @type {boolean}
  20864. * @readonly
  20865. */
  20866. get needsUpdate() {
  20867. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20868. }
  20869. /**
  20870. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20871. *
  20872. * @return {number} The cache key.
  20873. */
  20874. getDynamicCacheKey() {
  20875. let cacheKey = 0;
  20876. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20877. // the renderer is inside a shadow pass.
  20878. if ( this.material.isShadowPassMaterial !== true ) {
  20879. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20880. }
  20881. if ( this.camera.isArrayCamera ) {
  20882. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20883. }
  20884. if ( this.object.receiveShadow ) {
  20885. cacheKey = hash$1( cacheKey, 1 );
  20886. }
  20887. cacheKey = hash$1( cacheKey, this.renderer.contextNode.id, this.renderer.contextNode.version );
  20888. return cacheKey;
  20889. }
  20890. /**
  20891. * Returns the render object's cache key.
  20892. *
  20893. * @return {number} The cache key.
  20894. */
  20895. getCacheKey() {
  20896. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20897. }
  20898. /**
  20899. * Frees internal resources.
  20900. */
  20901. dispose() {
  20902. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20903. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20904. this.onDispose();
  20905. }
  20906. }
  20907. const _chainKeys$3 = [];
  20908. /**
  20909. * This module manages the render objects of the renderer.
  20910. *
  20911. * @private
  20912. */
  20913. class RenderObjects {
  20914. /**
  20915. * Constructs a new render object management component.
  20916. *
  20917. * @param {Renderer} renderer - The renderer.
  20918. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20919. * @param {Geometries} geometries - Renderer component for managing geometries.
  20920. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20921. * @param {Bindings} bindings - Renderer component for managing bindings.
  20922. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20923. */
  20924. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20925. /**
  20926. * The renderer.
  20927. *
  20928. * @type {Renderer}
  20929. */
  20930. this.renderer = renderer;
  20931. /**
  20932. * Renderer component for managing nodes related logic.
  20933. *
  20934. * @type {Nodes}
  20935. */
  20936. this.nodes = nodes;
  20937. /**
  20938. * Renderer component for managing geometries.
  20939. *
  20940. * @type {Geometries}
  20941. */
  20942. this.geometries = geometries;
  20943. /**
  20944. * Renderer component for managing pipelines.
  20945. *
  20946. * @type {Pipelines}
  20947. */
  20948. this.pipelines = pipelines;
  20949. /**
  20950. * Renderer component for managing bindings.
  20951. *
  20952. * @type {Bindings}
  20953. */
  20954. this.bindings = bindings;
  20955. /**
  20956. * Renderer component for managing metrics and monitoring data.
  20957. *
  20958. * @type {Info}
  20959. */
  20960. this.info = info;
  20961. /**
  20962. * A dictionary that manages render contexts in chain maps
  20963. * for each pass ID.
  20964. *
  20965. * @type {Object<string,ChainMap>}
  20966. */
  20967. this.chainMaps = {};
  20968. }
  20969. /**
  20970. * Returns a render object for the given object and state data.
  20971. *
  20972. * @param {Object3D} object - The 3D object.
  20973. * @param {Material} material - The 3D object's material.
  20974. * @param {Scene} scene - The scene the 3D object belongs to.
  20975. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20976. * @param {LightsNode} lightsNode - The lights node.
  20977. * @param {RenderContext} renderContext - The render context.
  20978. * @param {ClippingContext} clippingContext - The clipping context.
  20979. * @param {string} [passId] - An optional ID for identifying the pass.
  20980. * @return {RenderObject} The render object.
  20981. */
  20982. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20983. const chainMap = this.getChainMap( passId );
  20984. // set chain keys
  20985. _chainKeys$3[ 0 ] = object;
  20986. _chainKeys$3[ 1 ] = material;
  20987. _chainKeys$3[ 2 ] = renderContext;
  20988. _chainKeys$3[ 3 ] = lightsNode;
  20989. //
  20990. let renderObject = chainMap.get( _chainKeys$3 );
  20991. if ( renderObject === undefined ) {
  20992. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20993. chainMap.set( _chainKeys$3, renderObject );
  20994. } else {
  20995. // update references
  20996. renderObject.camera = camera;
  20997. //
  20998. renderObject.updateClipping( clippingContext );
  20999. if ( renderObject.needsGeometryUpdate ) {
  21000. renderObject.setGeometry( object.geometry );
  21001. }
  21002. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21003. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21004. renderObject.dispose();
  21005. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  21006. } else {
  21007. renderObject.version = material.version;
  21008. }
  21009. }
  21010. }
  21011. // reset chain array
  21012. _chainKeys$3[ 0 ] = null;
  21013. _chainKeys$3[ 1 ] = null;
  21014. _chainKeys$3[ 2 ] = null;
  21015. _chainKeys$3[ 3 ] = null;
  21016. //
  21017. return renderObject;
  21018. }
  21019. /**
  21020. * Returns a chain map for the given pass ID.
  21021. *
  21022. * @param {string} [passId='default'] - The pass ID.
  21023. * @return {ChainMap} The chain map.
  21024. */
  21025. getChainMap( passId = 'default' ) {
  21026. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21027. }
  21028. /**
  21029. * Frees internal resources.
  21030. */
  21031. dispose() {
  21032. this.chainMaps = {};
  21033. }
  21034. /**
  21035. * Factory method for creating render objects with the given list of parameters.
  21036. *
  21037. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21038. * @param {Geometries} geometries - Renderer component for managing geometries.
  21039. * @param {Renderer} renderer - The renderer.
  21040. * @param {Object3D} object - The 3D object.
  21041. * @param {Material} material - The object's material.
  21042. * @param {Scene} scene - The scene the 3D object belongs to.
  21043. * @param {Camera} camera - The camera the object should be rendered with.
  21044. * @param {LightsNode} lightsNode - The lights node.
  21045. * @param {RenderContext} renderContext - The render context.
  21046. * @param {ClippingContext} clippingContext - The clipping context.
  21047. * @param {string} [passId] - An optional ID for identifying the pass.
  21048. * @return {RenderObject} The render object.
  21049. */
  21050. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  21051. const chainMap = this.getChainMap( passId );
  21052. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  21053. renderObject.onDispose = () => {
  21054. this.pipelines.delete( renderObject );
  21055. this.bindings.deleteForRender( renderObject );
  21056. this.nodes.delete( renderObject );
  21057. chainMap.delete( renderObject.getChainArray() );
  21058. };
  21059. return renderObject;
  21060. }
  21061. }
  21062. /**
  21063. * Data structure for the renderer. It is intended to manage
  21064. * data of objects in dictionaries.
  21065. *
  21066. * @private
  21067. */
  21068. class DataMap {
  21069. /**
  21070. * Constructs a new data map.
  21071. */
  21072. constructor() {
  21073. /**
  21074. * `DataMap` internally uses a weak map
  21075. * to manage its data.
  21076. *
  21077. * @type {WeakMap<Object, Object>}
  21078. */
  21079. this.data = new WeakMap();
  21080. }
  21081. /**
  21082. * Returns the dictionary for the given object.
  21083. *
  21084. * @param {Object} object - The object.
  21085. * @return {Object} The dictionary.
  21086. */
  21087. get( object ) {
  21088. let map = this.data.get( object );
  21089. if ( map === undefined ) {
  21090. map = {};
  21091. this.data.set( object, map );
  21092. }
  21093. return map;
  21094. }
  21095. /**
  21096. * Deletes the dictionary for the given object.
  21097. *
  21098. * @param {Object} object - The object.
  21099. * @return {?Object} The deleted dictionary.
  21100. */
  21101. delete( object ) {
  21102. let map = null;
  21103. if ( this.data.has( object ) ) {
  21104. map = this.data.get( object );
  21105. this.data.delete( object );
  21106. }
  21107. return map;
  21108. }
  21109. /**
  21110. * Returns `true` if the given object has a dictionary defined.
  21111. *
  21112. * @param {Object} object - The object to test.
  21113. * @return {boolean} Whether a dictionary is defined or not.
  21114. */
  21115. has( object ) {
  21116. return this.data.has( object );
  21117. }
  21118. /**
  21119. * Frees internal resources.
  21120. */
  21121. dispose() {
  21122. this.data = new WeakMap();
  21123. }
  21124. }
  21125. const AttributeType = {
  21126. VERTEX: 1,
  21127. INDEX: 2,
  21128. STORAGE: 3,
  21129. INDIRECT: 4
  21130. };
  21131. // size of a chunk in bytes (STD140 layout)
  21132. const GPU_CHUNK_BYTES = 16;
  21133. // @TODO: Move to src/constants.js
  21134. const BlendColorFactor = 211;
  21135. const OneMinusBlendColorFactor = 212;
  21136. /**
  21137. * This renderer module manages geometry attributes.
  21138. *
  21139. * @private
  21140. * @augments DataMap
  21141. */
  21142. class Attributes extends DataMap {
  21143. /**
  21144. * Constructs a new attribute management component.
  21145. *
  21146. * @param {Backend} backend - The renderer's backend.
  21147. */
  21148. constructor( backend ) {
  21149. super();
  21150. /**
  21151. * The renderer's backend.
  21152. *
  21153. * @type {Backend}
  21154. */
  21155. this.backend = backend;
  21156. }
  21157. /**
  21158. * Deletes the data for the given attribute.
  21159. *
  21160. * @param {BufferAttribute} attribute - The attribute.
  21161. * @return {?Object} The deleted attribute data.
  21162. */
  21163. delete( attribute ) {
  21164. const attributeData = super.delete( attribute );
  21165. if ( attributeData !== null ) {
  21166. this.backend.destroyAttribute( attribute );
  21167. }
  21168. return attributeData;
  21169. }
  21170. /**
  21171. * Updates the given attribute. This method creates attribute buffers
  21172. * for new attributes and updates data for existing ones.
  21173. *
  21174. * @param {BufferAttribute} attribute - The attribute to update.
  21175. * @param {number} type - The attribute type.
  21176. */
  21177. update( attribute, type ) {
  21178. const data = this.get( attribute );
  21179. if ( data.version === undefined ) {
  21180. if ( type === AttributeType.VERTEX ) {
  21181. this.backend.createAttribute( attribute );
  21182. } else if ( type === AttributeType.INDEX ) {
  21183. this.backend.createIndexAttribute( attribute );
  21184. } else if ( type === AttributeType.STORAGE ) {
  21185. this.backend.createStorageAttribute( attribute );
  21186. } else if ( type === AttributeType.INDIRECT ) {
  21187. this.backend.createIndirectStorageAttribute( attribute );
  21188. }
  21189. data.version = this._getBufferAttribute( attribute ).version;
  21190. } else {
  21191. const bufferAttribute = this._getBufferAttribute( attribute );
  21192. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21193. this.backend.updateAttribute( attribute );
  21194. data.version = bufferAttribute.version;
  21195. }
  21196. }
  21197. }
  21198. /**
  21199. * Utility method for handling interleaved buffer attributes correctly.
  21200. * To process them, their `InterleavedBuffer` is returned.
  21201. *
  21202. * @param {BufferAttribute} attribute - The attribute.
  21203. * @return {BufferAttribute|InterleavedBuffer}
  21204. */
  21205. _getBufferAttribute( attribute ) {
  21206. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21207. return attribute;
  21208. }
  21209. }
  21210. /**
  21211. * Returns the wireframe version for the given geometry.
  21212. *
  21213. * @private
  21214. * @function
  21215. * @param {BufferGeometry} geometry - The geometry.
  21216. * @return {number} The version.
  21217. */
  21218. function getWireframeVersion( geometry ) {
  21219. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21220. }
  21221. /**
  21222. * Returns a wireframe index attribute for the given geometry.
  21223. *
  21224. * @private
  21225. * @function
  21226. * @param {BufferGeometry} geometry - The geometry.
  21227. * @return {BufferAttribute} The wireframe index attribute.
  21228. */
  21229. function getWireframeIndex( geometry ) {
  21230. const indices = [];
  21231. const geometryIndex = geometry.index;
  21232. const geometryPosition = geometry.attributes.position;
  21233. if ( geometryIndex !== null ) {
  21234. const array = geometryIndex.array;
  21235. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21236. const a = array[ i + 0 ];
  21237. const b = array[ i + 1 ];
  21238. const c = array[ i + 2 ];
  21239. indices.push( a, b, b, c, c, a );
  21240. }
  21241. } else {
  21242. const array = geometryPosition.array;
  21243. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21244. const a = i + 0;
  21245. const b = i + 1;
  21246. const c = i + 2;
  21247. indices.push( a, b, b, c, c, a );
  21248. }
  21249. }
  21250. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21251. attribute.version = getWireframeVersion( geometry );
  21252. return attribute;
  21253. }
  21254. /**
  21255. * This renderer module manages geometries.
  21256. *
  21257. * @private
  21258. * @augments DataMap
  21259. */
  21260. class Geometries extends DataMap {
  21261. /**
  21262. * Constructs a new geometry management component.
  21263. *
  21264. * @param {Attributes} attributes - Renderer component for managing attributes.
  21265. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21266. */
  21267. constructor( attributes, info ) {
  21268. super();
  21269. /**
  21270. * Renderer component for managing attributes.
  21271. *
  21272. * @type {Attributes}
  21273. */
  21274. this.attributes = attributes;
  21275. /**
  21276. * Renderer component for managing metrics and monitoring data.
  21277. *
  21278. * @type {Info}
  21279. */
  21280. this.info = info;
  21281. /**
  21282. * Weak Map for managing attributes for wireframe rendering.
  21283. *
  21284. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  21285. */
  21286. this.wireframes = new WeakMap();
  21287. /**
  21288. * This Weak Map is used to make sure buffer attributes are
  21289. * updated only once per render call.
  21290. *
  21291. * @type {WeakMap<BufferAttribute,number>}
  21292. */
  21293. this.attributeCall = new WeakMap();
  21294. /**
  21295. * Stores the event listeners attached to geometries.
  21296. *
  21297. * @private
  21298. * @type {Map<BufferGeometry,Function>}
  21299. */
  21300. this._geometryDisposeListeners = new Map();
  21301. }
  21302. /**
  21303. * Returns `true` if the given render object has an initialized geometry.
  21304. *
  21305. * @param {RenderObject} renderObject - The render object.
  21306. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  21307. */
  21308. has( renderObject ) {
  21309. const geometry = renderObject.geometry;
  21310. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21311. }
  21312. /**
  21313. * Prepares the geometry of the given render object for rendering.
  21314. *
  21315. * @param {RenderObject} renderObject - The render object.
  21316. */
  21317. updateForRender( renderObject ) {
  21318. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21319. this.updateAttributes( renderObject );
  21320. }
  21321. /**
  21322. * Initializes the geometry of the given render object.
  21323. *
  21324. * @param {RenderObject} renderObject - The render object.
  21325. */
  21326. initGeometry( renderObject ) {
  21327. const geometry = renderObject.geometry;
  21328. const geometryData = this.get( geometry );
  21329. geometryData.initialized = true;
  21330. this.info.memory.geometries ++;
  21331. const onDispose = () => {
  21332. this.info.memory.geometries --;
  21333. const index = geometry.index;
  21334. const geometryAttributes = renderObject.getAttributes();
  21335. if ( index !== null ) {
  21336. this.attributes.delete( index );
  21337. }
  21338. for ( const geometryAttribute of geometryAttributes ) {
  21339. this.attributes.delete( geometryAttribute );
  21340. }
  21341. const wireframeAttribute = this.wireframes.get( geometry );
  21342. if ( wireframeAttribute !== undefined ) {
  21343. this.attributes.delete( wireframeAttribute );
  21344. }
  21345. geometry.removeEventListener( 'dispose', onDispose );
  21346. this._geometryDisposeListeners.delete( geometry );
  21347. };
  21348. geometry.addEventListener( 'dispose', onDispose );
  21349. // see #31798 why tracking separate remove listeners is required right now
  21350. // TODO: Re-evaluate how onDispose() is managed in this component
  21351. this._geometryDisposeListeners.set( geometry, onDispose );
  21352. }
  21353. /**
  21354. * Updates the geometry attributes of the given render object.
  21355. *
  21356. * @param {RenderObject} renderObject - The render object.
  21357. */
  21358. updateAttributes( renderObject ) {
  21359. // attributes
  21360. const attributes = renderObject.getAttributes();
  21361. for ( const attribute of attributes ) {
  21362. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21363. this.updateAttribute( attribute, AttributeType.STORAGE );
  21364. } else {
  21365. this.updateAttribute( attribute, AttributeType.VERTEX );
  21366. }
  21367. }
  21368. // indexes
  21369. const index = this.getIndex( renderObject );
  21370. if ( index !== null ) {
  21371. this.updateAttribute( index, AttributeType.INDEX );
  21372. }
  21373. // indirect
  21374. const indirect = renderObject.geometry.indirect;
  21375. if ( indirect !== null ) {
  21376. this.updateAttribute( indirect, AttributeType.INDIRECT );
  21377. }
  21378. }
  21379. /**
  21380. * Updates the given attribute.
  21381. *
  21382. * @param {BufferAttribute} attribute - The attribute to update.
  21383. * @param {number} type - The attribute type.
  21384. */
  21385. updateAttribute( attribute, type ) {
  21386. const callId = this.info.render.calls;
  21387. if ( ! attribute.isInterleavedBufferAttribute ) {
  21388. if ( this.attributeCall.get( attribute ) !== callId ) {
  21389. this.attributes.update( attribute, type );
  21390. this.attributeCall.set( attribute, callId );
  21391. }
  21392. } else {
  21393. if ( this.attributeCall.get( attribute ) === undefined ) {
  21394. this.attributes.update( attribute, type );
  21395. this.attributeCall.set( attribute, callId );
  21396. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21397. this.attributes.update( attribute, type );
  21398. this.attributeCall.set( attribute.data, callId );
  21399. this.attributeCall.set( attribute, callId );
  21400. }
  21401. }
  21402. }
  21403. /**
  21404. * Returns the indirect buffer attribute of the given render object.
  21405. *
  21406. * @param {RenderObject} renderObject - The render object.
  21407. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  21408. */
  21409. getIndirect( renderObject ) {
  21410. return renderObject.geometry.indirect;
  21411. }
  21412. /**
  21413. * Returns the byte offset into the indirect attribute buffer of the given render object.
  21414. *
  21415. * @param {RenderObject} renderObject - The render object.
  21416. * @return {number} The byte offset into the indirect attribute buffer.
  21417. */
  21418. getIndirectOffset( renderObject ) {
  21419. return renderObject.geometry.indirectOffset;
  21420. }
  21421. /**
  21422. * Returns the index of the given render object's geometry. This is implemented
  21423. * in a method to return a wireframe index if necessary.
  21424. *
  21425. * @param {RenderObject} renderObject - The render object.
  21426. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  21427. */
  21428. getIndex( renderObject ) {
  21429. const { geometry, material } = renderObject;
  21430. let index = geometry.index;
  21431. if ( material.wireframe === true ) {
  21432. const wireframes = this.wireframes;
  21433. let wireframeAttribute = wireframes.get( geometry );
  21434. if ( wireframeAttribute === undefined ) {
  21435. wireframeAttribute = getWireframeIndex( geometry );
  21436. wireframes.set( geometry, wireframeAttribute );
  21437. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21438. this.attributes.delete( wireframeAttribute );
  21439. wireframeAttribute = getWireframeIndex( geometry );
  21440. wireframes.set( geometry, wireframeAttribute );
  21441. }
  21442. index = wireframeAttribute;
  21443. }
  21444. return index;
  21445. }
  21446. dispose() {
  21447. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  21448. geometry.removeEventListener( 'dispose', onDispose );
  21449. }
  21450. this._geometryDisposeListeners.clear();
  21451. }
  21452. }
  21453. /**
  21454. * This renderer module provides a series of statistical information
  21455. * about the GPU memory and the rendering process. Useful for debugging
  21456. * and monitoring.
  21457. */
  21458. class Info {
  21459. /**
  21460. * Constructs a new info component.
  21461. */
  21462. constructor() {
  21463. /**
  21464. * Whether frame related metrics should automatically
  21465. * be resetted or not. This property should be set to `false`
  21466. * by apps which manage their own animation loop. They must
  21467. * then call `renderer.info.reset()` once per frame manually.
  21468. *
  21469. * @type {boolean}
  21470. * @default true
  21471. */
  21472. this.autoReset = true;
  21473. /**
  21474. * The current frame ID. This ID is managed
  21475. * by `NodeFrame`.
  21476. *
  21477. * @type {number}
  21478. * @readonly
  21479. * @default 0
  21480. */
  21481. this.frame = 0;
  21482. /**
  21483. * The number of render calls since the
  21484. * app has been started.
  21485. *
  21486. * @type {number}
  21487. * @readonly
  21488. * @default 0
  21489. */
  21490. this.calls = 0;
  21491. /**
  21492. * Render related metrics.
  21493. *
  21494. * @type {Object}
  21495. * @readonly
  21496. * @property {number} calls - The number of render calls since the app has been started.
  21497. * @property {number} frameCalls - The number of render calls of the current frame.
  21498. * @property {number} drawCalls - The number of draw calls of the current frame.
  21499. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  21500. * @property {number} points - The number of rendered point primitives of the current frame.
  21501. * @property {number} lines - The number of rendered line primitives of the current frame.
  21502. * @property {number} timestamp - The timestamp of the frame.
  21503. */
  21504. this.render = {
  21505. calls: 0,
  21506. frameCalls: 0,
  21507. drawCalls: 0,
  21508. triangles: 0,
  21509. points: 0,
  21510. lines: 0,
  21511. timestamp: 0,
  21512. };
  21513. /**
  21514. * Compute related metrics.
  21515. *
  21516. * @type {Object}
  21517. * @readonly
  21518. * @property {number} calls - The number of compute calls since the app has been started.
  21519. * @property {number} frameCalls - The number of compute calls of the current frame.
  21520. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  21521. */
  21522. this.compute = {
  21523. calls: 0,
  21524. frameCalls: 0,
  21525. timestamp: 0
  21526. };
  21527. /**
  21528. * Memory related metrics.
  21529. *
  21530. * @type {Object}
  21531. * @readonly
  21532. * @property {number} geometries - The number of active geometries.
  21533. * @property {number} frameCalls - The number of active textures.
  21534. */
  21535. this.memory = {
  21536. geometries: 0,
  21537. textures: 0
  21538. };
  21539. }
  21540. /**
  21541. * This method should be executed per draw call and updates the corresponding metrics.
  21542. *
  21543. * @param {Object3D} object - The 3D object that is going to be rendered.
  21544. * @param {number} count - The vertex or index count.
  21545. * @param {number} instanceCount - The instance count.
  21546. */
  21547. update( object, count, instanceCount ) {
  21548. this.render.drawCalls ++;
  21549. if ( object.isMesh || object.isSprite ) {
  21550. this.render.triangles += instanceCount * ( count / 3 );
  21551. } else if ( object.isPoints ) {
  21552. this.render.points += instanceCount * count;
  21553. } else if ( object.isLineSegments ) {
  21554. this.render.lines += instanceCount * ( count / 2 );
  21555. } else if ( object.isLine ) {
  21556. this.render.lines += instanceCount * ( count - 1 );
  21557. } else {
  21558. error( 'WebGPUInfo: Unknown object type.' );
  21559. }
  21560. }
  21561. /**
  21562. * Resets frame related metrics.
  21563. */
  21564. reset() {
  21565. this.render.drawCalls = 0;
  21566. this.render.frameCalls = 0;
  21567. this.compute.frameCalls = 0;
  21568. this.render.triangles = 0;
  21569. this.render.points = 0;
  21570. this.render.lines = 0;
  21571. }
  21572. /**
  21573. * Performs a complete reset of the object.
  21574. */
  21575. dispose() {
  21576. this.reset();
  21577. this.calls = 0;
  21578. this.render.calls = 0;
  21579. this.compute.calls = 0;
  21580. this.render.timestamp = 0;
  21581. this.compute.timestamp = 0;
  21582. this.memory.geometries = 0;
  21583. this.memory.textures = 0;
  21584. }
  21585. }
  21586. /**
  21587. * Abstract class for representing pipelines.
  21588. *
  21589. * @private
  21590. * @abstract
  21591. */
  21592. class Pipeline {
  21593. /**
  21594. * Constructs a new pipeline.
  21595. *
  21596. * @param {string} cacheKey - The pipeline's cache key.
  21597. */
  21598. constructor( cacheKey ) {
  21599. /**
  21600. * The pipeline's cache key.
  21601. *
  21602. * @type {string}
  21603. */
  21604. this.cacheKey = cacheKey;
  21605. /**
  21606. * How often the pipeline is currently in use.
  21607. *
  21608. * @type {number}
  21609. * @default 0
  21610. */
  21611. this.usedTimes = 0;
  21612. }
  21613. }
  21614. /**
  21615. * Class for representing render pipelines.
  21616. *
  21617. * @private
  21618. * @augments Pipeline
  21619. */
  21620. class RenderObjectPipeline extends Pipeline {
  21621. /**
  21622. * Constructs a new render object pipeline.
  21623. *
  21624. * @param {string} cacheKey - The pipeline's cache key.
  21625. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  21626. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  21627. */
  21628. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21629. super( cacheKey );
  21630. /**
  21631. * The pipeline's vertex shader.
  21632. *
  21633. * @type {ProgrammableStage}
  21634. */
  21635. this.vertexProgram = vertexProgram;
  21636. /**
  21637. * The pipeline's fragment shader.
  21638. *
  21639. * @type {ProgrammableStage}
  21640. */
  21641. this.fragmentProgram = fragmentProgram;
  21642. }
  21643. }
  21644. /**
  21645. * Class for representing compute pipelines.
  21646. *
  21647. * @private
  21648. * @augments Pipeline
  21649. */
  21650. class ComputePipeline extends Pipeline {
  21651. /**
  21652. * Constructs a new render pipeline.
  21653. *
  21654. * @param {string} cacheKey - The pipeline's cache key.
  21655. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  21656. */
  21657. constructor( cacheKey, computeProgram ) {
  21658. super( cacheKey );
  21659. /**
  21660. * The pipeline's compute shader.
  21661. *
  21662. * @type {ProgrammableStage}
  21663. */
  21664. this.computeProgram = computeProgram;
  21665. /**
  21666. * This flag can be used for type testing.
  21667. *
  21668. * @type {boolean}
  21669. * @readonly
  21670. * @default true
  21671. */
  21672. this.isComputePipeline = true;
  21673. }
  21674. }
  21675. let _id$9 = 0;
  21676. /**
  21677. * Class for representing programmable stages which are vertex,
  21678. * fragment or compute shaders. Unlike fixed-function states (like blending),
  21679. * they represent the programmable part of a pipeline.
  21680. *
  21681. * @private
  21682. */
  21683. class ProgrammableStage {
  21684. /**
  21685. * Constructs a new programmable stage.
  21686. *
  21687. * @param {string} code - The shader code.
  21688. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  21689. * @param {string} name - The name of the shader.
  21690. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21691. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21692. */
  21693. constructor( code, stage, name, transforms = null, attributes = null ) {
  21694. /**
  21695. * The id of the programmable stage.
  21696. *
  21697. * @type {number}
  21698. */
  21699. this.id = _id$9 ++;
  21700. /**
  21701. * The shader code.
  21702. *
  21703. * @type {string}
  21704. */
  21705. this.code = code;
  21706. /**
  21707. * The type of stage.
  21708. *
  21709. * @type {string}
  21710. */
  21711. this.stage = stage;
  21712. /**
  21713. * The name of the stage.
  21714. * This is used for debugging purposes.
  21715. *
  21716. * @type {string}
  21717. */
  21718. this.name = name;
  21719. /**
  21720. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21721. *
  21722. * @type {?Array<Object>}
  21723. */
  21724. this.transforms = transforms;
  21725. /**
  21726. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  21727. *
  21728. * @type {?Array<Object>}
  21729. */
  21730. this.attributes = attributes;
  21731. /**
  21732. * How often the programmable stage is currently in use.
  21733. *
  21734. * @type {number}
  21735. * @default 0
  21736. */
  21737. this.usedTimes = 0;
  21738. }
  21739. }
  21740. /**
  21741. * This renderer module manages the pipelines of the renderer.
  21742. *
  21743. * @private
  21744. * @augments DataMap
  21745. */
  21746. class Pipelines extends DataMap {
  21747. /**
  21748. * Constructs a new pipeline management component.
  21749. *
  21750. * @param {Backend} backend - The renderer's backend.
  21751. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21752. */
  21753. constructor( backend, nodes ) {
  21754. super();
  21755. /**
  21756. * The renderer's backend.
  21757. *
  21758. * @type {Backend}
  21759. */
  21760. this.backend = backend;
  21761. /**
  21762. * Renderer component for managing nodes related logic.
  21763. *
  21764. * @type {Nodes}
  21765. */
  21766. this.nodes = nodes;
  21767. /**
  21768. * A references to the bindings management component.
  21769. * This reference will be set inside the `Bindings`
  21770. * constructor.
  21771. *
  21772. * @type {?Bindings}
  21773. * @default null
  21774. */
  21775. this.bindings = null;
  21776. /**
  21777. * Internal cache for maintaining pipelines.
  21778. * The key of the map is a cache key, the value the pipeline.
  21779. *
  21780. * @type {Map<string,Pipeline>}
  21781. */
  21782. this.caches = new Map();
  21783. /**
  21784. * This dictionary maintains for each shader stage type (vertex,
  21785. * fragment and compute) the programmable stage objects which
  21786. * represent the actual shader code.
  21787. *
  21788. * @type {Object<string,Map<string, ProgrammableStage>>}
  21789. */
  21790. this.programs = {
  21791. vertex: new Map(),
  21792. fragment: new Map(),
  21793. compute: new Map()
  21794. };
  21795. }
  21796. /**
  21797. * Returns a compute pipeline for the given compute node.
  21798. *
  21799. * @param {Node} computeNode - The compute node.
  21800. * @param {Array<BindGroup>} bindings - The bindings.
  21801. * @return {ComputePipeline} The compute pipeline.
  21802. */
  21803. getForCompute( computeNode, bindings ) {
  21804. const { backend } = this;
  21805. const data = this.get( computeNode );
  21806. if ( this._needsComputeUpdate( computeNode ) ) {
  21807. const previousPipeline = data.pipeline;
  21808. if ( previousPipeline ) {
  21809. previousPipeline.usedTimes --;
  21810. previousPipeline.computeProgram.usedTimes --;
  21811. }
  21812. // get shader
  21813. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21814. // programmable stage
  21815. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21816. if ( stageCompute === undefined ) {
  21817. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21818. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21819. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21820. backend.createProgram( stageCompute );
  21821. }
  21822. // determine compute pipeline
  21823. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21824. let pipeline = this.caches.get( cacheKey );
  21825. if ( pipeline === undefined ) {
  21826. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21827. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21828. }
  21829. // keep track of all used times
  21830. pipeline.usedTimes ++;
  21831. stageCompute.usedTimes ++;
  21832. //
  21833. data.version = computeNode.version;
  21834. data.pipeline = pipeline;
  21835. }
  21836. return data.pipeline;
  21837. }
  21838. /**
  21839. * Returns a render pipeline for the given render object.
  21840. *
  21841. * @param {RenderObject} renderObject - The render object.
  21842. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21843. * @return {RenderObjectPipeline} The render pipeline.
  21844. */
  21845. getForRender( renderObject, promises = null ) {
  21846. const { backend } = this;
  21847. const data = this.get( renderObject );
  21848. if ( this._needsRenderUpdate( renderObject ) ) {
  21849. const previousPipeline = data.pipeline;
  21850. if ( previousPipeline ) {
  21851. previousPipeline.usedTimes --;
  21852. previousPipeline.vertexProgram.usedTimes --;
  21853. previousPipeline.fragmentProgram.usedTimes --;
  21854. }
  21855. // get shader
  21856. const nodeBuilderState = renderObject.getNodeBuilderState();
  21857. const name = renderObject.material ? renderObject.material.name : '';
  21858. // programmable stages
  21859. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21860. if ( stageVertex === undefined ) {
  21861. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21862. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21863. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21864. backend.createProgram( stageVertex );
  21865. }
  21866. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21867. if ( stageFragment === undefined ) {
  21868. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21869. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21870. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21871. backend.createProgram( stageFragment );
  21872. }
  21873. // determine render pipeline
  21874. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21875. let pipeline = this.caches.get( cacheKey );
  21876. if ( pipeline === undefined ) {
  21877. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21878. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21879. } else {
  21880. renderObject.pipeline = pipeline;
  21881. }
  21882. // keep track of all used times
  21883. pipeline.usedTimes ++;
  21884. stageVertex.usedTimes ++;
  21885. stageFragment.usedTimes ++;
  21886. //
  21887. data.pipeline = pipeline;
  21888. }
  21889. return data.pipeline;
  21890. }
  21891. /**
  21892. * Deletes the pipeline for the given render object.
  21893. *
  21894. * @param {RenderObject} object - The render object.
  21895. * @return {?Object} The deleted dictionary.
  21896. */
  21897. delete( object ) {
  21898. const pipeline = this.get( object ).pipeline;
  21899. if ( pipeline ) {
  21900. // pipeline
  21901. pipeline.usedTimes --;
  21902. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21903. // programs
  21904. if ( pipeline.isComputePipeline ) {
  21905. pipeline.computeProgram.usedTimes --;
  21906. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21907. } else {
  21908. pipeline.fragmentProgram.usedTimes --;
  21909. pipeline.vertexProgram.usedTimes --;
  21910. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21911. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21912. }
  21913. }
  21914. return super.delete( object );
  21915. }
  21916. /**
  21917. * Frees internal resources.
  21918. */
  21919. dispose() {
  21920. super.dispose();
  21921. this.caches = new Map();
  21922. this.programs = {
  21923. vertex: new Map(),
  21924. fragment: new Map(),
  21925. compute: new Map()
  21926. };
  21927. }
  21928. /**
  21929. * Updates the pipeline for the given render object.
  21930. *
  21931. * @param {RenderObject} renderObject - The render object.
  21932. */
  21933. updateForRender( renderObject ) {
  21934. this.getForRender( renderObject );
  21935. }
  21936. /**
  21937. * Returns a compute pipeline for the given parameters.
  21938. *
  21939. * @private
  21940. * @param {Node} computeNode - The compute node.
  21941. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21942. * @param {string} cacheKey - The cache key.
  21943. * @param {Array<BindGroup>} bindings - The bindings.
  21944. * @return {ComputePipeline} The compute pipeline.
  21945. */
  21946. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21947. // check for existing pipeline
  21948. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21949. let pipeline = this.caches.get( cacheKey );
  21950. if ( pipeline === undefined ) {
  21951. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21952. this.caches.set( cacheKey, pipeline );
  21953. this.backend.createComputePipeline( pipeline, bindings );
  21954. }
  21955. return pipeline;
  21956. }
  21957. /**
  21958. * Returns a render pipeline for the given parameters.
  21959. *
  21960. * @private
  21961. * @param {RenderObject} renderObject - The render object.
  21962. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21963. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21964. * @param {string} cacheKey - The cache key.
  21965. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21966. * @return {RenderObjectPipeline} The render pipeline.
  21967. */
  21968. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21969. // check for existing pipeline
  21970. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21971. let pipeline = this.caches.get( cacheKey );
  21972. if ( pipeline === undefined ) {
  21973. pipeline = new RenderObjectPipeline( cacheKey, stageVertex, stageFragment );
  21974. this.caches.set( cacheKey, pipeline );
  21975. renderObject.pipeline = pipeline;
  21976. // The `promises` array is `null` by default and only set to an empty array when
  21977. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21978. // pending promises that resolve when the render pipelines are ready for rendering.
  21979. this.backend.createRenderPipeline( renderObject, promises );
  21980. }
  21981. return pipeline;
  21982. }
  21983. /**
  21984. * Computes a cache key representing a compute pipeline.
  21985. *
  21986. * @private
  21987. * @param {Node} computeNode - The compute node.
  21988. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21989. * @return {string} The cache key.
  21990. */
  21991. _getComputeCacheKey( computeNode, stageCompute ) {
  21992. return computeNode.id + ',' + stageCompute.id;
  21993. }
  21994. /**
  21995. * Computes a cache key representing a render pipeline.
  21996. *
  21997. * @private
  21998. * @param {RenderObject} renderObject - The render object.
  21999. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  22000. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  22001. * @return {string} The cache key.
  22002. */
  22003. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22004. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22005. }
  22006. /**
  22007. * Releases the given pipeline.
  22008. *
  22009. * @private
  22010. * @param {Pipeline} pipeline - The pipeline to release.
  22011. */
  22012. _releasePipeline( pipeline ) {
  22013. this.caches.delete( pipeline.cacheKey );
  22014. }
  22015. /**
  22016. * Releases the shader program.
  22017. *
  22018. * @private
  22019. * @param {Object} program - The shader program to release.
  22020. */
  22021. _releaseProgram( program ) {
  22022. const code = program.code;
  22023. const stage = program.stage;
  22024. this.programs[ stage ].delete( code );
  22025. }
  22026. /**
  22027. * Returns `true` if the compute pipeline for the given compute node requires an update.
  22028. *
  22029. * @private
  22030. * @param {Node} computeNode - The compute node.
  22031. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  22032. */
  22033. _needsComputeUpdate( computeNode ) {
  22034. const data = this.get( computeNode );
  22035. return data.pipeline === undefined || data.version !== computeNode.version;
  22036. }
  22037. /**
  22038. * Returns `true` if the render pipeline for the given render object requires an update.
  22039. *
  22040. * @private
  22041. * @param {RenderObject} renderObject - The render object.
  22042. * @return {boolean} Whether the render object for the given render object requires an update or not.
  22043. */
  22044. _needsRenderUpdate( renderObject ) {
  22045. const data = this.get( renderObject );
  22046. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22047. }
  22048. }
  22049. /**
  22050. * This renderer module manages the bindings of the renderer.
  22051. *
  22052. * @private
  22053. * @augments DataMap
  22054. */
  22055. class Bindings extends DataMap {
  22056. /**
  22057. * Constructs a new bindings management component.
  22058. *
  22059. * @param {Backend} backend - The renderer's backend.
  22060. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  22061. * @param {Textures} textures - Renderer component for managing textures.
  22062. * @param {Attributes} attributes - Renderer component for managing attributes.
  22063. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  22064. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22065. */
  22066. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22067. super();
  22068. /**
  22069. * The renderer's backend.
  22070. *
  22071. * @type {Backend}
  22072. */
  22073. this.backend = backend;
  22074. /**
  22075. * Renderer component for managing textures.
  22076. *
  22077. * @type {Textures}
  22078. */
  22079. this.textures = textures;
  22080. /**
  22081. * Renderer component for managing pipelines.
  22082. *
  22083. * @type {Pipelines}
  22084. */
  22085. this.pipelines = pipelines;
  22086. /**
  22087. * Renderer component for managing attributes.
  22088. *
  22089. * @type {Attributes}
  22090. */
  22091. this.attributes = attributes;
  22092. /**
  22093. * Renderer component for managing nodes related logic.
  22094. *
  22095. * @type {Nodes}
  22096. */
  22097. this.nodes = nodes;
  22098. /**
  22099. * Renderer component for managing metrics and monitoring data.
  22100. *
  22101. * @type {Info}
  22102. */
  22103. this.info = info;
  22104. this.pipelines.bindings = this; // assign bindings to pipelines
  22105. }
  22106. /**
  22107. * Returns the bind groups for the given render object.
  22108. *
  22109. * @param {RenderObject} renderObject - The render object.
  22110. * @return {Array<BindGroup>} The bind groups.
  22111. */
  22112. getForRender( renderObject ) {
  22113. const bindings = renderObject.getBindings();
  22114. for ( const bindGroup of bindings ) {
  22115. const groupData = this.get( bindGroup );
  22116. if ( groupData.bindGroup === undefined ) {
  22117. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22118. this._init( bindGroup );
  22119. this.backend.createBindings( bindGroup, bindings, 0 );
  22120. groupData.bindGroup = bindGroup;
  22121. }
  22122. }
  22123. return bindings;
  22124. }
  22125. /**
  22126. * Returns the bind groups for the given compute node.
  22127. *
  22128. * @param {Node} computeNode - The compute node.
  22129. * @return {Array<BindGroup>} The bind groups.
  22130. */
  22131. getForCompute( computeNode ) {
  22132. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22133. for ( const bindGroup of bindings ) {
  22134. const groupData = this.get( bindGroup );
  22135. if ( groupData.bindGroup === undefined ) {
  22136. this._init( bindGroup );
  22137. this.backend.createBindings( bindGroup, bindings, 0 );
  22138. groupData.bindGroup = bindGroup;
  22139. }
  22140. }
  22141. return bindings;
  22142. }
  22143. /**
  22144. * Updates the bindings for the given compute node.
  22145. *
  22146. * @param {Node} computeNode - The compute node.
  22147. */
  22148. updateForCompute( computeNode ) {
  22149. this._updateBindings( this.getForCompute( computeNode ) );
  22150. }
  22151. /**
  22152. * Updates the bindings for the given render object.
  22153. *
  22154. * @param {RenderObject} renderObject - The render object.
  22155. */
  22156. updateForRender( renderObject ) {
  22157. this._updateBindings( this.getForRender( renderObject ) );
  22158. }
  22159. /**
  22160. * Deletes the bindings for the given compute node.
  22161. *
  22162. * @param {Node} computeNode - The compute node.
  22163. */
  22164. deleteForCompute( computeNode ) {
  22165. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22166. for ( const bindGroup of bindings ) {
  22167. this.backend.deleteBindGroupData( bindGroup );
  22168. this.delete( bindGroup );
  22169. }
  22170. }
  22171. /**
  22172. * Deletes the bindings for the given renderObject node.
  22173. *
  22174. * @param {RenderObject} renderObject - The renderObject.
  22175. */
  22176. deleteForRender( renderObject ) {
  22177. const bindings = renderObject.getBindings();
  22178. for ( const bindGroup of bindings ) {
  22179. this.backend.deleteBindGroupData( bindGroup );
  22180. this.delete( bindGroup );
  22181. }
  22182. }
  22183. /**
  22184. * Updates the given array of bindings.
  22185. *
  22186. * @param {Array<BindGroup>} bindings - The bind groups.
  22187. */
  22188. _updateBindings( bindings ) {
  22189. for ( const bindGroup of bindings ) {
  22190. this._update( bindGroup, bindings );
  22191. }
  22192. }
  22193. /**
  22194. * Initializes the given bind group.
  22195. *
  22196. * @param {BindGroup} bindGroup - The bind group to initialize.
  22197. */
  22198. _init( bindGroup ) {
  22199. for ( const binding of bindGroup.bindings ) {
  22200. if ( binding.isSampledTexture ) {
  22201. this.textures.updateTexture( binding.texture );
  22202. } else if ( binding.isSampler ) {
  22203. this.textures.updateSampler( binding.texture );
  22204. } else if ( binding.isStorageBuffer ) {
  22205. const attribute = binding.attribute;
  22206. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22207. this.attributes.update( attribute, attributeType );
  22208. }
  22209. }
  22210. }
  22211. /**
  22212. * Updates the given bind group.
  22213. *
  22214. * @param {BindGroup} bindGroup - The bind group to update.
  22215. * @param {Array<BindGroup>} bindings - The bind groups.
  22216. */
  22217. _update( bindGroup, bindings ) {
  22218. const { backend } = this;
  22219. let needsBindingsUpdate = false;
  22220. let cacheBindings = true;
  22221. let cacheIndex = 0;
  22222. let version = 0;
  22223. // iterate over all bindings and check if buffer updates or a new binding group is required
  22224. for ( const binding of bindGroup.bindings ) {
  22225. const updatedGroup = this.nodes.updateGroup( binding );
  22226. // every uniforms group is a uniform buffer. So if no update is required,
  22227. // we move one with the next binding. Otherwise the next if block will update the group.
  22228. if ( updatedGroup === false ) continue;
  22229. //
  22230. if ( binding.isStorageBuffer ) {
  22231. const attribute = binding.attribute;
  22232. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  22233. const bindingData = backend.get( binding );
  22234. this.attributes.update( attribute, attributeType );
  22235. if ( bindingData.attribute !== attribute ) {
  22236. bindingData.attribute = attribute;
  22237. needsBindingsUpdate = true;
  22238. }
  22239. }
  22240. if ( binding.isUniformBuffer ) {
  22241. const updated = binding.update();
  22242. if ( updated ) {
  22243. backend.updateBinding( binding );
  22244. }
  22245. } else if ( binding.isSampledTexture ) {
  22246. const updated = binding.update();
  22247. // get the texture data after the update, to sync the texture reference from node
  22248. const texture = binding.texture;
  22249. const texturesTextureData = this.textures.get( texture );
  22250. if ( updated ) {
  22251. // version: update the texture data or create a new one
  22252. this.textures.updateTexture( texture );
  22253. // generation: update the bindings if a new texture has been created
  22254. if ( binding.generation !== texturesTextureData.generation ) {
  22255. binding.generation = texturesTextureData.generation;
  22256. needsBindingsUpdate = true;
  22257. cacheBindings = false;
  22258. }
  22259. }
  22260. const textureData = backend.get( texture );
  22261. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  22262. cacheBindings = false;
  22263. } else {
  22264. cacheIndex = cacheIndex * 10 + texture.id;
  22265. version += texture.version;
  22266. }
  22267. if ( texture.isStorageTexture === true && texture.mipmapsAutoUpdate === true ) {
  22268. const textureData = this.get( texture );
  22269. if ( binding.store === true ) {
  22270. textureData.needsMipmap = true;
  22271. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22272. this.backend.generateMipmaps( texture );
  22273. textureData.needsMipmap = false;
  22274. }
  22275. }
  22276. } else if ( binding.isSampler ) {
  22277. const updated = binding.update();
  22278. if ( updated ) {
  22279. const samplerKey = this.textures.updateSampler( binding.texture );
  22280. if ( binding.samplerKey !== samplerKey ) {
  22281. binding.samplerKey = samplerKey;
  22282. needsBindingsUpdate = true;
  22283. cacheBindings = false;
  22284. }
  22285. }
  22286. }
  22287. if ( binding.isBuffer && binding.updateRanges.length > 0 ) {
  22288. binding.clearUpdateRanges();
  22289. }
  22290. }
  22291. if ( needsBindingsUpdate === true ) {
  22292. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  22293. }
  22294. }
  22295. }
  22296. /**
  22297. * Default sorting function for opaque render items.
  22298. *
  22299. * @private
  22300. * @function
  22301. * @param {Object} a - The first render item.
  22302. * @param {Object} b - The second render item.
  22303. * @return {number} A numeric value which defines the sort order.
  22304. */
  22305. function painterSortStable( a, b ) {
  22306. if ( a.groupOrder !== b.groupOrder ) {
  22307. return a.groupOrder - b.groupOrder;
  22308. } else if ( a.renderOrder !== b.renderOrder ) {
  22309. return a.renderOrder - b.renderOrder;
  22310. } else if ( a.z !== b.z ) {
  22311. return a.z - b.z;
  22312. } else {
  22313. return a.id - b.id;
  22314. }
  22315. }
  22316. /**
  22317. * Default sorting function for transparent render items.
  22318. *
  22319. * @private
  22320. * @function
  22321. * @param {Object} a - The first render item.
  22322. * @param {Object} b - The second render item.
  22323. * @return {number} A numeric value which defines the sort order.
  22324. */
  22325. function reversePainterSortStable( a, b ) {
  22326. if ( a.groupOrder !== b.groupOrder ) {
  22327. return a.groupOrder - b.groupOrder;
  22328. } else if ( a.renderOrder !== b.renderOrder ) {
  22329. return a.renderOrder - b.renderOrder;
  22330. } else if ( a.z !== b.z ) {
  22331. return b.z - a.z;
  22332. } else {
  22333. return a.id - b.id;
  22334. }
  22335. }
  22336. /**
  22337. * Returns `true` if the given transparent material requires a double pass.
  22338. *
  22339. * @private
  22340. * @function
  22341. * @param {Material} material - The transparent material.
  22342. * @return {boolean} Whether the given material requires a double pass or not.
  22343. */
  22344. function needsDoublePass( material ) {
  22345. const hasTransmission = material.transmission > 0 || ( material.transmissionNode && material.transmissionNode.isNode );
  22346. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  22347. }
  22348. /**
  22349. * When the renderer analyzes the scene at the beginning of a render call,
  22350. * it stores 3D object for further processing in render lists. Depending on the
  22351. * properties of a 3D objects (like their transformation or material state), the
  22352. * objects are maintained in ordered lists for the actual rendering.
  22353. *
  22354. * Render lists are unique per scene and camera combination.
  22355. *
  22356. * @private
  22357. * @augments Pipeline
  22358. */
  22359. class RenderList {
  22360. /**
  22361. * Constructs a render list.
  22362. *
  22363. * @param {Lighting} lighting - The lighting management component.
  22364. * @param {Scene} scene - The scene.
  22365. * @param {Camera} camera - The camera the scene is rendered with.
  22366. */
  22367. constructor( lighting, scene, camera ) {
  22368. /**
  22369. * 3D objects are transformed into render items and stored in this array.
  22370. *
  22371. * @type {Array<Object>}
  22372. */
  22373. this.renderItems = [];
  22374. /**
  22375. * The current render items index.
  22376. *
  22377. * @type {number}
  22378. * @default 0
  22379. */
  22380. this.renderItemsIndex = 0;
  22381. /**
  22382. * A list with opaque render items.
  22383. *
  22384. * @type {Array<Object>}
  22385. */
  22386. this.opaque = [];
  22387. /**
  22388. * A list with transparent render items which require
  22389. * double pass rendering (e.g. transmissive objects).
  22390. *
  22391. * @type {Array<Object>}
  22392. */
  22393. this.transparentDoublePass = [];
  22394. /**
  22395. * A list with transparent render items.
  22396. *
  22397. * @type {Array<Object>}
  22398. */
  22399. this.transparent = [];
  22400. /**
  22401. * A list with transparent render bundle data.
  22402. *
  22403. * @type {Array<Object>}
  22404. */
  22405. this.bundles = [];
  22406. /**
  22407. * The render list's lights node. This node is later
  22408. * relevant for the actual analytical light nodes which
  22409. * compute the scene's lighting in the shader.
  22410. *
  22411. * @type {LightsNode}
  22412. */
  22413. this.lightsNode = lighting.getNode( scene, camera );
  22414. /**
  22415. * The scene's lights stored in an array. This array
  22416. * is used to setup the lights node.
  22417. *
  22418. * @type {Array<Light>}
  22419. */
  22420. this.lightsArray = [];
  22421. /**
  22422. * The scene.
  22423. *
  22424. * @type {Scene}
  22425. */
  22426. this.scene = scene;
  22427. /**
  22428. * The camera the scene is rendered with.
  22429. *
  22430. * @type {Camera}
  22431. */
  22432. this.camera = camera;
  22433. /**
  22434. * How many objects perform occlusion query tests.
  22435. *
  22436. * @type {number}
  22437. * @default 0
  22438. */
  22439. this.occlusionQueryCount = 0;
  22440. }
  22441. /**
  22442. * This method is called right at the beginning of a render call
  22443. * before the scene is analyzed. It prepares the internal data
  22444. * structures for the upcoming render lists generation.
  22445. *
  22446. * @return {RenderList} A reference to this render list.
  22447. */
  22448. begin() {
  22449. this.renderItemsIndex = 0;
  22450. this.opaque.length = 0;
  22451. this.transparentDoublePass.length = 0;
  22452. this.transparent.length = 0;
  22453. this.bundles.length = 0;
  22454. this.lightsArray.length = 0;
  22455. this.occlusionQueryCount = 0;
  22456. return this;
  22457. }
  22458. /**
  22459. * Returns a render item for the giving render item state. The state is defined
  22460. * by a series of object-related parameters.
  22461. *
  22462. * The method avoids object creation by holding render items and reusing them in
  22463. * subsequent render calls (just with different property values).
  22464. *
  22465. * @param {Object3D} object - The 3D object.
  22466. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22467. * @param {Material} material - The 3D object's material.
  22468. * @param {number} groupOrder - The current group order.
  22469. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22470. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22471. * @param {ClippingContext} clippingContext - The current clipping context.
  22472. * @return {Object} The render item.
  22473. */
  22474. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22475. let renderItem = this.renderItems[ this.renderItemsIndex ];
  22476. if ( renderItem === undefined ) {
  22477. renderItem = {
  22478. id: object.id,
  22479. object: object,
  22480. geometry: geometry,
  22481. material: material,
  22482. groupOrder: groupOrder,
  22483. renderOrder: object.renderOrder,
  22484. z: z,
  22485. group: group,
  22486. clippingContext: clippingContext
  22487. };
  22488. this.renderItems[ this.renderItemsIndex ] = renderItem;
  22489. } else {
  22490. renderItem.id = object.id;
  22491. renderItem.object = object;
  22492. renderItem.geometry = geometry;
  22493. renderItem.material = material;
  22494. renderItem.groupOrder = groupOrder;
  22495. renderItem.renderOrder = object.renderOrder;
  22496. renderItem.z = z;
  22497. renderItem.group = group;
  22498. renderItem.clippingContext = clippingContext;
  22499. }
  22500. this.renderItemsIndex ++;
  22501. return renderItem;
  22502. }
  22503. /**
  22504. * Pushes the given object as a render item to the internal render lists.
  22505. * The selected lists depend on the object properties.
  22506. *
  22507. * @param {Object3D} object - The 3D object.
  22508. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22509. * @param {Material} material - The 3D object's material.
  22510. * @param {number} groupOrder - The current group order.
  22511. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22512. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22513. * @param {ClippingContext} clippingContext - The current clipping context.
  22514. */
  22515. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22516. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22517. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  22518. if ( material.transparent === true || material.transmission > 0 ||
  22519. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22520. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22521. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  22522. this.transparent.push( renderItem );
  22523. } else {
  22524. this.opaque.push( renderItem );
  22525. }
  22526. }
  22527. /**
  22528. * Inserts the given object as a render item at the start of the internal render lists.
  22529. * The selected lists depend on the object properties.
  22530. *
  22531. * @param {Object3D} object - The 3D object.
  22532. * @param {BufferGeometry} geometry - The 3D object's geometry.
  22533. * @param {Material} material - The 3D object's material.
  22534. * @param {number} groupOrder - The current group order.
  22535. * @param {number} z - Th 3D object's depth value (z value in clip space).
  22536. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  22537. * @param {ClippingContext} clippingContext - The current clipping context.
  22538. */
  22539. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  22540. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  22541. if ( material.transparent === true || material.transmission > 0 ||
  22542. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  22543. ( material.backdropNode && material.backdropNode.isNode ) ) {
  22544. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  22545. this.transparent.unshift( renderItem );
  22546. } else {
  22547. this.opaque.unshift( renderItem );
  22548. }
  22549. }
  22550. /**
  22551. * Pushes render bundle group data into the render list.
  22552. *
  22553. * @param {Object} group - Bundle group data.
  22554. */
  22555. pushBundle( group ) {
  22556. this.bundles.push( group );
  22557. }
  22558. /**
  22559. * Pushes a light into the render list.
  22560. *
  22561. * @param {Light} light - The light.
  22562. */
  22563. pushLight( light ) {
  22564. this.lightsArray.push( light );
  22565. }
  22566. /**
  22567. * Sorts the internal render lists.
  22568. *
  22569. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  22570. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  22571. */
  22572. sort( customOpaqueSort, customTransparentSort ) {
  22573. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  22574. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  22575. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  22576. }
  22577. /**
  22578. * This method performs finalizing tasks right after the render lists
  22579. * have been generated.
  22580. */
  22581. finish() {
  22582. // update lights
  22583. this.lightsNode.setLights( this.lightsArray );
  22584. // Clear references from inactive renderItems in the list
  22585. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  22586. const renderItem = this.renderItems[ i ];
  22587. if ( renderItem.id === null ) break;
  22588. renderItem.id = null;
  22589. renderItem.object = null;
  22590. renderItem.geometry = null;
  22591. renderItem.material = null;
  22592. renderItem.groupOrder = null;
  22593. renderItem.renderOrder = null;
  22594. renderItem.z = null;
  22595. renderItem.group = null;
  22596. renderItem.clippingContext = null;
  22597. }
  22598. }
  22599. }
  22600. const _chainKeys$2 = [];
  22601. /**
  22602. * This renderer module manages the render lists which are unique
  22603. * per scene and camera combination.
  22604. *
  22605. * @private
  22606. */
  22607. class RenderLists {
  22608. /**
  22609. * Constructs a render lists management component.
  22610. *
  22611. * @param {Lighting} lighting - The lighting management component.
  22612. */
  22613. constructor( lighting ) {
  22614. /**
  22615. * The lighting management component.
  22616. *
  22617. * @type {Lighting}
  22618. */
  22619. this.lighting = lighting;
  22620. /**
  22621. * The internal chain map which holds the render lists.
  22622. *
  22623. * @type {ChainMap}
  22624. */
  22625. this.lists = new ChainMap();
  22626. }
  22627. /**
  22628. * Returns a render list for the given scene and camera.
  22629. *
  22630. * @param {Scene} scene - The scene.
  22631. * @param {Camera} camera - The camera.
  22632. * @return {RenderList} The render list.
  22633. */
  22634. get( scene, camera ) {
  22635. const lists = this.lists;
  22636. _chainKeys$2[ 0 ] = scene;
  22637. _chainKeys$2[ 1 ] = camera;
  22638. let list = lists.get( _chainKeys$2 );
  22639. if ( list === undefined ) {
  22640. list = new RenderList( this.lighting, scene, camera );
  22641. lists.set( _chainKeys$2, list );
  22642. }
  22643. _chainKeys$2[ 0 ] = null;
  22644. _chainKeys$2[ 1 ] = null;
  22645. return list;
  22646. }
  22647. /**
  22648. * Frees all internal resources.
  22649. */
  22650. dispose() {
  22651. this.lists = new ChainMap();
  22652. }
  22653. }
  22654. let _id$8 = 0;
  22655. /**
  22656. * Any render or compute command is executed in a specific context that defines
  22657. * the state of the renderer and its backend. Typical examples for such context
  22658. * data are the current clear values or data from the active framebuffer. This
  22659. * module is used to represent these contexts as objects.
  22660. *
  22661. * @private
  22662. */
  22663. class RenderContext {
  22664. /**
  22665. * Constructs a new render context.
  22666. */
  22667. constructor() {
  22668. /**
  22669. * The context's ID.
  22670. *
  22671. * @type {number}
  22672. */
  22673. this.id = _id$8 ++;
  22674. /**
  22675. * The MRT configuration.
  22676. *
  22677. * @type {?MRTNode}
  22678. * @default null
  22679. */
  22680. this.mrt = null;
  22681. /**
  22682. * Whether the current active framebuffer has a color attachment.
  22683. *
  22684. * @type {boolean}
  22685. * @default true
  22686. */
  22687. this.color = true;
  22688. /**
  22689. * Whether the color attachment should be cleared or not.
  22690. *
  22691. * @type {boolean}
  22692. * @default true
  22693. */
  22694. this.clearColor = true;
  22695. /**
  22696. * The clear color value.
  22697. *
  22698. * @type {Object}
  22699. * @default true
  22700. */
  22701. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  22702. /**
  22703. * Whether the current active framebuffer has a depth attachment.
  22704. *
  22705. * @type {boolean}
  22706. * @default true
  22707. */
  22708. this.depth = true;
  22709. /**
  22710. * Whether the depth attachment should be cleared or not.
  22711. *
  22712. * @type {boolean}
  22713. * @default true
  22714. */
  22715. this.clearDepth = true;
  22716. /**
  22717. * The clear depth value.
  22718. *
  22719. * @type {number}
  22720. * @default 1
  22721. */
  22722. this.clearDepthValue = 1;
  22723. /**
  22724. * Whether the current active framebuffer has a stencil attachment.
  22725. *
  22726. * @type {boolean}
  22727. * @default false
  22728. */
  22729. this.stencil = false;
  22730. /**
  22731. * Whether the stencil attachment should be cleared or not.
  22732. *
  22733. * @type {boolean}
  22734. * @default true
  22735. */
  22736. this.clearStencil = true;
  22737. /**
  22738. * The clear stencil value.
  22739. *
  22740. * @type {number}
  22741. * @default 1
  22742. */
  22743. this.clearStencilValue = 1;
  22744. /**
  22745. * By default the viewport encloses the entire framebuffer If a smaller
  22746. * viewport is manually defined, this property is to `true` by the renderer.
  22747. *
  22748. * @type {boolean}
  22749. * @default false
  22750. */
  22751. this.viewport = false;
  22752. /**
  22753. * The viewport value. This value is in physical pixels meaning it incorporates
  22754. * the renderer's pixel ratio. The viewport property of render targets or
  22755. * the renderer is in logical pixels.
  22756. *
  22757. * @type {Vector4}
  22758. */
  22759. this.viewportValue = new Vector4();
  22760. /**
  22761. * When the scissor test is active and scissor rectangle smaller than the
  22762. * framebuffers dimensions, this property is to `true` by the renderer.
  22763. *
  22764. * @type {boolean}
  22765. * @default false
  22766. */
  22767. this.scissor = false;
  22768. /**
  22769. * The scissor rectangle.
  22770. *
  22771. * @type {Vector4}
  22772. */
  22773. this.scissorValue = new Vector4();
  22774. /**
  22775. * The active render target.
  22776. *
  22777. * @type {?RenderTarget}
  22778. * @default null
  22779. */
  22780. this.renderTarget = null;
  22781. /**
  22782. * The textures of the active render target.
  22783. * `null` when no render target is set.
  22784. *
  22785. * @type {?Array<Texture>}
  22786. * @default null
  22787. */
  22788. this.textures = null;
  22789. /**
  22790. * The depth texture of the active render target.
  22791. * `null` when no render target is set.
  22792. *
  22793. * @type {?DepthTexture}
  22794. * @default null
  22795. */
  22796. this.depthTexture = null;
  22797. /**
  22798. * The active cube face.
  22799. *
  22800. * @type {number}
  22801. * @default 0
  22802. */
  22803. this.activeCubeFace = 0;
  22804. /**
  22805. * The active mipmap level.
  22806. *
  22807. * @type {number}
  22808. * @default 0
  22809. */
  22810. this.activeMipmapLevel = 0;
  22811. /**
  22812. * The number of MSAA samples. This value is always `1` when
  22813. * MSAA isn't used.
  22814. *
  22815. * @type {number}
  22816. * @default 1
  22817. */
  22818. this.sampleCount = 1;
  22819. /**
  22820. * The active render target's width in physical pixels.
  22821. *
  22822. * @type {number}
  22823. * @default 0
  22824. */
  22825. this.width = 0;
  22826. /**
  22827. * The active render target's height in physical pixels.
  22828. *
  22829. * @type {number}
  22830. * @default 0
  22831. */
  22832. this.height = 0;
  22833. /**
  22834. * The occlusion query count.
  22835. *
  22836. * @type {number}
  22837. * @default 0
  22838. */
  22839. this.occlusionQueryCount = 0;
  22840. /**
  22841. * The current clipping context.
  22842. *
  22843. * @type {?ClippingContext}
  22844. * @default null
  22845. */
  22846. this.clippingContext = null;
  22847. /**
  22848. * The current camera.
  22849. *
  22850. * @type {?Camera}
  22851. * @default null
  22852. */
  22853. this.camera = null;
  22854. /**
  22855. * This flag can be used for type testing.
  22856. *
  22857. * @type {boolean}
  22858. * @readonly
  22859. * @default true
  22860. */
  22861. this.isRenderContext = true;
  22862. }
  22863. /**
  22864. * Returns the cache key of this render context.
  22865. *
  22866. * @return {number} The cache key.
  22867. */
  22868. getCacheKey() {
  22869. return getCacheKey( this );
  22870. }
  22871. }
  22872. /**
  22873. * Computes a cache key for the given render context. This key
  22874. * should identify the render target state so it is possible to
  22875. * configure the correct attachments in the respective backend.
  22876. *
  22877. * @param {RenderContext} renderContext - The render context.
  22878. * @return {number} The cache key.
  22879. */
  22880. function getCacheKey( renderContext ) {
  22881. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22882. const values = [ activeCubeFace, activeMipmapLevel ];
  22883. for ( const texture of textures ) {
  22884. values.push( texture.id );
  22885. }
  22886. return hashArray( values );
  22887. }
  22888. /**
  22889. * This module manages the render contexts of the renderer.
  22890. *
  22891. * @private
  22892. */
  22893. class RenderContexts {
  22894. /**
  22895. * Constructs a new render context management component.
  22896. */
  22897. constructor() {
  22898. /**
  22899. * A dictionary that manages render contexts.
  22900. *
  22901. * @type {Object<string,RenderContext>}
  22902. */
  22903. this._renderContexts = {};
  22904. }
  22905. /**
  22906. * Returns a render context for the given scene, camera and render target.
  22907. *
  22908. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22909. * @param {?MRTNode} [mrt=null] - The MRT configuration
  22910. * @param {?number} [callDepth=0] - The call depth of the renderer.
  22911. * @return {RenderContext} The render context.
  22912. */
  22913. get( renderTarget = null, mrt = null, callDepth = 0 ) {
  22914. //
  22915. let attachmentState;
  22916. if ( renderTarget === null ) {
  22917. attachmentState = 'default';
  22918. } else {
  22919. const format = renderTarget.texture.format;
  22920. const type = renderTarget.texture.type;
  22921. const count = renderTarget.textures.length;
  22922. attachmentState = `${ count }:${ format }:${ type }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22923. }
  22924. //
  22925. const mrtState = ( mrt !== null ) ? mrt.id : 'default';
  22926. //
  22927. const renderStateKey = attachmentState + '-' + mrtState + '-' + callDepth;
  22928. let renderState = this._renderContexts[ renderStateKey ];
  22929. if ( renderState === undefined ) {
  22930. renderState = new RenderContext();
  22931. renderState.mrt = mrt;
  22932. this._renderContexts[ renderStateKey ] = renderState;
  22933. }
  22934. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22935. return renderState;
  22936. }
  22937. /**
  22938. * Frees internal resources.
  22939. */
  22940. dispose() {
  22941. this._renderContexts = {};
  22942. }
  22943. }
  22944. const _size$3 = /*@__PURE__*/ new Vector3();
  22945. /**
  22946. * This module manages the textures of the renderer.
  22947. *
  22948. * @private
  22949. * @augments DataMap
  22950. */
  22951. class Textures extends DataMap {
  22952. /**
  22953. * Constructs a new texture management component.
  22954. *
  22955. * @param {Renderer} renderer - The renderer.
  22956. * @param {Backend} backend - The renderer's backend.
  22957. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22958. */
  22959. constructor( renderer, backend, info ) {
  22960. super();
  22961. /**
  22962. * The renderer.
  22963. *
  22964. * @type {Renderer}
  22965. */
  22966. this.renderer = renderer;
  22967. /**
  22968. * The backend.
  22969. *
  22970. * @type {Backend}
  22971. */
  22972. this.backend = backend;
  22973. /**
  22974. * Renderer component for managing metrics and monitoring data.
  22975. *
  22976. * @type {Info}
  22977. */
  22978. this.info = info;
  22979. }
  22980. /**
  22981. * Updates the given render target. Based on the given render target configuration,
  22982. * it updates the texture states representing the attachments of the framebuffer.
  22983. *
  22984. * @param {RenderTarget} renderTarget - The render target to update.
  22985. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22986. */
  22987. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22988. const renderTargetData = this.get( renderTarget );
  22989. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22990. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22991. const textures = renderTarget.textures;
  22992. const size = this.getSize( textures[ 0 ] );
  22993. const mipWidth = size.width >> activeMipmapLevel;
  22994. const mipHeight = size.height >> activeMipmapLevel;
  22995. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22996. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22997. let textureNeedsUpdate = false;
  22998. if ( depthTexture === undefined && useDepthTexture ) {
  22999. depthTexture = new DepthTexture();
  23000. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  23001. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  23002. depthTexture.image.width = mipWidth;
  23003. depthTexture.image.height = mipHeight;
  23004. depthTexture.image.depth = size.depth;
  23005. depthTexture.renderTarget = renderTarget;
  23006. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  23007. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  23008. }
  23009. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  23010. textureNeedsUpdate = true;
  23011. if ( depthTexture ) {
  23012. depthTexture.needsUpdate = true;
  23013. depthTexture.image.width = mipWidth;
  23014. depthTexture.image.height = mipHeight;
  23015. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  23016. }
  23017. }
  23018. renderTargetData.width = size.width;
  23019. renderTargetData.height = size.height;
  23020. renderTargetData.textures = textures;
  23021. renderTargetData.depthTexture = depthTexture || null;
  23022. renderTargetData.depth = renderTarget.depthBuffer;
  23023. renderTargetData.stencil = renderTarget.stencilBuffer;
  23024. renderTargetData.renderTarget = renderTarget;
  23025. if ( renderTargetData.sampleCount !== sampleCount ) {
  23026. textureNeedsUpdate = true;
  23027. if ( depthTexture ) {
  23028. depthTexture.needsUpdate = true;
  23029. }
  23030. renderTargetData.sampleCount = sampleCount;
  23031. }
  23032. //
  23033. const options = { sampleCount };
  23034. // XR render targets require no texture updates
  23035. if ( renderTarget.isXRRenderTarget !== true ) {
  23036. for ( let i = 0; i < textures.length; i ++ ) {
  23037. const texture = textures[ i ];
  23038. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  23039. this.updateTexture( texture, options );
  23040. }
  23041. if ( depthTexture ) {
  23042. this.updateTexture( depthTexture, options );
  23043. }
  23044. }
  23045. // dispose handler
  23046. if ( renderTargetData.initialized !== true ) {
  23047. renderTargetData.initialized = true;
  23048. // dispose
  23049. renderTargetData.onDispose = () => {
  23050. this._destroyRenderTarget( renderTarget );
  23051. };
  23052. renderTarget.addEventListener( 'dispose', renderTargetData.onDispose );
  23053. }
  23054. }
  23055. /**
  23056. * Updates the given texture. Depending on the texture state, this method
  23057. * triggers the upload of texture data to the GPU memory. If the texture data are
  23058. * not yet ready for the upload, it uses default texture data for as a placeholder.
  23059. *
  23060. * @param {Texture} texture - The texture to update.
  23061. * @param {Object} [options={}] - The options.
  23062. */
  23063. updateTexture( texture, options = {} ) {
  23064. const textureData = this.get( texture );
  23065. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  23066. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  23067. const backend = this.backend;
  23068. if ( isRenderTarget && textureData.initialized === true ) {
  23069. // it's an update
  23070. backend.destroyTexture( texture );
  23071. }
  23072. //
  23073. if ( texture.isFramebufferTexture ) {
  23074. const renderTarget = this.renderer.getRenderTarget();
  23075. if ( renderTarget ) {
  23076. texture.type = renderTarget.texture.type;
  23077. } else {
  23078. texture.type = UnsignedByteType;
  23079. }
  23080. }
  23081. //
  23082. const { width, height, depth } = this.getSize( texture );
  23083. options.width = width;
  23084. options.height = height;
  23085. options.depth = depth;
  23086. options.needsMipmaps = this.needsMipmaps( texture );
  23087. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  23088. // TODO: Uniformly handle mipmap definitions
  23089. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  23090. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  23091. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  23092. //
  23093. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  23094. backend.createTexture( texture, options );
  23095. textureData.generation = texture.version;
  23096. } else {
  23097. if ( texture.version > 0 ) {
  23098. const image = texture.image;
  23099. if ( image === undefined ) {
  23100. warn( 'Renderer: Texture marked for update but image is undefined.' );
  23101. } else if ( image.complete === false ) {
  23102. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  23103. } else {
  23104. if ( texture.images ) {
  23105. const images = [];
  23106. for ( const image of texture.images ) {
  23107. images.push( image );
  23108. }
  23109. options.images = images;
  23110. } else {
  23111. options.image = image;
  23112. }
  23113. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  23114. backend.createTexture( texture, options );
  23115. textureData.isDefaultTexture = false;
  23116. textureData.generation = texture.version;
  23117. }
  23118. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  23119. const skipAutoGeneration = texture.isStorageTexture === true && texture.mipmapsAutoUpdate === false;
  23120. if ( options.needsMipmaps && texture.mipmaps.length === 0 && ! skipAutoGeneration ) {
  23121. backend.generateMipmaps( texture );
  23122. }
  23123. if ( texture.onUpdate ) texture.onUpdate( texture );
  23124. }
  23125. } else {
  23126. // async update
  23127. backend.createDefaultTexture( texture );
  23128. textureData.isDefaultTexture = true;
  23129. textureData.generation = texture.version;
  23130. }
  23131. }
  23132. // dispose handler
  23133. if ( textureData.initialized !== true ) {
  23134. textureData.initialized = true;
  23135. textureData.generation = texture.version;
  23136. //
  23137. this.info.memory.textures ++;
  23138. //
  23139. if ( texture.isVideoTexture && ColorManagement.enabled === true && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  23140. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  23141. }
  23142. // dispose
  23143. textureData.onDispose = () => {
  23144. this._destroyTexture( texture );
  23145. };
  23146. texture.addEventListener( 'dispose', textureData.onDispose );
  23147. }
  23148. //
  23149. textureData.version = texture.version;
  23150. }
  23151. /**
  23152. * Updates the sampler for the given texture. This method has no effect
  23153. * for the WebGL backend since it has no concept of samplers. Texture
  23154. * parameters are configured with the `texParameter()` command for each
  23155. * texture.
  23156. *
  23157. * In WebGPU, samplers are objects like textures and it's possible to share
  23158. * them when the texture parameters match.
  23159. *
  23160. * @param {Texture} texture - The texture to update the sampler for.
  23161. * @return {string} The current sampler key.
  23162. */
  23163. updateSampler( texture ) {
  23164. return this.backend.updateSampler( texture );
  23165. }
  23166. /**
  23167. * Computes the size of the given texture and writes the result
  23168. * into the target vector. This vector is also returned by the
  23169. * method.
  23170. *
  23171. * If no texture data are available for the compute yet, the method
  23172. * returns default size values.
  23173. *
  23174. * @param {Texture} texture - The texture to compute the size for.
  23175. * @param {Vector3} target - The target vector.
  23176. * @return {Vector3} The target vector.
  23177. */
  23178. getSize( texture, target = _size$3 ) {
  23179. let image = texture.images ? texture.images[ 0 ] : texture.image;
  23180. if ( image ) {
  23181. if ( image.image !== undefined ) image = image.image;
  23182. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  23183. target.width = image.videoWidth || 1;
  23184. target.height = image.videoHeight || 1;
  23185. target.depth = 1;
  23186. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  23187. target.width = image.displayWidth || 1;
  23188. target.height = image.displayHeight || 1;
  23189. target.depth = 1;
  23190. } else {
  23191. target.width = image.width || 1;
  23192. target.height = image.height || 1;
  23193. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  23194. }
  23195. } else {
  23196. target.width = target.height = target.depth = 1;
  23197. }
  23198. return target;
  23199. }
  23200. /**
  23201. * Computes the number of mipmap levels for the given texture.
  23202. *
  23203. * @param {Texture} texture - The texture.
  23204. * @param {number} width - The texture's width.
  23205. * @param {number} height - The texture's height.
  23206. * @return {number} The number of mipmap levels.
  23207. */
  23208. getMipLevels( texture, width, height ) {
  23209. let mipLevelCount;
  23210. if ( texture.mipmaps.length > 0 ) {
  23211. mipLevelCount = texture.mipmaps.length;
  23212. } else {
  23213. if ( texture.isCompressedTexture === true ) {
  23214. // it is not possible to compute mipmaps for compressed textures. So
  23215. // when no mipmaps are defined in "texture.mipmaps", force a texture
  23216. // level of 1
  23217. mipLevelCount = 1;
  23218. } else {
  23219. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  23220. }
  23221. }
  23222. return mipLevelCount;
  23223. }
  23224. /**
  23225. * Returns `true` if the given texture makes use of mipmapping.
  23226. *
  23227. * @param {Texture} texture - The texture.
  23228. * @return {boolean} Whether mipmaps are required or not.
  23229. */
  23230. needsMipmaps( texture ) {
  23231. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  23232. }
  23233. /**
  23234. * Frees internal resources when the given render target isn't
  23235. * required anymore.
  23236. *
  23237. * @param {RenderTarget} renderTarget - The render target to destroy.
  23238. */
  23239. _destroyRenderTarget( renderTarget ) {
  23240. if ( this.has( renderTarget ) === true ) {
  23241. const renderTargetData = this.get( renderTarget );
  23242. const textures = renderTargetData.textures;
  23243. const depthTexture = renderTargetData.depthTexture;
  23244. //
  23245. renderTarget.removeEventListener( 'dispose', renderTargetData.onDispose );
  23246. //
  23247. for ( let i = 0; i < textures.length; i ++ ) {
  23248. this._destroyTexture( textures[ i ] );
  23249. }
  23250. if ( depthTexture ) {
  23251. this._destroyTexture( depthTexture );
  23252. }
  23253. this.delete( renderTarget );
  23254. this.backend.delete( renderTarget );
  23255. }
  23256. }
  23257. /**
  23258. * Frees internal resource when the given texture isn't
  23259. * required anymore.
  23260. *
  23261. * @param {Texture} texture - The texture to destroy.
  23262. */
  23263. _destroyTexture( texture ) {
  23264. if ( this.has( texture ) === true ) {
  23265. const textureData = this.get( texture );
  23266. //
  23267. texture.removeEventListener( 'dispose', textureData.onDispose );
  23268. // if a texture is not ready for use, it falls back to a default texture so it's possible
  23269. // to use it for rendering. If a texture in this state is disposed, it's important to
  23270. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  23271. // other textures.
  23272. const isDefaultTexture = textureData.isDefaultTexture;
  23273. this.backend.destroyTexture( texture, isDefaultTexture );
  23274. this.delete( texture );
  23275. this.info.memory.textures --;
  23276. }
  23277. }
  23278. }
  23279. /**
  23280. * A four-component version of {@link Color} which is internally
  23281. * used by the renderer to represents clear color with alpha as
  23282. * one object.
  23283. *
  23284. * @private
  23285. * @augments Color
  23286. */
  23287. class Color4 extends Color {
  23288. /**
  23289. * Constructs a new four-component color.
  23290. * You can also pass a single THREE.Color, hex or
  23291. * string argument to this constructor.
  23292. *
  23293. * @param {number|string} [r=1] - The red value.
  23294. * @param {number} [g=1] - The green value.
  23295. * @param {number} [b=1] - The blue value.
  23296. * @param {number} [a=1] - The alpha value.
  23297. */
  23298. constructor( r, g, b, a = 1 ) {
  23299. super( r, g, b );
  23300. this.a = a;
  23301. }
  23302. /**
  23303. * Overwrites the default to honor alpha.
  23304. * You can also pass a single THREE.Color, hex or
  23305. * string argument to this method.
  23306. *
  23307. * @param {number|string|Color} r - The red value.
  23308. * @param {number} [g] - The green value.
  23309. * @param {number} [b] - The blue value.
  23310. * @param {number} [a=1] - The alpha value.
  23311. * @return {Color4} A reference to this object.
  23312. */
  23313. set( r, g, b, a = 1 ) {
  23314. this.a = a;
  23315. return super.set( r, g, b );
  23316. }
  23317. /**
  23318. * Overwrites the default to honor alpha.
  23319. *
  23320. * @param {Color4} color - The color to copy.
  23321. * @return {Color4} A reference to this object.
  23322. */
  23323. copy( color ) {
  23324. if ( color.a !== undefined ) this.a = color.a;
  23325. return super.copy( color );
  23326. }
  23327. /**
  23328. * Overwrites the default to honor alpha.
  23329. *
  23330. * @return {Color4} The cloned color.
  23331. */
  23332. clone() {
  23333. return new this.constructor( this.r, this.g, this.b, this.a );
  23334. }
  23335. }
  23336. /**
  23337. * Special version of {@link PropertyNode} which is used for parameters.
  23338. *
  23339. * @augments PropertyNode
  23340. */
  23341. class ParameterNode extends PropertyNode {
  23342. static get type() {
  23343. return 'ParameterNode';
  23344. }
  23345. /**
  23346. * Constructs a new parameter node.
  23347. *
  23348. * @param {string} nodeType - The type of the node.
  23349. * @param {?string} [name=null] - The name of the parameter in the shader.
  23350. */
  23351. constructor( nodeType, name = null ) {
  23352. super( nodeType, name );
  23353. /**
  23354. * This flag can be used for type testing.
  23355. *
  23356. * @type {boolean}
  23357. * @readonly
  23358. * @default true
  23359. */
  23360. this.isParameterNode = true;
  23361. }
  23362. /**
  23363. * Gets the type of a member variable in the parameter node.
  23364. *
  23365. * @param {NodeBuilder} builder - The node builder.
  23366. * @param {string} name - The name of the member variable.
  23367. * @returns {string}
  23368. */
  23369. getMemberType( builder, name ) {
  23370. const type = this.getNodeType( builder );
  23371. const struct = builder.getStructTypeNode( type );
  23372. let memberType;
  23373. if ( struct !== null ) {
  23374. memberType = struct.getMemberType( builder, name );
  23375. } else {
  23376. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  23377. memberType = 'float';
  23378. }
  23379. return memberType;
  23380. }
  23381. getHash() {
  23382. return this.uuid;
  23383. }
  23384. generate() {
  23385. return this.name;
  23386. }
  23387. }
  23388. /**
  23389. * TSL function for creating a parameter node.
  23390. *
  23391. * @tsl
  23392. * @function
  23393. * @param {string} type - The type of the node.
  23394. * @param {?string} name - The name of the parameter in the shader.
  23395. * @returns {ParameterNode}
  23396. */
  23397. const parameter = ( type, name ) => new ParameterNode( type, name );
  23398. /**
  23399. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  23400. * They are usually needed in cases like `If`, `Else`.
  23401. *
  23402. * @augments Node
  23403. */
  23404. class StackNode extends Node {
  23405. static get type() {
  23406. return 'StackNode';
  23407. }
  23408. /**
  23409. * Constructs a new stack node.
  23410. *
  23411. * @param {?StackNode} [parent=null] - The parent stack node.
  23412. */
  23413. constructor( parent = null ) {
  23414. super();
  23415. /**
  23416. * List of nodes.
  23417. *
  23418. * @type {Array<Node>}
  23419. */
  23420. this.nodes = [];
  23421. /**
  23422. * The output node.
  23423. *
  23424. * @type {?Node}
  23425. * @default null
  23426. */
  23427. this.outputNode = null;
  23428. /**
  23429. * The parent stack node.
  23430. *
  23431. * @type {?StackNode}
  23432. * @default null
  23433. */
  23434. this.parent = parent;
  23435. /**
  23436. * The current conditional node.
  23437. *
  23438. * @private
  23439. * @type {ConditionalNode}
  23440. * @default null
  23441. */
  23442. this._currentCond = null;
  23443. /**
  23444. * The expression node. Only
  23445. * relevant for Switch/Case.
  23446. *
  23447. * @private
  23448. * @type {Node}
  23449. * @default null
  23450. */
  23451. this._expressionNode = null;
  23452. /**
  23453. * The current node being processed.
  23454. *
  23455. * @private
  23456. * @type {Node}
  23457. * @default null
  23458. */
  23459. this._currentNode = null;
  23460. /**
  23461. * This flag can be used for type testing.
  23462. *
  23463. * @type {boolean}
  23464. * @readonly
  23465. * @default true
  23466. */
  23467. this.isStackNode = true;
  23468. }
  23469. getElementType( builder ) {
  23470. return this.hasOutput( builder ) ? this.outputNode.getElementType( builder ) : 'void';
  23471. }
  23472. getNodeType( builder ) {
  23473. return this.hasOutput( builder ) ? this.outputNode.getNodeType( builder ) : 'void';
  23474. }
  23475. getMemberType( builder, name ) {
  23476. return this.hasOutput( builder ) ? this.outputNode.getMemberType( builder, name ) : 'void';
  23477. }
  23478. /**
  23479. * Adds a node to this stack.
  23480. *
  23481. * @param {Node} node - The node to add.
  23482. * @param {number} [index=this.nodes.length] - The index where the node should be added.
  23483. * @return {StackNode} A reference to this stack node.
  23484. */
  23485. addToStack( node, index = this.nodes.length ) {
  23486. if ( node.isNode !== true ) {
  23487. error( 'TSL: Invalid node added to stack.' );
  23488. return this;
  23489. }
  23490. this.nodes.splice( index, 0, node );
  23491. return this;
  23492. }
  23493. /**
  23494. * Adds a node to the stack before the current node.
  23495. *
  23496. * @param {Node} node - The node to add.
  23497. * @return {StackNode} A reference to this stack node.
  23498. */
  23499. addToStackBefore( node ) {
  23500. const index = this._currentNode ? this.nodes.indexOf( this._currentNode ) : 0;
  23501. return this.addToStack( node, index );
  23502. }
  23503. /**
  23504. * Represent an `if` statement in TSL.
  23505. *
  23506. * @param {Node} boolNode - Represents the condition.
  23507. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23508. * @return {StackNode} A reference to this stack node.
  23509. */
  23510. If( boolNode, method ) {
  23511. const methodNode = new ShaderNode( method );
  23512. this._currentCond = select( boolNode, methodNode );
  23513. return this.addToStack( this._currentCond );
  23514. }
  23515. /**
  23516. * Represent an `elseif` statement in TSL.
  23517. *
  23518. * @param {Node} boolNode - Represents the condition.
  23519. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23520. * @return {StackNode} A reference to this stack node.
  23521. */
  23522. ElseIf( boolNode, method ) {
  23523. const methodNode = new ShaderNode( method );
  23524. const ifNode = select( boolNode, methodNode );
  23525. this._currentCond.elseNode = ifNode;
  23526. this._currentCond = ifNode;
  23527. return this;
  23528. }
  23529. /**
  23530. * Represent an `else` statement in TSL.
  23531. *
  23532. * @param {Function} method - TSL code which is executed in the `else` case.
  23533. * @return {StackNode} A reference to this stack node.
  23534. */
  23535. Else( method ) {
  23536. this._currentCond.elseNode = new ShaderNode( method );
  23537. return this;
  23538. }
  23539. /**
  23540. * Represents a `switch` statement in TSL.
  23541. *
  23542. * @param {any} expression - Represents the expression.
  23543. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  23544. * @return {StackNode} A reference to this stack node.
  23545. */
  23546. Switch( expression ) {
  23547. this._expressionNode = nodeObject( expression );
  23548. return this;
  23549. }
  23550. /**
  23551. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  23552. * The last parameter must be the callback method that should be executed in the `true` case.
  23553. *
  23554. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  23555. * @return {StackNode} A reference to this stack node.
  23556. */
  23557. Case( ...params ) {
  23558. const caseNodes = [];
  23559. // extract case nodes from the parameter list
  23560. if ( params.length >= 2 ) {
  23561. for ( let i = 0; i < params.length - 1; i ++ ) {
  23562. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  23563. }
  23564. } else {
  23565. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  23566. }
  23567. // extract method
  23568. const method = params[ params.length - 1 ];
  23569. const methodNode = new ShaderNode( method );
  23570. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  23571. let caseNode = caseNodes[ 0 ];
  23572. for ( let i = 1; i < caseNodes.length; i ++ ) {
  23573. caseNode = caseNode.or( caseNodes[ i ] );
  23574. }
  23575. // build condition
  23576. const condNode = select( caseNode, methodNode );
  23577. if ( this._currentCond === null ) {
  23578. this._currentCond = condNode;
  23579. return this.addToStack( this._currentCond );
  23580. } else {
  23581. this._currentCond.elseNode = condNode;
  23582. this._currentCond = condNode;
  23583. return this;
  23584. }
  23585. }
  23586. /**
  23587. * Represents the default code block of a Switch/Case statement.
  23588. *
  23589. * @param {Function} method - TSL code which is executed in the `else` case.
  23590. * @return {StackNode} A reference to this stack node.
  23591. */
  23592. Default( method ) {
  23593. this.Else( method );
  23594. return this;
  23595. }
  23596. setup( builder ) {
  23597. const nodeProperties = builder.getNodeProperties( this );
  23598. let index = 0;
  23599. for ( const childNode of this.getChildren() ) {
  23600. if ( childNode.isVarNode && childNode.isIntent( builder ) ) {
  23601. if ( childNode.isAssign( builder ) !== true ) {
  23602. continue;
  23603. }
  23604. }
  23605. nodeProperties[ 'node' + index ++ ] = childNode;
  23606. }
  23607. // return a outputNode if exists or null
  23608. return nodeProperties.outputNode || null;
  23609. }
  23610. hasOutput( builder ) {
  23611. return this.outputNode && this.outputNode.isNode && this.outputNode.getNodeType( builder ) !== 'void';
  23612. }
  23613. build( builder, ...params ) {
  23614. const previousStack = getCurrentStack();
  23615. const buildStage = builder.buildStage;
  23616. setCurrentStack( this );
  23617. builder.setActiveStack( this );
  23618. //
  23619. const buildNode = ( node ) => {
  23620. this._currentNode = node;
  23621. if ( node.isVarNode && node.isIntent( builder ) ) {
  23622. if ( node.isAssign( builder ) !== true ) {
  23623. return;
  23624. }
  23625. }
  23626. if ( buildStage === 'setup' ) {
  23627. node.build( builder );
  23628. } else if ( buildStage === 'analyze' ) {
  23629. node.build( builder, this );
  23630. } else if ( buildStage === 'generate' ) {
  23631. const stages = builder.getDataFromNode( node, 'any' ).stages;
  23632. const parents = stages && stages[ builder.shaderStage ];
  23633. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  23634. return; // skip var nodes that are only used in .toVarying()
  23635. }
  23636. node.build( builder, 'void' );
  23637. }
  23638. };
  23639. //
  23640. const nodes = [ ...this.nodes ];
  23641. for ( const node of nodes ) {
  23642. buildNode( node );
  23643. }
  23644. this._currentNode = null;
  23645. const newNodes = this.nodes.filter( ( node ) => nodes.indexOf( node ) === -1 );
  23646. for ( const node of newNodes ) {
  23647. buildNode( node );
  23648. }
  23649. //
  23650. let result;
  23651. if ( this.hasOutput( builder ) ) {
  23652. result = this.outputNode.build( builder, ...params );
  23653. } else {
  23654. result = super.build( builder, ...params );
  23655. }
  23656. setCurrentStack( previousStack );
  23657. builder.removeActiveStack( this );
  23658. return result;
  23659. }
  23660. }
  23661. /**
  23662. * TSL function for creating a stack node.
  23663. *
  23664. * @tsl
  23665. * @function
  23666. * @param {?StackNode} [parent=null] - The parent stack node.
  23667. * @returns {StackNode}
  23668. */
  23669. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  23670. /**
  23671. * Generates a layout for struct members.
  23672. * This function takes an object representing struct members and returns an array of member layouts.
  23673. * Each member layout includes the member's name, type, and whether it is atomic.
  23674. *
  23675. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  23676. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  23677. */
  23678. function getMembersLayout( members ) {
  23679. return Object.entries( members ).map( ( [ name, value ] ) => {
  23680. if ( typeof value === 'string' ) {
  23681. return { name, type: value, atomic: false };
  23682. }
  23683. return { name, type: value.type, atomic: value.atomic || false };
  23684. } );
  23685. }
  23686. /**
  23687. * Represents a struct type node in the node-based system.
  23688. * This class is used to define and manage the layout and types of struct members.
  23689. * It extends the base Node class and provides methods to get the length of the struct,
  23690. * retrieve member types, and generate the struct type for a builder.
  23691. *
  23692. * @augments Node
  23693. */
  23694. class StructTypeNode extends Node {
  23695. static get type() {
  23696. return 'StructTypeNode';
  23697. }
  23698. /**
  23699. * Creates an instance of StructTypeNode.
  23700. *
  23701. * @param {Object} membersLayout - The layout of the members for the struct.
  23702. * @param {?string} [name=null] - The optional name of the struct.
  23703. */
  23704. constructor( membersLayout, name = null ) {
  23705. super( 'struct' );
  23706. /**
  23707. * The layout of the members for the struct
  23708. *
  23709. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  23710. */
  23711. this.membersLayout = getMembersLayout( membersLayout );
  23712. /**
  23713. * The name of the struct.
  23714. *
  23715. * @type {?string}
  23716. * @default null
  23717. */
  23718. this.name = name;
  23719. /**
  23720. * This flag can be used for type testing.
  23721. *
  23722. * @type {boolean}
  23723. * @readonly
  23724. * @default true
  23725. */
  23726. this.isStructLayoutNode = true;
  23727. }
  23728. /**
  23729. * Returns the length of the struct.
  23730. * The length is calculated by summing the lengths of the struct's members.
  23731. *
  23732. * @returns {number} The length of the struct.
  23733. */
  23734. getLength() {
  23735. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  23736. let maxAlignment = 1; // maximum alignment value in this struct
  23737. let offset = 0; // global buffer offset in 4 byte elements
  23738. for ( const member of this.membersLayout ) {
  23739. const type = member.type;
  23740. const itemSize = getMemoryLengthFromType( type );
  23741. const alignment = getAlignmentFromType( type ) / BYTES_PER_ELEMENT;
  23742. maxAlignment = Math.max( maxAlignment, alignment );
  23743. const chunkOffset = offset % maxAlignment; // offset in the current chunk of maxAlignment elements
  23744. const overhang = chunkOffset % alignment; // distance from the last aligned offset
  23745. if ( overhang !== 0 ) {
  23746. offset += alignment - overhang; // move to next aligned offset
  23747. }
  23748. offset += itemSize;
  23749. }
  23750. return ( Math.ceil( offset / maxAlignment ) * maxAlignment ); // ensure length is a multiple of maxAlignment
  23751. }
  23752. getMemberType( builder, name ) {
  23753. const member = this.membersLayout.find( m => m.name === name );
  23754. return member ? member.type : 'void';
  23755. }
  23756. getNodeType( builder ) {
  23757. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23758. return structType.name;
  23759. }
  23760. setup( builder ) {
  23761. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  23762. builder.addInclude( this );
  23763. }
  23764. generate( builder ) {
  23765. return this.getNodeType( builder );
  23766. }
  23767. }
  23768. /**
  23769. * StructNode allows to create custom structures with multiple members.
  23770. * This can also be used to define structures in attribute and uniform data.
  23771. *
  23772. * ```js
  23773. * // Define a custom struct
  23774. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  23775. *
  23776. * // Create a new instance of the struct
  23777. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  23778. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  23779. *
  23780. * // Access the struct members
  23781. * const min = bb.get( 'min' );
  23782. *
  23783. * // Assign a new value to a member
  23784. * min.assign( vec3() );
  23785. * ```
  23786. * @augments Node
  23787. */
  23788. class StructNode extends Node {
  23789. static get type() {
  23790. return 'StructNode';
  23791. }
  23792. constructor( structTypeNode, values ) {
  23793. super( 'vec3' );
  23794. this.structTypeNode = structTypeNode;
  23795. this.values = values;
  23796. this.isStructNode = true;
  23797. }
  23798. getNodeType( builder ) {
  23799. return this.structTypeNode.getNodeType( builder );
  23800. }
  23801. getMemberType( builder, name ) {
  23802. return this.structTypeNode.getMemberType( builder, name );
  23803. }
  23804. _getChildren() {
  23805. // Ensure struct type is the last child for correct code generation order
  23806. const children = super._getChildren();
  23807. const structTypeProperty = children.find( child => child.childNode === this.structTypeNode );
  23808. children.splice( children.indexOf( structTypeProperty ), 1 );
  23809. children.push( structTypeProperty );
  23810. return children;
  23811. }
  23812. generate( builder ) {
  23813. const nodeVar = builder.getVarFromNode( this );
  23814. const structType = nodeVar.type;
  23815. const propertyName = builder.getPropertyName( nodeVar );
  23816. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  23817. return nodeVar.name;
  23818. }
  23819. }
  23820. /**
  23821. * TSL function for creating a struct node.
  23822. *
  23823. * @tsl
  23824. * @function
  23825. * @param {Object} membersLayout - The layout of the struct members.
  23826. * @param {?string} [name=null] - The name of the struct.
  23827. * @returns {Function} The struct function.
  23828. */
  23829. const struct = ( membersLayout, name = null ) => {
  23830. const structLayout = new StructTypeNode( membersLayout, name );
  23831. const struct = ( ...params ) => {
  23832. let values = null;
  23833. if ( params.length > 0 ) {
  23834. if ( params[ 0 ].isNode ) {
  23835. values = {};
  23836. const names = Object.keys( membersLayout );
  23837. for ( let i = 0; i < params.length; i ++ ) {
  23838. values[ names[ i ] ] = params[ i ];
  23839. }
  23840. } else {
  23841. values = params[ 0 ];
  23842. }
  23843. }
  23844. return new StructNode( structLayout, values );
  23845. };
  23846. struct.layout = structLayout;
  23847. struct.isStruct = true;
  23848. return struct;
  23849. };
  23850. /**
  23851. * This node can be used to define multiple outputs in a shader programs.
  23852. *
  23853. * @augments Node
  23854. */
  23855. class OutputStructNode extends Node {
  23856. static get type() {
  23857. return 'OutputStructNode';
  23858. }
  23859. /**
  23860. * Constructs a new output struct node. The constructor can be invoked with an
  23861. * arbitrary number of nodes representing the members.
  23862. *
  23863. * @param {...Node} members - A parameter list of nodes.
  23864. */
  23865. constructor( ...members ) {
  23866. super();
  23867. /**
  23868. * An array of nodes which defines the output.
  23869. *
  23870. * @type {Array<Node>}
  23871. */
  23872. this.members = members;
  23873. /**
  23874. * This flag can be used for type testing.
  23875. *
  23876. * @type {boolean}
  23877. * @readonly
  23878. * @default true
  23879. */
  23880. this.isOutputStructNode = true;
  23881. }
  23882. getNodeType( /*builder*/ ) {
  23883. return 'OutputType';
  23884. }
  23885. generate( builder ) {
  23886. const nodeData = builder.getDataFromNode( this );
  23887. if ( nodeData.membersLayout === undefined ) {
  23888. const members = this.members;
  23889. const membersLayout = [];
  23890. for ( let i = 0; i < members.length; i ++ ) {
  23891. const name = 'm' + i;
  23892. const type = members[ i ].getNodeType( builder );
  23893. membersLayout.push( { name, type, index: i } );
  23894. }
  23895. nodeData.membersLayout = membersLayout;
  23896. nodeData.structType = builder.getOutputStructTypeFromNode( this, nodeData.membersLayout );
  23897. }
  23898. //
  23899. const propertyName = builder.getOutputStructName();
  23900. const members = this.members;
  23901. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23902. for ( let i = 0; i < members.length; i ++ ) {
  23903. const snippet = members[ i ].build( builder );
  23904. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23905. }
  23906. return propertyName;
  23907. }
  23908. }
  23909. /**
  23910. * TSL function for creating an output struct node.
  23911. *
  23912. * @tsl
  23913. * @function
  23914. * @param {...Node} members - A parameter list of nodes.
  23915. * @returns {OutputStructNode}
  23916. */
  23917. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23918. /**
  23919. * Represents blending configuration.
  23920. *
  23921. * This class encapsulates all blending-related properties that control how
  23922. * a material's colors are combined with the colors already in the frame buffer.
  23923. */
  23924. class BlendMode {
  23925. /**
  23926. * Constructs a new blending configuration.
  23927. *
  23928. * @param {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)} [blending=NormalBlending] - The blending mode.
  23929. */
  23930. constructor( blending = NormalBlending ) {
  23931. /**
  23932. * Defines the blending type.
  23933. *
  23934. * It must be set to `CustomBlending` if custom blending properties like
  23935. * {@link BlendMode#blendSrc}, {@link BlendMode#blendDst} or {@link BlendMode#blendEquation}
  23936. * should have any effect.
  23937. *
  23938. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending|MaterialBlending)}
  23939. * @default NormalBlending
  23940. */
  23941. this.blending = blending;
  23942. /**
  23943. * Defines the blending source factor.
  23944. *
  23945. * This determines how the source (incoming) fragment color is factored before being added
  23946. * to the destination (existing) fragment color in the frame buffer.
  23947. *
  23948. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  23949. * @default SrcAlphaFactor
  23950. */
  23951. this.blendSrc = SrcAlphaFactor;
  23952. /**
  23953. * Defines the blending destination factor.
  23954. *
  23955. * This determines how the destination (existing) fragment color in the frame buffer
  23956. * is factored before being combined with the source (incoming) fragment color.
  23957. *
  23958. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  23959. * @default OneMinusSrcAlphaFactor
  23960. */
  23961. this.blendDst = OneMinusSrcAlphaFactor;
  23962. /**
  23963. * Defines the blending equation.
  23964. *
  23965. * This determines how the source and destination colors are combined.
  23966. *
  23967. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  23968. * @default AddEquation
  23969. */
  23970. this.blendEquation = AddEquation;
  23971. /**
  23972. * Defines the blending source alpha factor.
  23973. *
  23974. * When set, this allows separate control of the alpha channel's source blending factor.
  23975. * If `null`, {@link BlendMode#blendSrc} is used for the alpha channel as well.
  23976. *
  23977. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  23978. * @default null
  23979. */
  23980. this.blendSrcAlpha = null;
  23981. /**
  23982. * Defines the blending destination alpha factor.
  23983. *
  23984. * When set, this allows separate control of the alpha channel's destination blending factor.
  23985. * If `null`, {@link BlendMode#blendDst} is used for the alpha channel as well.
  23986. *
  23987. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  23988. * @default null
  23989. */
  23990. this.blendDstAlpha = null;
  23991. /**
  23992. * Defines the blending equation of the alpha channel.
  23993. *
  23994. * When set, this allows separate control of the alpha channel's blending equation.
  23995. * If `null`, {@link BlendMode#blendEquation} is used for the alpha channel as well.
  23996. *
  23997. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  23998. * @default null
  23999. */
  24000. this.blendEquationAlpha = null;
  24001. /**
  24002. * Defines whether to premultiply the alpha (transparency) value.
  24003. *
  24004. * If `true`, the RGB color of the texture or material is multiplied by its alpha value.
  24005. * This is useful for transparent textures/materials where the color data
  24006. * should already include the transparency information.
  24007. *
  24008. * @type {boolean}
  24009. * @default false
  24010. */
  24011. this.premultiplyAlpha = false;
  24012. }
  24013. /**
  24014. * Copies the blending properties from the given source to this instance.
  24015. *
  24016. * @param {BlendMode} source - The blending configuration to copy from.
  24017. * @return {BlendMode} A reference to this instance.
  24018. */
  24019. copy( source ) {
  24020. this.blending = source.blending;
  24021. this.blendSrc = source.blendSrc;
  24022. this.blendDst = source.blendDst;
  24023. this.blendEquation = source.blendEquation;
  24024. this.blendSrcAlpha = source.blendSrcAlpha;
  24025. this.blendDstAlpha = source.blendDstAlpha;
  24026. this.blendEquationAlpha = source.blendEquationAlpha;
  24027. this.premultiplyAlpha = source.premultiplyAlpha;
  24028. return this;
  24029. }
  24030. /**
  24031. * Returns a clone of this blending configuration.
  24032. *
  24033. * @return {BlendMode} A new Blending instance with the same properties.
  24034. */
  24035. clone() {
  24036. return new this.constructor().copy( this );
  24037. }
  24038. }
  24039. // Predefined blend modes for MRT nodes.
  24040. const _noBlending = /**@__PURE__*/ new BlendMode( NoBlending );
  24041. const _materialBlending = /**@__PURE__*/ new BlendMode( MaterialBlending );
  24042. /**
  24043. * Returns the MRT texture index for the given name.
  24044. *
  24045. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  24046. * @param {string} name - The name of the MRT texture which index is requested.
  24047. * @return {number} The texture index.
  24048. */
  24049. function getTextureIndex( textures, name ) {
  24050. for ( let i = 0; i < textures.length; i ++ ) {
  24051. if ( textures[ i ].name === name ) {
  24052. return i;
  24053. }
  24054. }
  24055. return -1;
  24056. }
  24057. /**
  24058. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  24059. * post-processing is shown below:
  24060. * ```js
  24061. * const mrtNode = mrt( {
  24062. * output: output,
  24063. * normal: normalView
  24064. * } ) ;
  24065. * ```
  24066. * The MRT output is defined as a dictionary.
  24067. *
  24068. * @augments OutputStructNode
  24069. */
  24070. class MRTNode extends OutputStructNode {
  24071. static get type() {
  24072. return 'MRTNode';
  24073. }
  24074. /**
  24075. * Constructs a new output struct node.
  24076. *
  24077. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24078. */
  24079. constructor( outputNodes ) {
  24080. super();
  24081. /**
  24082. * A dictionary representing the MRT outputs. The key
  24083. * is the name of the output, the value the node which produces
  24084. * the output result.
  24085. *
  24086. * @type {Object<string, Node>}
  24087. */
  24088. this.outputNodes = outputNodes;
  24089. /**
  24090. * A dictionary storing the blend modes for each output.
  24091. *
  24092. * @type {Object<string, BlendMode>}
  24093. */
  24094. this.blendModes = {
  24095. output: _materialBlending
  24096. };
  24097. /**
  24098. * This flag can be used for type testing.
  24099. *
  24100. * @type {boolean}
  24101. * @readonly
  24102. * @default true
  24103. */
  24104. this.isMRTNode = true;
  24105. }
  24106. /**
  24107. * Sets the blend mode for the given output name.
  24108. *
  24109. * @param {string} name - The name of the output.
  24110. * @param {BlendMode} blend - The blending mode.
  24111. * @return {MRTNode} The current MRT node.
  24112. */
  24113. setBlendMode( name, blend ) {
  24114. this.blendModes[ name ] = blend;
  24115. return this;
  24116. }
  24117. /**
  24118. * Returns the blend mode for the given output name.
  24119. *
  24120. * @param {string} name - The name of the output.
  24121. * @return {BlendMode} The blend mode.
  24122. */
  24123. getBlendMode( name ) {
  24124. return this.blendModes[ name ] || _noBlending;
  24125. }
  24126. /**
  24127. * Returns `true` if the MRT node has an output with the given name.
  24128. *
  24129. * @param {string} name - The name of the output.
  24130. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  24131. */
  24132. has( name ) {
  24133. return this.outputNodes[ name ] !== undefined;
  24134. }
  24135. /**
  24136. * Returns the output node for the given name.
  24137. *
  24138. * @param {string} name - The name of the output.
  24139. * @return {Node} The output node.
  24140. */
  24141. get( name ) {
  24142. return this.outputNodes[ name ];
  24143. }
  24144. /**
  24145. * Merges the outputs of the given MRT node with the outputs of this node.
  24146. *
  24147. * @param {MRTNode} mrtNode - The MRT to merge.
  24148. * @return {MRTNode} A new MRT node with merged outputs..
  24149. */
  24150. merge( mrtNode ) {
  24151. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  24152. const blendings = { ...this.blendModes, ...mrtNode.blendModes };
  24153. const mrtTarget = mrt( outputs );
  24154. mrtTarget.blendings = blendings;
  24155. return mrtTarget;
  24156. }
  24157. setup( builder ) {
  24158. const outputNodes = this.outputNodes;
  24159. const mrt = builder.renderer.getRenderTarget();
  24160. const members = [];
  24161. const textures = mrt.textures;
  24162. for ( const name in outputNodes ) {
  24163. const index = getTextureIndex( textures, name );
  24164. members[ index ] = vec4( outputNodes[ name ] );
  24165. }
  24166. this.members = members;
  24167. return super.setup( builder );
  24168. }
  24169. }
  24170. /**
  24171. * TSL function for creating a MRT node.
  24172. *
  24173. * @tsl
  24174. * @function
  24175. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  24176. * @returns {MRTNode}
  24177. */
  24178. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  24179. /**
  24180. * This node represents an operation that reinterprets the bit representation of a value
  24181. * in one type as a value in another type.
  24182. *
  24183. * @augments TempNode
  24184. */
  24185. class BitcastNode extends TempNode {
  24186. static get type() {
  24187. return 'BitcastNode';
  24188. }
  24189. /**
  24190. * Constructs a new bitcast node.
  24191. *
  24192. * @param {Node} valueNode - The value to convert.
  24193. * @param {string} conversionType - The type to convert to.
  24194. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  24195. */
  24196. constructor( valueNode, conversionType, inputType = null ) {
  24197. super();
  24198. /**
  24199. * The data to bitcast to a new type.
  24200. *
  24201. * @type {Node}
  24202. */
  24203. this.valueNode = valueNode;
  24204. /**
  24205. * The type the value will be converted to.
  24206. *
  24207. * @type {string}
  24208. */
  24209. this.conversionType = conversionType;
  24210. /**
  24211. * The expected input data type of the bitcast operation.
  24212. *
  24213. *
  24214. * @type {string}
  24215. * @default null
  24216. */
  24217. this.inputType = inputType;
  24218. /**
  24219. * This flag can be used for type testing.
  24220. *
  24221. * @type {boolean}
  24222. * @readonly
  24223. * @default true
  24224. */
  24225. this.isBitcastNode = true;
  24226. }
  24227. getNodeType( builder ) {
  24228. // GLSL aliasing
  24229. if ( this.inputType !== null ) {
  24230. const valueType = this.valueNode.getNodeType( builder );
  24231. const valueLength = builder.getTypeLength( valueType );
  24232. return builder.getTypeFromLength( valueLength, this.conversionType );
  24233. }
  24234. return this.conversionType;
  24235. }
  24236. generate( builder ) {
  24237. const type = this.getNodeType( builder );
  24238. let inputType = '';
  24239. if ( this.inputType !== null ) {
  24240. const valueType = this.valueNode.getNodeType( builder );
  24241. const valueTypeLength = builder.getTypeLength( valueType );
  24242. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  24243. } else {
  24244. inputType = this.valueNode.getNodeType( builder );
  24245. }
  24246. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  24247. }
  24248. }
  24249. /**
  24250. * Reinterpret the bit representation of a value in one type as a value in another type.
  24251. *
  24252. * @tsl
  24253. * @function
  24254. * @param {Node | number} x - The parameter.
  24255. * @param {string} y - The new type.
  24256. * @returns {Node}
  24257. */
  24258. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  24259. /**
  24260. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  24261. *
  24262. * @tsl
  24263. * @function
  24264. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24265. * @returns {BitcastNode}
  24266. */
  24267. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  24268. /**
  24269. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  24270. *
  24271. * @tsl
  24272. * @function
  24273. * @param {Node<float>} value - The float or vector of floats to bitcast.
  24274. * @returns {BitcastNode}
  24275. */
  24276. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  24277. /**
  24278. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  24279. *
  24280. * @tsl
  24281. * @function
  24282. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  24283. * @returns {BitcastNode}
  24284. */
  24285. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  24286. /**
  24287. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  24288. *
  24289. * @tsl
  24290. * @function
  24291. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  24292. * @returns {BitcastNode}
  24293. */
  24294. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  24295. const registeredBitcountFunctions = {};
  24296. /**
  24297. * This node represents an operation that counts the bits of a piece of shader data.
  24298. *
  24299. * @augments MathNode
  24300. */
  24301. class BitcountNode extends MathNode {
  24302. static get type() {
  24303. return 'BitcountNode';
  24304. }
  24305. /**
  24306. * Constructs a new math node.
  24307. *
  24308. * @param {'countTrailingZeros'|'countLeadingZeros'|'countOneBits'} method - The method name.
  24309. * @param {Node} aNode - The first input.
  24310. */
  24311. constructor( method, aNode ) {
  24312. super( method, aNode );
  24313. /**
  24314. * This flag can be used for type testing.
  24315. *
  24316. * @type {boolean}
  24317. * @readonly
  24318. * @default true
  24319. */
  24320. this.isBitcountNode = true;
  24321. }
  24322. /**
  24323. * Casts the input value of the function to an integer if necessary.
  24324. *
  24325. * @private
  24326. * @param {Node<uint>|Node<int>} inputNode - The input value.
  24327. * @param {Node<uint>} outputNode - The output value.
  24328. * @param {string} elementType - The type of the input value.
  24329. */
  24330. _resolveElementType( inputNode, outputNode, elementType ) {
  24331. if ( elementType === 'int' ) {
  24332. outputNode.assign( bitcast( inputNode, 'uint' ) );
  24333. } else {
  24334. outputNode.assign( inputNode );
  24335. }
  24336. }
  24337. _returnDataNode( inputType ) {
  24338. switch ( inputType ) {
  24339. case 'uint': {
  24340. return uint;
  24341. }
  24342. case 'int': {
  24343. return int;
  24344. }
  24345. case 'uvec2': {
  24346. return uvec2;
  24347. }
  24348. case 'uvec3': {
  24349. return uvec3;
  24350. }
  24351. case 'uvec4': {
  24352. return uvec4;
  24353. }
  24354. case 'ivec2': {
  24355. return ivec2;
  24356. }
  24357. case 'ivec3': {
  24358. return ivec3;
  24359. }
  24360. case 'ivec4': {
  24361. return ivec4;
  24362. }
  24363. }
  24364. }
  24365. /**
  24366. * Creates and registers a reusable GLSL function that emulates the behavior of countTrailingZeros.
  24367. *
  24368. * @private
  24369. * @param {string} method - The name of the function to create.
  24370. * @param {string} elementType - The type of the input value.
  24371. * @returns {Function} - The generated function
  24372. */
  24373. _createTrailingZerosBaseLayout( method, elementType ) {
  24374. const outputConvertNode = this._returnDataNode( elementType );
  24375. const fnDef = Fn( ( [ value ] ) => {
  24376. const v = uint( 0.0 );
  24377. this._resolveElementType( value, v, elementType );
  24378. const f = float( v.bitAnd( negate( v ) ) );
  24379. const uintBits = floatBitsToUint( f );
  24380. const numTrailingZeros = ( uintBits.shiftRight( 23 ) ).sub( 127 );
  24381. return outputConvertNode( numTrailingZeros );
  24382. } ).setLayout( {
  24383. name: method,
  24384. type: elementType,
  24385. inputs: [
  24386. { name: 'value', type: elementType }
  24387. ]
  24388. } );
  24389. return fnDef;
  24390. }
  24391. /**
  24392. * Creates and registers a reusable GLSL function that emulates the behavior of countLeadingZeros.
  24393. *
  24394. * @private
  24395. * @param {string} method - The name of the function to create.
  24396. * @param {string} elementType - The type of the input value.
  24397. * @returns {Function} - The generated function
  24398. */
  24399. _createLeadingZerosBaseLayout( method, elementType ) {
  24400. const outputConvertNode = this._returnDataNode( elementType );
  24401. const fnDef = Fn( ( [ value ] ) => {
  24402. If( value.equal( uint( 0 ) ), () => {
  24403. return uint( 32 );
  24404. } );
  24405. const v = uint( 0 );
  24406. const n = uint( 0 );
  24407. this._resolveElementType( value, v, elementType );
  24408. If( v.shiftRight( 16 ).equal( 0 ), () => {
  24409. n.addAssign( 16 );
  24410. v.shiftLeftAssign( 16 );
  24411. } );
  24412. If( v.shiftRight( 24 ).equal( 0 ), () => {
  24413. n.addAssign( 8 );
  24414. v.shiftLeftAssign( 8 );
  24415. } );
  24416. If( v.shiftRight( 28 ).equal( 0 ), () => {
  24417. n.addAssign( 4 );
  24418. v.shiftLeftAssign( 4 );
  24419. } );
  24420. If( v.shiftRight( 30 ).equal( 0 ), () => {
  24421. n.addAssign( 2 );
  24422. v.shiftLeftAssign( 2 );
  24423. } );
  24424. If( v.shiftRight( 31 ).equal( 0 ), () => {
  24425. n.addAssign( 1 );
  24426. } );
  24427. return outputConvertNode( n );
  24428. } ).setLayout( {
  24429. name: method,
  24430. type: elementType,
  24431. inputs: [
  24432. { name: 'value', type: elementType }
  24433. ]
  24434. } );
  24435. return fnDef;
  24436. }
  24437. /**
  24438. * Creates and registers a reusable GLSL function that emulates the behavior of countOneBits.
  24439. *
  24440. * @private
  24441. * @param {string} method - The name of the function to create.
  24442. * @param {string} elementType - The type of the input value.
  24443. * @returns {Function} - The generated function
  24444. */
  24445. _createOneBitsBaseLayout( method, elementType ) {
  24446. const outputConvertNode = this._returnDataNode( elementType );
  24447. const fnDef = Fn( ( [ value ] ) => {
  24448. const v = uint( 0.0 );
  24449. this._resolveElementType( value, v, elementType );
  24450. v.assign( v.sub( v.shiftRight( uint( 1 ) ).bitAnd( uint( 0x55555555 ) ) ) );
  24451. v.assign( v.bitAnd( uint( 0x33333333 ) ).add( v.shiftRight( uint( 2 ) ).bitAnd( uint( 0x33333333 ) ) ) );
  24452. const numBits = v.add( v.shiftRight( uint( 4 ) ) ).bitAnd( uint( 0xF0F0F0F ) ).mul( uint( 0x1010101 ) ).shiftRight( uint( 24 ) );
  24453. return outputConvertNode( numBits );
  24454. } ).setLayout( {
  24455. name: method,
  24456. type: elementType,
  24457. inputs: [
  24458. { name: 'value', type: elementType }
  24459. ]
  24460. } );
  24461. return fnDef;
  24462. }
  24463. /**
  24464. * Creates and registers a reusable GLSL function that emulates the behavior of the specified bitcount function.
  24465. * including considerations for component-wise bitcounts on vector type inputs.
  24466. *
  24467. * @private
  24468. * @param {string} method - The name of the function to create.
  24469. * @param {string} inputType - The type of the input value.
  24470. * @param {number} typeLength - The vec length of the input value.
  24471. * @param {Function} baseFn - The base function that operates on an individual component of the vector.
  24472. * @returns {Function} - The alias function for the specified bitcount method.
  24473. */
  24474. _createMainLayout( method, inputType, typeLength, baseFn ) {
  24475. const outputConvertNode = this._returnDataNode( inputType );
  24476. const fnDef = Fn( ( [ value ] ) => {
  24477. if ( typeLength === 1 ) {
  24478. return outputConvertNode( baseFn( value ) );
  24479. } else {
  24480. const vec = outputConvertNode( 0 );
  24481. const components = [ 'x', 'y', 'z', 'w' ];
  24482. for ( let i = 0; i < typeLength; i ++ ) {
  24483. const component = components[ i ];
  24484. vec[ component ].assign( baseFn( value[ component ] ) );
  24485. }
  24486. return vec;
  24487. }
  24488. } ).setLayout( {
  24489. name: method,
  24490. type: inputType,
  24491. inputs: [
  24492. { name: 'value', type: inputType }
  24493. ]
  24494. } );
  24495. return fnDef;
  24496. }
  24497. setup( builder ) {
  24498. const { method, aNode } = this;
  24499. const { renderer } = builder;
  24500. if ( renderer.backend.isWebGPUBackend ) {
  24501. // use built-in WGSL functions for WebGPU
  24502. return super.setup( builder );
  24503. }
  24504. const inputType = this.getInputType( builder );
  24505. const elementType = builder.getElementType( inputType );
  24506. const typeLength = builder.getTypeLength( inputType );
  24507. const baseMethod = `${method}_base_${elementType}`;
  24508. const newMethod = `${method}_${inputType}`;
  24509. let baseFn = registeredBitcountFunctions[ baseMethod ];
  24510. if ( baseFn === undefined ) {
  24511. switch ( method ) {
  24512. case BitcountNode.COUNT_LEADING_ZEROS: {
  24513. baseFn = this._createLeadingZerosBaseLayout( baseMethod, elementType );
  24514. break;
  24515. }
  24516. case BitcountNode.COUNT_TRAILING_ZEROS: {
  24517. baseFn = this._createTrailingZerosBaseLayout( baseMethod, elementType );
  24518. break;
  24519. }
  24520. case BitcountNode.COUNT_ONE_BITS: {
  24521. baseFn = this._createOneBitsBaseLayout( baseMethod, elementType );
  24522. break;
  24523. }
  24524. }
  24525. registeredBitcountFunctions[ baseMethod ] = baseFn;
  24526. }
  24527. let fn = registeredBitcountFunctions[ newMethod ];
  24528. if ( fn === undefined ) {
  24529. fn = this._createMainLayout( newMethod, inputType, typeLength, baseFn );
  24530. registeredBitcountFunctions[ newMethod ] = fn;
  24531. }
  24532. const output = Fn( () => {
  24533. return fn(
  24534. aNode,
  24535. );
  24536. } );
  24537. return output();
  24538. }
  24539. }
  24540. BitcountNode.COUNT_TRAILING_ZEROS = 'countTrailingZeros';
  24541. BitcountNode.COUNT_LEADING_ZEROS = 'countLeadingZeros';
  24542. BitcountNode.COUNT_ONE_BITS = 'countOneBits';
  24543. /**
  24544. * Finds the number of consecutive 0 bits from the least significant bit of the input value,
  24545. * which is also the index of the least significant bit of the input value.
  24546. *
  24547. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24548. *
  24549. * @tsl
  24550. * @function
  24551. * @param {Node | number} x - The input value.
  24552. * @returns {Node}
  24553. */
  24554. const countTrailingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_TRAILING_ZEROS ).setParameterLength( 1 );
  24555. /**
  24556. * Finds the number of consecutive 0 bits starting from the most significant bit of the input value.
  24557. *
  24558. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24559. *
  24560. * @tsl
  24561. * @function
  24562. * @param {Node | number} x - The input value.
  24563. * @returns {Node}
  24564. */
  24565. const countLeadingZeros = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_LEADING_ZEROS ).setParameterLength( 1 );
  24566. /**
  24567. * Finds the number of '1' bits set in the input value
  24568. *
  24569. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  24570. *
  24571. * @tsl
  24572. * @function
  24573. * @returns {Node}
  24574. */
  24575. const countOneBits = /*@__PURE__*/ nodeProxyIntent( BitcountNode, BitcountNode.COUNT_ONE_BITS ).setParameterLength( 1 );
  24576. /**
  24577. * Generates a hash value in the range `[0, 1]` from the given seed.
  24578. *
  24579. * @tsl
  24580. * @function
  24581. * @param {Node<float>} seed - The seed.
  24582. * @return {Node<float>} The hash value.
  24583. */
  24584. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  24585. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  24586. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  24587. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  24588. const result = word.shiftRight( 22 ).bitXor( word );
  24589. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  24590. } );
  24591. /**
  24592. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24593. * The corners are mapped to `0` and the center to `1`.
  24594. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24595. *
  24596. * @tsl
  24597. * @function
  24598. * @param {Node<float>} x - The value to remap.
  24599. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  24600. * @return {Node<float>} The remapped value.
  24601. */
  24602. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  24603. /**
  24604. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24605. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  24606. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24607. *
  24608. * @tsl
  24609. * @function
  24610. * @param {Node<float>} x - The value to remap.
  24611. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  24612. * @return {Node<float>} The remapped value.
  24613. */
  24614. 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 ) );
  24615. /**
  24616. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  24617. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  24618. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24619. *
  24620. * @tsl
  24621. * @function
  24622. * @param {Node<float>} x - The value to remap.
  24623. * @param {Node<float>} a - First control parameter.
  24624. * @param {Node<float>} b - Second control parameter.
  24625. * @return {Node<float>} The remapped value.
  24626. */
  24627. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  24628. /**
  24629. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  24630. * Reference: {@link https://iquilezles.org/articles/functions/}.
  24631. *
  24632. * @tsl
  24633. * @function
  24634. * @param {Node<float>} x - The value to compute the sin for.
  24635. * @param {Node<float>} k - Controls the amount of bounces.
  24636. * @return {Node<float>} The result value.
  24637. */
  24638. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  24639. /**
  24640. * This node represents an operation that packs floating-point values of a vector into an unsigned 32-bit integer
  24641. *
  24642. * @augments TempNode
  24643. */
  24644. class PackFloatNode extends TempNode {
  24645. static get type() {
  24646. return 'PackFloatNode';
  24647. }
  24648. /**
  24649. *
  24650. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  24651. * @param {Node} vectorNode - The vector node to be packed
  24652. */
  24653. constructor( encoding, vectorNode ) {
  24654. super();
  24655. /**
  24656. * The vector to be packed.
  24657. *
  24658. * @type {Node}
  24659. */
  24660. this.vectorNode = vectorNode;
  24661. /**
  24662. * The numeric encoding.
  24663. *
  24664. * @type {string}
  24665. */
  24666. this.encoding = encoding;
  24667. /**
  24668. * This flag can be used for type testing.
  24669. *
  24670. * @type {boolean}
  24671. * @readonly
  24672. * @default true
  24673. */
  24674. this.isPackFloatNode = true;
  24675. }
  24676. getNodeType() {
  24677. return 'uint';
  24678. }
  24679. generate( builder ) {
  24680. const inputType = this.vectorNode.getNodeType( builder );
  24681. return `${ builder.getFloatPackingMethod( this.encoding ) }(${ this.vectorNode.build( builder, inputType )})`;
  24682. }
  24683. }
  24684. /**
  24685. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24686. * round(clamp(c, -1, +1) * 32767.0)
  24687. *
  24688. * @tsl
  24689. * @function
  24690. * @param {Node<vec2>} value - The 2-component vector to be packed
  24691. * @returns {Node}
  24692. */
  24693. const packSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'snorm' ).setParameterLength( 1 );
  24694. /**
  24695. * Converts each component of the normalized float to 16-bit integer values. The results are packed into a single unsigned integer.
  24696. * round(clamp(c, 0, +1) * 65535.0)
  24697. *
  24698. * @tsl
  24699. * @function
  24700. * @param {Node<vec2>} value - The 2-component vector to be packed
  24701. * @returns {Node}
  24702. */
  24703. const packUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'unorm' ).setParameterLength( 1 );
  24704. /**
  24705. * Converts each component of the vec2 to 16-bit floating-point values. The results are packed into a single unsigned integer.
  24706. *
  24707. * @tsl
  24708. * @function
  24709. * @param {Node<vec2>} value - The 2-component vector to be packed
  24710. * @returns {Node}
  24711. */
  24712. const packHalf2x16 = /*@__PURE__*/ nodeProxyIntent( PackFloatNode, 'float16' ).setParameterLength( 1 );
  24713. /**
  24714. * This node represents an operation that unpacks values from a 32-bit unsigned integer, reinterpreting the results as a floating-point vector
  24715. *
  24716. * @augments TempNode
  24717. */
  24718. class UnpackFloatNode extends TempNode {
  24719. static get type() {
  24720. return 'UnpackFloatNode';
  24721. }
  24722. /**
  24723. *
  24724. * @param {'snorm' | 'unorm' | 'float16'} encoding - The numeric encoding that describes how the integer values are mapped to the float range
  24725. * @param {Node} uintNode - The uint node to be unpacked
  24726. */
  24727. constructor( encoding, uintNode ) {
  24728. super();
  24729. /**
  24730. * The unsigned integer to be unpacked.
  24731. *
  24732. * @type {Node}
  24733. */
  24734. this.uintNode = uintNode;
  24735. /**
  24736. * The numeric encoding.
  24737. *
  24738. * @type {string}
  24739. */
  24740. this.encoding = encoding;
  24741. /**
  24742. * This flag can be used for type testing.
  24743. *
  24744. * @type {boolean}
  24745. * @readonly
  24746. * @default true
  24747. */
  24748. this.isUnpackFloatNode = true;
  24749. }
  24750. getNodeType() {
  24751. return 'vec2';
  24752. }
  24753. generate( builder ) {
  24754. const inputType = this.uintNode.getNodeType( builder );
  24755. return `${ builder.getFloatUnpackingMethod( this.encoding ) }(${ this.uintNode.build( builder, inputType )})`;
  24756. }
  24757. }
  24758. /**
  24759. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized signed integers. Returns a vec2 with both values.
  24760. *
  24761. * @tsl
  24762. * @function
  24763. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24764. * @returns {Node}
  24765. */
  24766. const unpackSnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'snorm' ).setParameterLength( 1 );
  24767. /**
  24768. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as normalized unsigned integers. Returns a vec2 with both values.
  24769. *
  24770. * @tsl
  24771. * @function
  24772. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24773. * @returns {Node}
  24774. */
  24775. const unpackUnorm2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'unorm' ).setParameterLength( 1 );
  24776. /**
  24777. * Unpacks a 32-bit unsigned integer into two 16-bit values, interpreted as 16-bit floating-point numbers. Returns a vec2 with both values.
  24778. *
  24779. * @tsl
  24780. * @function
  24781. * @param {Node<uint>} value - The unsigned integer to be unpacked
  24782. * @returns {Node}
  24783. */
  24784. const unpackHalf2x16 = /*@__PURE__*/ nodeProxyIntent( UnpackFloatNode, 'float16' ).setParameterLength( 1 );
  24785. // https://github.com/cabbibo/glsl-tri-noise-3d
  24786. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  24787. return x.fract().sub( .5 ).abs();
  24788. } ).setLayout( {
  24789. name: 'tri',
  24790. type: 'float',
  24791. inputs: [
  24792. { name: 'x', type: 'float' }
  24793. ]
  24794. } );
  24795. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  24796. 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. ) ) ) ) );
  24797. } ).setLayout( {
  24798. name: 'tri3',
  24799. type: 'vec3',
  24800. inputs: [
  24801. { name: 'p', type: 'vec3' }
  24802. ]
  24803. } );
  24804. /**
  24805. * Generates a noise value from the given position, speed and time parameters.
  24806. *
  24807. * @tsl
  24808. * @function
  24809. * @param {Node<vec3>} position - The position.
  24810. * @param {Node<float>} speed - The speed.
  24811. * @param {Node<float>} time - The time.
  24812. * @return {Node<float>} The generated noise.
  24813. */
  24814. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  24815. const p = vec3( position ).toVar();
  24816. const z = float( 1.4 ).toVar();
  24817. const rz = float( 0.0 ).toVar();
  24818. const bp = vec3( p ).toVar();
  24819. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  24820. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  24821. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  24822. bp.mulAssign( 1.8 );
  24823. z.mulAssign( 1.5 );
  24824. p.mulAssign( 1.2 );
  24825. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  24826. rz.addAssign( t.div( z ) );
  24827. bp.addAssign( 0.14 );
  24828. } );
  24829. return rz;
  24830. } ).setLayout( {
  24831. name: 'triNoise3D',
  24832. type: 'float',
  24833. inputs: [
  24834. { name: 'position', type: 'vec3' },
  24835. { name: 'speed', type: 'float' },
  24836. { name: 'time', type: 'float' }
  24837. ]
  24838. } );
  24839. /**
  24840. * This class allows to define multiple overloaded versions
  24841. * of the same function. Depending on the parameters of the function
  24842. * call, the node picks the best-fit overloaded version.
  24843. *
  24844. * @augments Node
  24845. */
  24846. class FunctionOverloadingNode extends Node {
  24847. static get type() {
  24848. return 'FunctionOverloadingNode';
  24849. }
  24850. /**
  24851. * Constructs a new function overloading node.
  24852. *
  24853. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24854. * @param {...Node} parametersNodes - A list of parameter nodes.
  24855. */
  24856. constructor( functionNodes = [], ...parametersNodes ) {
  24857. super();
  24858. /**
  24859. * Array of `Fn` function definitions.
  24860. *
  24861. * @type {Array<Function>}
  24862. */
  24863. this.functionNodes = functionNodes;
  24864. /**
  24865. * A list of parameter nodes.
  24866. *
  24867. * @type {Array<Node>}
  24868. */
  24869. this.parametersNodes = parametersNodes;
  24870. /**
  24871. * The selected overloaded function call.
  24872. *
  24873. * @private
  24874. * @type {ShaderCallNodeInternal}
  24875. */
  24876. this._candidateFn = null;
  24877. /**
  24878. * This node is marked as global.
  24879. *
  24880. * @type {boolean}
  24881. * @default true
  24882. */
  24883. this.global = true;
  24884. }
  24885. /**
  24886. * This method is overwritten since the node type is inferred from
  24887. * the function's return type.
  24888. *
  24889. * @param {NodeBuilder} builder - The current node builder.
  24890. * @return {string} The node type.
  24891. */
  24892. getNodeType( builder ) {
  24893. const candidateFn = this.getCandidateFn( builder );
  24894. return candidateFn.shaderNode.layout.type;
  24895. }
  24896. /**
  24897. * Returns the candidate function for the current parameters.
  24898. *
  24899. * @param {NodeBuilder} builder - The current node builder.
  24900. * @return {FunctionNode} The candidate function.
  24901. */
  24902. getCandidateFn( builder ) {
  24903. const params = this.parametersNodes;
  24904. let candidateFn = this._candidateFn;
  24905. if ( candidateFn === null ) {
  24906. let bestCandidateFn = null;
  24907. let bestScore = -1;
  24908. for ( const functionNode of this.functionNodes ) {
  24909. const shaderNode = functionNode.shaderNode;
  24910. const layout = shaderNode.layout;
  24911. if ( layout === null ) {
  24912. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  24913. }
  24914. const inputs = layout.inputs;
  24915. if ( params.length === inputs.length ) {
  24916. let currentScore = 0;
  24917. for ( let i = 0; i < params.length; i ++ ) {
  24918. const param = params[ i ];
  24919. const input = inputs[ i ];
  24920. if ( param.getNodeType( builder ) === input.type ) {
  24921. currentScore ++;
  24922. }
  24923. }
  24924. if ( currentScore > bestScore ) {
  24925. bestCandidateFn = functionNode;
  24926. bestScore = currentScore;
  24927. }
  24928. }
  24929. }
  24930. this._candidateFn = candidateFn = bestCandidateFn;
  24931. }
  24932. return candidateFn;
  24933. }
  24934. /**
  24935. * Sets up the node for the current parameters.
  24936. *
  24937. * @param {NodeBuilder} builder - The current node builder.
  24938. * @return {Node} The setup node.
  24939. */
  24940. setup( builder ) {
  24941. const candidateFn = this.getCandidateFn( builder );
  24942. return candidateFn( ...this.parametersNodes );
  24943. }
  24944. }
  24945. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  24946. /**
  24947. * TSL function for creating a function overloading node.
  24948. *
  24949. * @tsl
  24950. * @function
  24951. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  24952. * @returns {FunctionOverloadingNode}
  24953. */
  24954. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  24955. /**
  24956. * Represents the elapsed time in seconds.
  24957. *
  24958. * @tsl
  24959. * @type {UniformNode<float>}
  24960. */
  24961. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  24962. /**
  24963. * Represents the delta time in seconds.
  24964. *
  24965. * @tsl
  24966. * @type {UniformNode<float>}
  24967. */
  24968. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  24969. /**
  24970. * Represents the current frame ID.
  24971. *
  24972. * @tsl
  24973. * @type {UniformNode<uint>}
  24974. */
  24975. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  24976. /**
  24977. * Generates a sine wave oscillation based on a timer.
  24978. *
  24979. * @tsl
  24980. * @function
  24981. * @param {Node<float>} t - The timer to generate the oscillation with.
  24982. * @return {Node<float>} The oscillation node.
  24983. */
  24984. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  24985. /**
  24986. * Generates a square wave oscillation based on a timer.
  24987. *
  24988. * @tsl
  24989. * @function
  24990. * @param {Node<float>} t - The timer to generate the oscillation with.
  24991. * @return {Node<float>} The oscillation node.
  24992. */
  24993. const oscSquare = ( t = time ) => t.fract().round();
  24994. /**
  24995. * Generates a triangle wave oscillation based on a timer.
  24996. *
  24997. * @tsl
  24998. * @function
  24999. * @param {Node<float>} t - The timer to generate the oscillation with.
  25000. * @return {Node<float>} The oscillation node.
  25001. */
  25002. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  25003. /**
  25004. * Generates a sawtooth wave oscillation based on a timer.
  25005. *
  25006. * @tsl
  25007. * @function
  25008. * @param {Node<float>} t - The timer to generate the oscillation with.
  25009. * @return {Node<float>} The oscillation node.
  25010. */
  25011. const oscSawtooth = ( t = time ) => t.fract();
  25012. /**
  25013. * Replaces the default UV coordinates used in texture lookups.
  25014. *
  25015. * ```js
  25016. *material.contextNode = replaceDefaultUV( ( textureNode ) => {
  25017. *
  25018. * // ...
  25019. * return customUVCoordinates;
  25020. *
  25021. *} );
  25022. *```
  25023. *
  25024. * @tsl
  25025. * @function
  25026. * @param {function(Node):Node<vec2>} callback - A callback that receives the texture node
  25027. * and must return the new uv coordinates.
  25028. * @param {Node} [node=null] - An optional node to which the context will be applied.
  25029. * @return {ContextNode} A context node that replaces the default UV coordinates.
  25030. */
  25031. function replaceDefaultUV( callback, node = null ) {
  25032. return context( node, { getUV: callback } );
  25033. }
  25034. /**
  25035. * Rotates the given uv coordinates around a center point
  25036. *
  25037. * @tsl
  25038. * @function
  25039. * @param {Node<vec2>} uv - The uv coordinates.
  25040. * @param {Node<float>} rotation - The rotation defined in radians.
  25041. * @param {Node<vec2>} center - The center of rotation
  25042. * @return {Node<vec2>} The rotated uv coordinates.
  25043. */
  25044. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  25045. return rotate( uv.sub( center ), rotation ).add( center );
  25046. } );
  25047. /**
  25048. * Applies a spherical warping effect to the given uv coordinates.
  25049. *
  25050. * @tsl
  25051. * @function
  25052. * @param {Node<vec2>} uv - The uv coordinates.
  25053. * @param {Node<float>} strength - The strength of the effect.
  25054. * @param {Node<vec2>} center - The center point
  25055. * @return {Node<vec2>} The updated uv coordinates.
  25056. */
  25057. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  25058. const delta = uv.sub( center );
  25059. const delta2 = delta.dot( delta );
  25060. const delta4 = delta2.mul( delta2 );
  25061. const deltaOffset = delta4.mul( strength );
  25062. return uv.add( delta.mul( deltaOffset ) );
  25063. } );
  25064. /**
  25065. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  25066. * oriented always towards the camera.
  25067. *
  25068. * ```js
  25069. * material.vertexNode = billboarding();
  25070. * ```
  25071. *
  25072. * @tsl
  25073. * @function
  25074. * @param {Object} config - The configuration object.
  25075. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  25076. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  25077. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  25078. * @return {Node<vec3>} The updated vertex position in clip space.
  25079. */
  25080. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  25081. let worldMatrix;
  25082. if ( position !== null ) {
  25083. worldMatrix = modelWorldMatrix.toVar();
  25084. worldMatrix[ 3 ][ 0 ] = position.x;
  25085. worldMatrix[ 3 ][ 1 ] = position.y;
  25086. worldMatrix[ 3 ][ 2 ] = position.z;
  25087. } else {
  25088. worldMatrix = modelWorldMatrix;
  25089. }
  25090. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  25091. if ( defined( horizontal ) ) {
  25092. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  25093. modelViewMatrix[ 0 ][ 1 ] = 0;
  25094. modelViewMatrix[ 0 ][ 2 ] = 0;
  25095. }
  25096. if ( defined( vertical ) ) {
  25097. modelViewMatrix[ 1 ][ 0 ] = 0;
  25098. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  25099. modelViewMatrix[ 1 ][ 2 ] = 0;
  25100. }
  25101. modelViewMatrix[ 2 ][ 0 ] = 0;
  25102. modelViewMatrix[ 2 ][ 1 ] = 0;
  25103. modelViewMatrix[ 2 ][ 2 ] = 1;
  25104. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25105. } );
  25106. /**
  25107. * A special version of a screen uv function that involves a depth comparison
  25108. * when computing the final uvs. The function mitigates visual errors when
  25109. * using viewport texture nodes for refraction purposes. Without this function
  25110. * objects in front of a refractive surface might appear on the refractive surface
  25111. * which is incorrect.
  25112. *
  25113. * @tsl
  25114. * @function
  25115. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  25116. * @return {Node<vec2>} The update uv coordinates.
  25117. */
  25118. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  25119. const depth = linearDepth();
  25120. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  25121. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  25122. return finalUV;
  25123. } );
  25124. /**
  25125. * TSL function for computing texture coordinates for animated sprite sheets.
  25126. *
  25127. * ```js
  25128. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  25129. *
  25130. * material.colorNode = texture( spriteSheet, uvNode );
  25131. * ```
  25132. *
  25133. * @tsl
  25134. * @function
  25135. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  25136. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  25137. * @param {?Node<float>} [frameNode=float(0)] - The node that defines the current frame/sprite.
  25138. * @returns {Node<vec2>}
  25139. */
  25140. const spritesheetUV = /*@__PURE__*/ Fn( ( [ countNode, uvNode = uv$1(), frameNode = float( 0 ) ] ) => {
  25141. const width = countNode.x;
  25142. const height = countNode.y;
  25143. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  25144. const column = frameNum.mod( width );
  25145. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  25146. const scale = countNode.reciprocal();
  25147. const uvFrameOffset = vec2( column, row );
  25148. return uvNode.add( uvFrameOffset ).mul( scale );
  25149. } );
  25150. /**
  25151. * TSL function for creating a triplanar textures node.
  25152. *
  25153. * Can be used for triplanar texture mapping.
  25154. *
  25155. * ```js
  25156. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  25157. * ```
  25158. *
  25159. * @tsl
  25160. * @function
  25161. * @param {Node} textureXNode - First texture node.
  25162. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25163. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25164. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25165. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25166. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25167. * @returns {Node<vec4>}
  25168. */
  25169. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  25170. // Reference: https://github.com/keijiro/StandardTriplanar
  25171. // Blending factor of triplanar mapping
  25172. let bf = normalNode.abs().normalize();
  25173. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  25174. // Triplanar mapping
  25175. const tx = positionNode.yz.mul( scaleNode );
  25176. const ty = positionNode.zx.mul( scaleNode );
  25177. const tz = positionNode.xy.mul( scaleNode );
  25178. // Base color
  25179. const textureX = textureXNode.value;
  25180. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  25181. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  25182. const cx = texture( textureX, tx ).mul( bf.x );
  25183. const cy = texture( textureY, ty ).mul( bf.y );
  25184. const cz = texture( textureZ, tz ).mul( bf.z );
  25185. return add( cx, cy, cz );
  25186. } );
  25187. /**
  25188. * TSL function for creating a triplanar textures node.
  25189. *
  25190. * @tsl
  25191. * @function
  25192. * @param {Node} textureXNode - First texture node.
  25193. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  25194. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  25195. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  25196. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  25197. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  25198. * @returns {Node<vec4>}
  25199. */
  25200. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  25201. const _reflectorPlane = new Plane();
  25202. const _normal = new Vector3();
  25203. const _reflectorWorldPosition = new Vector3();
  25204. const _cameraWorldPosition = new Vector3();
  25205. const _rotationMatrix = new Matrix4();
  25206. const _lookAtPosition = new Vector3( 0, 0, -1 );
  25207. const clipPlane = new Vector4();
  25208. const _view = new Vector3();
  25209. const _target = new Vector3();
  25210. const _q = new Vector4();
  25211. const _size$2 = new Vector2();
  25212. const _defaultRT = new RenderTarget();
  25213. const _defaultUV = screenUV.flipX();
  25214. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  25215. let _inReflector = false;
  25216. /**
  25217. * This node can be used to implement mirror-like flat reflective surfaces.
  25218. *
  25219. * ```js
  25220. * const groundReflector = reflector();
  25221. * material.colorNode = groundReflector;
  25222. *
  25223. * const plane = new Mesh( geometry, material );
  25224. * plane.add( groundReflector.target );
  25225. * ```
  25226. *
  25227. * @augments TextureNode
  25228. */
  25229. class ReflectorNode extends TextureNode {
  25230. static get type() {
  25231. return 'ReflectorNode';
  25232. }
  25233. /**
  25234. * Constructs a new reflector node.
  25235. *
  25236. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25237. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25238. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25239. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25240. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25241. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25242. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25243. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25244. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25245. */
  25246. constructor( parameters = {} ) {
  25247. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  25248. /**
  25249. * A reference to the internal reflector base node which holds the actual implementation.
  25250. *
  25251. * @private
  25252. * @type {ReflectorBaseNode}
  25253. * @default ReflectorBaseNode
  25254. */
  25255. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  25256. /**
  25257. * A reference to the internal depth node.
  25258. *
  25259. * @private
  25260. * @type {?Node}
  25261. * @default null
  25262. */
  25263. this._depthNode = null;
  25264. this.setUpdateMatrix( false );
  25265. }
  25266. /**
  25267. * A reference to the internal reflector node.
  25268. *
  25269. * @type {ReflectorBaseNode}
  25270. */
  25271. get reflector() {
  25272. return this._reflectorBaseNode;
  25273. }
  25274. /**
  25275. * A reference to 3D object the reflector is linked to.
  25276. *
  25277. * @type {Object3D}
  25278. */
  25279. get target() {
  25280. return this._reflectorBaseNode.target;
  25281. }
  25282. /**
  25283. * Returns a node representing the mirror's depth. That can be used
  25284. * to implement more advanced reflection effects like distance attenuation.
  25285. *
  25286. * @return {Node} The depth node.
  25287. */
  25288. getDepthNode() {
  25289. if ( this._depthNode === null ) {
  25290. if ( this._reflectorBaseNode.depth !== true ) {
  25291. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  25292. }
  25293. this._depthNode = nodeObject( new ReflectorNode( {
  25294. defaultTexture: _defaultRT.depthTexture,
  25295. reflector: this._reflectorBaseNode
  25296. } ) );
  25297. }
  25298. return this._depthNode;
  25299. }
  25300. setup( builder ) {
  25301. // ignore if used in post-processing
  25302. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  25303. return super.setup( builder );
  25304. }
  25305. clone() {
  25306. const newNode = new this.constructor( this.reflectorNode );
  25307. newNode.uvNode = this.uvNode;
  25308. newNode.levelNode = this.levelNode;
  25309. newNode.biasNode = this.biasNode;
  25310. newNode.sampler = this.sampler;
  25311. newNode.depthNode = this.depthNode;
  25312. newNode.compareNode = this.compareNode;
  25313. newNode.gradNode = this.gradNode;
  25314. newNode.offsetNode = this.offsetNode;
  25315. newNode._reflectorBaseNode = this._reflectorBaseNode;
  25316. return newNode;
  25317. }
  25318. /**
  25319. * Frees internal resources. Should be called when the node is no longer in use.
  25320. */
  25321. dispose() {
  25322. super.dispose();
  25323. this._reflectorBaseNode.dispose();
  25324. }
  25325. }
  25326. /**
  25327. * Holds the actual implementation of the reflector.
  25328. *
  25329. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  25330. * in `ReflectorNode`, see #29619.
  25331. *
  25332. * @private
  25333. * @augments Node
  25334. */
  25335. class ReflectorBaseNode extends Node {
  25336. static get type() {
  25337. return 'ReflectorBaseNode';
  25338. }
  25339. /**
  25340. * Constructs a new reflector base node.
  25341. *
  25342. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  25343. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25344. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25345. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  25346. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25347. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25348. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25349. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25350. */
  25351. constructor( textureNode, parameters = {} ) {
  25352. super();
  25353. const {
  25354. target = new Object3D(),
  25355. resolutionScale = 1,
  25356. generateMipmaps = false,
  25357. bounces = true,
  25358. depth = false,
  25359. samples = 0
  25360. } = parameters;
  25361. /**
  25362. * Represents the rendered reflections as a texture node.
  25363. *
  25364. * @type {TextureNode}
  25365. */
  25366. this.textureNode = textureNode;
  25367. /**
  25368. * The 3D object the reflector is linked to.
  25369. *
  25370. * @type {Object3D}
  25371. * @default {new Object3D()}
  25372. */
  25373. this.target = target;
  25374. /**
  25375. * The resolution scale.
  25376. *
  25377. * @type {number}
  25378. * @default {1}
  25379. */
  25380. this.resolutionScale = resolutionScale;
  25381. if ( parameters.resolution !== undefined ) {
  25382. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  25383. this.resolutionScale = parameters.resolution;
  25384. }
  25385. /**
  25386. * Whether mipmaps should be generated or not.
  25387. *
  25388. * @type {boolean}
  25389. * @default {false}
  25390. */
  25391. this.generateMipmaps = generateMipmaps;
  25392. /**
  25393. * Whether reflectors can render other reflector nodes or not.
  25394. *
  25395. * @type {boolean}
  25396. * @default {true}
  25397. */
  25398. this.bounces = bounces;
  25399. /**
  25400. * Whether depth data should be generated or not.
  25401. *
  25402. * @type {boolean}
  25403. * @default {false}
  25404. */
  25405. this.depth = depth;
  25406. /**
  25407. * The number of anti-aliasing samples for the render-target
  25408. *
  25409. * @type {number}
  25410. * @default {0}
  25411. */
  25412. this.samples = samples;
  25413. /**
  25414. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  25415. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  25416. *
  25417. * @type {string}
  25418. * @default 'render'
  25419. */
  25420. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  25421. /**
  25422. * Weak map for managing virtual cameras.
  25423. *
  25424. * @type {WeakMap<Camera, Camera>}
  25425. */
  25426. this.virtualCameras = new WeakMap();
  25427. /**
  25428. * Weak map for managing render targets.
  25429. *
  25430. * @type {Map<Camera, RenderTarget>}
  25431. */
  25432. this.renderTargets = new Map();
  25433. /**
  25434. * Force render even if reflector is facing away from camera.
  25435. *
  25436. * @type {boolean}
  25437. * @default {false}
  25438. */
  25439. this.forceUpdate = false;
  25440. /**
  25441. * Whether the reflector has been rendered or not.
  25442. *
  25443. * When the reflector is facing away from the camera,
  25444. * this flag is set to `false` and the texture will be empty(black).
  25445. *
  25446. * @type {boolean}
  25447. * @default {false}
  25448. */
  25449. this.hasOutput = false;
  25450. }
  25451. /**
  25452. * Updates the resolution of the internal render target.
  25453. *
  25454. * @private
  25455. * @param {RenderTarget} renderTarget - The render target to resize.
  25456. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  25457. */
  25458. _updateResolution( renderTarget, renderer ) {
  25459. const resolution = this.resolutionScale;
  25460. renderer.getDrawingBufferSize( _size$2 );
  25461. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  25462. }
  25463. setup( builder ) {
  25464. this._updateResolution( _defaultRT, builder.renderer );
  25465. return super.setup( builder );
  25466. }
  25467. /**
  25468. * Frees internal resources. Should be called when the node is no longer in use.
  25469. */
  25470. dispose() {
  25471. super.dispose();
  25472. for ( const renderTarget of this.renderTargets.values() ) {
  25473. renderTarget.dispose();
  25474. }
  25475. }
  25476. /**
  25477. * Returns a virtual camera for the given camera. The virtual camera is used to
  25478. * render the scene from the reflector's view so correct reflections can be produced.
  25479. *
  25480. * @param {Camera} camera - The scene's camera.
  25481. * @return {Camera} The corresponding virtual camera.
  25482. */
  25483. getVirtualCamera( camera ) {
  25484. let virtualCamera = this.virtualCameras.get( camera );
  25485. if ( virtualCamera === undefined ) {
  25486. virtualCamera = camera.clone();
  25487. this.virtualCameras.set( camera, virtualCamera );
  25488. }
  25489. return virtualCamera;
  25490. }
  25491. /**
  25492. * Returns a render target for the given camera. The reflections are rendered
  25493. * into this render target.
  25494. *
  25495. * @param {Camera} camera - The scene's camera.
  25496. * @return {RenderTarget} The render target.
  25497. */
  25498. getRenderTarget( camera ) {
  25499. let renderTarget = this.renderTargets.get( camera );
  25500. if ( renderTarget === undefined ) {
  25501. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  25502. if ( this.generateMipmaps === true ) {
  25503. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  25504. renderTarget.texture.generateMipmaps = true;
  25505. }
  25506. if ( this.depth === true ) {
  25507. renderTarget.depthTexture = new DepthTexture();
  25508. }
  25509. this.renderTargets.set( camera, renderTarget );
  25510. }
  25511. return renderTarget;
  25512. }
  25513. updateBefore( frame ) {
  25514. if ( this.bounces === false && _inReflector ) return false;
  25515. _inReflector = true;
  25516. const { scene, camera, renderer, material } = frame;
  25517. const { target } = this;
  25518. const virtualCamera = this.getVirtualCamera( camera );
  25519. const renderTarget = this.getRenderTarget( virtualCamera );
  25520. renderer.getDrawingBufferSize( _size$2 );
  25521. this._updateResolution( renderTarget, renderer );
  25522. //
  25523. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  25524. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  25525. _rotationMatrix.extractRotation( target.matrixWorld );
  25526. _normal.set( 0, 0, 1 );
  25527. _normal.applyMatrix4( _rotationMatrix );
  25528. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  25529. // Avoid rendering when reflector is facing away unless forcing an update
  25530. const isFacingAway = _view.dot( _normal ) > 0;
  25531. let needsClear = false;
  25532. if ( isFacingAway === true && this.forceUpdate === false ) {
  25533. if ( this.hasOutput === false ) {
  25534. _inReflector = false;
  25535. return;
  25536. }
  25537. needsClear = true;
  25538. }
  25539. _view.reflect( _normal ).negate();
  25540. _view.add( _reflectorWorldPosition );
  25541. _rotationMatrix.extractRotation( camera.matrixWorld );
  25542. _lookAtPosition.set( 0, 0, -1 );
  25543. _lookAtPosition.applyMatrix4( _rotationMatrix );
  25544. _lookAtPosition.add( _cameraWorldPosition );
  25545. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  25546. _target.reflect( _normal ).negate();
  25547. _target.add( _reflectorWorldPosition );
  25548. //
  25549. virtualCamera.coordinateSystem = camera.coordinateSystem;
  25550. virtualCamera.position.copy( _view );
  25551. virtualCamera.up.set( 0, 1, 0 );
  25552. virtualCamera.up.applyMatrix4( _rotationMatrix );
  25553. virtualCamera.up.reflect( _normal );
  25554. virtualCamera.lookAt( _target );
  25555. virtualCamera.near = camera.near;
  25556. virtualCamera.far = camera.far;
  25557. virtualCamera.updateMatrixWorld();
  25558. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  25559. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  25560. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  25561. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  25562. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  25563. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  25564. const projectionMatrix = virtualCamera.projectionMatrix;
  25565. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  25566. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  25567. _q.z = -1;
  25568. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  25569. // Calculate the scaled plane vector
  25570. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  25571. const clipBias = 0;
  25572. // Replacing the third row of the projection matrix
  25573. projectionMatrix.elements[ 2 ] = clipPlane.x;
  25574. projectionMatrix.elements[ 6 ] = clipPlane.y;
  25575. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  25576. projectionMatrix.elements[ 14 ] = clipPlane.w;
  25577. //
  25578. this.textureNode.value = renderTarget.texture;
  25579. if ( this.depth === true ) {
  25580. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  25581. }
  25582. material.visible = false;
  25583. const currentRenderTarget = renderer.getRenderTarget();
  25584. const currentMRT = renderer.getMRT();
  25585. const currentAutoClear = renderer.autoClear;
  25586. renderer.setMRT( null );
  25587. renderer.setRenderTarget( renderTarget );
  25588. renderer.autoClear = true;
  25589. const previousName = scene.name;
  25590. scene.name = ( scene.name || 'Scene' ) + ' [ Reflector ]'; // TODO: Add bounce index
  25591. if ( needsClear ) {
  25592. renderer.clear();
  25593. this.hasOutput = false;
  25594. } else {
  25595. renderer.render( scene, virtualCamera );
  25596. this.hasOutput = true;
  25597. }
  25598. scene.name = previousName;
  25599. renderer.setMRT( currentMRT );
  25600. renderer.setRenderTarget( currentRenderTarget );
  25601. renderer.autoClear = currentAutoClear;
  25602. material.visible = true;
  25603. _inReflector = false;
  25604. this.forceUpdate = false;
  25605. }
  25606. /**
  25607. * The resolution scale.
  25608. *
  25609. * @deprecated
  25610. * @type {number}
  25611. * @default {1}
  25612. */
  25613. get resolution() {
  25614. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25615. return this.resolutionScale;
  25616. }
  25617. set resolution( value ) {
  25618. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  25619. this.resolutionScale = value;
  25620. }
  25621. }
  25622. /**
  25623. * TSL function for creating a reflector node.
  25624. *
  25625. * @tsl
  25626. * @function
  25627. * @param {Object} [parameters={}] - An object holding configuration parameters.
  25628. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  25629. * @param {number} [parameters.resolution=1] - The resolution scale.
  25630. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  25631. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  25632. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  25633. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  25634. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  25635. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  25636. * @returns {ReflectorNode}
  25637. */
  25638. const reflector = ( parameters ) => new ReflectorNode( parameters );
  25639. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  25640. /**
  25641. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  25642. *
  25643. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  25644. *
  25645. * @private
  25646. * @augments BufferGeometry
  25647. */
  25648. class QuadGeometry extends BufferGeometry {
  25649. /**
  25650. * Constructs a new quad geometry.
  25651. *
  25652. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  25653. */
  25654. constructor( flipY = false ) {
  25655. super();
  25656. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  25657. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  25658. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  25659. }
  25660. }
  25661. const _geometry = /*@__PURE__*/ new QuadGeometry();
  25662. /**
  25663. * This module is a helper for passes which need to render a full
  25664. * screen effect which is quite common in context of post processing.
  25665. *
  25666. * The intended usage is to reuse a single quad mesh for rendering
  25667. * subsequent passes by just reassigning the `material` reference.
  25668. *
  25669. * Note: This module can only be used with `WebGPURenderer`.
  25670. *
  25671. * @augments Mesh
  25672. */
  25673. class QuadMesh extends Mesh {
  25674. /**
  25675. * Constructs a new quad mesh.
  25676. *
  25677. * @param {?Material} [material=null] - The material to render the quad mesh with.
  25678. */
  25679. constructor( material = null ) {
  25680. super( _geometry, material );
  25681. /**
  25682. * The camera to render the quad mesh with.
  25683. *
  25684. * @type {OrthographicCamera}
  25685. * @readonly
  25686. */
  25687. this.camera = _camera;
  25688. /**
  25689. * This flag can be used for type testing.
  25690. *
  25691. * @type {boolean}
  25692. * @readonly
  25693. * @default true
  25694. */
  25695. this.isQuadMesh = true;
  25696. }
  25697. /**
  25698. * Async version of `render()`.
  25699. *
  25700. * @async
  25701. * @deprecated
  25702. * @param {Renderer} renderer - The renderer.
  25703. * @return {Promise} A Promise that resolves when the render has been finished.
  25704. */
  25705. async renderAsync( renderer ) {
  25706. warnOnce( 'QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  25707. await renderer.init();
  25708. renderer.render( this, _camera );
  25709. }
  25710. /**
  25711. * Renders the quad mesh
  25712. *
  25713. * @param {Renderer} renderer - The renderer.
  25714. */
  25715. render( renderer ) {
  25716. renderer.render( this, _camera );
  25717. }
  25718. }
  25719. const _size$1 = /*@__PURE__*/ new Vector2();
  25720. /**
  25721. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  25722. * This module is especially relevant in context of post processing where certain nodes require
  25723. * texture input for their effects. With the helper function `convertToTexture()` which is based
  25724. * on this module, the node system can automatically ensure texture input if required.
  25725. *
  25726. * @augments TextureNode
  25727. */
  25728. class RTTNode extends TextureNode {
  25729. static get type() {
  25730. return 'RTTNode';
  25731. }
  25732. /**
  25733. * Constructs a new RTT node.
  25734. *
  25735. * @param {Node} node - The node to render a texture with.
  25736. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25737. * @param {?number} [height=null] - The height of the internal render target.
  25738. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25739. */
  25740. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  25741. const renderTarget = new RenderTarget( width, height, options );
  25742. super( renderTarget.texture, uv$1() );
  25743. /**
  25744. * This flag can be used for type testing.
  25745. *
  25746. * @type {boolean}
  25747. * @readonly
  25748. * @default true
  25749. */
  25750. this.isRTTNode = true;
  25751. /**
  25752. * The node to render a texture with.
  25753. *
  25754. * @type {Node}
  25755. */
  25756. this.node = node;
  25757. /**
  25758. * The width of the internal render target.
  25759. * If not width is applied, the render target is automatically resized.
  25760. *
  25761. * @type {?number}
  25762. * @default null
  25763. */
  25764. this.width = width;
  25765. /**
  25766. * The height of the internal render target.
  25767. *
  25768. * @type {?number}
  25769. * @default null
  25770. */
  25771. this.height = height;
  25772. /**
  25773. * The pixel ratio
  25774. *
  25775. * @type {number}
  25776. * @default 1
  25777. */
  25778. this.pixelRatio = 1;
  25779. /**
  25780. * The render target
  25781. *
  25782. * @type {RenderTarget}
  25783. */
  25784. this.renderTarget = renderTarget;
  25785. /**
  25786. * Whether the texture requires an update or not.
  25787. *
  25788. * @type {boolean}
  25789. * @default true
  25790. */
  25791. this.textureNeedsUpdate = true;
  25792. /**
  25793. * Whether the texture should automatically be updated or not.
  25794. *
  25795. * @type {boolean}
  25796. * @default true
  25797. */
  25798. this.autoUpdate = true;
  25799. /**
  25800. * The node which is used with the quad mesh for RTT.
  25801. *
  25802. * @private
  25803. * @type {Node}
  25804. * @default null
  25805. */
  25806. this._rttNode = null;
  25807. /**
  25808. * The internal quad mesh for RTT.
  25809. *
  25810. * @private
  25811. * @type {QuadMesh}
  25812. */
  25813. this._quadMesh = new QuadMesh( new NodeMaterial() );
  25814. /**
  25815. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  25816. * the texture once per render in its {@link RTTNode#updateBefore} method.
  25817. *
  25818. * @type {string}
  25819. * @default 'render'
  25820. */
  25821. this.updateBeforeType = NodeUpdateType.RENDER;
  25822. }
  25823. /**
  25824. * Whether the internal render target should automatically be resized or not.
  25825. *
  25826. * @type {boolean}
  25827. * @readonly
  25828. * @default true
  25829. */
  25830. get autoResize() {
  25831. return this.width === null;
  25832. }
  25833. setup( builder ) {
  25834. this._rttNode = this.node.context( builder.getSharedContext() );
  25835. this._quadMesh.material.name = 'RTT';
  25836. this._quadMesh.material.needsUpdate = true;
  25837. return super.setup( builder );
  25838. }
  25839. /**
  25840. * Sets the size of the internal render target
  25841. *
  25842. * @param {number} width - The width to set.
  25843. * @param {number} height - The width to set.
  25844. */
  25845. setSize( width, height ) {
  25846. this.width = width;
  25847. this.height = height;
  25848. const effectiveWidth = width * this.pixelRatio;
  25849. const effectiveHeight = height * this.pixelRatio;
  25850. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25851. this.textureNeedsUpdate = true;
  25852. }
  25853. /**
  25854. * Sets the pixel ratio. This will also resize the render target.
  25855. *
  25856. * @param {number} pixelRatio - The pixel ratio to set.
  25857. */
  25858. setPixelRatio( pixelRatio ) {
  25859. this.pixelRatio = pixelRatio;
  25860. this.setSize( this.width, this.height );
  25861. }
  25862. updateBefore( { renderer } ) {
  25863. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  25864. this.textureNeedsUpdate = false;
  25865. //
  25866. if ( this.autoResize === true ) {
  25867. const pixelRatio = renderer.getPixelRatio();
  25868. const size = renderer.getSize( _size$1 );
  25869. const effectiveWidth = Math.floor( size.width * pixelRatio );
  25870. const effectiveHeight = Math.floor( size.height * pixelRatio );
  25871. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  25872. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25873. this.textureNeedsUpdate = true;
  25874. }
  25875. }
  25876. //
  25877. let name = 'RTT';
  25878. if ( this.node.name ) {
  25879. name = this.node.name + ' [ ' + name + ' ]';
  25880. }
  25881. this._quadMesh.material.fragmentNode = this._rttNode;
  25882. this._quadMesh.name = name;
  25883. //
  25884. const currentRenderTarget = renderer.getRenderTarget();
  25885. renderer.setRenderTarget( this.renderTarget );
  25886. this._quadMesh.render( renderer );
  25887. renderer.setRenderTarget( currentRenderTarget );
  25888. }
  25889. clone() {
  25890. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  25891. newNode.sampler = this.sampler;
  25892. newNode.referenceNode = this;
  25893. return newNode;
  25894. }
  25895. }
  25896. /**
  25897. * TSL function for creating a RTT node.
  25898. *
  25899. * @tsl
  25900. * @function
  25901. * @param {Node} node - The node to render a texture with.
  25902. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25903. * @param {?number} [height=null] - The height of the internal render target.
  25904. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25905. * @returns {RTTNode}
  25906. */
  25907. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  25908. /**
  25909. * TSL function for converting nodes to textures nodes.
  25910. *
  25911. * @tsl
  25912. * @function
  25913. * @param {Node} node - The node to render a texture with.
  25914. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  25915. * @param {?number} [height=null] - The height of the internal render target.
  25916. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  25917. * @returns {RTTNode}
  25918. */
  25919. const convertToTexture = ( node, ...params ) => {
  25920. if ( node.isSampleNode || node.isTextureNode ) return node;
  25921. if ( node.isPassNode ) return node.getTextureNode();
  25922. return rtt( node, ...params );
  25923. };
  25924. /**
  25925. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  25926. * depth value and the camera's inverse projection matrix.
  25927. *
  25928. * @tsl
  25929. * @function
  25930. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  25931. * @param {Node<float>} depth - The fragment's depth value.
  25932. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25933. * @return {Node<vec3>} The fragments position in view space.
  25934. */
  25935. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  25936. let clipSpacePosition;
  25937. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25938. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  25939. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  25940. } else {
  25941. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  25942. }
  25943. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  25944. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  25945. } );
  25946. /**
  25947. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  25948. * and the camera's projection matrix
  25949. *
  25950. * @tsl
  25951. * @function
  25952. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  25953. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  25954. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  25955. */
  25956. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  25957. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  25958. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  25959. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  25960. } );
  25961. /**
  25962. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  25963. * target is available or if flat surface normals are required.
  25964. *
  25965. * @tsl
  25966. * @function
  25967. * @param {Node<vec2>} uv - The texture coordinate.
  25968. * @param {DepthTexture} depthTexture - The depth texture.
  25969. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  25970. * @return {Node<vec3>} The computed normal vector.
  25971. */
  25972. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  25973. const size = textureSize( textureLoad( depthTexture ) );
  25974. const p = ivec2( uv.mul( size ) ).toVar();
  25975. const c0 = textureLoad( depthTexture, p ).toVar();
  25976. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  25977. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  25978. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  25979. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  25980. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  25981. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  25982. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  25983. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  25984. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  25985. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  25986. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  25987. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  25988. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  25989. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  25990. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  25991. return normalize( cross( dpdx, dpdy ) );
  25992. } );
  25993. /**
  25994. * Interleaved Gradient Noise (IGN) from Jimenez 2014.
  25995. *
  25996. * IGN has "low discrepancy" resulting in evenly distributed samples. It's superior compared to
  25997. * default white noise, blue noise or Bayer.
  25998. *
  25999. * References:
  26000. * - {@link https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/}
  26001. * - {@link https://blog.demofox.org/2022/01/01/interleaved-gradient-noise-a-different-kind-of-low-discrepancy-sequence/}
  26002. *
  26003. * @tsl
  26004. * @function
  26005. * @param {Node<vec2>} position - The input position, usually screen coordinates.
  26006. * @return {Node<float>} The noise value.
  26007. */
  26008. const interleavedGradientNoise = Fn( ( [ position ] ) => {
  26009. return fract( float( 52.9829189 ).mul( fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ) );
  26010. } ).setLayout( {
  26011. name: 'interleavedGradientNoise',
  26012. type: 'float',
  26013. inputs: [
  26014. { name: 'position', type: 'vec2' }
  26015. ]
  26016. } );
  26017. /**
  26018. * Vogel disk sampling for uniform circular distribution.
  26019. *
  26020. * This function generates sample points distributed uniformly on a disk using the golden angle,
  26021. * resulting in an efficient low-discrepancy sequence for sampling. The rotation parameter (phi)
  26022. * allows randomizing the pattern per-pixel when combined with IGN.
  26023. *
  26024. * @tsl
  26025. * @function
  26026. * @param {Node<int>} sampleIndex - The index of the current sample (0-based).
  26027. * @param {Node<int>} samplesCount - The total number of samples.
  26028. * @param {Node<float>} phi - Rotation angle in radians (typically from IGN * 2π).
  26029. * @return {Node<vec2>} A 2D point on the unit disk.
  26030. */
  26031. const vogelDiskSample = Fn( ( [ sampleIndex, samplesCount, phi ] ) => {
  26032. const goldenAngle = float( 2.399963229728653 ); // 2π * (2 - φ) where φ is golden ratio
  26033. const r = sqrt( float( sampleIndex ).add( 0.5 ).div( float( samplesCount ) ) );
  26034. const theta = float( sampleIndex ).mul( goldenAngle ).add( phi );
  26035. return vec2( cos( theta ), sin( theta ) ).mul( r );
  26036. } ).setLayout( {
  26037. name: 'vogelDiskSample',
  26038. type: 'vec2',
  26039. inputs: [
  26040. { name: 'sampleIndex', type: 'int' },
  26041. { name: 'samplesCount', type: 'int' },
  26042. { name: 'phi', type: 'float' }
  26043. ]
  26044. } );
  26045. /**
  26046. * Class representing a node that samples a value using a provided callback function.
  26047. *
  26048. * @extends Node
  26049. */
  26050. class SampleNode extends Node {
  26051. /**
  26052. * Returns the type of the node.
  26053. *
  26054. * @type {string}
  26055. * @readonly
  26056. * @static
  26057. */
  26058. static get type() {
  26059. return 'SampleNode';
  26060. }
  26061. /**
  26062. * Creates an instance of SampleNode.
  26063. *
  26064. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26065. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  26066. */
  26067. constructor( callback, uvNode = null ) {
  26068. super();
  26069. this.callback = callback;
  26070. /**
  26071. * Represents the texture coordinates.
  26072. *
  26073. * @type {?Node<vec2|vec3>}
  26074. * @default null
  26075. */
  26076. this.uvNode = uvNode;
  26077. /**
  26078. * This flag can be used for type testing.
  26079. *
  26080. * @type {boolean}
  26081. * @readonly
  26082. * @default true
  26083. */
  26084. this.isSampleNode = true;
  26085. }
  26086. /**
  26087. * Sets up the node by sampling with the default UV accessor.
  26088. *
  26089. * @returns {Node} The result of the callback function when called with the UV node.
  26090. */
  26091. setup() {
  26092. return this.sample( uv$1() );
  26093. }
  26094. /**
  26095. * Calls the callback function with the provided UV node.
  26096. *
  26097. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  26098. * @returns {Node} The result of the callback function.
  26099. */
  26100. sample( uv ) {
  26101. return this.callback( uv );
  26102. }
  26103. }
  26104. /**
  26105. * Helper function to create a SampleNode wrapped as a node object.
  26106. *
  26107. * @function
  26108. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  26109. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  26110. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  26111. */
  26112. const sample = ( callback, uv = null ) => new SampleNode( callback, nodeObject( uv ) );
  26113. /**
  26114. * EventNode is a node that executes a callback during specific update phases.
  26115. *
  26116. * @augments Node
  26117. */
  26118. class EventNode extends Node {
  26119. static get type() {
  26120. return 'EventNode';
  26121. }
  26122. /**
  26123. * Creates an EventNode.
  26124. *
  26125. * @param {string} eventType - The type of event
  26126. * @param {Function} callback - The callback to execute on update.
  26127. */
  26128. constructor( eventType, callback ) {
  26129. super( 'void' );
  26130. this.eventType = eventType;
  26131. this.callback = callback;
  26132. if ( eventType === EventNode.OBJECT ) {
  26133. this.updateType = NodeUpdateType.OBJECT;
  26134. } else if ( eventType === EventNode.MATERIAL ) {
  26135. this.updateType = NodeUpdateType.RENDER;
  26136. } else if ( eventType === EventNode.BEFORE_OBJECT ) {
  26137. this.updateBeforeType = NodeUpdateType.OBJECT;
  26138. } else if ( eventType === EventNode.BEFORE_MATERIAL ) {
  26139. this.updateBeforeType = NodeUpdateType.RENDER;
  26140. }
  26141. }
  26142. update( frame ) {
  26143. this.callback( frame );
  26144. }
  26145. updateBefore( frame ) {
  26146. this.callback( frame );
  26147. }
  26148. }
  26149. EventNode.OBJECT = 'object';
  26150. EventNode.MATERIAL = 'material';
  26151. EventNode.BEFORE_OBJECT = 'beforeObject';
  26152. EventNode.BEFORE_MATERIAL = 'beforeMaterial';
  26153. /**
  26154. * Helper to create an EventNode and add it to the stack.
  26155. *
  26156. * @param {string} type - The event type.
  26157. * @param {Function} callback - The callback function.
  26158. * @returns {EventNode}
  26159. */
  26160. const createEvent = ( type, callback ) => new EventNode( type, callback ).toStack();
  26161. /**
  26162. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  26163. *
  26164. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26165. *
  26166. * @param {Function} callback - The callback function.
  26167. * @returns {EventNode}
  26168. */
  26169. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  26170. /**
  26171. * Creates an event that triggers a function when the first object that uses the material is rendered.
  26172. *
  26173. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26174. *
  26175. * @param {Function} callback - The callback function.
  26176. * @returns {EventNode}
  26177. */
  26178. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  26179. /**
  26180. * Creates an event that triggers a function before an object (Mesh|Sprite) is updated.
  26181. *
  26182. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26183. *
  26184. * @param {Function} callback - The callback function.
  26185. * @returns {EventNode}
  26186. */
  26187. const OnBeforeObjectUpdate = ( callback ) => createEvent( EventNode.BEFORE_OBJECT, callback );
  26188. /**
  26189. * Creates an event that triggers a function before the material is updated.
  26190. *
  26191. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  26192. *
  26193. * @param {Function} callback - The callback function.
  26194. * @returns {EventNode}
  26195. */
  26196. const OnBeforeMaterialUpdate = ( callback ) => createEvent( EventNode.BEFORE_MATERIAL, callback );
  26197. /**
  26198. * This special type of instanced buffer attribute is intended for compute shaders.
  26199. * In earlier three.js versions it was only possible to update attribute data
  26200. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26201. * new material system and renderer it is now possible to use compute shaders
  26202. * to compute the data for an attribute more efficiently on the GPU.
  26203. *
  26204. * The idea is to create an instance of this class and provide it as an input
  26205. * to {@link StorageBufferNode}.
  26206. *
  26207. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26208. *
  26209. * @augments InstancedBufferAttribute
  26210. */
  26211. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  26212. /**
  26213. * Constructs a new storage instanced buffer attribute.
  26214. *
  26215. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26216. * The subsequent parameters are then obsolete.
  26217. * @param {number} itemSize - The item size.
  26218. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26219. */
  26220. constructor( count, itemSize, typeClass = Float32Array ) {
  26221. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26222. super( array, itemSize );
  26223. /**
  26224. * This flag can be used for type testing.
  26225. *
  26226. * @type {boolean}
  26227. * @readonly
  26228. * @default true
  26229. */
  26230. this.isStorageInstancedBufferAttribute = true;
  26231. }
  26232. }
  26233. /**
  26234. * This special type of buffer attribute is intended for compute shaders.
  26235. * In earlier three.js versions it was only possible to update attribute data
  26236. * on the CPU via JavaScript and then upload the data to the GPU. With the
  26237. * new material system and renderer it is now possible to use compute shaders
  26238. * to compute the data for an attribute more efficiently on the GPU.
  26239. *
  26240. * The idea is to create an instance of this class and provide it as an input
  26241. * to {@link StorageBufferNode}.
  26242. *
  26243. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  26244. *
  26245. * @augments BufferAttribute
  26246. */
  26247. class StorageBufferAttribute extends BufferAttribute {
  26248. /**
  26249. * Constructs a new storage buffer attribute.
  26250. *
  26251. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  26252. * The subsequent parameters are then obsolete.
  26253. * @param {number} itemSize - The item size.
  26254. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  26255. */
  26256. constructor( count, itemSize, typeClass = Float32Array ) {
  26257. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  26258. super( array, itemSize );
  26259. /**
  26260. * This flag can be used for type testing.
  26261. *
  26262. * @type {boolean}
  26263. * @readonly
  26264. * @default true
  26265. */
  26266. this.isStorageBufferAttribute = true;
  26267. }
  26268. }
  26269. /**
  26270. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  26271. *
  26272. * @tsl
  26273. * @function
  26274. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26275. * @param {string|Struct} [type='float'] - The data type.
  26276. * @returns {StorageBufferNode}
  26277. */
  26278. const attributeArray = ( count, type = 'float' ) => {
  26279. let itemSize, typedArray;
  26280. if ( type.isStruct === true ) {
  26281. itemSize = type.layout.getLength();
  26282. typedArray = getTypedArrayFromType( 'float' );
  26283. } else {
  26284. itemSize = getLengthFromType( type );
  26285. typedArray = getTypedArrayFromType( type );
  26286. }
  26287. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  26288. const node = storage( buffer, type, count );
  26289. return node;
  26290. };
  26291. /**
  26292. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  26293. *
  26294. * @tsl
  26295. * @function
  26296. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  26297. * @param {string|Struct} [type='float'] - The data type.
  26298. * @returns {StorageBufferNode}
  26299. */
  26300. const instancedArray = ( count, type = 'float' ) => {
  26301. let itemSize, typedArray;
  26302. if ( type.isStruct === true ) {
  26303. itemSize = type.layout.getLength();
  26304. typedArray = getTypedArrayFromType( 'float' );
  26305. } else {
  26306. itemSize = getLengthFromType( type );
  26307. typedArray = getTypedArrayFromType( type );
  26308. }
  26309. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  26310. const node = storage( buffer, type, count );
  26311. return node;
  26312. };
  26313. /**
  26314. * A node for representing the uv coordinates of points.
  26315. *
  26316. * Can only be used with a WebGL backend. In WebGPU, point
  26317. * primitives always have the size of one pixel and can thus
  26318. * can't be used as sprite-like objects that display textures.
  26319. *
  26320. * @augments Node
  26321. */
  26322. class PointUVNode extends Node {
  26323. static get type() {
  26324. return 'PointUVNode';
  26325. }
  26326. /**
  26327. * Constructs a new point uv node.
  26328. */
  26329. constructor() {
  26330. super( 'vec2' );
  26331. /**
  26332. * This flag can be used for type testing.
  26333. *
  26334. * @type {boolean}
  26335. * @readonly
  26336. * @default true
  26337. */
  26338. this.isPointUVNode = true;
  26339. }
  26340. generate( /*builder*/ ) {
  26341. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  26342. }
  26343. }
  26344. /**
  26345. * TSL object that represents the uv coordinates of points.
  26346. *
  26347. * @tsl
  26348. * @type {PointUVNode}
  26349. */
  26350. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  26351. const _e1 = /*@__PURE__*/ new Euler();
  26352. const _m1 = /*@__PURE__*/ new Matrix4();
  26353. /**
  26354. * TSL object that represents the scene's background blurriness.
  26355. *
  26356. * @tsl
  26357. * @type {Node<float>}
  26358. */
  26359. const backgroundBlurriness = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundBlurriness );
  26360. /**
  26361. * TSL object that represents the scene's background intensity.
  26362. *
  26363. * @tsl
  26364. * @type {Node<float>}
  26365. */
  26366. const backgroundIntensity = /*@__PURE__*/ uniform( 1 ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => scene.backgroundIntensity );
  26367. /**
  26368. * TSL object that represents the scene's background rotation.
  26369. *
  26370. * @tsl
  26371. * @type {Node<mat4>}
  26372. */
  26373. const backgroundRotation = /*@__PURE__*/ uniform( new Matrix4() ).setGroup( renderGroup ).onRenderUpdate( ( { scene } ) => {
  26374. const background = scene.background;
  26375. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  26376. _e1.copy( scene.backgroundRotation );
  26377. // accommodate left-handed frame
  26378. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  26379. _m1.makeRotationFromEuler( _e1 );
  26380. } else {
  26381. _m1.identity();
  26382. }
  26383. return _m1;
  26384. } );
  26385. /**
  26386. * This special version of a texture node can be used to
  26387. * write data into a storage texture with a compute shader.
  26388. *
  26389. * ```js
  26390. * const storageTexture = new THREE.StorageTexture( width, height );
  26391. *
  26392. * const computeTexture = Fn( ( { storageTexture } ) => {
  26393. *
  26394. * const posX = instanceIndex.mod( width );
  26395. * const posY = instanceIndex.div( width );
  26396. * const indexUV = uvec2( posX, posY );
  26397. *
  26398. * // generate RGB values
  26399. *
  26400. * const r = 1;
  26401. * const g = 1;
  26402. * const b = 1;
  26403. *
  26404. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  26405. *
  26406. * } );
  26407. *
  26408. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  26409. * renderer.computeAsync( computeNode );
  26410. * ```
  26411. *
  26412. * This node can only be used with a WebGPU backend.
  26413. *
  26414. * @augments TextureNode
  26415. */
  26416. class StorageTextureNode extends TextureNode {
  26417. static get type() {
  26418. return 'StorageTextureNode';
  26419. }
  26420. /**
  26421. * Constructs a new storage texture node.
  26422. *
  26423. * @param {StorageTexture} value - The storage texture.
  26424. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26425. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26426. */
  26427. constructor( value, uvNode, storeNode = null ) {
  26428. super( value, uvNode );
  26429. /**
  26430. * The value node that should be stored in the texture.
  26431. *
  26432. * @type {?Node}
  26433. * @default null
  26434. */
  26435. this.storeNode = storeNode;
  26436. /**
  26437. * The mip level to write to for storage textures.
  26438. *
  26439. * @type {number}
  26440. * @default 0
  26441. */
  26442. this.mipLevel = 0;
  26443. /**
  26444. * This flag can be used for type testing.
  26445. *
  26446. * @type {boolean}
  26447. * @readonly
  26448. * @default true
  26449. */
  26450. this.isStorageTextureNode = true;
  26451. /**
  26452. * The access type of the texture node.
  26453. *
  26454. * @type {string}
  26455. * @default 'writeOnly'
  26456. */
  26457. this.access = NodeAccess.WRITE_ONLY;
  26458. }
  26459. /**
  26460. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  26461. *
  26462. * @param {NodeBuilder} builder - The current node builder.
  26463. * @return {string} The input type.
  26464. */
  26465. getInputType( /*builder*/ ) {
  26466. return 'storageTexture';
  26467. }
  26468. setup( builder ) {
  26469. super.setup( builder );
  26470. const properties = builder.getNodeProperties( this );
  26471. properties.storeNode = this.storeNode;
  26472. return properties;
  26473. }
  26474. /**
  26475. * Defines the node access.
  26476. *
  26477. * @param {string} value - The node access.
  26478. * @return {StorageTextureNode} A reference to this node.
  26479. */
  26480. setAccess( value ) {
  26481. this.access = value;
  26482. return this;
  26483. }
  26484. /**
  26485. * Sets the mip level to write to.
  26486. *
  26487. * @param {number} level - The mip level.
  26488. * @return {StorageTextureNode} A reference to this node.
  26489. */
  26490. setMipLevel( level ) {
  26491. this.mipLevel = level;
  26492. return this;
  26493. }
  26494. /**
  26495. * Generates the code snippet of the storage node. If no `storeNode`
  26496. * is defined, the texture node is generated as normal texture.
  26497. *
  26498. * @param {NodeBuilder} builder - The current node builder.
  26499. * @param {string} output - The current output.
  26500. * @return {string} The generated code snippet.
  26501. */
  26502. generate( builder, output ) {
  26503. let snippet;
  26504. if ( this.storeNode !== null ) {
  26505. snippet = this.generateStore( builder );
  26506. } else {
  26507. snippet = super.generate( builder, output );
  26508. }
  26509. return snippet;
  26510. }
  26511. /**
  26512. * Convenience method for configuring a read/write node access.
  26513. *
  26514. * @return {StorageTextureNode} A reference to this node.
  26515. */
  26516. toReadWrite() {
  26517. return this.setAccess( NodeAccess.READ_WRITE );
  26518. }
  26519. /**
  26520. * Convenience method for configuring a read-only node access.
  26521. *
  26522. * @return {StorageTextureNode} A reference to this node.
  26523. */
  26524. toReadOnly() {
  26525. return this.setAccess( NodeAccess.READ_ONLY );
  26526. }
  26527. /**
  26528. * Convenience method for configuring a write-only node access.
  26529. *
  26530. * @return {StorageTextureNode} A reference to this node.
  26531. */
  26532. toWriteOnly() {
  26533. return this.setAccess( NodeAccess.WRITE_ONLY );
  26534. }
  26535. /**
  26536. * Generates the code snippet of the storage texture node.
  26537. *
  26538. * @param {NodeBuilder} builder - The current node builder.
  26539. */
  26540. generateStore( builder ) {
  26541. const properties = builder.getNodeProperties( this );
  26542. const { uvNode, storeNode, depthNode } = properties;
  26543. const textureProperty = super.generate( builder, 'property' );
  26544. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  26545. const storeSnippet = storeNode.build( builder, 'vec4' );
  26546. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  26547. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  26548. builder.addLineFlowCode( snippet, this );
  26549. }
  26550. clone() {
  26551. const newNode = super.clone();
  26552. newNode.storeNode = this.storeNode;
  26553. newNode.mipLevel = this.mipLevel;
  26554. newNode.access = this.access;
  26555. return newNode;
  26556. }
  26557. }
  26558. /**
  26559. * TSL function for creating a storage texture node.
  26560. *
  26561. * @tsl
  26562. * @function
  26563. * @param {StorageTexture} value - The storage texture.
  26564. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  26565. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26566. * @returns {StorageTextureNode}
  26567. */
  26568. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  26569. /**
  26570. * TODO: Explain difference to `storageTexture()`.
  26571. *
  26572. * @tsl
  26573. * @function
  26574. * @param {StorageTexture} value - The storage texture.
  26575. * @param {Node<vec2|vec3>} uvNode - The uv node.
  26576. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  26577. * @returns {StorageTextureNode}
  26578. */
  26579. const textureStore = ( value, uvNode, storeNode ) => {
  26580. let node;
  26581. if ( value.isStorageTextureNode === true ) {
  26582. // Derive new storage texture node from existing one
  26583. node = value.clone();
  26584. node.uvNode = uvNode;
  26585. node.storeNode = storeNode;
  26586. } else {
  26587. node = storageTexture( value, uvNode, storeNode );
  26588. }
  26589. if ( storeNode !== null ) node.toStack();
  26590. return node;
  26591. };
  26592. const normal = Fn( ( { texture, uv } ) => {
  26593. const epsilon = 0.0001;
  26594. const ret = vec3().toVar();
  26595. If( uv.x.lessThan( epsilon ), () => {
  26596. ret.assign( vec3( 1, 0, 0 ) );
  26597. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  26598. ret.assign( vec3( 0, 1, 0 ) );
  26599. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  26600. ret.assign( vec3( 0, 0, 1 ) );
  26601. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  26602. ret.assign( vec3( -1, 0, 0 ) );
  26603. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  26604. ret.assign( vec3( 0, -1, 0 ) );
  26605. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  26606. ret.assign( vec3( 0, 0, -1 ) );
  26607. } ).Else( () => {
  26608. const step = 0.01;
  26609. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  26610. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  26611. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  26612. ret.assign( vec3( x, y, z ) );
  26613. } );
  26614. return ret.normalize();
  26615. } );
  26616. /**
  26617. * This type of uniform node represents a 3D texture.
  26618. *
  26619. * @augments TextureNode
  26620. */
  26621. class Texture3DNode extends TextureNode {
  26622. static get type() {
  26623. return 'Texture3DNode';
  26624. }
  26625. /**
  26626. * Constructs a new 3D texture node.
  26627. *
  26628. * @param {Data3DTexture} value - The 3D texture.
  26629. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  26630. * @param {?Node<int>} [levelNode=null] - The level node.
  26631. */
  26632. constructor( value, uvNode = null, levelNode = null ) {
  26633. super( value, uvNode, levelNode );
  26634. /**
  26635. * This flag can be used for type testing.
  26636. *
  26637. * @type {boolean}
  26638. * @readonly
  26639. * @default true
  26640. */
  26641. this.isTexture3DNode = true;
  26642. }
  26643. /**
  26644. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  26645. *
  26646. * @param {NodeBuilder} builder - The current node builder.
  26647. * @return {string} The input type.
  26648. */
  26649. getInputType( /*builder*/ ) {
  26650. return 'texture3D';
  26651. }
  26652. /**
  26653. * Returns a default uv node which is in context of 3D textures a three-dimensional
  26654. * uv node.
  26655. *
  26656. * @return {Node<vec3>} The default uv node.
  26657. */
  26658. getDefaultUV() {
  26659. return vec3( 0.5, 0.5, 0.5 );
  26660. }
  26661. /**
  26662. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  26663. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  26664. *
  26665. * @param {boolean} value - The update toggle.
  26666. */
  26667. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  26668. /**
  26669. * Generates the uv code snippet.
  26670. *
  26671. * @param {NodeBuilder} builder - The current node builder.
  26672. * @param {Node} uvNode - The uv node to generate code for.
  26673. * @return {string} The generated code snippet.
  26674. */
  26675. generateUV( builder, uvNode ) {
  26676. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  26677. }
  26678. /**
  26679. * Generates the offset code snippet.
  26680. *
  26681. * @param {NodeBuilder} builder - The current node builder.
  26682. * @param {Node} offsetNode - The offset node to generate code for.
  26683. * @return {string} The generated code snippet.
  26684. */
  26685. generateOffset( builder, offsetNode ) {
  26686. return offsetNode.build( builder, 'ivec3' );
  26687. }
  26688. /**
  26689. * TODO.
  26690. *
  26691. * @param {Node<vec3>} uvNode - The uv node .
  26692. * @return {Node<vec3>} TODO.
  26693. */
  26694. normal( uvNode ) {
  26695. return normal( { texture: this, uv: uvNode } );
  26696. }
  26697. }
  26698. /**
  26699. * TSL function for creating a 3D texture node.
  26700. *
  26701. * @tsl
  26702. * @function
  26703. * @param {Data3DTexture} value - The 3D texture.
  26704. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26705. * @param {?Node<int>} [levelNode=null] - The level node.
  26706. * @returns {Texture3DNode}
  26707. */
  26708. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  26709. /**
  26710. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26711. *
  26712. * @tsl
  26713. * @function
  26714. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26715. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26716. * @param {?Node<int>} [levelNode=null] - The level node.
  26717. * @param {?Node<float>} [biasNode=null] - The bias node.
  26718. * @returns {TextureNode}
  26719. */
  26720. const texture3DLoad = ( ...params ) => texture3D( ...params ).setSampler( false );
  26721. /**
  26722. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  26723. *
  26724. * @tsl
  26725. * @function
  26726. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  26727. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  26728. * @param {?Node<int>} [levelNode=null] - The level node.
  26729. * @returns {TextureNode}
  26730. */
  26731. const texture3DLevel = ( value, uvNode, levelNode ) => texture3D( value, uvNode ).level( levelNode );
  26732. /**
  26733. * A special type of reference node that allows to link values in
  26734. * `userData` fields to node objects.
  26735. * ```js
  26736. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  26737. *
  26738. * const material = new THREE.SpriteNodeMaterial();
  26739. * material.rotationNode = userData( 'rotation', 'float' );
  26740. * ```
  26741. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  26742. * will automatically be updated when the `rotation` user data field changes.
  26743. *
  26744. * @augments ReferenceNode
  26745. */
  26746. class UserDataNode extends ReferenceNode {
  26747. static get type() {
  26748. return 'UserDataNode';
  26749. }
  26750. /**
  26751. * Constructs a new user data node.
  26752. *
  26753. * @param {string} property - The property name that should be referenced by the node.
  26754. * @param {string} inputType - The node data type of the reference.
  26755. * @param {?Object} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  26756. */
  26757. constructor( property, inputType, userData = null ) {
  26758. super( property, inputType, userData );
  26759. /**
  26760. * A reference to the `userData` object. If not provided, the `userData`
  26761. * property of the 3D object that uses the node material is evaluated.
  26762. *
  26763. * @type {?Object}
  26764. * @default null
  26765. */
  26766. this.userData = userData;
  26767. }
  26768. /**
  26769. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  26770. * `userData` field.
  26771. *
  26772. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  26773. * @return {Object} A reference to the `userData` field.
  26774. */
  26775. updateReference( state ) {
  26776. this.reference = this.userData !== null ? this.userData : state.object.userData;
  26777. return this.reference;
  26778. }
  26779. }
  26780. /**
  26781. * TSL function for creating a user data node.
  26782. *
  26783. * @tsl
  26784. * @function
  26785. * @param {string} name - The property name that should be referenced by the node.
  26786. * @param {string} inputType - The node data type of the reference.
  26787. * @param {?Object} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  26788. * @returns {UserDataNode}
  26789. */
  26790. const userData = ( name, inputType, userData ) => new UserDataNode( name, inputType, userData );
  26791. const _objectData = new WeakMap();
  26792. /**
  26793. * A node for representing motion or velocity vectors. Foundation
  26794. * for advanced post processing effects like motion blur or TRAA.
  26795. *
  26796. * The node keeps track of the model, view and projection matrices
  26797. * of the previous frame and uses them to compute offsets in NDC space.
  26798. * These offsets represent the final velocity.
  26799. *
  26800. * @augments TempNode
  26801. */
  26802. class VelocityNode extends TempNode {
  26803. static get type() {
  26804. return 'VelocityNode';
  26805. }
  26806. /**
  26807. * Constructs a new vertex color node.
  26808. */
  26809. constructor() {
  26810. super( 'vec2' );
  26811. /**
  26812. * The current projection matrix.
  26813. *
  26814. * @type {?Matrix4}
  26815. * @default null
  26816. */
  26817. this.projectionMatrix = null;
  26818. /**
  26819. * Overwritten since velocity nodes are updated per object.
  26820. *
  26821. * @type {string}
  26822. * @default 'object'
  26823. */
  26824. this.updateType = NodeUpdateType.OBJECT;
  26825. /**
  26826. * Overwritten since velocity nodes save data after the update.
  26827. *
  26828. * @type {string}
  26829. * @default 'object'
  26830. */
  26831. this.updateAfterType = NodeUpdateType.OBJECT;
  26832. /**
  26833. * Uniform node representing the previous model matrix in world space.
  26834. *
  26835. * @type {UniformNode<mat4>}
  26836. * @default null
  26837. */
  26838. this.previousModelWorldMatrix = uniform( new Matrix4() );
  26839. /**
  26840. * Uniform node representing the previous projection matrix.
  26841. *
  26842. * @type {UniformNode<mat4>}
  26843. * @default null
  26844. */
  26845. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  26846. /**
  26847. * Uniform node representing the previous view matrix.
  26848. *
  26849. * @type {UniformNode<mat4>}
  26850. * @default null
  26851. */
  26852. this.previousCameraViewMatrix = uniform( new Matrix4() );
  26853. }
  26854. /**
  26855. * Sets the given projection matrix.
  26856. *
  26857. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  26858. */
  26859. setProjectionMatrix( projectionMatrix ) {
  26860. this.projectionMatrix = projectionMatrix;
  26861. }
  26862. /**
  26863. * Updates velocity specific uniforms.
  26864. *
  26865. * @param {NodeFrame} frame - A reference to the current node frame.
  26866. */
  26867. update( { frameId, camera, object } ) {
  26868. const previousModelMatrix = getPreviousMatrix( object );
  26869. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  26870. //
  26871. const cameraData = getData( camera );
  26872. if ( cameraData.frameId !== frameId ) {
  26873. cameraData.frameId = frameId;
  26874. if ( cameraData.previousProjectionMatrix === undefined ) {
  26875. cameraData.previousProjectionMatrix = new Matrix4();
  26876. cameraData.previousCameraViewMatrix = new Matrix4();
  26877. cameraData.currentProjectionMatrix = new Matrix4();
  26878. cameraData.currentCameraViewMatrix = new Matrix4();
  26879. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26880. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  26881. } else {
  26882. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  26883. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  26884. }
  26885. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  26886. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  26887. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  26888. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  26889. }
  26890. }
  26891. /**
  26892. * Overwritten to updated velocity specific uniforms.
  26893. *
  26894. * @param {NodeFrame} frame - A reference to the current node frame.
  26895. */
  26896. updateAfter( { object } ) {
  26897. getPreviousMatrix( object ).copy( object.matrixWorld );
  26898. }
  26899. /**
  26900. * Implements the velocity computation based on the previous and current vertex data.
  26901. *
  26902. * @param {NodeBuilder} builder - A reference to the current node builder.
  26903. * @return {Node<vec2>} The motion vector.
  26904. */
  26905. setup( /*builder*/ ) {
  26906. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  26907. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  26908. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  26909. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  26910. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  26911. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  26912. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  26913. return velocity;
  26914. }
  26915. }
  26916. function getData( object ) {
  26917. let objectData = _objectData.get( object );
  26918. if ( objectData === undefined ) {
  26919. objectData = {};
  26920. _objectData.set( object, objectData );
  26921. }
  26922. return objectData;
  26923. }
  26924. function getPreviousMatrix( object, index = 0 ) {
  26925. const objectData = getData( object );
  26926. let matrix = objectData[ index ];
  26927. if ( matrix === undefined ) {
  26928. objectData[ index ] = matrix = new Matrix4();
  26929. objectData[ index ].copy( object.matrixWorld );
  26930. }
  26931. return matrix;
  26932. }
  26933. /**
  26934. * TSL object that represents the velocity of a render pass.
  26935. *
  26936. * @tsl
  26937. * @type {VelocityNode}
  26938. */
  26939. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  26940. /**
  26941. * Computes a grayscale value for the given RGB color value.
  26942. *
  26943. * @tsl
  26944. * @function
  26945. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  26946. * @return {Node<vec3>} The grayscale color.
  26947. */
  26948. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26949. return luminance( color.rgb );
  26950. } );
  26951. /**
  26952. * Super-saturates or desaturates the given RGB color.
  26953. *
  26954. * @tsl
  26955. * @function
  26956. * @param {Node<vec3>} color - The input color.
  26957. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  26958. * @return {Node<vec3>} The saturated color.
  26959. */
  26960. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26961. return adjustment.mix( luminance( color.rgb ), color.rgb );
  26962. } );
  26963. /**
  26964. * Selectively enhance the intensity of less saturated RGB colors. Can result
  26965. * in a more natural and visually appealing image with enhanced color depth
  26966. * compared to {@link ColorAdjustment#saturation}.
  26967. *
  26968. * @tsl
  26969. * @function
  26970. * @param {Node<vec3>} color - The input color.
  26971. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  26972. * @return {Node<vec3>} The updated color.
  26973. */
  26974. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26975. const average = add( color.r, color.g, color.b ).div( 3.0 );
  26976. const mx = color.r.max( color.g.max( color.b ) );
  26977. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  26978. return mix( color.rgb, mx, amt );
  26979. } );
  26980. /**
  26981. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  26982. *
  26983. * @tsl
  26984. * @function
  26985. * @param {Node<vec3>} color - The input color.
  26986. * @param {Node<float>} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  26987. * @return {Node<vec3>} The updated color.
  26988. */
  26989. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  26990. const k = vec3( 0.57735, 0.57735, 0.57735 );
  26991. const cosAngle = adjustment.cos();
  26992. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  26993. } );
  26994. /**
  26995. * Computes the luminance for the given RGB color value.
  26996. *
  26997. * @tsl
  26998. * @function
  26999. * @param {Node<vec3>} color - The color value to compute the luminance for.
  27000. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  27001. * @return {Node<float>} The luminance.
  27002. */
  27003. const luminance = (
  27004. color,
  27005. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  27006. ) => dot( color, luminanceCoefficients );
  27007. /**
  27008. * Color Decision List (CDL) v1.2
  27009. *
  27010. * Compact representation of color grading information, defined by slope, offset, power, and
  27011. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  27012. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  27013. *
  27014. * @tsl
  27015. * @function
  27016. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  27017. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  27018. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  27019. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  27020. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  27021. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  27022. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  27023. *
  27024. * References:
  27025. * - ASC CDL v1.2
  27026. * - {@link https://blender.stackexchange.com/a/55239/43930}
  27027. * - {@link https://docs.acescentral.com/specifications/acescc/}
  27028. */
  27029. const cdl = /*@__PURE__*/ Fn( ( [
  27030. color,
  27031. slope = vec3( 1 ),
  27032. offset = vec3( 0 ),
  27033. power = vec3( 1 ),
  27034. saturation = float( 1 ),
  27035. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  27036. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  27037. ] ) => {
  27038. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  27039. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  27040. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  27041. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  27042. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  27043. const pv = v.pow( power ).toVar();
  27044. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  27045. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  27046. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  27047. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  27048. return vec4( v.rgb, color.a );
  27049. } );
  27050. /**
  27051. * Represents a posterize effect which reduces the number of colors
  27052. * in an image, resulting in a more blocky and stylized appearance.
  27053. *
  27054. * @augments TempNode
  27055. */
  27056. class PosterizeNode extends TempNode {
  27057. static get type() {
  27058. return 'PosterizeNode';
  27059. }
  27060. /**
  27061. * Constructs a new posterize node.
  27062. *
  27063. * @param {Node} sourceNode - The input color.
  27064. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27065. */
  27066. constructor( sourceNode, stepsNode ) {
  27067. super();
  27068. /**
  27069. * The input color.
  27070. *
  27071. * @type {Node}
  27072. */
  27073. this.sourceNode = sourceNode;
  27074. /**
  27075. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27076. *
  27077. * @type {Node}
  27078. */
  27079. this.stepsNode = stepsNode;
  27080. }
  27081. setup() {
  27082. const { sourceNode, stepsNode } = this;
  27083. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  27084. }
  27085. }
  27086. /**
  27087. * TSL function for creating a posterize node.
  27088. *
  27089. * @tsl
  27090. * @function
  27091. * @param {Node} sourceNode - The input color.
  27092. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  27093. * @returns {PosterizeNode}
  27094. */
  27095. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  27096. let _sharedFramebuffer = null;
  27097. /**
  27098. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  27099. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  27100. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  27101. *
  27102. * @augments ViewportTextureNode
  27103. */
  27104. class ViewportSharedTextureNode extends ViewportTextureNode {
  27105. static get type() {
  27106. return 'ViewportSharedTextureNode';
  27107. }
  27108. /**
  27109. * Constructs a new viewport shared texture node.
  27110. *
  27111. * @param {Node} [uvNode=screenUV] - The uv node.
  27112. * @param {?Node} [levelNode=null] - The level node.
  27113. */
  27114. constructor( uvNode = screenUV, levelNode = null ) {
  27115. if ( _sharedFramebuffer === null ) {
  27116. _sharedFramebuffer = new FramebufferTexture();
  27117. }
  27118. super( uvNode, levelNode, _sharedFramebuffer );
  27119. }
  27120. /**
  27121. * Overwritten so the method always returns the unique shared
  27122. * framebuffer texture.
  27123. *
  27124. * @return {FramebufferTexture} The shared framebuffer texture.
  27125. */
  27126. getTextureForReference() {
  27127. return _sharedFramebuffer;
  27128. }
  27129. updateReference() {
  27130. return this;
  27131. }
  27132. }
  27133. /**
  27134. * TSL function for creating a shared viewport texture node.
  27135. *
  27136. * @tsl
  27137. * @function
  27138. * @param {?Node} [uvNode=screenUV] - The uv node.
  27139. * @param {?Node} [levelNode=null] - The level node.
  27140. * @returns {ViewportSharedTextureNode}
  27141. */
  27142. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  27143. const _size = /*@__PURE__*/ new Vector2();
  27144. /**
  27145. * Represents the texture of a pass node.
  27146. *
  27147. * @augments TextureNode
  27148. */
  27149. class PassTextureNode extends TextureNode {
  27150. static get type() {
  27151. return 'PassTextureNode';
  27152. }
  27153. /**
  27154. * Constructs a new pass texture node.
  27155. *
  27156. * @param {PassNode} passNode - The pass node.
  27157. * @param {Texture} texture - The output texture.
  27158. */
  27159. constructor( passNode, texture ) {
  27160. super( texture );
  27161. /**
  27162. * A reference to the pass node.
  27163. *
  27164. * @type {PassNode}
  27165. */
  27166. this.passNode = passNode;
  27167. this.setUpdateMatrix( false );
  27168. }
  27169. setup( builder ) {
  27170. this.passNode.build( builder );
  27171. return super.setup( builder );
  27172. }
  27173. clone() {
  27174. return new this.constructor( this.passNode, this.value );
  27175. }
  27176. }
  27177. /**
  27178. * An extension of `PassTextureNode` which allows to manage more than one
  27179. * internal texture. Relevant for the `getPreviousTexture()` related API.
  27180. *
  27181. * @augments PassTextureNode
  27182. */
  27183. class PassMultipleTextureNode extends PassTextureNode {
  27184. static get type() {
  27185. return 'PassMultipleTextureNode';
  27186. }
  27187. /**
  27188. * Constructs a new pass texture node.
  27189. *
  27190. * @param {PassNode} passNode - The pass node.
  27191. * @param {string} textureName - The output texture name.
  27192. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  27193. */
  27194. constructor( passNode, textureName, previousTexture = false ) {
  27195. // null is passed to the super call since this class does not
  27196. // use an external texture for rendering pass data into. Instead
  27197. // the texture is managed by the pass node itself
  27198. super( passNode, null );
  27199. /**
  27200. * The output texture name.
  27201. *
  27202. * @type {string}
  27203. */
  27204. this.textureName = textureName;
  27205. /**
  27206. * Whether previous frame data should be used or not.
  27207. *
  27208. * @type {boolean}
  27209. */
  27210. this.previousTexture = previousTexture;
  27211. }
  27212. /**
  27213. * Updates the texture reference of this node.
  27214. */
  27215. updateTexture() {
  27216. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  27217. }
  27218. setup( builder ) {
  27219. this.updateTexture();
  27220. return super.setup( builder );
  27221. }
  27222. clone() {
  27223. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  27224. newNode.uvNode = this.uvNode;
  27225. newNode.levelNode = this.levelNode;
  27226. newNode.biasNode = this.biasNode;
  27227. newNode.sampler = this.sampler;
  27228. newNode.depthNode = this.depthNode;
  27229. newNode.compareNode = this.compareNode;
  27230. newNode.gradNode = this.gradNode;
  27231. newNode.offsetNode = this.offsetNode;
  27232. return newNode;
  27233. }
  27234. }
  27235. /**
  27236. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  27237. * This pass produces a render for the given scene and camera and can provide multiple outputs
  27238. * via MRT for further processing.
  27239. *
  27240. * ```js
  27241. * const postProcessing = new RenderPipeline( renderer );
  27242. *
  27243. * const scenePass = pass( scene, camera );
  27244. *
  27245. * postProcessing.outputNode = scenePass;
  27246. * ```
  27247. *
  27248. * @augments TempNode
  27249. */
  27250. class PassNode extends TempNode {
  27251. static get type() {
  27252. return 'PassNode';
  27253. }
  27254. /**
  27255. * Constructs a new pass node.
  27256. *
  27257. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  27258. * @param {Scene} scene - A reference to the scene.
  27259. * @param {Camera} camera - A reference to the camera.
  27260. * @param {Object} options - Options for the internal render target.
  27261. */
  27262. constructor( scope, scene, camera, options = {} ) {
  27263. super( 'vec4' );
  27264. /**
  27265. * The scope of the pass. The scope determines whether the node outputs color or depth.
  27266. *
  27267. * @type {('color'|'depth')}
  27268. */
  27269. this.scope = scope;
  27270. /**
  27271. * A reference to the scene.
  27272. *
  27273. * @type {Scene}
  27274. */
  27275. this.scene = scene;
  27276. /**
  27277. * A reference to the camera.
  27278. *
  27279. * @type {Camera}
  27280. */
  27281. this.camera = camera;
  27282. /**
  27283. * Options for the internal render target.
  27284. *
  27285. * @type {Object}
  27286. */
  27287. this.options = options;
  27288. /**
  27289. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  27290. *
  27291. * @private
  27292. * @type {number}
  27293. * @default 1
  27294. */
  27295. this._pixelRatio = 1;
  27296. /**
  27297. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  27298. * @private
  27299. * @type {number}
  27300. * @default 1
  27301. */
  27302. this._width = 1;
  27303. /**
  27304. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  27305. * @private
  27306. * @type {number}
  27307. * @default 1
  27308. */
  27309. this._height = 1;
  27310. const depthTexture = new DepthTexture();
  27311. depthTexture.isRenderTargetTexture = true;
  27312. //depthTexture.type = FloatType;
  27313. depthTexture.name = 'depth';
  27314. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  27315. renderTarget.texture.name = 'output';
  27316. renderTarget.depthTexture = depthTexture;
  27317. /**
  27318. * The pass's render target.
  27319. *
  27320. * @type {RenderTarget}
  27321. */
  27322. this.renderTarget = renderTarget;
  27323. /**
  27324. * An optional override material for the pass.
  27325. *
  27326. * @type {Material|null}
  27327. */
  27328. this.overrideMaterial = null;
  27329. /**
  27330. * Whether the pass is transparent.
  27331. *
  27332. * @type {boolean}
  27333. * @default false
  27334. */
  27335. this.transparent = true;
  27336. /**
  27337. * Whether the pass is opaque.
  27338. *
  27339. * @type {boolean}
  27340. * @default true
  27341. */
  27342. this.opaque = true;
  27343. /**
  27344. * An optional global context for the pass.
  27345. *
  27346. * @type {ContextNode|null}
  27347. */
  27348. this.contextNode = null;
  27349. /**
  27350. * A cache for the context node.
  27351. *
  27352. * @private
  27353. * @type {?Object}
  27354. * @default null
  27355. */
  27356. this._contextNodeCache = null;
  27357. /**
  27358. * A dictionary holding the internal result textures.
  27359. *
  27360. * @private
  27361. * @type {Object<string, Texture>}
  27362. */
  27363. this._textures = {
  27364. output: renderTarget.texture,
  27365. depth: depthTexture
  27366. };
  27367. /**
  27368. * A dictionary holding the internal texture nodes.
  27369. *
  27370. * @private
  27371. * @type {Object<string, TextureNode>}
  27372. */
  27373. this._textureNodes = {};
  27374. /**
  27375. * A dictionary holding the internal depth nodes.
  27376. *
  27377. * @private
  27378. * @type {Object}
  27379. */
  27380. this._linearDepthNodes = {};
  27381. /**
  27382. * A dictionary holding the internal viewZ nodes.
  27383. *
  27384. * @private
  27385. * @type {Object}
  27386. */
  27387. this._viewZNodes = {};
  27388. /**
  27389. * A dictionary holding the texture data of the previous frame.
  27390. * Used for computing velocity/motion vectors.
  27391. *
  27392. * @private
  27393. * @type {Object<string, Texture>}
  27394. */
  27395. this._previousTextures = {};
  27396. /**
  27397. * A dictionary holding the texture nodes of the previous frame.
  27398. * Used for computing velocity/motion vectors.
  27399. *
  27400. * @private
  27401. * @type {Object<string, TextureNode>}
  27402. */
  27403. this._previousTextureNodes = {};
  27404. /**
  27405. * The `near` property of the camera as a uniform.
  27406. *
  27407. * @private
  27408. * @type {UniformNode}
  27409. */
  27410. this._cameraNear = uniform( 0 );
  27411. /**
  27412. * The `far` property of the camera as a uniform.
  27413. *
  27414. * @private
  27415. * @type {UniformNode}
  27416. */
  27417. this._cameraFar = uniform( 0 );
  27418. /**
  27419. * A MRT node configuring the MRT settings.
  27420. *
  27421. * @private
  27422. * @type {?MRTNode}
  27423. * @default null
  27424. */
  27425. this._mrt = null;
  27426. /**
  27427. * Layer object for configuring the camera that is used
  27428. * to produce the pass.
  27429. *
  27430. * @private
  27431. * @type {?Layers}
  27432. * @default null
  27433. */
  27434. this._layers = null;
  27435. /**
  27436. * Scales the resolution of the internal render target.
  27437. *
  27438. * @private
  27439. * @type {number}
  27440. * @default 1
  27441. */
  27442. this._resolutionScale = 1;
  27443. /**
  27444. * Custom viewport definition.
  27445. *
  27446. * @private
  27447. * @type {?Vector4}
  27448. * @default null
  27449. */
  27450. this._viewport = null;
  27451. /**
  27452. * Custom scissor definition.
  27453. *
  27454. * @private
  27455. * @type {?Vector4}
  27456. * @default null
  27457. */
  27458. this._scissor = null;
  27459. /**
  27460. * This flag can be used for type testing.
  27461. *
  27462. * @type {boolean}
  27463. * @readonly
  27464. * @default true
  27465. */
  27466. this.isPassNode = true;
  27467. /**
  27468. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  27469. * scene once per frame in its {@link PassNode#updateBefore} method.
  27470. *
  27471. * @type {string}
  27472. * @default 'frame'
  27473. */
  27474. this.updateBeforeType = NodeUpdateType.FRAME;
  27475. /**
  27476. * This flag is used for global cache.
  27477. *
  27478. * @type {boolean}
  27479. * @default true
  27480. */
  27481. this.global = true;
  27482. }
  27483. /**
  27484. * Sets the resolution scale for the pass.
  27485. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  27486. *
  27487. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  27488. * @return {PassNode} A reference to this pass.
  27489. */
  27490. setResolutionScale( resolutionScale ) {
  27491. this._resolutionScale = resolutionScale;
  27492. return this;
  27493. }
  27494. /**
  27495. * Gets the current resolution scale of the pass.
  27496. *
  27497. * @return {number} The current resolution scale. A value of `1` means full resolution.
  27498. */
  27499. getResolutionScale() {
  27500. return this._resolutionScale;
  27501. }
  27502. /**
  27503. * Sets the resolution for the pass.
  27504. * The resolution is a factor that is multiplied with the renderer's width and height.
  27505. *
  27506. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  27507. * @return {PassNode} A reference to this pass.
  27508. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  27509. */
  27510. setResolution( resolution ) { // @deprecated, r181
  27511. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  27512. return this.setResolutionScale( resolution );
  27513. }
  27514. /**
  27515. * Gets the current resolution of the pass.
  27516. *
  27517. * @return {number} The current resolution. A value of `1` means full resolution.
  27518. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  27519. */
  27520. getResolution() { // @deprecated, r181
  27521. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  27522. return this.getResolutionScale();
  27523. }
  27524. /**
  27525. * Sets the layer configuration that should be used when rendering the pass.
  27526. *
  27527. * @param {Layers} layers - The layers object to set.
  27528. * @return {PassNode} A reference to this pass.
  27529. */
  27530. setLayers( layers ) {
  27531. this._layers = layers;
  27532. return this;
  27533. }
  27534. /**
  27535. * Gets the current layer configuration of the pass.
  27536. *
  27537. * @return {?Layers} .
  27538. */
  27539. getLayers() {
  27540. return this._layers;
  27541. }
  27542. /**
  27543. * Sets the given MRT node to setup MRT for this pass.
  27544. *
  27545. * @param {MRTNode} mrt - The MRT object.
  27546. * @return {PassNode} A reference to this pass.
  27547. */
  27548. setMRT( mrt ) {
  27549. this._mrt = mrt;
  27550. return this;
  27551. }
  27552. /**
  27553. * Returns the current MRT node.
  27554. *
  27555. * @return {MRTNode} The current MRT node.
  27556. */
  27557. getMRT() {
  27558. return this._mrt;
  27559. }
  27560. /**
  27561. * Returns the texture for the given output name.
  27562. *
  27563. * @param {string} name - The output name to get the texture for.
  27564. * @return {Texture} The texture.
  27565. */
  27566. getTexture( name ) {
  27567. let texture = this._textures[ name ];
  27568. if ( texture === undefined ) {
  27569. const refTexture = this.renderTarget.texture;
  27570. texture = refTexture.clone();
  27571. texture.name = name;
  27572. this._textures[ name ] = texture;
  27573. this.renderTarget.textures.push( texture );
  27574. }
  27575. return texture;
  27576. }
  27577. /**
  27578. * Returns the texture holding the data of the previous frame for the given output name.
  27579. *
  27580. * @param {string} name - The output name to get the texture for.
  27581. * @return {Texture} The texture holding the data of the previous frame.
  27582. */
  27583. getPreviousTexture( name ) {
  27584. let texture = this._previousTextures[ name ];
  27585. if ( texture === undefined ) {
  27586. texture = this.getTexture( name ).clone();
  27587. this._previousTextures[ name ] = texture;
  27588. }
  27589. return texture;
  27590. }
  27591. /**
  27592. * Switches current and previous textures for the given output name.
  27593. *
  27594. * @param {string} name - The output name.
  27595. */
  27596. toggleTexture( name ) {
  27597. const prevTexture = this._previousTextures[ name ];
  27598. if ( prevTexture !== undefined ) {
  27599. const texture = this._textures[ name ];
  27600. const index = this.renderTarget.textures.indexOf( texture );
  27601. this.renderTarget.textures[ index ] = prevTexture;
  27602. this._textures[ name ] = prevTexture;
  27603. this._previousTextures[ name ] = texture;
  27604. this._textureNodes[ name ].updateTexture();
  27605. this._previousTextureNodes[ name ].updateTexture();
  27606. }
  27607. }
  27608. /**
  27609. * Returns the texture node for the given output name.
  27610. *
  27611. * @param {string} [name='output'] - The output name to get the texture node for.
  27612. * @return {TextureNode} The texture node.
  27613. */
  27614. getTextureNode( name = 'output' ) {
  27615. let textureNode = this._textureNodes[ name ];
  27616. if ( textureNode === undefined ) {
  27617. textureNode = new PassMultipleTextureNode( this, name );
  27618. textureNode.updateTexture();
  27619. this._textureNodes[ name ] = textureNode;
  27620. }
  27621. return textureNode;
  27622. }
  27623. /**
  27624. * Returns the previous texture node for the given output name.
  27625. *
  27626. * @param {string} [name='output'] - The output name to get the previous texture node for.
  27627. * @return {TextureNode} The previous texture node.
  27628. */
  27629. getPreviousTextureNode( name = 'output' ) {
  27630. let textureNode = this._previousTextureNodes[ name ];
  27631. if ( textureNode === undefined ) {
  27632. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  27633. textureNode = new PassMultipleTextureNode( this, name, true );
  27634. textureNode.updateTexture();
  27635. this._previousTextureNodes[ name ] = textureNode;
  27636. }
  27637. return textureNode;
  27638. }
  27639. /**
  27640. * Returns a viewZ node of this pass.
  27641. *
  27642. * @param {string} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  27643. * @return {Node} The viewZ node.
  27644. */
  27645. getViewZNode( name = 'depth' ) {
  27646. let viewZNode = this._viewZNodes[ name ];
  27647. if ( viewZNode === undefined ) {
  27648. const cameraNear = this._cameraNear;
  27649. const cameraFar = this._cameraFar;
  27650. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  27651. }
  27652. return viewZNode;
  27653. }
  27654. /**
  27655. * Returns a linear depth node of this pass.
  27656. *
  27657. * @param {string} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  27658. * @return {Node} The linear depth node.
  27659. */
  27660. getLinearDepthNode( name = 'depth' ) {
  27661. let linearDepthNode = this._linearDepthNodes[ name ];
  27662. if ( linearDepthNode === undefined ) {
  27663. const cameraNear = this._cameraNear;
  27664. const cameraFar = this._cameraFar;
  27665. const viewZNode = this.getViewZNode( name );
  27666. // TODO: just if ( builder.camera.isPerspectiveCamera )
  27667. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  27668. }
  27669. return linearDepthNode;
  27670. }
  27671. /**
  27672. * Precompiles the pass.
  27673. *
  27674. * Note that this method must be called after the pass configuration is complete.
  27675. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  27676. *
  27677. * @async
  27678. * @param {Renderer} renderer - The renderer.
  27679. * @return {Promise} A Promise that resolves when the compile has been finished.
  27680. * @see {@link Renderer#compileAsync}
  27681. */
  27682. async compileAsync( renderer ) {
  27683. const currentRenderTarget = renderer.getRenderTarget();
  27684. const currentMRT = renderer.getMRT();
  27685. renderer.setRenderTarget( this.renderTarget );
  27686. renderer.setMRT( this._mrt );
  27687. await renderer.compileAsync( this.scene, this.camera );
  27688. renderer.setRenderTarget( currentRenderTarget );
  27689. renderer.setMRT( currentMRT );
  27690. }
  27691. setup( { renderer } ) {
  27692. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  27693. this.renderTarget.texture.type = renderer.getOutputBufferType();
  27694. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  27695. }
  27696. updateBefore( frame ) {
  27697. const { renderer } = frame;
  27698. const { scene } = this;
  27699. let camera;
  27700. let pixelRatio;
  27701. const outputRenderTarget = renderer.getOutputRenderTarget();
  27702. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  27703. pixelRatio = 1;
  27704. camera = renderer.xr.getCamera();
  27705. renderer.xr.updateCamera( camera );
  27706. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  27707. } else {
  27708. camera = this.camera;
  27709. pixelRatio = renderer.getPixelRatio();
  27710. renderer.getSize( _size );
  27711. }
  27712. this._pixelRatio = pixelRatio;
  27713. this.setSize( _size.width, _size.height );
  27714. const currentRenderTarget = renderer.getRenderTarget();
  27715. const currentMRT = renderer.getMRT();
  27716. const currentAutoClear = renderer.autoClear;
  27717. const currentTransparent = renderer.transparent;
  27718. const currentOpaque = renderer.opaque;
  27719. const currentMask = camera.layers.mask;
  27720. const currentContextNode = renderer.contextNode;
  27721. const currentOverrideMaterial = scene.overrideMaterial;
  27722. this._cameraNear.value = camera.near;
  27723. this._cameraFar.value = camera.far;
  27724. if ( this._layers !== null ) {
  27725. camera.layers.mask = this._layers.mask;
  27726. }
  27727. for ( const name in this._previousTextures ) {
  27728. this.toggleTexture( name );
  27729. }
  27730. if ( this.overrideMaterial !== null ) {
  27731. scene.overrideMaterial = this.overrideMaterial;
  27732. }
  27733. renderer.setRenderTarget( this.renderTarget );
  27734. renderer.setMRT( this._mrt );
  27735. renderer.autoClear = true;
  27736. renderer.transparent = this.transparent;
  27737. renderer.opaque = this.opaque;
  27738. if ( this.contextNode !== null ) {
  27739. if ( this._contextNodeCache === null || this._contextNodeCache.version !== this.version ) {
  27740. this._contextNodeCache = {
  27741. version: this.version,
  27742. context: context( { ...renderer.contextNode.getFlowContextData(), ...this.contextNode.getFlowContextData() } )
  27743. };
  27744. }
  27745. renderer.contextNode = this._contextNodeCache.context;
  27746. }
  27747. const currentSceneName = scene.name;
  27748. scene.name = this.name ? this.name : scene.name;
  27749. renderer.render( scene, camera );
  27750. scene.name = currentSceneName;
  27751. scene.overrideMaterial = currentOverrideMaterial;
  27752. renderer.setRenderTarget( currentRenderTarget );
  27753. renderer.setMRT( currentMRT );
  27754. renderer.autoClear = currentAutoClear;
  27755. renderer.transparent = currentTransparent;
  27756. renderer.opaque = currentOpaque;
  27757. renderer.contextNode = currentContextNode;
  27758. camera.layers.mask = currentMask;
  27759. }
  27760. /**
  27761. * Sets the size of the pass's render target. Honors the pixel ratio.
  27762. *
  27763. * @param {number} width - The width to set.
  27764. * @param {number} height - The height to set.
  27765. */
  27766. setSize( width, height ) {
  27767. this._width = width;
  27768. this._height = height;
  27769. const effectiveWidth = Math.floor( this._width * this._pixelRatio * this._resolutionScale );
  27770. const effectiveHeight = Math.floor( this._height * this._pixelRatio * this._resolutionScale );
  27771. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  27772. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  27773. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  27774. }
  27775. /**
  27776. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  27777. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27778. * with `null` as the single argument.
  27779. *
  27780. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  27781. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  27782. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  27783. * @param {number} width - The width of the scissor box in logical pixel unit.
  27784. * @param {number} height - The height of the scissor box in logical pixel unit.
  27785. */
  27786. setScissor( x, y, width, height ) {
  27787. if ( x === null ) {
  27788. this._scissor = null;
  27789. } else {
  27790. if ( this._scissor === null ) this._scissor = new Vector4();
  27791. if ( x.isVector4 ) {
  27792. this._scissor.copy( x );
  27793. } else {
  27794. this._scissor.set( x, y, width, height );
  27795. }
  27796. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27797. }
  27798. }
  27799. /**
  27800. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  27801. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  27802. * with `null` as the single argument.
  27803. *
  27804. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27805. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  27806. * @param {number} width - The width of the viewport in logical pixel unit.
  27807. * @param {number} height - The height of the viewport in logical pixel unit.
  27808. */
  27809. setViewport( x, y, width, height ) {
  27810. if ( x === null ) {
  27811. this._viewport = null;
  27812. } else {
  27813. if ( this._viewport === null ) this._viewport = new Vector4();
  27814. if ( x.isVector4 ) {
  27815. this._viewport.copy( x );
  27816. } else {
  27817. this._viewport.set( x, y, width, height );
  27818. }
  27819. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  27820. }
  27821. }
  27822. /**
  27823. * Sets the pixel ratio the pass's render target and updates the size.
  27824. *
  27825. * @param {number} pixelRatio - The pixel ratio to set.
  27826. */
  27827. setPixelRatio( pixelRatio ) {
  27828. this._pixelRatio = pixelRatio;
  27829. this.setSize( this._width, this._height );
  27830. }
  27831. /**
  27832. * Frees internal resources. Should be called when the node is no longer in use.
  27833. */
  27834. dispose() {
  27835. this.renderTarget.dispose();
  27836. }
  27837. }
  27838. /**
  27839. * @static
  27840. * @type {'color'}
  27841. * @default 'color'
  27842. */
  27843. PassNode.COLOR = 'color';
  27844. /**
  27845. * @static
  27846. * @type {'depth'}
  27847. * @default 'depth'
  27848. */
  27849. PassNode.DEPTH = 'depth';
  27850. /**
  27851. * TSL function for creating a pass node.
  27852. *
  27853. * @tsl
  27854. * @function
  27855. * @param {Scene} scene - A reference to the scene.
  27856. * @param {Camera} camera - A reference to the camera.
  27857. * @param {Object} options - Options for the internal render target.
  27858. * @returns {PassNode}
  27859. */
  27860. const pass = ( scene, camera, options ) => new PassNode( PassNode.COLOR, scene, camera, options );
  27861. /**
  27862. * TSL function for creating a pass texture node.
  27863. *
  27864. * @tsl
  27865. * @function
  27866. * @param {PassNode} pass - The pass node.
  27867. * @param {Texture} texture - The output texture.
  27868. * @returns {PassTextureNode}
  27869. */
  27870. const passTexture = ( pass, texture ) => new PassTextureNode( pass, texture );
  27871. /**
  27872. * TSL function for creating a depth pass node.
  27873. *
  27874. * @tsl
  27875. * @function
  27876. * @param {Scene} scene - A reference to the scene.
  27877. * @param {Camera} camera - A reference to the camera.
  27878. * @param {Object} options - Options for the internal render target.
  27879. * @returns {PassNode}
  27880. */
  27881. const depthPass = ( scene, camera, options ) => new PassNode( PassNode.DEPTH, scene, camera, options );
  27882. /**
  27883. * Represents a render pass for producing a toon outline effect on compatible objects.
  27884. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  27885. * will receive the outline.
  27886. *
  27887. * ```js
  27888. * const postProcessing = new RenderPipeline( renderer );
  27889. *
  27890. * const scenePass = toonOutlinePass( scene, camera );
  27891. *
  27892. * postProcessing.outputNode = scenePass;
  27893. * ```
  27894. * @augments PassNode
  27895. */
  27896. class ToonOutlinePassNode extends PassNode {
  27897. static get type() {
  27898. return 'ToonOutlinePassNode';
  27899. }
  27900. /**
  27901. * Constructs a new outline pass node.
  27902. *
  27903. * @param {Scene} scene - A reference to the scene.
  27904. * @param {Camera} camera - A reference to the camera.
  27905. * @param {Node} colorNode - Defines the outline's color.
  27906. * @param {Node} thicknessNode - Defines the outline's thickness.
  27907. * @param {Node} alphaNode - Defines the outline's alpha.
  27908. */
  27909. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  27910. super( PassNode.COLOR, scene, camera );
  27911. /**
  27912. * Defines the outline's color.
  27913. *
  27914. * @type {Node}
  27915. */
  27916. this.colorNode = colorNode;
  27917. /**
  27918. * Defines the outline's thickness.
  27919. *
  27920. * @type {Node}
  27921. */
  27922. this.thicknessNode = thicknessNode;
  27923. /**
  27924. * Defines the outline's alpha.
  27925. *
  27926. * @type {Node}
  27927. */
  27928. this.alphaNode = alphaNode;
  27929. /**
  27930. * An internal material cache.
  27931. *
  27932. * @private
  27933. * @type {WeakMap<Material, NodeMaterial>}
  27934. */
  27935. this._materialCache = new WeakMap();
  27936. /**
  27937. * The name of this pass.
  27938. *
  27939. * @type {string}
  27940. * @default 'Outline Pass'
  27941. */
  27942. this.name = 'Outline Pass';
  27943. }
  27944. updateBefore( frame ) {
  27945. const { renderer } = frame;
  27946. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27947. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  27948. // only render outline for supported materials
  27949. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  27950. if ( material.wireframe === false ) {
  27951. const outlineMaterial = this._getOutlineMaterial( material );
  27952. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  27953. }
  27954. }
  27955. // default
  27956. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  27957. } );
  27958. super.updateBefore( frame );
  27959. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27960. }
  27961. /**
  27962. * Creates the material used for outline rendering.
  27963. *
  27964. * @private
  27965. * @return {NodeMaterial} The outline material.
  27966. */
  27967. _createMaterial() {
  27968. const material = new NodeMaterial();
  27969. material.isMeshToonOutlineMaterial = true;
  27970. material.name = 'Toon_Outline';
  27971. material.side = BackSide;
  27972. // vertex node
  27973. const outlineNormal = normalLocal.negate();
  27974. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  27975. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  27976. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  27977. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  27978. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  27979. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  27980. // color node
  27981. material.colorNode = vec4( this.colorNode, this.alphaNode );
  27982. return material;
  27983. }
  27984. /**
  27985. * For the given toon material, this method returns a corresponding
  27986. * outline material.
  27987. *
  27988. * @private
  27989. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  27990. * @return {NodeMaterial} The outline material.
  27991. */
  27992. _getOutlineMaterial( originalMaterial ) {
  27993. let outlineMaterial = this._materialCache.get( originalMaterial );
  27994. if ( outlineMaterial === undefined ) {
  27995. outlineMaterial = this._createMaterial();
  27996. this._materialCache.set( originalMaterial, outlineMaterial );
  27997. }
  27998. return outlineMaterial;
  27999. }
  28000. }
  28001. /**
  28002. * TSL function for creating a toon outline pass node.
  28003. *
  28004. * @tsl
  28005. * @function
  28006. * @param {Scene} scene - A reference to the scene.
  28007. * @param {Camera} camera - A reference to the camera.
  28008. * @param {Color} color - Defines the outline's color.
  28009. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  28010. * @param {number} [alpha=1] - Defines the outline's alpha.
  28011. * @returns {ToonOutlinePassNode}
  28012. */
  28013. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  28014. /**
  28015. * Linear tone mapping, exposure only.
  28016. *
  28017. * @tsl
  28018. * @function
  28019. * @param {Node<vec3>} color - The color that should be tone mapped.
  28020. * @param {Node<float>} exposure - The exposure.
  28021. * @return {Node<vec3>} The tone mapped color.
  28022. */
  28023. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28024. return color.mul( exposure ).clamp();
  28025. } ).setLayout( {
  28026. name: 'linearToneMapping',
  28027. type: 'vec3',
  28028. inputs: [
  28029. { name: 'color', type: 'vec3' },
  28030. { name: 'exposure', type: 'float' }
  28031. ]
  28032. } );
  28033. /**
  28034. * Reinhard tone mapping.
  28035. *
  28036. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  28037. *
  28038. * @tsl
  28039. * @function
  28040. * @param {Node<vec3>} color - The color that should be tone mapped.
  28041. * @param {Node<float>} exposure - The exposure.
  28042. * @return {Node<vec3>} The tone mapped color.
  28043. */
  28044. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28045. color = color.mul( exposure );
  28046. return color.div( color.add( 1.0 ) ).clamp();
  28047. } ).setLayout( {
  28048. name: 'reinhardToneMapping',
  28049. type: 'vec3',
  28050. inputs: [
  28051. { name: 'color', type: 'vec3' },
  28052. { name: 'exposure', type: 'float' }
  28053. ]
  28054. } );
  28055. /**
  28056. * Cineon tone mapping.
  28057. *
  28058. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  28059. *
  28060. * @tsl
  28061. * @function
  28062. * @param {Node<vec3>} color - The color that should be tone mapped.
  28063. * @param {Node<float>} exposure - The exposure.
  28064. * @return {Node<vec3>} The tone mapped color.
  28065. */
  28066. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28067. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  28068. color = color.mul( exposure );
  28069. color = color.sub( 0.004 ).max( 0.0 );
  28070. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  28071. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  28072. return a.div( b ).pow( 2.2 );
  28073. } ).setLayout( {
  28074. name: 'cineonToneMapping',
  28075. type: 'vec3',
  28076. inputs: [
  28077. { name: 'color', type: 'vec3' },
  28078. { name: 'exposure', type: 'float' }
  28079. ]
  28080. } );
  28081. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  28082. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  28083. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  28084. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  28085. return a.div( b );
  28086. } );
  28087. /**
  28088. * ACESFilmic tone mapping.
  28089. *
  28090. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  28091. *
  28092. * @tsl
  28093. * @function
  28094. * @param {Node<vec3>} color - The color that should be tone mapped.
  28095. * @param {Node<float>} exposure - The exposure.
  28096. * @return {Node<vec3>} The tone mapped color.
  28097. */
  28098. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28099. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  28100. const ACESInputMat = mat3(
  28101. 0.59719, 0.35458, 0.04823,
  28102. 0.07600, 0.90834, 0.01566,
  28103. 0.02840, 0.13383, 0.83777
  28104. );
  28105. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  28106. const ACESOutputMat = mat3(
  28107. 1.60475, -0.53108, -0.07367,
  28108. -0.10208, 1.10813, -605e-5,
  28109. -327e-5, -0.07276, 1.07602
  28110. );
  28111. color = color.mul( exposure ).div( 0.6 );
  28112. color = ACESInputMat.mul( color );
  28113. // Apply RRT and ODT
  28114. color = RRTAndODTFit( color );
  28115. color = ACESOutputMat.mul( color );
  28116. // Clamp to [0, 1]
  28117. return color.clamp();
  28118. } ).setLayout( {
  28119. name: 'acesFilmicToneMapping',
  28120. type: 'vec3',
  28121. inputs: [
  28122. { name: 'color', type: 'vec3' },
  28123. { name: 'exposure', type: 'float' }
  28124. ]
  28125. } );
  28126. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, -0.1246, -0.0182 ), vec3( -0.5876, 1.1329, -0.1006 ), vec3( -0.0728, -83e-4, 1.1187 ) );
  28127. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  28128. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28129. const x = vec3( x_immutable ).toVar();
  28130. const x2 = vec3( x.mul( x ) ).toVar();
  28131. const x4 = vec3( x2.mul( x2 ) ).toVar();
  28132. 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 ) ) ) );
  28133. } );
  28134. /**
  28135. * AgX tone mapping.
  28136. *
  28137. * @tsl
  28138. * @function
  28139. * @param {Node<vec3>} color - The color that should be tone mapped.
  28140. * @param {Node<float>} exposure - The exposure.
  28141. * @return {Node<vec3>} The tone mapped color.
  28142. */
  28143. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28144. const colortone = vec3( color ).toVar();
  28145. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  28146. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  28147. const AgxMinEv = float( -12.47393 );
  28148. const AgxMaxEv = float( 4.026069 );
  28149. colortone.mulAssign( exposure );
  28150. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  28151. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  28152. colortone.assign( max$1( colortone, 1e-10 ) );
  28153. colortone.assign( log2( colortone ) );
  28154. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  28155. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28156. colortone.assign( agxDefaultContrastApprox( colortone ) );
  28157. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  28158. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  28159. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  28160. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  28161. return colortone;
  28162. } ).setLayout( {
  28163. name: 'agxToneMapping',
  28164. type: 'vec3',
  28165. inputs: [
  28166. { name: 'color', type: 'vec3' },
  28167. { name: 'exposure', type: 'float' }
  28168. ]
  28169. } );
  28170. /**
  28171. * Neutral tone mapping.
  28172. *
  28173. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  28174. *
  28175. * @tsl
  28176. * @function
  28177. * @param {Node<vec3>} color - The color that should be tone mapped.
  28178. * @param {Node<float>} exposure - The exposure.
  28179. * @return {Node<vec3>} The tone mapped color.
  28180. */
  28181. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  28182. const StartCompression = float( 0.8 - 0.04 );
  28183. const Desaturation = float( 0.15 );
  28184. color = color.mul( exposure );
  28185. const x = min$1( color.r, min$1( color.g, color.b ) );
  28186. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  28187. color.subAssign( offset );
  28188. const peak = max$1( color.r, max$1( color.g, color.b ) );
  28189. If( peak.lessThan( StartCompression ), () => {
  28190. return color;
  28191. } );
  28192. const d = sub( 1, StartCompression );
  28193. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  28194. color.mulAssign( newPeak.div( peak ) );
  28195. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  28196. return mix( color, vec3( newPeak ), g );
  28197. } ).setLayout( {
  28198. name: 'neutralToneMapping',
  28199. type: 'vec3',
  28200. inputs: [
  28201. { name: 'color', type: 'vec3' },
  28202. { name: 'exposure', type: 'float' }
  28203. ]
  28204. } );
  28205. /**
  28206. * This class represents native code sections. It is the base
  28207. * class for modules like {@link FunctionNode} which allows to implement
  28208. * functions with native shader languages.
  28209. *
  28210. * @augments Node
  28211. */
  28212. class CodeNode extends Node {
  28213. static get type() {
  28214. return 'CodeNode';
  28215. }
  28216. /**
  28217. * Constructs a new code node.
  28218. *
  28219. * @param {string} [code=''] - The native code.
  28220. * @param {Array<Node>} [includes=[]] - An array of includes.
  28221. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28222. */
  28223. constructor( code = '', includes = [], language = '' ) {
  28224. super( 'code' );
  28225. /**
  28226. * This flag can be used for type testing.
  28227. *
  28228. * @type {boolean}
  28229. * @readonly
  28230. * @default true
  28231. */
  28232. this.isCodeNode = true;
  28233. /**
  28234. * This flag is used for global cache.
  28235. *
  28236. * @type {boolean}
  28237. * @default true
  28238. */
  28239. this.global = true;
  28240. /**
  28241. * The native code.
  28242. *
  28243. * @type {string}
  28244. * @default ''
  28245. */
  28246. this.code = code;
  28247. /**
  28248. * An array of includes
  28249. *
  28250. * @type {Array<Node>}
  28251. * @default []
  28252. */
  28253. this.includes = includes;
  28254. /**
  28255. * The used language.
  28256. *
  28257. * @type {('js'|'wgsl'|'glsl')}
  28258. * @default ''
  28259. */
  28260. this.language = language;
  28261. }
  28262. /**
  28263. * Sets the includes of this code node.
  28264. *
  28265. * @param {Array<Node>} includes - The includes to set.
  28266. * @return {CodeNode} A reference to this node.
  28267. */
  28268. setIncludes( includes ) {
  28269. this.includes = includes;
  28270. return this;
  28271. }
  28272. /**
  28273. * Returns the includes of this code node.
  28274. *
  28275. * @param {NodeBuilder} builder - The current node builder.
  28276. * @return {Array<Node>} The includes.
  28277. */
  28278. getIncludes( /*builder*/ ) {
  28279. return this.includes;
  28280. }
  28281. generate( builder ) {
  28282. const includes = this.getIncludes( builder );
  28283. for ( const include of includes ) {
  28284. include.build( builder );
  28285. }
  28286. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  28287. nodeCode.code = this.code;
  28288. return nodeCode.code;
  28289. }
  28290. serialize( data ) {
  28291. super.serialize( data );
  28292. data.code = this.code;
  28293. data.language = this.language;
  28294. }
  28295. deserialize( data ) {
  28296. super.deserialize( data );
  28297. this.code = data.code;
  28298. this.language = data.language;
  28299. }
  28300. }
  28301. /**
  28302. * TSL function for creating a code node.
  28303. *
  28304. * @tsl
  28305. * @function
  28306. * @param {string} [code] - The native code.
  28307. * @param {?Array<Node>} [includes=[]] - An array of includes.
  28308. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28309. * @returns {CodeNode}
  28310. */
  28311. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  28312. /**
  28313. * TSL function for creating a JS code node.
  28314. *
  28315. * @tsl
  28316. * @function
  28317. * @param {string} src - The native code.
  28318. * @param {Array<Node>} includes - An array of includes.
  28319. * @returns {CodeNode}
  28320. */
  28321. const js = ( src, includes ) => code( src, includes, 'js' );
  28322. /**
  28323. * TSL function for creating a WGSL code node.
  28324. *
  28325. * @tsl
  28326. * @function
  28327. * @param {string} src - The native code.
  28328. * @param {Array<Node>} includes - An array of includes.
  28329. * @returns {CodeNode}
  28330. */
  28331. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  28332. /**
  28333. * TSL function for creating a GLSL code node.
  28334. *
  28335. * @tsl
  28336. * @function
  28337. * @param {string} src - The native code.
  28338. * @param {Array<Node>} includes - An array of includes.
  28339. * @returns {CodeNode}
  28340. */
  28341. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  28342. /**
  28343. * This class represents a native shader function. It can be used to implement
  28344. * certain aspects of a node material with native shader code. There are two predefined
  28345. * TSL functions for easier usage.
  28346. *
  28347. * - `wgslFn`: Creates a WGSL function node.
  28348. * - `glslFn`: Creates a GLSL function node.
  28349. *
  28350. * A basic example with one include looks like so:
  28351. *
  28352. * ```js
  28353. * const desaturateWGSLFn = wgslFn( `
  28354. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  28355. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  28356. * return vec3<f32>( dot( lum, color ) );
  28357. * }`
  28358. *);
  28359. * const someWGSLFn = wgslFn( `
  28360. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  28361. * return desaturate( color );
  28362. * }
  28363. * `, [ desaturateWGSLFn ] );
  28364. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  28365. *```
  28366. * @augments CodeNode
  28367. */
  28368. class FunctionNode extends CodeNode {
  28369. static get type() {
  28370. return 'FunctionNode';
  28371. }
  28372. /**
  28373. * Constructs a new function node.
  28374. *
  28375. * @param {string} [code=''] - The native code.
  28376. * @param {Array<Node>} [includes=[]] - An array of includes.
  28377. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  28378. */
  28379. constructor( code = '', includes = [], language = '' ) {
  28380. super( code, includes, language );
  28381. }
  28382. /**
  28383. * Returns the type of this function node.
  28384. *
  28385. * @param {NodeBuilder} builder - The current node builder.
  28386. * @return {string} The type.
  28387. */
  28388. getNodeType( builder ) {
  28389. return this.getNodeFunction( builder ).type;
  28390. }
  28391. /**
  28392. * Returns the type of a member of this function node.
  28393. *
  28394. * @param {NodeBuilder} builder - The current node builder.
  28395. * @param {string} name - The name of the member.
  28396. * @return {string} The type of the member.
  28397. */
  28398. getMemberType( builder, name ) {
  28399. const type = this.getNodeType( builder );
  28400. const structType = builder.getStructTypeNode( type );
  28401. return structType.getMemberType( builder, name );
  28402. }
  28403. /**
  28404. * Returns the inputs of this function node.
  28405. *
  28406. * @param {NodeBuilder} builder - The current node builder.
  28407. * @return {Array<NodeFunctionInput>} The inputs.
  28408. */
  28409. getInputs( builder ) {
  28410. return this.getNodeFunction( builder ).inputs;
  28411. }
  28412. /**
  28413. * Returns the node function for this function node.
  28414. *
  28415. * @param {NodeBuilder} builder - The current node builder.
  28416. * @return {NodeFunction} The node function.
  28417. */
  28418. getNodeFunction( builder ) {
  28419. const nodeData = builder.getDataFromNode( this );
  28420. let nodeFunction = nodeData.nodeFunction;
  28421. if ( nodeFunction === undefined ) {
  28422. nodeFunction = builder.parser.parseFunction( this.code );
  28423. nodeData.nodeFunction = nodeFunction;
  28424. }
  28425. return nodeFunction;
  28426. }
  28427. generate( builder, output ) {
  28428. super.generate( builder );
  28429. const nodeFunction = this.getNodeFunction( builder );
  28430. const name = nodeFunction.name;
  28431. const type = nodeFunction.type;
  28432. const nodeCode = builder.getCodeFromNode( this, type );
  28433. if ( name !== '' ) {
  28434. // use a custom property name
  28435. nodeCode.name = name;
  28436. }
  28437. const propertyName = builder.getPropertyName( nodeCode );
  28438. const code = this.getNodeFunction( builder ).getCode( propertyName );
  28439. nodeCode.code = code + '\n';
  28440. if ( output === 'property' ) {
  28441. return propertyName;
  28442. } else {
  28443. return builder.format( `${ propertyName }()`, type, output );
  28444. }
  28445. }
  28446. }
  28447. const nativeFn = ( code, includes = [], language = '' ) => {
  28448. for ( let i = 0; i < includes.length; i ++ ) {
  28449. const include = includes[ i ];
  28450. // TSL Function: glslFn, wgslFn
  28451. if ( typeof include === 'function' ) {
  28452. includes[ i ] = include.functionNode;
  28453. }
  28454. }
  28455. const functionNode = new FunctionNode( code, includes, language );
  28456. const fn = ( ...params ) => functionNode.call( ...params );
  28457. fn.functionNode = functionNode;
  28458. return fn;
  28459. };
  28460. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  28461. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  28462. /**
  28463. * `ScriptableNode` uses this class to manage script inputs and outputs.
  28464. *
  28465. * @augments Node
  28466. */
  28467. class ScriptableValueNode extends Node {
  28468. static get type() {
  28469. return 'ScriptableValueNode';
  28470. }
  28471. /**
  28472. * Constructs a new scriptable node.
  28473. *
  28474. * @param {any} [value=null] - The value.
  28475. */
  28476. constructor( value = null ) {
  28477. super();
  28478. /**
  28479. * A reference to the value.
  28480. *
  28481. * @private
  28482. * @default null
  28483. */
  28484. this._value = value;
  28485. /**
  28486. * Depending on the type of `_value`, this property might cache parsed data.
  28487. *
  28488. * @private
  28489. * @default null
  28490. */
  28491. this._cache = null;
  28492. /**
  28493. * If this node represents an input, this property represents the input type.
  28494. *
  28495. * @type {?string}
  28496. * @default null
  28497. */
  28498. this.inputType = null;
  28499. /**
  28500. * If this node represents an output, this property represents the output type.
  28501. *
  28502. * @type {?string}
  28503. * @default null
  28504. */
  28505. this.outputType = null;
  28506. /**
  28507. * An event dispatcher for managing events.
  28508. *
  28509. * @type {EventDispatcher}
  28510. */
  28511. this.events = new EventDispatcher();
  28512. /**
  28513. * This flag can be used for type testing.
  28514. *
  28515. * @type {boolean}
  28516. * @readonly
  28517. * @default true
  28518. */
  28519. this.isScriptableValueNode = true;
  28520. }
  28521. /**
  28522. * Whether this node represents an output or not.
  28523. *
  28524. * @type {boolean}
  28525. * @readonly
  28526. * @default true
  28527. */
  28528. get isScriptableOutputNode() {
  28529. return this.outputType !== null;
  28530. }
  28531. set value( val ) {
  28532. if ( this._value === val ) return;
  28533. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  28534. URL.revokeObjectURL( this._cache );
  28535. this._cache = null;
  28536. }
  28537. this._value = val;
  28538. this.events.dispatchEvent( { type: 'change' } );
  28539. this.refresh();
  28540. }
  28541. /**
  28542. * The node's value.
  28543. *
  28544. * @type {any}
  28545. */
  28546. get value() {
  28547. return this._value;
  28548. }
  28549. /**
  28550. * Dispatches the `refresh` event.
  28551. */
  28552. refresh() {
  28553. this.events.dispatchEvent( { type: 'refresh' } );
  28554. }
  28555. /**
  28556. * The `value` property usually represents a node or even binary data in form of array buffers.
  28557. * In this case, this method tries to return the actual value behind the complex type.
  28558. *
  28559. * @return {any} The value.
  28560. */
  28561. getValue() {
  28562. const value = this.value;
  28563. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  28564. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  28565. } else if ( value && value.value !== null && value.value !== undefined && (
  28566. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  28567. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  28568. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  28569. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  28570. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  28571. ( this.inputType === 'Color' && value.value.isColor ) ||
  28572. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  28573. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  28574. ) ) {
  28575. return value.value;
  28576. }
  28577. return this._cache || value;
  28578. }
  28579. /**
  28580. * Overwritten since the node type is inferred from the value.
  28581. *
  28582. * @param {NodeBuilder} builder - The current node builder.
  28583. * @return {string} The node type.
  28584. */
  28585. getNodeType( builder ) {
  28586. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  28587. }
  28588. setup() {
  28589. return this.value && this.value.isNode ? this.value : float();
  28590. }
  28591. serialize( data ) {
  28592. super.serialize( data );
  28593. if ( this.value !== null ) {
  28594. if ( this.inputType === 'ArrayBuffer' ) {
  28595. data.value = arrayBufferToBase64( this.value );
  28596. } else {
  28597. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  28598. }
  28599. } else {
  28600. data.value = null;
  28601. }
  28602. data.inputType = this.inputType;
  28603. data.outputType = this.outputType;
  28604. }
  28605. deserialize( data ) {
  28606. super.deserialize( data );
  28607. let value = null;
  28608. if ( data.value !== null ) {
  28609. if ( data.inputType === 'ArrayBuffer' ) {
  28610. value = base64ToArrayBuffer( data.value );
  28611. } else if ( data.inputType === 'Texture' ) {
  28612. value = data.meta.textures[ data.value ];
  28613. } else {
  28614. value = data.meta.nodes[ data.value ] || null;
  28615. }
  28616. }
  28617. this.value = value;
  28618. this.inputType = data.inputType;
  28619. this.outputType = data.outputType;
  28620. }
  28621. }
  28622. /**
  28623. * TSL function for creating a scriptable value node.
  28624. *
  28625. * @tsl
  28626. * @function
  28627. * @param {any} [value] - The value.
  28628. * @returns {ScriptableValueNode}
  28629. */
  28630. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  28631. /**
  28632. * A Map-like data structure for managing resources of scriptable nodes.
  28633. *
  28634. * @augments Map
  28635. */
  28636. class Resources extends Map {
  28637. get( key, callback = null, ...params ) {
  28638. if ( this.has( key ) ) return super.get( key );
  28639. if ( callback !== null ) {
  28640. const value = callback( ...params );
  28641. this.set( key, value );
  28642. return value;
  28643. }
  28644. }
  28645. }
  28646. class Parameters {
  28647. constructor( scriptableNode ) {
  28648. this.scriptableNode = scriptableNode;
  28649. }
  28650. get parameters() {
  28651. return this.scriptableNode.parameters;
  28652. }
  28653. get layout() {
  28654. return this.scriptableNode.getLayout();
  28655. }
  28656. getInputLayout( id ) {
  28657. return this.scriptableNode.getInputLayout( id );
  28658. }
  28659. get( name ) {
  28660. const param = this.parameters[ name ];
  28661. const value = param ? param.getValue() : null;
  28662. return value;
  28663. }
  28664. }
  28665. /**
  28666. * Defines the resources (e.g. namespaces) of scriptable nodes.
  28667. *
  28668. * @type {Resources}
  28669. */
  28670. const ScriptableNodeResources = new Resources();
  28671. /**
  28672. * This type of node allows to implement nodes with custom scripts. The script
  28673. * section is represented as an instance of `CodeNode` written with JavaScript.
  28674. * The script itself must adhere to a specific structure.
  28675. *
  28676. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  28677. * - layout: The layout object defines the script's interface (inputs and outputs).
  28678. *
  28679. * ```js
  28680. * ScriptableNodeResources.set( 'TSL', TSL );
  28681. *
  28682. * const scriptableNode = scriptable( js( `
  28683. * layout = {
  28684. * outputType: 'node',
  28685. * elements: [
  28686. * { name: 'source', inputType: 'node' },
  28687. * ]
  28688. * };
  28689. *
  28690. * const { mul, oscSine } = TSL;
  28691. *
  28692. * function main() {
  28693. * const source = parameters.get( 'source' ) || float();
  28694. * return mul( source, oscSine() ) );
  28695. * }
  28696. *
  28697. * ` ) );
  28698. *
  28699. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  28700. *
  28701. * const material = new THREE.MeshBasicNodeMaterial();
  28702. * material.colorNode = scriptableNode;
  28703. * ```
  28704. *
  28705. * @augments Node
  28706. */
  28707. class ScriptableNode extends Node {
  28708. static get type() {
  28709. return 'ScriptableNode';
  28710. }
  28711. /**
  28712. * Constructs a new scriptable node.
  28713. *
  28714. * @param {?CodeNode} [codeNode=null] - The code node.
  28715. * @param {Object} [parameters={}] - The parameters definition.
  28716. */
  28717. constructor( codeNode = null, parameters = {} ) {
  28718. super();
  28719. /**
  28720. * The code node.
  28721. *
  28722. * @type {?CodeNode}
  28723. * @default null
  28724. */
  28725. this.codeNode = codeNode;
  28726. /**
  28727. * The parameters definition.
  28728. *
  28729. * @type {Object}
  28730. * @default {}
  28731. */
  28732. this.parameters = parameters;
  28733. this._local = new Resources();
  28734. this._output = scriptableValue( null );
  28735. this._outputs = {};
  28736. this._source = this.source;
  28737. this._method = null;
  28738. this._object = null;
  28739. this._value = null;
  28740. this._needsOutputUpdate = true;
  28741. this.onRefresh = this.onRefresh.bind( this );
  28742. /**
  28743. * This flag can be used for type testing.
  28744. *
  28745. * @type {boolean}
  28746. * @readonly
  28747. * @default true
  28748. */
  28749. this.isScriptableNode = true;
  28750. }
  28751. /**
  28752. * The source code of the scriptable node.
  28753. *
  28754. * @type {string}
  28755. */
  28756. get source() {
  28757. return this.codeNode ? this.codeNode.code : '';
  28758. }
  28759. /**
  28760. * Sets the reference of a local script variable.
  28761. *
  28762. * @param {string} name - The variable name.
  28763. * @param {Object} value - The reference to set.
  28764. * @return {Resources} The resource map
  28765. */
  28766. setLocal( name, value ) {
  28767. return this._local.set( name, value );
  28768. }
  28769. /**
  28770. * Gets the value of a local script variable.
  28771. *
  28772. * @param {string} name - The variable name.
  28773. * @return {Object} The value.
  28774. */
  28775. getLocal( name ) {
  28776. return this._local.get( name );
  28777. }
  28778. /**
  28779. * Event listener for the `refresh` event.
  28780. */
  28781. onRefresh() {
  28782. this._refresh();
  28783. }
  28784. /**
  28785. * Returns an input from the layout with the given id/name.
  28786. *
  28787. * @param {string} id - The id/name of the input.
  28788. * @return {Object} The element entry.
  28789. */
  28790. getInputLayout( id ) {
  28791. for ( const element of this.getLayout() ) {
  28792. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  28793. return element;
  28794. }
  28795. }
  28796. }
  28797. /**
  28798. * Returns an output from the layout with the given id/name.
  28799. *
  28800. * @param {string} id - The id/name of the output.
  28801. * @return {Object} The element entry.
  28802. */
  28803. getOutputLayout( id ) {
  28804. for ( const element of this.getLayout() ) {
  28805. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  28806. return element;
  28807. }
  28808. }
  28809. }
  28810. /**
  28811. * Defines a script output for the given name and value.
  28812. *
  28813. * @param {string} name - The name of the output.
  28814. * @param {Node} value - The node value.
  28815. * @return {ScriptableNode} A reference to this node.
  28816. */
  28817. setOutput( name, value ) {
  28818. const outputs = this._outputs;
  28819. if ( outputs[ name ] === undefined ) {
  28820. outputs[ name ] = scriptableValue( value );
  28821. } else {
  28822. outputs[ name ].value = value;
  28823. }
  28824. return this;
  28825. }
  28826. /**
  28827. * Returns a script output for the given name.
  28828. *
  28829. * @param {string} name - The name of the output.
  28830. * @return {ScriptableValueNode} The node value.
  28831. */
  28832. getOutput( name ) {
  28833. return this._outputs[ name ];
  28834. }
  28835. /**
  28836. * Returns a parameter for the given name
  28837. *
  28838. * @param {string} name - The name of the parameter.
  28839. * @return {ScriptableValueNode} The node value.
  28840. */
  28841. getParameter( name ) {
  28842. return this.parameters[ name ];
  28843. }
  28844. /**
  28845. * Sets a value for the given parameter name.
  28846. *
  28847. * @param {string} name - The parameter name.
  28848. * @param {any} value - The parameter value.
  28849. * @return {ScriptableNode} A reference to this node.
  28850. */
  28851. setParameter( name, value ) {
  28852. const parameters = this.parameters;
  28853. if ( value && value.isScriptableNode ) {
  28854. this.deleteParameter( name );
  28855. parameters[ name ] = value;
  28856. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  28857. } else if ( value && value.isScriptableValueNode ) {
  28858. this.deleteParameter( name );
  28859. parameters[ name ] = value;
  28860. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28861. } else if ( parameters[ name ] === undefined ) {
  28862. parameters[ name ] = scriptableValue( value );
  28863. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  28864. } else {
  28865. parameters[ name ].value = value;
  28866. }
  28867. return this;
  28868. }
  28869. /**
  28870. * Returns the value of this node which is the value of
  28871. * the default output.
  28872. *
  28873. * @return {Node} The value.
  28874. */
  28875. getValue() {
  28876. return this.getDefaultOutput().getValue();
  28877. }
  28878. /**
  28879. * Deletes a parameter from the script.
  28880. *
  28881. * @param {string} name - The parameter to remove.
  28882. * @return {ScriptableNode} A reference to this node.
  28883. */
  28884. deleteParameter( name ) {
  28885. let valueNode = this.parameters[ name ];
  28886. if ( valueNode ) {
  28887. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28888. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  28889. }
  28890. return this;
  28891. }
  28892. /**
  28893. * Deletes all parameters from the script.
  28894. *
  28895. * @return {ScriptableNode} A reference to this node.
  28896. */
  28897. clearParameters() {
  28898. for ( const name of Object.keys( this.parameters ) ) {
  28899. this.deleteParameter( name );
  28900. }
  28901. this.needsUpdate = true;
  28902. return this;
  28903. }
  28904. /**
  28905. * Calls a function from the script.
  28906. *
  28907. * @param {string} name - The function name.
  28908. * @param {...any} params - A list of parameters.
  28909. * @return {any} The result of the function call.
  28910. */
  28911. call( name, ...params ) {
  28912. const object = this.getObject();
  28913. const method = object[ name ];
  28914. if ( typeof method === 'function' ) {
  28915. return method( ...params );
  28916. }
  28917. }
  28918. /**
  28919. * Asynchronously calls a function from the script.
  28920. *
  28921. * @param {string} name - The function name.
  28922. * @param {...any} params - A list of parameters.
  28923. * @return {Promise<any>} The result of the function call.
  28924. */
  28925. async callAsync( name, ...params ) {
  28926. const object = this.getObject();
  28927. const method = object[ name ];
  28928. if ( typeof method === 'function' ) {
  28929. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  28930. }
  28931. }
  28932. /**
  28933. * Overwritten since the node types is inferred from the script's output.
  28934. *
  28935. * @param {NodeBuilder} builder - The current node builder
  28936. * @return {string} The node type.
  28937. */
  28938. getNodeType( builder ) {
  28939. return this.getDefaultOutputNode().getNodeType( builder );
  28940. }
  28941. /**
  28942. * Refreshes the script node.
  28943. *
  28944. * @param {?string} [output=null] - An optional output.
  28945. */
  28946. refresh( output = null ) {
  28947. if ( output !== null ) {
  28948. this.getOutput( output ).refresh();
  28949. } else {
  28950. this._refresh();
  28951. }
  28952. }
  28953. /**
  28954. * Returns an object representation of the script.
  28955. *
  28956. * @return {Object} The result object.
  28957. */
  28958. getObject() {
  28959. if ( this.needsUpdate ) this.dispose();
  28960. if ( this._object !== null ) return this._object;
  28961. //
  28962. const refresh = () => this.refresh();
  28963. const setOutput = ( id, value ) => this.setOutput( id, value );
  28964. const parameters = new Parameters( this );
  28965. const THREE = ScriptableNodeResources.get( 'THREE' );
  28966. const TSL = ScriptableNodeResources.get( 'TSL' );
  28967. const method = this.getMethod();
  28968. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  28969. this._object = method( ...params );
  28970. const layout = this._object.layout;
  28971. if ( layout ) {
  28972. if ( layout.cache === false ) {
  28973. this._local.clear();
  28974. }
  28975. // default output
  28976. this._output.outputType = layout.outputType || null;
  28977. if ( Array.isArray( layout.elements ) ) {
  28978. for ( const element of layout.elements ) {
  28979. const id = element.id || element.name;
  28980. if ( element.inputType ) {
  28981. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  28982. this.getParameter( id ).inputType = element.inputType;
  28983. }
  28984. if ( element.outputType ) {
  28985. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  28986. this.getOutput( id ).outputType = element.outputType;
  28987. }
  28988. }
  28989. }
  28990. }
  28991. return this._object;
  28992. }
  28993. deserialize( data ) {
  28994. super.deserialize( data );
  28995. for ( const name in this.parameters ) {
  28996. let valueNode = this.parameters[ name ];
  28997. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  28998. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  28999. }
  29000. }
  29001. /**
  29002. * Returns the layout of the script.
  29003. *
  29004. * @return {Object} The script's layout.
  29005. */
  29006. getLayout() {
  29007. return this.getObject().layout;
  29008. }
  29009. /**
  29010. * Returns default node output of the script.
  29011. *
  29012. * @return {Node} The default node output.
  29013. */
  29014. getDefaultOutputNode() {
  29015. const output = this.getDefaultOutput().value;
  29016. if ( output && output.isNode ) {
  29017. return output;
  29018. }
  29019. return float();
  29020. }
  29021. /**
  29022. * Returns default output of the script.
  29023. *
  29024. * @return {ScriptableValueNode} The default output.
  29025. */
  29026. getDefaultOutput() {
  29027. return this._exec()._output;
  29028. }
  29029. /**
  29030. * Returns a function created from the node's script.
  29031. *
  29032. * @return {Function} The function representing the node's code.
  29033. */
  29034. getMethod() {
  29035. if ( this.needsUpdate ) this.dispose();
  29036. if ( this._method !== null ) return this._method;
  29037. //
  29038. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  29039. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  29040. const properties = interfaceProps.join( ', ' );
  29041. const declarations = 'var ' + properties + '; var output = {};\n';
  29042. const returns = '\nreturn { ...output, ' + properties + ' };';
  29043. const code = declarations + this.codeNode.code + returns;
  29044. //
  29045. this._method = new Function( ...parametersProps, code );
  29046. return this._method;
  29047. }
  29048. /**
  29049. * Frees all internal resources.
  29050. */
  29051. dispose() {
  29052. if ( this._method === null ) return;
  29053. if ( this._object && typeof this._object.dispose === 'function' ) {
  29054. this._object.dispose();
  29055. }
  29056. this._method = null;
  29057. this._object = null;
  29058. this._source = null;
  29059. this._value = null;
  29060. this._needsOutputUpdate = true;
  29061. this._output.value = null;
  29062. this._outputs = {};
  29063. }
  29064. setup() {
  29065. return this.getDefaultOutputNode();
  29066. }
  29067. getCacheKey( force ) {
  29068. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  29069. for ( const param in this.parameters ) {
  29070. values.push( this.parameters[ param ].getCacheKey( force ) );
  29071. }
  29072. return hashArray( values );
  29073. }
  29074. set needsUpdate( value ) {
  29075. if ( value === true ) this.dispose();
  29076. }
  29077. get needsUpdate() {
  29078. return this.source !== this._source;
  29079. }
  29080. /**
  29081. * Executes the `main` function of the script.
  29082. *
  29083. * @private
  29084. * @return {ScriptableNode} A reference to this node.
  29085. */
  29086. _exec() {
  29087. if ( this.codeNode === null ) return this;
  29088. if ( this._needsOutputUpdate === true ) {
  29089. this._value = this.call( 'main' );
  29090. this._needsOutputUpdate = false;
  29091. }
  29092. this._output.value = this._value;
  29093. return this;
  29094. }
  29095. /**
  29096. * Executes the refresh.
  29097. *
  29098. * @private
  29099. */
  29100. _refresh() {
  29101. this.needsUpdate = true;
  29102. this._exec();
  29103. this._output.refresh();
  29104. }
  29105. }
  29106. /**
  29107. * TSL function for creating a scriptable node.
  29108. *
  29109. * @tsl
  29110. * @function
  29111. * @param {CodeNode} [codeNode] - The code node.
  29112. * @param {?Object} [parameters={}] - The parameters definition.
  29113. * @returns {ScriptableNode}
  29114. */
  29115. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  29116. /**
  29117. * Returns a node that represents the `z` coordinate in view space
  29118. * for the current fragment. It's a different representation of the
  29119. * default depth value.
  29120. *
  29121. * This value can be part of a computation that defines how the fog
  29122. * density increases when moving away from the camera.
  29123. *
  29124. * @param {NodeBuilder} builder - The current node builder.
  29125. * @return {Node} The viewZ node.
  29126. */
  29127. function getViewZNode( builder ) {
  29128. let viewZ;
  29129. const getViewZ = builder.context.getViewZ;
  29130. if ( getViewZ !== undefined ) {
  29131. viewZ = getViewZ( this );
  29132. }
  29133. return ( viewZ || positionView.z ).negate();
  29134. }
  29135. /**
  29136. * Constructs a new range factor node.
  29137. *
  29138. * @tsl
  29139. * @function
  29140. * @param {Node} near - Defines the near value.
  29141. * @param {Node} far - Defines the far value.
  29142. */
  29143. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  29144. const viewZ = getViewZNode( builder );
  29145. return smoothstep( near, far, viewZ );
  29146. } );
  29147. /**
  29148. * Represents an exponential squared fog. This type of fog gives
  29149. * a clear view near the camera and a faster than exponentially
  29150. * densening fog farther from the camera.
  29151. *
  29152. * @tsl
  29153. * @function
  29154. * @param {Node} density - Defines the fog density.
  29155. */
  29156. const densityFogFactor = Fn( ( [ density ], builder ) => {
  29157. const viewZ = getViewZNode( builder );
  29158. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  29159. } );
  29160. /**
  29161. * Constructs a new height fog factor node. This fog factor requires a Y-up coordinate system.
  29162. *
  29163. * @tsl
  29164. * @function
  29165. * @param {Node} density - Defines the fog density.
  29166. * @param {Node} height - The height threshold in world space. Everything below this y-coordinate is affected by fog.
  29167. */
  29168. const exponentialHeightFogFactor = Fn( ( [ density, height ], builder ) => {
  29169. const viewZ = getViewZNode( builder );
  29170. const distance = height.sub( positionWorld.y ).max( 0 ).toConst();
  29171. const m = distance.mul( viewZ ).toConst();
  29172. return density.mul( density, m, m ).negate().exp().oneMinus();
  29173. } );
  29174. /**
  29175. * This class can be used to configure a fog for the scene.
  29176. * Nodes of this type are assigned to `Scene.fogNode`.
  29177. *
  29178. * @tsl
  29179. * @function
  29180. * @param {Node} color - Defines the color of the fog.
  29181. * @param {Node} factor - Defines how the fog is factored in the scene.
  29182. */
  29183. const fog = Fn( ( [ color, factor ] ) => {
  29184. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  29185. } );
  29186. let min = null;
  29187. let max = null;
  29188. /**
  29189. * `RangeNode` generates random instanced attribute data in a defined range.
  29190. * An exemplary use case for this utility node is to generate random per-instance
  29191. * colors:
  29192. * ```js
  29193. * const material = new MeshBasicNodeMaterial();
  29194. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  29195. * const mesh = new InstancedMesh( geometry, material, count );
  29196. * ```
  29197. * @augments Node
  29198. */
  29199. class RangeNode extends Node {
  29200. static get type() {
  29201. return 'RangeNode';
  29202. }
  29203. /**
  29204. * Constructs a new range node.
  29205. *
  29206. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29207. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29208. */
  29209. constructor( minNode = float(), maxNode = float() ) {
  29210. super();
  29211. /**
  29212. * A node defining the lower bound of the range.
  29213. *
  29214. * @type {Node<any>}
  29215. * @default float()
  29216. */
  29217. this.minNode = minNode;
  29218. /**
  29219. * A node defining the upper bound of the range.
  29220. *
  29221. * @type {Node<any>}
  29222. * @default float()
  29223. */
  29224. this.maxNode = maxNode;
  29225. }
  29226. /**
  29227. * Returns the vector length which is computed based on the range definition.
  29228. *
  29229. * @param {NodeBuilder} builder - The current node builder.
  29230. * @return {number} The vector length.
  29231. */
  29232. getVectorLength( builder ) {
  29233. const minNode = this.getConstNode( this.minNode );
  29234. const maxNode = this.getConstNode( this.maxNode );
  29235. const minLength = builder.getTypeLength( getValueType( minNode.value ) );
  29236. const maxLength = builder.getTypeLength( getValueType( maxNode.value ) );
  29237. return minLength > maxLength ? minLength : maxLength;
  29238. }
  29239. /**
  29240. * This method is overwritten since the node type is inferred from range definition.
  29241. *
  29242. * @param {NodeBuilder} builder - The current node builder.
  29243. * @return {string} The node type.
  29244. */
  29245. getNodeType( builder ) {
  29246. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  29247. }
  29248. /**
  29249. * Returns a constant node from the given node by traversing it.
  29250. *
  29251. * @param {Node} node - The node to traverse.
  29252. * @returns {Node} The constant node, if found.
  29253. */
  29254. getConstNode( node ) {
  29255. let output = null;
  29256. node.traverse( n => {
  29257. if ( n.isConstNode === true ) {
  29258. output = n;
  29259. }
  29260. } );
  29261. if ( output === null ) {
  29262. throw new Error( 'THREE.TSL: No "ConstNode" found in node graph.' );
  29263. }
  29264. return output;
  29265. }
  29266. setup( builder ) {
  29267. const object = builder.object;
  29268. let output = null;
  29269. if ( object.count > 1 ) {
  29270. const minNode = this.getConstNode( this.minNode );
  29271. const maxNode = this.getConstNode( this.maxNode );
  29272. const minValue = minNode.value;
  29273. const maxValue = maxNode.value;
  29274. const minLength = builder.getTypeLength( getValueType( minValue ) );
  29275. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  29276. min = min || new Vector4();
  29277. max = max || new Vector4();
  29278. min.setScalar( 0 );
  29279. max.setScalar( 0 );
  29280. if ( minLength === 1 ) min.setScalar( minValue );
  29281. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  29282. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  29283. if ( maxLength === 1 ) max.setScalar( maxValue );
  29284. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  29285. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  29286. const stride = 4;
  29287. const length = stride * object.count;
  29288. const array = new Float32Array( length );
  29289. for ( let i = 0; i < length; i ++ ) {
  29290. const index = i % stride;
  29291. const minElementValue = min.getComponent( index );
  29292. const maxElementValue = max.getComponent( index );
  29293. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  29294. }
  29295. const nodeType = this.getNodeType( builder );
  29296. if ( object.count <= 4096 ) {
  29297. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  29298. } else {
  29299. // TODO: Improve anonymous buffer attribute creation removing this part
  29300. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  29301. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  29302. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  29303. }
  29304. } else {
  29305. output = float( 0 );
  29306. }
  29307. return output;
  29308. }
  29309. }
  29310. /**
  29311. * TSL function for creating a range node.
  29312. *
  29313. * @tsl
  29314. * @function
  29315. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  29316. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  29317. * @returns {RangeNode}
  29318. */
  29319. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  29320. /**
  29321. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  29322. * about the currently running dispatch and/or the device it is running on.
  29323. *
  29324. * This node can only be used with a WebGPU backend.
  29325. *
  29326. * @augments Node
  29327. */
  29328. class ComputeBuiltinNode extends Node {
  29329. static get type() {
  29330. return 'ComputeBuiltinNode';
  29331. }
  29332. /**
  29333. * Constructs a new compute builtin node.
  29334. *
  29335. * @param {string} builtinName - The built-in name.
  29336. * @param {string} nodeType - The node type.
  29337. */
  29338. constructor( builtinName, nodeType ) {
  29339. super( nodeType );
  29340. /**
  29341. * The built-in name.
  29342. *
  29343. * @private
  29344. * @type {string}
  29345. */
  29346. this._builtinName = builtinName;
  29347. }
  29348. /**
  29349. * This method is overwritten since hash is derived from the built-in name.
  29350. *
  29351. * @param {NodeBuilder} builder - The current node builder.
  29352. * @return {string} The hash.
  29353. */
  29354. getHash( builder ) {
  29355. return this.getBuiltinName( builder );
  29356. }
  29357. /**
  29358. * This method is overwritten since the node type is simply derived from `nodeType`..
  29359. *
  29360. * @param {NodeBuilder} builder - The current node builder.
  29361. * @return {string} The node type.
  29362. */
  29363. getNodeType( /*builder*/ ) {
  29364. return this.nodeType;
  29365. }
  29366. /**
  29367. * Sets the builtin name.
  29368. *
  29369. * @param {string} builtinName - The built-in name.
  29370. * @return {ComputeBuiltinNode} A reference to this node.
  29371. */
  29372. setBuiltinName( builtinName ) {
  29373. this._builtinName = builtinName;
  29374. return this;
  29375. }
  29376. /**
  29377. * Returns the builtin name.
  29378. *
  29379. * @param {NodeBuilder} builder - The current node builder.
  29380. * @return {string} The builtin name.
  29381. */
  29382. getBuiltinName( /*builder*/ ) {
  29383. return this._builtinName;
  29384. }
  29385. /**
  29386. * Whether the current node builder has the builtin or not.
  29387. *
  29388. * @param {NodeBuilder} builder - The current node builder.
  29389. * @return {boolean} Whether the builder has the builtin or not.
  29390. */
  29391. hasBuiltin( builder ) {
  29392. return builder.hasBuiltin( this._builtinName );
  29393. }
  29394. generate( builder, output ) {
  29395. const builtinName = this.getBuiltinName( builder );
  29396. const nodeType = this.getNodeType( builder );
  29397. if ( builder.shaderStage === 'compute' ) {
  29398. return builder.format( builtinName, nodeType, output );
  29399. } else {
  29400. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  29401. return builder.generateConst( nodeType );
  29402. }
  29403. }
  29404. serialize( data ) {
  29405. super.serialize( data );
  29406. data.global = this.global;
  29407. data._builtinName = this._builtinName;
  29408. }
  29409. deserialize( data ) {
  29410. super.deserialize( data );
  29411. this.global = data.global;
  29412. this._builtinName = data._builtinName;
  29413. }
  29414. }
  29415. /**
  29416. * TSL function for creating a compute builtin node.
  29417. *
  29418. * @tsl
  29419. * @function
  29420. * @param {string} name - The built-in name.
  29421. * @param {string} nodeType - The node type.
  29422. * @returns {ComputeBuiltinNode}
  29423. */
  29424. const computeBuiltin = ( name, nodeType ) => new ComputeBuiltinNode( name, nodeType );
  29425. /**
  29426. * Represents the number of workgroups dispatched by the compute shader.
  29427. * ```js
  29428. * // Run 512 invocations/threads with a workgroup size of 128.
  29429. * const computeFn = Fn(() => {
  29430. *
  29431. * // numWorkgroups.x = 4
  29432. * storageBuffer.element(0).assign(numWorkgroups.x)
  29433. *
  29434. * })().compute(512, [128]);
  29435. *
  29436. * // Run 512 invocations/threads with the default workgroup size of 64.
  29437. * const computeFn = Fn(() => {
  29438. *
  29439. * // numWorkgroups.x = 8
  29440. * storageBuffer.element(0).assign(numWorkgroups.x)
  29441. *
  29442. * })().compute(512);
  29443. * ```
  29444. *
  29445. * @tsl
  29446. * @type {ComputeBuiltinNode<uvec3>}
  29447. */
  29448. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  29449. /**
  29450. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  29451. * ```js
  29452. * // Execute 12 compute threads with a workgroup size of 3.
  29453. * const computeFn = Fn( () => {
  29454. *
  29455. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  29456. *
  29457. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  29458. *
  29459. * } ).Else( () => {
  29460. *
  29461. * storageBuffer.element( instanceIndex ).assign( 0 );
  29462. *
  29463. * } );
  29464. *
  29465. * } )().compute( 12, [ 3 ] );
  29466. *
  29467. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  29468. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  29469. * ```
  29470. *
  29471. * @tsl
  29472. * @type {ComputeBuiltinNode<uvec3>}
  29473. */
  29474. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  29475. /**
  29476. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  29477. *
  29478. * @tsl
  29479. * @type {ComputeBuiltinNode<uvec3>}
  29480. */
  29481. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  29482. /**
  29483. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  29484. *
  29485. * @tsl
  29486. * @type {ComputeBuiltinNode<uvec3>}
  29487. */
  29488. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  29489. /**
  29490. * A device dependent variable that exposes the size of the current invocation's subgroup.
  29491. *
  29492. * @tsl
  29493. * @type {ComputeBuiltinNode<uint>}
  29494. */
  29495. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  29496. /**
  29497. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  29498. *
  29499. * This node can only be used with a WebGPU backend.
  29500. *
  29501. * @augments Node
  29502. */
  29503. class BarrierNode extends Node {
  29504. /**
  29505. * Constructs a new barrier node.
  29506. *
  29507. * @param {string} scope - The scope defines the behavior of the node.
  29508. */
  29509. constructor( scope ) {
  29510. super();
  29511. this.scope = scope;
  29512. }
  29513. generate( builder ) {
  29514. const { scope } = this;
  29515. const { renderer } = builder;
  29516. if ( renderer.backend.isWebGLBackend === true ) {
  29517. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  29518. } else {
  29519. builder.addLineFlowCode( `${scope}Barrier()`, this );
  29520. }
  29521. }
  29522. }
  29523. /**
  29524. * TSL function for creating a barrier node.
  29525. *
  29526. * @tsl
  29527. * @function
  29528. * @param {string} scope - The scope defines the behavior of the node..
  29529. * @returns {BarrierNode}
  29530. */
  29531. const barrier = nodeProxy( BarrierNode );
  29532. /**
  29533. * TSL function for creating a workgroup barrier. All compute shader
  29534. * invocations must wait for each invocation within a workgroup to
  29535. * complete before the barrier can be surpassed.
  29536. *
  29537. * @tsl
  29538. * @function
  29539. * @returns {BarrierNode}
  29540. */
  29541. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  29542. /**
  29543. * TSL function for creating a storage barrier. All invocations must
  29544. * wait for each access to variables within the 'storage' address space
  29545. * to complete before the barrier can be passed.
  29546. *
  29547. * @tsl
  29548. * @function
  29549. * @returns {BarrierNode}
  29550. */
  29551. const storageBarrier = () => barrier( 'storage' ).toStack();
  29552. /**
  29553. * TSL function for creating a texture barrier. All invocations must
  29554. * wait for each access to variables within the 'texture' address space
  29555. * to complete before the barrier can be passed.
  29556. *
  29557. * @tsl
  29558. * @function
  29559. * @returns {BarrierNode}
  29560. */
  29561. const textureBarrier = () => barrier( 'texture' ).toStack();
  29562. /**
  29563. * Represents an element of a 'workgroup' scoped buffer.
  29564. *
  29565. * @augments ArrayElementNode
  29566. */
  29567. class WorkgroupInfoElementNode extends ArrayElementNode {
  29568. /**
  29569. * Constructs a new workgroup info element node.
  29570. *
  29571. * @param {Node} workgroupInfoNode - The workgroup info node.
  29572. * @param {Node} indexNode - The index node that defines the element access.
  29573. */
  29574. constructor( workgroupInfoNode, indexNode ) {
  29575. super( workgroupInfoNode, indexNode );
  29576. /**
  29577. * This flag can be used for type testing.
  29578. *
  29579. * @type {boolean}
  29580. * @readonly
  29581. * @default true
  29582. */
  29583. this.isWorkgroupInfoElementNode = true;
  29584. }
  29585. generate( builder, output ) {
  29586. let snippet;
  29587. const isAssignContext = builder.context.assign;
  29588. snippet = super.generate( builder );
  29589. if ( isAssignContext !== true ) {
  29590. const type = this.getNodeType( builder );
  29591. snippet = builder.format( snippet, type, output );
  29592. }
  29593. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  29594. return snippet;
  29595. }
  29596. }
  29597. /**
  29598. * A node allowing the user to create a 'workgroup' scoped buffer within the
  29599. * context of a compute shader. Typically, workgroup scoped buffers are
  29600. * created to hold data that is transferred from a global storage scope into
  29601. * a local workgroup scope. For invocations within a workgroup, data
  29602. * access speeds on 'workgroup' scoped buffers can be significantly faster
  29603. * than similar access operations on globally accessible storage buffers.
  29604. *
  29605. * This node can only be used with a WebGPU backend.
  29606. *
  29607. * @augments Node
  29608. */
  29609. class WorkgroupInfoNode extends Node {
  29610. /**
  29611. * Constructs a new buffer scoped to type scope.
  29612. *
  29613. * @param {string} scope - TODO.
  29614. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  29615. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  29616. */
  29617. constructor( scope, bufferType, bufferCount = 0 ) {
  29618. super( bufferType );
  29619. /**
  29620. * The buffer type.
  29621. *
  29622. * @type {string}
  29623. */
  29624. this.bufferType = bufferType;
  29625. /**
  29626. * The buffer count.
  29627. *
  29628. * @type {number}
  29629. * @default 0
  29630. */
  29631. this.bufferCount = bufferCount;
  29632. /**
  29633. * This flag can be used for type testing.
  29634. *
  29635. * @type {boolean}
  29636. * @readonly
  29637. * @default true
  29638. */
  29639. this.isWorkgroupInfoNode = true;
  29640. /**
  29641. * The data type of the array buffer.
  29642. *
  29643. * @type {string}
  29644. */
  29645. this.elementType = bufferType;
  29646. /**
  29647. * TODO.
  29648. *
  29649. * @type {string}
  29650. */
  29651. this.scope = scope;
  29652. /**
  29653. * The name of the workgroup scoped buffer.
  29654. *
  29655. * @type {string}
  29656. * @default ''
  29657. */
  29658. this.name = '';
  29659. }
  29660. /**
  29661. * Sets the name of this node.
  29662. *
  29663. * @param {string} name - The name to set.
  29664. * @return {WorkgroupInfoNode} A reference to this node.
  29665. */
  29666. setName( name ) {
  29667. this.name = name;
  29668. return this;
  29669. }
  29670. /**
  29671. * Sets the name/label of this node.
  29672. *
  29673. * @deprecated
  29674. * @param {string} name - The name to set.
  29675. * @return {WorkgroupInfoNode} A reference to this node.
  29676. */
  29677. label( name ) {
  29678. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  29679. return this.setName( name );
  29680. }
  29681. /**
  29682. * Sets the scope of this node.
  29683. *
  29684. * @param {string} scope - The scope to set.
  29685. * @return {WorkgroupInfoNode} A reference to this node.
  29686. */
  29687. setScope( scope ) {
  29688. this.scope = scope;
  29689. return this;
  29690. }
  29691. /**
  29692. * The data type of the array buffer.
  29693. *
  29694. * @return {string} The element type.
  29695. */
  29696. getElementType() {
  29697. return this.elementType;
  29698. }
  29699. /**
  29700. * Overwrites the default implementation since the input type
  29701. * is inferred from the scope.
  29702. *
  29703. * @param {NodeBuilder} builder - The current node builder.
  29704. * @return {string} The input type.
  29705. */
  29706. getInputType( /*builder*/ ) {
  29707. return `${this.scope}Array`;
  29708. }
  29709. /**
  29710. * This method can be used to access elements via an index node.
  29711. *
  29712. * @param {IndexNode} indexNode - indexNode.
  29713. * @return {WorkgroupInfoElementNode} A reference to an element.
  29714. */
  29715. element( indexNode ) {
  29716. return new WorkgroupInfoElementNode( this, indexNode );
  29717. }
  29718. generate( builder ) {
  29719. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  29720. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  29721. }
  29722. }
  29723. /**
  29724. * TSL function for creating a workgroup info node.
  29725. * Creates a new 'workgroup' scoped array buffer.
  29726. *
  29727. * @tsl
  29728. * @function
  29729. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  29730. * @param {number} [count=0] - The number of elements in the buffer.
  29731. * @returns {WorkgroupInfoNode}
  29732. */
  29733. const workgroupArray = ( type, count ) => new WorkgroupInfoNode( 'Workgroup', type, count );
  29734. /**
  29735. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  29736. * within a shader. In an atomic function, any modification to an atomic variable will
  29737. * occur as an indivisible step with a defined order relative to other modifications.
  29738. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  29739. * atomic operations will not interfere with each other.
  29740. *
  29741. * This node can only be used with a WebGPU backend.
  29742. *
  29743. * @augments Node
  29744. */
  29745. class AtomicFunctionNode extends Node {
  29746. static get type() {
  29747. return 'AtomicFunctionNode';
  29748. }
  29749. /**
  29750. * Constructs a new atomic function node.
  29751. *
  29752. * @param {string} method - The signature of the atomic function to construct.
  29753. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29754. * @param {Node} valueNode - The value that mutates the atomic variable.
  29755. */
  29756. constructor( method, pointerNode, valueNode ) {
  29757. super( 'uint' );
  29758. /**
  29759. * The signature of the atomic function to construct.
  29760. *
  29761. * @type {string}
  29762. */
  29763. this.method = method;
  29764. /**
  29765. * An atomic variable or element of an atomic buffer.
  29766. *
  29767. * @type {Node}
  29768. */
  29769. this.pointerNode = pointerNode;
  29770. /**
  29771. * A value that modifies the atomic variable.
  29772. *
  29773. * @type {Node}
  29774. */
  29775. this.valueNode = valueNode;
  29776. /**
  29777. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  29778. *
  29779. * @type {boolean}
  29780. * @default true
  29781. */
  29782. this.parents = true;
  29783. }
  29784. /**
  29785. * Overwrites the default implementation to return the type of
  29786. * the pointer node.
  29787. *
  29788. * @param {NodeBuilder} builder - The current node builder.
  29789. * @return {string} The input type.
  29790. */
  29791. getInputType( builder ) {
  29792. return this.pointerNode.getNodeType( builder );
  29793. }
  29794. /**
  29795. * Overwritten since the node type is inferred from the input type.
  29796. *
  29797. * @param {NodeBuilder} builder - The current node builder.
  29798. * @return {string} The node type.
  29799. */
  29800. getNodeType( builder ) {
  29801. return this.getInputType( builder );
  29802. }
  29803. generate( builder ) {
  29804. const properties = builder.getNodeProperties( this );
  29805. const parents = properties.parents;
  29806. const method = this.method;
  29807. const type = this.getNodeType( builder );
  29808. const inputType = this.getInputType( builder );
  29809. const a = this.pointerNode;
  29810. const b = this.valueNode;
  29811. const params = [];
  29812. params.push( `&${ a.build( builder, inputType ) }` );
  29813. if ( b !== null ) {
  29814. params.push( b.build( builder, inputType ) );
  29815. }
  29816. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  29817. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  29818. if ( isVoid ) {
  29819. builder.addLineFlowCode( methodSnippet, this );
  29820. } else {
  29821. if ( properties.constNode === undefined ) {
  29822. properties.constNode = expression( methodSnippet, type ).toConst();
  29823. }
  29824. return properties.constNode.build( builder );
  29825. }
  29826. }
  29827. }
  29828. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  29829. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  29830. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  29831. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  29832. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  29833. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  29834. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  29835. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  29836. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  29837. /**
  29838. * TSL function for creating an atomic function node.
  29839. *
  29840. * @tsl
  29841. * @function
  29842. * @param {string} method - The signature of the atomic function to construct.
  29843. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29844. * @param {Node} valueNode - The value that mutates the atomic variable.
  29845. * @returns {AtomicFunctionNode}
  29846. */
  29847. const atomicNode = nodeProxy( AtomicFunctionNode );
  29848. /**
  29849. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  29850. *
  29851. * @tsl
  29852. * @function
  29853. * @param {string} method - The signature of the atomic function to construct.
  29854. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29855. * @param {Node} valueNode - The value that mutates the atomic variable.
  29856. * @returns {AtomicFunctionNode}
  29857. */
  29858. const atomicFunc = ( method, pointerNode, valueNode ) => {
  29859. return atomicNode( method, pointerNode, valueNode ).toStack();
  29860. };
  29861. /**
  29862. * Loads the value stored in the atomic variable.
  29863. *
  29864. * @tsl
  29865. * @function
  29866. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29867. * @returns {AtomicFunctionNode}
  29868. */
  29869. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  29870. /**
  29871. * Stores a value in the atomic variable.
  29872. *
  29873. * @tsl
  29874. * @function
  29875. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29876. * @param {Node} valueNode - The value that mutates the atomic variable.
  29877. * @returns {AtomicFunctionNode}
  29878. */
  29879. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  29880. /**
  29881. * Increments the value stored in the atomic variable.
  29882. *
  29883. * @tsl
  29884. * @function
  29885. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29886. * @param {Node} valueNode - The value that mutates the atomic variable.
  29887. * @returns {AtomicFunctionNode}
  29888. */
  29889. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  29890. /**
  29891. * Decrements the value stored in the atomic variable.
  29892. *
  29893. * @tsl
  29894. * @function
  29895. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29896. * @param {Node} valueNode - The value that mutates the atomic variable.
  29897. * @returns {AtomicFunctionNode}
  29898. */
  29899. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  29900. /**
  29901. * Stores in an atomic variable the maximum between its current value and a parameter.
  29902. *
  29903. * @tsl
  29904. * @function
  29905. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29906. * @param {Node} valueNode - The value that mutates the atomic variable.
  29907. * @returns {AtomicFunctionNode}
  29908. */
  29909. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  29910. /**
  29911. * Stores in an atomic variable the minimum between its current value and a parameter.
  29912. *
  29913. * @tsl
  29914. * @function
  29915. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29916. * @param {Node} valueNode - The value that mutates the atomic variable.
  29917. * @returns {AtomicFunctionNode}
  29918. */
  29919. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  29920. /**
  29921. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  29922. *
  29923. * @tsl
  29924. * @function
  29925. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29926. * @param {Node} valueNode - The value that mutates the atomic variable.
  29927. * @returns {AtomicFunctionNode}
  29928. */
  29929. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  29930. /**
  29931. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  29932. *
  29933. * @tsl
  29934. * @function
  29935. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29936. * @param {Node} valueNode - The value that mutates the atomic variable.
  29937. * @returns {AtomicFunctionNode}
  29938. */
  29939. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  29940. /**
  29941. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  29942. *
  29943. * @tsl
  29944. * @function
  29945. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  29946. * @param {Node} valueNode - The value that mutates the atomic variable.
  29947. * @returns {AtomicFunctionNode}
  29948. */
  29949. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  29950. /**
  29951. * This class represents a set of built in WGSL shader functions that sync
  29952. * synchronously execute an operation across a subgroup, or 'warp', of compute
  29953. * or fragment shader invocations within a workgroup. Typically, these functions
  29954. * will synchronously execute an operation using data from all active invocations
  29955. * within the subgroup, then broadcast that result to all active invocations. In
  29956. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  29957. * (DirectX/HLSL) or warp intrinsics (CUDA).
  29958. *
  29959. * @augments TempNode
  29960. */
  29961. class SubgroupFunctionNode extends TempNode {
  29962. static get type() {
  29963. return 'SubgroupFunctionNode';
  29964. }
  29965. /**
  29966. * Constructs a new function node.
  29967. *
  29968. * @param {string} method - The subgroup/wave intrinsic method to construct.
  29969. * @param {Node} [aNode=null] - The method's first argument.
  29970. * @param {Node} [bNode=null] - The method's second argument.
  29971. */
  29972. constructor( method, aNode = null, bNode = null ) {
  29973. super();
  29974. /**
  29975. * The subgroup/wave intrinsic method to construct.
  29976. *
  29977. * @type {string}
  29978. */
  29979. this.method = method;
  29980. /**
  29981. * The method's first argument.
  29982. *
  29983. * @type {Node}
  29984. */
  29985. this.aNode = aNode;
  29986. /**
  29987. * The method's second argument.
  29988. *
  29989. * @type {Node}
  29990. */
  29991. this.bNode = bNode;
  29992. }
  29993. getInputType( builder ) {
  29994. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  29995. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  29996. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  29997. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  29998. if ( aLen > bLen ) {
  29999. return aType;
  30000. } else {
  30001. return bType;
  30002. }
  30003. }
  30004. getNodeType( builder ) {
  30005. const method = this.method;
  30006. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  30007. return 'bool';
  30008. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  30009. return 'uvec4';
  30010. } else {
  30011. return this.getInputType( builder );
  30012. }
  30013. }
  30014. generate( builder, output ) {
  30015. const method = this.method;
  30016. const type = this.getNodeType( builder );
  30017. const inputType = this.getInputType( builder );
  30018. const a = this.aNode;
  30019. const b = this.bNode;
  30020. const params = [];
  30021. if (
  30022. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  30023. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  30024. method === SubgroupFunctionNode.QUAD_BROADCAST
  30025. ) {
  30026. const bType = b.getNodeType( builder );
  30027. params.push(
  30028. a.build( builder, type ),
  30029. b.build( builder, bType === 'float' ? 'int' : type )
  30030. );
  30031. } else if (
  30032. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  30033. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  30034. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  30035. ) {
  30036. params.push(
  30037. a.build( builder, type ),
  30038. b.build( builder, 'uint' )
  30039. );
  30040. } else {
  30041. if ( a !== null ) params.push( a.build( builder, inputType ) );
  30042. if ( b !== null ) params.push( b.build( builder, inputType ) );
  30043. }
  30044. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  30045. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  30046. }
  30047. serialize( data ) {
  30048. super.serialize( data );
  30049. data.method = this.method;
  30050. }
  30051. deserialize( data ) {
  30052. super.deserialize( data );
  30053. this.method = data.method;
  30054. }
  30055. }
  30056. // 0 inputs
  30057. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  30058. // 1 input
  30059. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  30060. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  30061. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  30062. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  30063. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  30064. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  30065. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  30066. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  30067. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  30068. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  30069. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  30070. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  30071. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  30072. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  30073. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  30074. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  30075. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  30076. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  30077. // 2 inputs
  30078. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  30079. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  30080. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  30081. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  30082. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  30083. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  30084. /**
  30085. * Returns true if this invocation has the lowest subgroup_invocation_id
  30086. * among active invocations in the subgroup.
  30087. *
  30088. * @tsl
  30089. * @method
  30090. * @return {bool} The result of the computation.
  30091. */
  30092. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  30093. /**
  30094. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  30095. * is 1 if pred is true for that active invocation and 0 otherwise.
  30096. *
  30097. * @tsl
  30098. * @method
  30099. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  30100. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  30101. */
  30102. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  30103. /**
  30104. * A reduction that adds e among all active invocations and returns that result.
  30105. *
  30106. * @tsl
  30107. * @method
  30108. * @param {number} e - The value provided to the reduction by the current invocation.
  30109. * @return {number} The accumulated result of the reduction operation.
  30110. */
  30111. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  30112. /**
  30113. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30114. *
  30115. * @tsl
  30116. * @method
  30117. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30118. * @return {number} The accumulated result of the inclusive scan operation.
  30119. */
  30120. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  30121. /**
  30122. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  30123. *
  30124. * @tsl
  30125. * @method
  30126. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30127. * @return {number} The accumulated result of the exclusive scan operation.
  30128. */
  30129. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  30130. /**
  30131. * A reduction that multiplies e among all active invocations and returns that result.
  30132. *
  30133. * @tsl
  30134. * @method
  30135. * @param {number} e - The value provided to the reduction by the current invocation.
  30136. * @return {number} The accumulated result of the reduction operation.
  30137. */
  30138. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  30139. /**
  30140. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  30141. *
  30142. * @tsl
  30143. * @method
  30144. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  30145. * @return {number} The accumulated result of the inclusive scan operation.
  30146. */
  30147. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  30148. /**
  30149. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  30150. *
  30151. * @tsl
  30152. * @method
  30153. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  30154. * @return {number} The accumulated result of the exclusive scan operation.
  30155. */
  30156. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  30157. /**
  30158. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  30159. *
  30160. * @tsl
  30161. * @method
  30162. * @param {number} e - The value provided to the reduction by the current invocation.
  30163. * @return {number} The result of the reduction operation.
  30164. */
  30165. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  30166. /**
  30167. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  30168. *
  30169. * @tsl
  30170. * @method
  30171. * @param {number} e - The value provided to the reduction by the current invocation.
  30172. * @return {number} The result of the reduction operation.
  30173. */
  30174. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  30175. /**
  30176. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  30177. *
  30178. * @tsl
  30179. * @method
  30180. * @param {number} e - The value provided to the reduction by the current invocation.
  30181. * @return {number} The result of the reduction operation.
  30182. */
  30183. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  30184. /**
  30185. * A reduction that performs a min of e among all active invocations and returns that result.
  30186. *
  30187. * @tsl
  30188. * @method
  30189. * @param {number} e - The value provided to the reduction by the current invocation.
  30190. * @return {number} The result of the reduction operation.
  30191. */
  30192. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  30193. /**
  30194. * A reduction that performs a max of e among all active invocations and returns that result.
  30195. *
  30196. * @tsl
  30197. * @method
  30198. * @param {number} e - The value provided to the reduction by the current invocation.
  30199. * @return {number} The result of the reduction operation.
  30200. */
  30201. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  30202. /**
  30203. * Returns true if e is true for all active invocations in the subgroup.
  30204. *
  30205. * @tsl
  30206. * @method
  30207. * @return {bool} The result of the computation.
  30208. */
  30209. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  30210. /**
  30211. * Returns true if e is true for any active invocation in the subgroup
  30212. *
  30213. * @tsl
  30214. * @method
  30215. * @return {bool} The result of the computation.
  30216. */
  30217. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  30218. /**
  30219. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  30220. *
  30221. * @tsl
  30222. * @method
  30223. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  30224. * @param {number} id - The subgroup invocation to broadcast from.
  30225. * @return {number} The broadcast value.
  30226. */
  30227. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  30228. /**
  30229. * Swaps e between invocations in the quad in the X direction.
  30230. *
  30231. * @tsl
  30232. * @method
  30233. * @param {number} e - The value to swap from the current invocation.
  30234. * @return {number} The value received from the swap operation.
  30235. */
  30236. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  30237. /**
  30238. * Swaps e between invocations in the quad in the Y direction.
  30239. *
  30240. * @tsl
  30241. * @method
  30242. * @param {number} e - The value to swap from the current invocation.
  30243. * @return {number} The value received from the swap operation.
  30244. */
  30245. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  30246. /**
  30247. * Swaps e between invocations in the quad diagonally.
  30248. *
  30249. * @tsl
  30250. * @method
  30251. * @param {number} e - The value to swap from the current invocation.
  30252. * @return {number} The value received from the swap operation.
  30253. */
  30254. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  30255. /**
  30256. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  30257. *
  30258. * @tsl
  30259. * @method
  30260. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  30261. * @param {number} id - The subgroup invocation to broadcast from.
  30262. * @return {number} The broadcast value.
  30263. */
  30264. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  30265. /**
  30266. * Returns v from the active invocation whose subgroup_invocation_id matches id
  30267. *
  30268. * @tsl
  30269. * @method
  30270. * @param {number} v - The value to return from subgroup invocation id^mask.
  30271. * @param {number} id - The subgroup invocation which returns the value v.
  30272. * @return {number} The broadcast value.
  30273. */
  30274. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  30275. /**
  30276. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  30277. *
  30278. * @tsl
  30279. * @method
  30280. * @param {number} v - The value to return from subgroup invocation id^mask.
  30281. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  30282. * @return {number} The broadcast value.
  30283. */
  30284. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  30285. /**
  30286. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  30287. *
  30288. * @tsl
  30289. * @method
  30290. * @param {number} v - The value to return from subgroup invocation id^mask.
  30291. * @param {number} delta - A value that offsets the current in.
  30292. * @return {number} The broadcast value.
  30293. */
  30294. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  30295. /**
  30296. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  30297. *
  30298. * @tsl
  30299. * @method
  30300. * @param {number} v - The value to return from subgroup invocation id^mask.
  30301. * @param {number} delta - A value that offsets the current subgroup invocation.
  30302. * @return {number} The broadcast value.
  30303. */
  30304. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  30305. /**
  30306. * Broadcasts e from the quad invocation with id equal to id.
  30307. *
  30308. * @tsl
  30309. * @method
  30310. * @param {number} e - The value to broadcast.
  30311. * @return {number} The broadcast value.
  30312. */
  30313. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  30314. let uniformsLib;
  30315. function getLightData( light ) {
  30316. uniformsLib = uniformsLib || new WeakMap();
  30317. let uniforms = uniformsLib.get( light );
  30318. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  30319. return uniforms;
  30320. }
  30321. /**
  30322. * TSL function for getting a shadow matrix uniform node for the given light.
  30323. *
  30324. * @tsl
  30325. * @function
  30326. * @param {Light} light -The light source.
  30327. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  30328. */
  30329. function lightShadowMatrix( light ) {
  30330. const data = getLightData( light );
  30331. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  30332. // normally, shadow matrices are updated in ShadowNode. However, if the shadow matrix is used outside
  30333. // of shadow rendering (like in ProjectorLightNode), the shadow matrix still requires an update
  30334. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  30335. if ( light.shadow.camera.coordinateSystem !== frame.camera.coordinateSystem ) {
  30336. light.shadow.camera.coordinateSystem = frame.camera.coordinateSystem;
  30337. light.shadow.camera.updateProjectionMatrix();
  30338. }
  30339. light.shadow.updateMatrices( light );
  30340. }
  30341. return light.shadow.matrix;
  30342. } ) );
  30343. }
  30344. /**
  30345. * TSL function for getting projected uv coordinates for the given light.
  30346. * Relevant when using maps with spot lights.
  30347. *
  30348. * @tsl
  30349. * @function
  30350. * @param {Light} light -The light source.
  30351. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  30352. * @returns {Node<vec3>} The projected uvs.
  30353. */
  30354. function lightProjectionUV( light, position = positionWorld ) {
  30355. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  30356. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  30357. return projectionUV;
  30358. }
  30359. /**
  30360. * TSL function for getting the position in world space for the given light.
  30361. *
  30362. * @tsl
  30363. * @function
  30364. * @param {Light} light -The light source.
  30365. * @returns {UniformNode<vec3>} The light's position in world space.
  30366. */
  30367. function lightPosition( light ) {
  30368. const data = getLightData( light );
  30369. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  30370. }
  30371. /**
  30372. * TSL function for getting the light target position in world space for the given light.
  30373. *
  30374. * @tsl
  30375. * @function
  30376. * @param {Light} light -The light source.
  30377. * @returns {UniformNode<vec3>} The light target position in world space.
  30378. */
  30379. function lightTargetPosition( light ) {
  30380. const data = getLightData( light );
  30381. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  30382. }
  30383. /**
  30384. * TSL function for getting the position in view space for the given light.
  30385. *
  30386. * @tsl
  30387. * @function
  30388. * @param {Light} light - The light source.
  30389. * @returns {UniformNode<vec3>} The light's position in view space.
  30390. */
  30391. function lightViewPosition( light ) {
  30392. const data = getLightData( light );
  30393. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  30394. self.value = self.value || new Vector3();
  30395. self.value.setFromMatrixPosition( light.matrixWorld );
  30396. self.value.applyMatrix4( camera.matrixWorldInverse );
  30397. } ) );
  30398. }
  30399. /**
  30400. * TSL function for getting the light target direction for the given light.
  30401. *
  30402. * @tsl
  30403. * @function
  30404. * @param {Light} light -The light source.
  30405. * @returns {Node<vec3>} The light's target direction.
  30406. */
  30407. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  30408. const sortLights = ( lights ) => {
  30409. return lights.sort( ( a, b ) => a.id - b.id );
  30410. };
  30411. const getLightNodeById = ( id, lightNodes ) => {
  30412. for ( const lightNode of lightNodes ) {
  30413. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  30414. return lightNode;
  30415. }
  30416. }
  30417. return null;
  30418. };
  30419. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  30420. const _hashData = [];
  30421. /**
  30422. * This node represents the scene's lighting and manages the lighting model's life cycle
  30423. * for the current build 3D object. It is responsible for computing the total outgoing
  30424. * light in a given lighting context.
  30425. *
  30426. * @augments Node
  30427. */
  30428. class LightsNode extends Node {
  30429. static get type() {
  30430. return 'LightsNode';
  30431. }
  30432. /**
  30433. * Constructs a new lights node.
  30434. */
  30435. constructor() {
  30436. super( 'vec3' );
  30437. /**
  30438. * A node representing the total diffuse light.
  30439. *
  30440. * @type {Node<vec3>}
  30441. */
  30442. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  30443. /**
  30444. * A node representing the total specular light.
  30445. *
  30446. * @type {Node<vec3>}
  30447. */
  30448. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  30449. /**
  30450. * A node representing the outgoing light.
  30451. *
  30452. * @type {Node<vec3>}
  30453. */
  30454. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  30455. /**
  30456. * An array representing the lights in the scene.
  30457. *
  30458. * @private
  30459. * @type {Array<Light>}
  30460. */
  30461. this._lights = [];
  30462. /**
  30463. * For each light in the scene, this node will create a
  30464. * corresponding light node.
  30465. *
  30466. * @private
  30467. * @type {?Array<LightingNode>}
  30468. * @default null
  30469. */
  30470. this._lightNodes = null;
  30471. /**
  30472. * A hash for identifying the current light nodes setup.
  30473. *
  30474. * @private
  30475. * @type {?string}
  30476. * @default null
  30477. */
  30478. this._lightNodesHash = null;
  30479. /**
  30480. * `LightsNode` sets this property to `true` by default.
  30481. *
  30482. * @type {boolean}
  30483. * @default true
  30484. */
  30485. this.global = true;
  30486. }
  30487. /**
  30488. * Overwrites the default {@link Node#customCacheKey} implementation by including
  30489. * light data into the cache key.
  30490. *
  30491. * @return {number} The custom cache key.
  30492. */
  30493. customCacheKey() {
  30494. const lights = this._lights;
  30495. for ( let i = 0; i < lights.length; i ++ ) {
  30496. const light = lights[ i ];
  30497. _hashData.push( light.id );
  30498. _hashData.push( light.castShadow ? 1 : 0 );
  30499. if ( light.isSpotLight === true ) {
  30500. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  30501. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  30502. _hashData.push( hashMap, hashColorNode );
  30503. }
  30504. }
  30505. const cacheKey = hashArray( _hashData );
  30506. _hashData.length = 0;
  30507. return cacheKey;
  30508. }
  30509. /**
  30510. * Computes a hash value for identifying the current light nodes setup.
  30511. *
  30512. * @param {NodeBuilder} builder - A reference to the current node builder.
  30513. * @return {string} The computed hash.
  30514. */
  30515. getHash( builder ) {
  30516. if ( this._lightNodesHash === null ) {
  30517. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30518. const hash = [];
  30519. for ( const lightNode of this._lightNodes ) {
  30520. hash.push( lightNode.getHash() );
  30521. }
  30522. this._lightNodesHash = 'lights-' + hash.join( ',' );
  30523. }
  30524. return this._lightNodesHash;
  30525. }
  30526. analyze( builder ) {
  30527. const properties = builder.getNodeProperties( this );
  30528. for ( const node of properties.nodes ) {
  30529. node.build( builder );
  30530. }
  30531. properties.outputNode.build( builder );
  30532. }
  30533. /**
  30534. * Creates lighting nodes for each scene light. This makes it possible to further
  30535. * process lights in the node system.
  30536. *
  30537. * @param {NodeBuilder} builder - A reference to the current node builder.
  30538. */
  30539. setupLightsNode( builder ) {
  30540. const lightNodes = [];
  30541. const previousLightNodes = this._lightNodes;
  30542. const lights = sortLights( this._lights );
  30543. const nodeLibrary = builder.renderer.library;
  30544. for ( const light of lights ) {
  30545. if ( light.isNode ) {
  30546. lightNodes.push( nodeObject( light ) );
  30547. } else {
  30548. let lightNode = null;
  30549. if ( previousLightNodes !== null ) {
  30550. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  30551. }
  30552. if ( lightNode === null ) {
  30553. // find the corresponding node type for a given light
  30554. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  30555. if ( lightNodeClass === null ) {
  30556. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  30557. continue;
  30558. }
  30559. let lightNode = null;
  30560. if ( ! _lightsNodeRef.has( light ) ) {
  30561. lightNode = new lightNodeClass( light );
  30562. _lightsNodeRef.set( light, lightNode );
  30563. } else {
  30564. lightNode = _lightsNodeRef.get( light );
  30565. }
  30566. lightNodes.push( lightNode );
  30567. }
  30568. }
  30569. }
  30570. this._lightNodes = lightNodes;
  30571. }
  30572. /**
  30573. * Sets up a direct light in the lighting model.
  30574. *
  30575. * @param {Object} builder - The builder object containing the context and stack.
  30576. * @param {Object} lightNode - The light node.
  30577. * @param {Object} lightData - The light object containing color and direction properties.
  30578. */
  30579. setupDirectLight( builder, lightNode, lightData ) {
  30580. const { lightingModel, reflectedLight } = builder.context;
  30581. lightingModel.direct( {
  30582. ...lightData,
  30583. lightNode,
  30584. reflectedLight
  30585. }, builder );
  30586. }
  30587. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  30588. const { lightingModel, reflectedLight } = builder.context;
  30589. lightingModel.directRectArea( {
  30590. ...lightData,
  30591. lightNode,
  30592. reflectedLight
  30593. }, builder );
  30594. }
  30595. /**
  30596. * Setups the internal lights by building all respective
  30597. * light nodes.
  30598. *
  30599. * @param {NodeBuilder} builder - A reference to the current node builder.
  30600. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  30601. */
  30602. setupLights( builder, lightNodes ) {
  30603. for ( const lightNode of lightNodes ) {
  30604. lightNode.build( builder );
  30605. }
  30606. }
  30607. getLightNodes( builder ) {
  30608. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  30609. return this._lightNodes;
  30610. }
  30611. /**
  30612. * The implementation makes sure that for each light in the scene
  30613. * there is a corresponding light node. By building the light nodes
  30614. * and evaluating the lighting model the outgoing light is computed.
  30615. *
  30616. * @param {NodeBuilder} builder - A reference to the current node builder.
  30617. * @return {Node<vec3>} A node representing the outgoing light.
  30618. */
  30619. setup( builder ) {
  30620. const currentLightsNode = builder.lightsNode;
  30621. builder.lightsNode = this;
  30622. //
  30623. let outgoingLightNode = this.outgoingLightNode;
  30624. const context = builder.context;
  30625. const lightingModel = context.lightingModel;
  30626. const properties = builder.getNodeProperties( this );
  30627. if ( lightingModel ) {
  30628. const { totalDiffuseNode, totalSpecularNode } = this;
  30629. context.outgoingLight = outgoingLightNode;
  30630. const stack = builder.addStack();
  30631. //
  30632. properties.nodes = stack.nodes;
  30633. //
  30634. lightingModel.start( builder );
  30635. //
  30636. const { backdrop, backdropAlpha } = context;
  30637. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  30638. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  30639. if ( backdrop !== null ) {
  30640. if ( backdropAlpha !== null ) {
  30641. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  30642. } else {
  30643. totalDiffuse = vec3( backdrop );
  30644. }
  30645. }
  30646. totalDiffuseNode.assign( totalDiffuse );
  30647. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  30648. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  30649. //
  30650. lightingModel.finish( builder );
  30651. //
  30652. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  30653. } else {
  30654. properties.nodes = [];
  30655. }
  30656. //
  30657. builder.lightsNode = currentLightsNode;
  30658. return outgoingLightNode;
  30659. }
  30660. /**
  30661. * Configures this node with an array of lights.
  30662. *
  30663. * @param {Array<Light>} lights - An array of lights.
  30664. * @return {LightsNode} A reference to this node.
  30665. */
  30666. setLights( lights ) {
  30667. this._lights = lights;
  30668. this._lightNodes = null;
  30669. this._lightNodesHash = null;
  30670. return this;
  30671. }
  30672. /**
  30673. * Returns an array of the scene's lights.
  30674. *
  30675. * @return {Array<Light>} The scene's lights.
  30676. */
  30677. getLights() {
  30678. return this._lights;
  30679. }
  30680. /**
  30681. * Whether the scene has lights or not.
  30682. *
  30683. * @type {boolean}
  30684. */
  30685. get hasLights() {
  30686. return this._lights.length > 0;
  30687. }
  30688. }
  30689. /**
  30690. * TSL function for creating an instance of `LightsNode` and configuring
  30691. * it with the given array of lights.
  30692. *
  30693. * @tsl
  30694. * @function
  30695. * @param {Array<Light>} lights - An array of lights.
  30696. * @return {LightsNode} The created lights node.
  30697. */
  30698. const lights = ( lights = [] ) => new LightsNode().setLights( lights );
  30699. /**
  30700. * Base class for all shadow nodes.
  30701. *
  30702. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  30703. * Lighting nodes might share the same shadow node type or use specific ones depending on
  30704. * their requirements.
  30705. *
  30706. * @augments Node
  30707. */
  30708. class ShadowBaseNode extends Node {
  30709. static get type() {
  30710. return 'ShadowBaseNode';
  30711. }
  30712. /**
  30713. * Constructs a new shadow base node.
  30714. *
  30715. * @param {Light} light - The shadow casting light.
  30716. */
  30717. constructor( light ) {
  30718. super();
  30719. /**
  30720. * The shadow casting light.
  30721. *
  30722. * @type {Light}
  30723. */
  30724. this.light = light;
  30725. /**
  30726. * Overwritten since shadows are updated by default per render.
  30727. *
  30728. * @type {string}
  30729. * @default 'render'
  30730. */
  30731. this.updateBeforeType = NodeUpdateType.RENDER;
  30732. /**
  30733. * This flag can be used for type testing.
  30734. *
  30735. * @type {boolean}
  30736. * @readonly
  30737. * @default true
  30738. */
  30739. this.isShadowBaseNode = true;
  30740. }
  30741. /**
  30742. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  30743. *
  30744. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  30745. */
  30746. setupShadowPosition( { context, material } ) {
  30747. // Use assign inside an Fn()
  30748. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  30749. }
  30750. }
  30751. /**
  30752. * TSL object that represents the vertex position in world space during the shadow pass.
  30753. *
  30754. * @tsl
  30755. * @type {Node<vec3>}
  30756. */
  30757. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  30758. /**
  30759. * Saves the state of the given renderer and stores it into the given state object.
  30760. *
  30761. * If not state object is provided, the function creates one.
  30762. *
  30763. * @private
  30764. * @function
  30765. * @param {Renderer} renderer - The renderer.
  30766. * @param {Object} [state={}] - The state.
  30767. * @return {Object} The state.
  30768. */
  30769. function saveRendererState( renderer, state = {} ) {
  30770. state.toneMapping = renderer.toneMapping;
  30771. state.toneMappingExposure = renderer.toneMappingExposure;
  30772. state.outputColorSpace = renderer.outputColorSpace;
  30773. state.renderTarget = renderer.getRenderTarget();
  30774. state.activeCubeFace = renderer.getActiveCubeFace();
  30775. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  30776. state.renderObjectFunction = renderer.getRenderObjectFunction();
  30777. state.pixelRatio = renderer.getPixelRatio();
  30778. state.mrt = renderer.getMRT();
  30779. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  30780. state.clearAlpha = renderer.getClearAlpha();
  30781. state.autoClear = renderer.autoClear;
  30782. state.scissorTest = renderer.getScissorTest();
  30783. return state;
  30784. }
  30785. /**
  30786. * Saves the state of the given renderer and stores it into the given state object.
  30787. * Besides, the function also resets the state of the renderer to its default values.
  30788. *
  30789. * If not state object is provided, the function creates one.
  30790. *
  30791. * @private
  30792. * @function
  30793. * @param {Renderer} renderer - The renderer.
  30794. * @param {Object} [state={}] - The state.
  30795. * @return {Object} The state.
  30796. */
  30797. function resetRendererState( renderer, state ) {
  30798. state = saveRendererState( renderer, state );
  30799. renderer.setMRT( null );
  30800. renderer.setRenderObjectFunction( null );
  30801. renderer.setClearColor( 0x000000, 1 );
  30802. renderer.autoClear = true;
  30803. return state;
  30804. }
  30805. /**
  30806. * Restores the state of the given renderer from the given state object.
  30807. *
  30808. * @private
  30809. * @function
  30810. * @param {Renderer} renderer - The renderer.
  30811. * @param {Object} state - The state to restore.
  30812. */
  30813. function restoreRendererState( renderer, state ) {
  30814. renderer.toneMapping = state.toneMapping;
  30815. renderer.toneMappingExposure = state.toneMappingExposure;
  30816. renderer.outputColorSpace = state.outputColorSpace;
  30817. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  30818. renderer.setRenderObjectFunction( state.renderObjectFunction );
  30819. renderer.setPixelRatio( state.pixelRatio );
  30820. renderer.setMRT( state.mrt );
  30821. renderer.setClearColor( state.clearColor, state.clearAlpha );
  30822. renderer.autoClear = state.autoClear;
  30823. renderer.setScissorTest( state.scissorTest );
  30824. }
  30825. /**
  30826. * Saves the state of the given scene and stores it into the given state object.
  30827. *
  30828. * If not state object is provided, the function creates one.
  30829. *
  30830. * @private
  30831. * @function
  30832. * @param {Scene} scene - The scene.
  30833. * @param {Object} [state={}] - The state.
  30834. * @return {Object} The state.
  30835. */
  30836. function saveSceneState( scene, state = {} ) {
  30837. state.background = scene.background;
  30838. state.backgroundNode = scene.backgroundNode;
  30839. state.overrideMaterial = scene.overrideMaterial;
  30840. return state;
  30841. }
  30842. /**
  30843. * Saves the state of the given scene and stores it into the given state object.
  30844. * Besides, the function also resets the state of the scene to its default values.
  30845. *
  30846. * If not state object is provided, the function creates one.
  30847. *
  30848. * @private
  30849. * @function
  30850. * @param {Scene} scene - The scene.
  30851. * @param {Object} [state={}] - The state.
  30852. * @return {Object} The state.
  30853. */
  30854. function resetSceneState( scene, state ) {
  30855. state = saveSceneState( scene, state );
  30856. scene.background = null;
  30857. scene.backgroundNode = null;
  30858. scene.overrideMaterial = null;
  30859. return state;
  30860. }
  30861. /**
  30862. * Restores the state of the given scene from the given state object.
  30863. *
  30864. * @private
  30865. * @function
  30866. * @param {Scene} scene - The scene.
  30867. * @param {Object} state - The state to restore.
  30868. */
  30869. function restoreSceneState( scene, state ) {
  30870. scene.background = state.background;
  30871. scene.backgroundNode = state.backgroundNode;
  30872. scene.overrideMaterial = state.overrideMaterial;
  30873. }
  30874. /**
  30875. * Saves the state of the given renderer and scene and stores it into the given state object.
  30876. *
  30877. * If not state object is provided, the function creates one.
  30878. *
  30879. * @private
  30880. * @function
  30881. * @param {Renderer} renderer - The renderer.
  30882. * @param {Scene} scene - The scene.
  30883. * @param {Object} [state={}] - The state.
  30884. * @return {Object} The state.
  30885. */
  30886. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  30887. state = saveRendererState( renderer, state );
  30888. state = saveSceneState( scene, state );
  30889. return state;
  30890. }
  30891. /**
  30892. * Saves the state of the given renderer and scene and stores it into the given state object.
  30893. * Besides, the function also resets the state of the renderer and scene to its default values.
  30894. *
  30895. * If not state object is provided, the function creates one.
  30896. *
  30897. * @private
  30898. * @function
  30899. * @param {Renderer} renderer - The renderer.
  30900. * @param {Scene} scene - The scene.
  30901. * @param {Object} [state={}] - The state.
  30902. * @return {Object} The state.
  30903. */
  30904. function resetRendererAndSceneState( renderer, scene, state ) {
  30905. state = resetRendererState( renderer, state );
  30906. state = resetSceneState( scene, state );
  30907. return state;
  30908. }
  30909. /**
  30910. * Restores the state of the given renderer and scene from the given state object.
  30911. *
  30912. * @private
  30913. * @function
  30914. * @param {Renderer} renderer - The renderer.
  30915. * @param {Scene} scene - The scene.
  30916. * @param {Object} state - The state to restore.
  30917. */
  30918. function restoreRendererAndSceneState( renderer, scene, state ) {
  30919. restoreRendererState( renderer, state );
  30920. restoreSceneState( scene, state );
  30921. }
  30922. var RendererUtils = /*#__PURE__*/Object.freeze({
  30923. __proto__: null,
  30924. resetRendererAndSceneState: resetRendererAndSceneState,
  30925. resetRendererState: resetRendererState,
  30926. resetSceneState: resetSceneState,
  30927. restoreRendererAndSceneState: restoreRendererAndSceneState,
  30928. restoreRendererState: restoreRendererState,
  30929. restoreSceneState: restoreSceneState,
  30930. saveRendererAndSceneState: saveRendererAndSceneState,
  30931. saveRendererState: saveRendererState,
  30932. saveSceneState: saveSceneState
  30933. });
  30934. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  30935. /**
  30936. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  30937. * with a binary `[0,1]` result.
  30938. *
  30939. * @method
  30940. * @param {Object} inputs - The input parameter object.
  30941. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30942. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30943. * @return {Node<float>} The filtering result.
  30944. */
  30945. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  30946. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  30947. if ( depthTexture.isArrayTexture ) {
  30948. basic = basic.depth( depthLayer );
  30949. }
  30950. return basic.compare( shadowCoord.z );
  30951. } );
  30952. /**
  30953. * A shadow filtering function performing PCF filtering with Vogel disk sampling and IGN.
  30954. *
  30955. * Uses 5 samples distributed via Vogel disk pattern, rotated per-pixel using Interleaved
  30956. * Gradient Noise (IGN) to break up banding artifacts. Combined with hardware PCF (4-tap
  30957. * filtering per sample), this effectively provides 20 filtered taps with better distribution.
  30958. *
  30959. * @method
  30960. * @param {Object} inputs - The input parameter object.
  30961. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30962. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30963. * @param {LightShadow} inputs.shadow - The light shadow.
  30964. * @return {Node<float>} The filtering result.
  30965. */
  30966. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  30967. const depthCompare = ( uv, compare ) => {
  30968. let depth = texture( depthTexture, uv );
  30969. if ( depthTexture.isArrayTexture ) {
  30970. depth = depth.depth( depthLayer );
  30971. }
  30972. return depth.compare( compare );
  30973. };
  30974. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  30975. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30976. const texelSize = vec2( 1 ).div( mapSize );
  30977. const radiusScaled = radius.mul( texelSize.x );
  30978. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  30979. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  30980. // 5 samples using Vogel disk distribution
  30981. return add(
  30982. depthCompare( shadowCoord.xy.add( vogelDiskSample( 0, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30983. depthCompare( shadowCoord.xy.add( vogelDiskSample( 1, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30984. depthCompare( shadowCoord.xy.add( vogelDiskSample( 2, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30985. depthCompare( shadowCoord.xy.add( vogelDiskSample( 3, 5, phi ).mul( radiusScaled ) ), shadowCoord.z ),
  30986. depthCompare( shadowCoord.xy.add( vogelDiskSample( 4, 5, phi ).mul( radiusScaled ) ), shadowCoord.z )
  30987. ).mul( 1 / 5 );
  30988. } );
  30989. /**
  30990. * A shadow filtering function performing PCF soft filtering.
  30991. *
  30992. * @method
  30993. * @param {Object} inputs - The input parameter object.
  30994. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30995. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  30996. * @param {LightShadow} inputs.shadow - The light shadow.
  30997. * @return {Node<float>} The filtering result.
  30998. */
  30999. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  31000. const depthCompare = ( uv, compare ) => {
  31001. let depth = texture( depthTexture, uv );
  31002. if ( depthTexture.isArrayTexture ) {
  31003. depth = depth.depth( depthLayer );
  31004. }
  31005. return depth.compare( compare );
  31006. };
  31007. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31008. const texelSize = vec2( 1 ).div( mapSize );
  31009. const dx = texelSize.x;
  31010. const dy = texelSize.y;
  31011. const uv = shadowCoord.xy;
  31012. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  31013. uv.subAssign( f.mul( texelSize ) );
  31014. return add(
  31015. depthCompare( uv, shadowCoord.z ),
  31016. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  31017. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  31018. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  31019. mix(
  31020. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  31021. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  31022. f.x
  31023. ),
  31024. mix(
  31025. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  31026. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  31027. f.x
  31028. ),
  31029. mix(
  31030. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  31031. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  31032. f.y
  31033. ),
  31034. mix(
  31035. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  31036. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  31037. f.y
  31038. ),
  31039. mix(
  31040. mix(
  31041. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  31042. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  31043. f.x
  31044. ),
  31045. mix(
  31046. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  31047. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  31048. f.x
  31049. ),
  31050. f.y
  31051. )
  31052. ).mul( 1 / 9 );
  31053. } );
  31054. /**
  31055. * A shadow filtering function performing VSM filtering.
  31056. *
  31057. * @method
  31058. * @param {Object} inputs - The input parameter object.
  31059. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31060. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  31061. * @return {Node<float>} The filtering result.
  31062. */
  31063. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  31064. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  31065. if ( depthTexture.isArrayTexture ) {
  31066. distribution = distribution.depth( depthLayer );
  31067. }
  31068. distribution = distribution.rg;
  31069. const mean = distribution.x;
  31070. const variance = max$1( 0.0000001, distribution.y.mul( distribution.y ) );
  31071. const hardShadow = step( shadowCoord.z, mean );
  31072. const output = float( 1 ).toVar(); // default, fully lit
  31073. If( hardShadow.notEqual( 1.0 ), () => {
  31074. // Distance from mean
  31075. const d = shadowCoord.z.sub( mean );
  31076. // Chebyshev's inequality for upper bound on probability
  31077. let p_max = variance.div( variance.add( d.mul( d ) ) );
  31078. // Reduce light bleeding by remapping [amount, 1] to [0, 1]
  31079. p_max = clamp( sub( p_max, 0.3 ).div( 0.65 ) );
  31080. output.assign( max$1( hardShadow, p_max ) );
  31081. } );
  31082. return output;
  31083. } );
  31084. /**
  31085. * Retrieves or creates a shadow material for the given light source.
  31086. *
  31087. * This function checks if a shadow material already exists for the provided light.
  31088. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  31089. * in the `shadowMaterialLib` for future use.
  31090. *
  31091. * @tsl
  31092. * @function
  31093. * @param {Light} light - The light source for which the shadow material is needed.
  31094. * If the light is a point light, a depth node is calculated
  31095. * using the linear shadow distance.
  31096. * @returns {NodeMaterial} The shadow material associated with the given light.
  31097. */
  31098. const getShadowMaterial = ( light ) => {
  31099. let material = shadowMaterialLib.get( light );
  31100. if ( material === undefined ) {
  31101. material = new NodeMaterial();
  31102. material.colorNode = vec4( 0, 0, 0, 1 );
  31103. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  31104. material.name = 'ShadowMaterial';
  31105. material.blending = NoBlending;
  31106. material.fog = false;
  31107. shadowMaterialLib.set( light, material );
  31108. }
  31109. return material;
  31110. };
  31111. /**
  31112. * Disposes the shadow material for the given light source.
  31113. *
  31114. * @param {Light} light - The light source.
  31115. */
  31116. const disposeShadowMaterial = ( light ) => {
  31117. const material = shadowMaterialLib.get( light );
  31118. if ( material !== undefined ) {
  31119. material.dispose();
  31120. shadowMaterialLib.delete( light );
  31121. }
  31122. };
  31123. //
  31124. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  31125. const _shadowRenderObjectKeys = [];
  31126. /**
  31127. * Creates a function to render shadow objects in a scene.
  31128. *
  31129. * @tsl
  31130. * @function
  31131. * @param {Renderer} renderer - The renderer.
  31132. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  31133. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  31134. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  31135. * @return {shadowRenderObjectFunction} A function that renders shadow objects.
  31136. */
  31137. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  31138. _shadowRenderObjectKeys[ 0 ] = renderer;
  31139. _shadowRenderObjectKeys[ 1 ] = shadow;
  31140. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  31141. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  31142. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  31143. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  31144. if ( useVelocity ) {
  31145. getDataFromObject( object ).useVelocity = true;
  31146. }
  31147. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31148. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  31149. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  31150. }
  31151. };
  31152. renderObjectFunction.shadowType = shadowType;
  31153. renderObjectFunction.useVelocity = useVelocity;
  31154. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  31155. }
  31156. _shadowRenderObjectKeys[ 0 ] = null;
  31157. _shadowRenderObjectKeys[ 1 ] = null;
  31158. return renderObjectFunction;
  31159. };
  31160. /**
  31161. * Represents the shader code for the first VSM render pass.
  31162. *
  31163. * @private
  31164. * @method
  31165. * @param {Object} inputs - The input parameter object.
  31166. * @param {Node<float>} inputs.samples - The number of samples
  31167. * @param {Node<float>} inputs.radius - The radius.
  31168. * @param {Node<float>} inputs.size - The size.
  31169. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  31170. * @return {Node<vec2>} The VSM output.
  31171. */
  31172. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31173. const mean = float( 0 ).toVar( 'meanVertical' );
  31174. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  31175. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31176. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31177. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31178. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31179. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  31180. if ( shadowPass.value.isArrayTexture ) {
  31181. depth = depth.depth( depthLayer );
  31182. }
  31183. depth = depth.x;
  31184. mean.addAssign( depth );
  31185. squaredMean.addAssign( depth.mul( depth ) );
  31186. } );
  31187. mean.divAssign( samples );
  31188. squaredMean.divAssign( samples );
  31189. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31190. return vec2( mean, std_dev );
  31191. } );
  31192. /**
  31193. * Represents the shader code for the second VSM render pass.
  31194. *
  31195. * @private
  31196. * @method
  31197. * @param {Object} inputs - The input parameter object.
  31198. * @param {Node<float>} inputs.samples - The number of samples
  31199. * @param {Node<float>} inputs.radius - The radius.
  31200. * @param {Node<float>} inputs.size - The size.
  31201. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  31202. * @return {Node<vec2>} The VSM output.
  31203. */
  31204. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  31205. const mean = float( 0 ).toVar( 'meanHorizontal' );
  31206. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  31207. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  31208. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  31209. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  31210. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  31211. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  31212. if ( shadowPass.value.isArrayTexture ) {
  31213. distribution = distribution.depth( depthLayer );
  31214. }
  31215. mean.addAssign( distribution.x );
  31216. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  31217. } );
  31218. mean.divAssign( samples );
  31219. squaredMean.divAssign( samples );
  31220. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ).max( 0 ) );
  31221. return vec2( mean, std_dev );
  31222. } );
  31223. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  31224. //
  31225. let _rendererState;
  31226. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  31227. /**
  31228. * Represents the default shadow implementation for lighting nodes.
  31229. *
  31230. * @augments ShadowBaseNode
  31231. */
  31232. class ShadowNode extends ShadowBaseNode {
  31233. static get type() {
  31234. return 'ShadowNode';
  31235. }
  31236. /**
  31237. * Constructs a new shadow node.
  31238. *
  31239. * @param {Light} light - The shadow casting light.
  31240. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  31241. */
  31242. constructor( light, shadow = null ) {
  31243. super( light );
  31244. /**
  31245. * The light shadow which defines the properties light's
  31246. * shadow.
  31247. *
  31248. * @type {?LightShadow}
  31249. * @default null
  31250. */
  31251. this.shadow = shadow || light.shadow;
  31252. /**
  31253. * A reference to the shadow map which is a render target.
  31254. *
  31255. * @type {?RenderTarget}
  31256. * @default null
  31257. */
  31258. this.shadowMap = null;
  31259. /**
  31260. * Only relevant for VSM shadows. Render target for the
  31261. * first VSM render pass.
  31262. *
  31263. * @type {?RenderTarget}
  31264. * @default null
  31265. */
  31266. this.vsmShadowMapVertical = null;
  31267. /**
  31268. * Only relevant for VSM shadows. Render target for the
  31269. * second VSM render pass.
  31270. *
  31271. * @type {?RenderTarget}
  31272. * @default null
  31273. */
  31274. this.vsmShadowMapHorizontal = null;
  31275. /**
  31276. * Only relevant for VSM shadows. Node material which
  31277. * is used to render the first VSM pass.
  31278. *
  31279. * @type {?NodeMaterial}
  31280. * @default null
  31281. */
  31282. this.vsmMaterialVertical = null;
  31283. /**
  31284. * Only relevant for VSM shadows. Node material which
  31285. * is used to render the second VSM pass.
  31286. *
  31287. * @type {?NodeMaterial}
  31288. * @default null
  31289. */
  31290. this.vsmMaterialHorizontal = null;
  31291. /**
  31292. * A reference to the output node which defines the
  31293. * final result of this shadow node.
  31294. *
  31295. * @type {?Node}
  31296. * @private
  31297. * @default null
  31298. */
  31299. this._node = null;
  31300. /**
  31301. * The current shadow map type of this shadow node.
  31302. *
  31303. * @type {?number}
  31304. * @private
  31305. * @default null
  31306. */
  31307. this._currentShadowType = null;
  31308. /**
  31309. * A Weak Map holding the current frame ID per camera. Used
  31310. * to control the update of shadow maps.
  31311. *
  31312. * @type {WeakMap<Camera,number>}
  31313. * @private
  31314. */
  31315. this._cameraFrameId = new WeakMap();
  31316. /**
  31317. * This flag can be used for type testing.
  31318. *
  31319. * @type {boolean}
  31320. * @readonly
  31321. * @default true
  31322. */
  31323. this.isShadowNode = true;
  31324. /**
  31325. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  31326. *
  31327. * @type {number}
  31328. * @readonly
  31329. * @default true
  31330. */
  31331. this.depthLayer = 0;
  31332. }
  31333. /**
  31334. * Setups the shadow filtering.
  31335. *
  31336. * @param {NodeBuilder} builder - A reference to the current node builder.
  31337. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31338. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31339. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  31340. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31341. * @param {LightShadow} inputs.shadow - The light shadow.
  31342. * @return {Node<float>} The result node of the shadow filtering.
  31343. */
  31344. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  31345. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  31346. .and( shadowCoord.x.lessThanEqual( 1 ) )
  31347. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  31348. .and( shadowCoord.y.lessThanEqual( 1 ) )
  31349. .and( shadowCoord.z.lessThanEqual( 1 ) );
  31350. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  31351. return frustumTest.select( shadowNode, float( 1 ) );
  31352. }
  31353. /**
  31354. * Setups the shadow coordinates.
  31355. *
  31356. * @param {NodeBuilder} builder - A reference to the current node builder.
  31357. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31358. * @return {Node<vec3>} The shadow coordinates.
  31359. */
  31360. setupShadowCoord( builder, shadowPosition ) {
  31361. const { shadow } = this;
  31362. const { renderer } = builder;
  31363. const bias = shadow.biasNode || reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31364. let shadowCoord = shadowPosition;
  31365. let coordZ;
  31366. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  31367. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  31368. coordZ = shadowCoord.z;
  31369. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31370. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  31371. }
  31372. } else {
  31373. const w = shadowCoord.w;
  31374. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  31375. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  31376. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  31377. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  31378. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  31379. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  31380. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  31381. }
  31382. shadowCoord = vec3(
  31383. shadowCoord.x,
  31384. shadowCoord.y.oneMinus(), // follow webgpu standards
  31385. coordZ.add( bias )
  31386. );
  31387. return shadowCoord;
  31388. }
  31389. /**
  31390. * Returns the shadow filtering function for the given shadow type.
  31391. *
  31392. * @param {number} type - The shadow type.
  31393. * @return {Function} The filtering function.
  31394. */
  31395. getShadowFilterFn( type ) {
  31396. return _shadowFilterLib[ type ];
  31397. }
  31398. setupRenderTarget( shadow, builder ) {
  31399. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  31400. depthTexture.name = 'ShadowDepthTexture';
  31401. depthTexture.compareFunction = LessEqualCompare;
  31402. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  31403. shadowMap.texture.name = 'ShadowMap';
  31404. shadowMap.texture.type = shadow.mapType;
  31405. shadowMap.depthTexture = depthTexture;
  31406. return { shadowMap, depthTexture };
  31407. }
  31408. /**
  31409. * Setups the shadow output node.
  31410. *
  31411. * @param {NodeBuilder} builder - A reference to the current node builder.
  31412. * @return {Node<vec3>} The shadow output node.
  31413. */
  31414. setupShadow( builder ) {
  31415. const { renderer, camera } = builder;
  31416. const { light, shadow } = this;
  31417. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  31418. const shadowMapType = renderer.shadowMap.type;
  31419. if ( shadowMapType === PCFShadowMap || shadowMapType === PCFSoftShadowMap ) {
  31420. depthTexture.minFilter = LinearFilter;
  31421. depthTexture.magFilter = LinearFilter;
  31422. } else {
  31423. depthTexture.minFilter = NearestFilter;
  31424. depthTexture.magFilter = NearestFilter;
  31425. }
  31426. shadow.camera.coordinateSystem = camera.coordinateSystem;
  31427. shadow.camera.updateProjectionMatrix();
  31428. // VSM
  31429. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31430. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  31431. if ( shadowMap.depth > 1 ) {
  31432. if ( ! shadowMap._vsmShadowMapVertical ) {
  31433. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31434. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  31435. }
  31436. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  31437. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  31438. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  31439. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  31440. }
  31441. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  31442. } else {
  31443. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31444. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  31445. }
  31446. let shadowPassVertical = texture( depthTexture );
  31447. if ( depthTexture.isArrayTexture ) {
  31448. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  31449. }
  31450. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  31451. if ( depthTexture.isArrayTexture ) {
  31452. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  31453. }
  31454. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  31455. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31456. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31457. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  31458. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31459. material.name = 'VSMVertical';
  31460. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  31461. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  31462. material.name = 'VSMHorizontal';
  31463. }
  31464. //
  31465. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  31466. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  31467. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  31468. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  31469. //
  31470. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  31471. if ( filterFn === null ) {
  31472. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  31473. }
  31474. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  31475. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  31476. let shadowColor;
  31477. if ( renderer.shadowMap.transmitted === true ) {
  31478. if ( shadowMap.texture.isCubeTexture ) {
  31479. // For cube shadow maps (point lights), use cubeTexture with vec3 coordinates
  31480. shadowColor = cubeTexture( shadowMap.texture, shadowCoord.xyz );
  31481. } else {
  31482. shadowColor = texture( shadowMap.texture, shadowCoord );
  31483. if ( depthTexture.isArrayTexture ) {
  31484. shadowColor = shadowColor.depth( this.depthLayer );
  31485. }
  31486. }
  31487. }
  31488. //
  31489. let shadowOutput;
  31490. if ( shadowColor ) {
  31491. shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  31492. } else {
  31493. shadowOutput = mix( 1, shadowNode, shadowIntensity ).toVar();
  31494. }
  31495. this.shadowMap = shadowMap;
  31496. this.shadow.map = shadowMap;
  31497. // Shadow Output + Inspector
  31498. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  31499. if ( shadowColor ) {
  31500. shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  31501. if ( this.shadowMap.texture.isCubeTexture ) {
  31502. return cubeTexture( this.shadowMap.texture );
  31503. }
  31504. return texture( this.shadowMap.texture );
  31505. } );
  31506. }
  31507. return shadowOutput.toInspector( `${ inspectName } / Depth`, () => {
  31508. // TODO: Use linear depth
  31509. if ( this.shadowMap.texture.isCubeTexture ) {
  31510. return cubeTexture( this.shadowMap.texture ).r.oneMinus();
  31511. }
  31512. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).r.oneMinus();
  31513. } );
  31514. }
  31515. /**
  31516. * The implementation performs the setup of the output node. An output is only
  31517. * produces if shadow mapping is globally enabled in the renderer.
  31518. *
  31519. * @param {NodeBuilder} builder - A reference to the current node builder.
  31520. * @return {ShaderCallNodeInternal} The output node.
  31521. */
  31522. setup( builder ) {
  31523. if ( builder.renderer.shadowMap.enabled === false ) return;
  31524. return Fn( () => {
  31525. const currentShadowType = builder.renderer.shadowMap.type;
  31526. if ( this._currentShadowType !== currentShadowType ) {
  31527. this._reset();
  31528. this._node = null;
  31529. }
  31530. let node = this._node;
  31531. this.setupShadowPosition( builder );
  31532. if ( node === null ) {
  31533. this._node = node = this.setupShadow( builder );
  31534. this._currentShadowType = currentShadowType;
  31535. }
  31536. if ( builder.material.receivedShadowNode ) {
  31537. node = builder.material.receivedShadowNode( node );
  31538. }
  31539. return node;
  31540. } )();
  31541. }
  31542. /**
  31543. * Renders the shadow. The logic of this function could be included
  31544. * into {@link ShadowNode#updateShadow} however more specialized shadow
  31545. * nodes might require a custom shadow map rendering. By having a
  31546. * dedicated method, it's easier to overwrite the default behavior.
  31547. *
  31548. * @param {NodeFrame} frame - A reference to the current node frame.
  31549. */
  31550. renderShadow( frame ) {
  31551. const { shadow, shadowMap, light } = this;
  31552. const { renderer, scene } = frame;
  31553. shadow.updateMatrices( light );
  31554. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  31555. const currentSceneName = scene.name;
  31556. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  31557. renderer.render( scene, shadow.camera );
  31558. scene.name = currentSceneName;
  31559. }
  31560. /**
  31561. * Updates the shadow.
  31562. *
  31563. * @param {NodeFrame} frame - A reference to the current node frame.
  31564. */
  31565. updateShadow( frame ) {
  31566. const { shadowMap, light, shadow } = this;
  31567. const { renderer, scene, camera } = frame;
  31568. const shadowType = renderer.shadowMap.type;
  31569. const depthVersion = shadowMap.depthTexture.version;
  31570. this._depthVersionCached = depthVersion;
  31571. const _shadowCameraLayer = shadow.camera.layers.mask;
  31572. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  31573. shadow.camera.layers.mask = camera.layers.mask;
  31574. }
  31575. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  31576. const currentMRT = renderer.getMRT();
  31577. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  31578. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  31579. scene.overrideMaterial = getShadowMaterial( light );
  31580. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  31581. renderer.setClearColor( 0x000000, 0 );
  31582. renderer.setRenderTarget( shadowMap );
  31583. this.renderShadow( frame );
  31584. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  31585. // vsm blur pass
  31586. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  31587. this.vsmPass( renderer );
  31588. }
  31589. shadow.camera.layers.mask = _shadowCameraLayer;
  31590. restoreRendererAndSceneState( renderer, scene, _rendererState );
  31591. }
  31592. /**
  31593. * For VSM additional render passes are required.
  31594. *
  31595. * @param {Renderer} renderer - A reference to the current renderer.
  31596. */
  31597. vsmPass( renderer ) {
  31598. const { shadow } = this;
  31599. const depth = this.shadowMap.depth;
  31600. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31601. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  31602. renderer.setRenderTarget( this.vsmShadowMapVertical );
  31603. _quadMesh.material = this.vsmMaterialVertical;
  31604. _quadMesh.render( renderer );
  31605. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  31606. _quadMesh.material = this.vsmMaterialHorizontal;
  31607. _quadMesh.render( renderer );
  31608. }
  31609. /**
  31610. * Frees the internal resources of this shadow node.
  31611. */
  31612. dispose() {
  31613. this._reset();
  31614. super.dispose();
  31615. }
  31616. /**
  31617. * Resets the resouce state of this shadow node.
  31618. *
  31619. * @private
  31620. */
  31621. _reset() {
  31622. this._currentShadowType = null;
  31623. disposeShadowMaterial( this.light );
  31624. if ( this.shadowMap ) {
  31625. this.shadowMap.dispose();
  31626. this.shadowMap = null;
  31627. }
  31628. if ( this.vsmShadowMapVertical !== null ) {
  31629. this.vsmShadowMapVertical.dispose();
  31630. this.vsmShadowMapVertical = null;
  31631. this.vsmMaterialVertical.dispose();
  31632. this.vsmMaterialVertical = null;
  31633. }
  31634. if ( this.vsmShadowMapHorizontal !== null ) {
  31635. this.vsmShadowMapHorizontal.dispose();
  31636. this.vsmShadowMapHorizontal = null;
  31637. this.vsmMaterialHorizontal.dispose();
  31638. this.vsmMaterialHorizontal = null;
  31639. }
  31640. }
  31641. /**
  31642. * The implementation performs the update of the shadow map if necessary.
  31643. *
  31644. * @param {NodeFrame} frame - A reference to the current node frame.
  31645. */
  31646. updateBefore( frame ) {
  31647. const { shadow } = this;
  31648. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  31649. if ( needsUpdate ) {
  31650. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  31651. needsUpdate = false;
  31652. }
  31653. this._cameraFrameId[ frame.camera ] = frame.frameId;
  31654. }
  31655. if ( needsUpdate ) {
  31656. this.updateShadow( frame );
  31657. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  31658. shadow.needsUpdate = false;
  31659. }
  31660. }
  31661. }
  31662. }
  31663. /**
  31664. * Shadow Render Object Function.
  31665. *
  31666. * @function shadowRenderObjectFunction
  31667. * @param {Object3D} object - The 3D object to render.
  31668. * @param {Scene} scene - The scene containing the object.
  31669. * @param {Camera} _camera - The camera used for rendering.
  31670. * @param {BufferGeometry} geometry - The geometry of the object.
  31671. * @param {Material} material - The material of the object.
  31672. * @param {Group} group - The group the object belongs to.
  31673. * @param {...any} params - Additional parameters for rendering.
  31674. */
  31675. /**
  31676. * TSL function for creating an instance of `ShadowNode`.
  31677. *
  31678. * @tsl
  31679. * @function
  31680. * @param {Light} light - The shadow casting light.
  31681. * @param {?LightShadow} [shadow] - The light shadow.
  31682. * @return {ShadowNode} The created shadow node.
  31683. */
  31684. const shadow = ( light, shadow ) => new ShadowNode( light, shadow );
  31685. const _clearColor$1 = /*@__PURE__*/ new Color();
  31686. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  31687. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  31688. const _lookTarget = /*@__PURE__*/ new Vector3();
  31689. // Cube map face directions and up vectors for point light shadows
  31690. // Face order: +X, -X, +Y, -Y, +Z, -Z
  31691. // WebGPU coordinate system - Y faces swapped to match texture sampling convention
  31692. const _cubeDirectionsWebGPU = [
  31693. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ),
  31694. /*@__PURE__*/ new Vector3( 0, 1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31695. ];
  31696. const _cubeUpsWebGPU = [
  31697. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, -1 ),
  31698. /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31699. ];
  31700. // WebGL coordinate system - standard OpenGL convention
  31701. const _cubeDirectionsWebGL = [
  31702. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  31703. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  31704. ];
  31705. const _cubeUpsWebGL = [
  31706. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  31707. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  31708. ];
  31709. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp } ) => {
  31710. return cubeTexture( depthTexture, bd3D ).compare( dp );
  31711. } );
  31712. /**
  31713. * A shadow filtering function for point lights using Vogel disk sampling and IGN.
  31714. *
  31715. * Uses 5 samples distributed via Vogel disk pattern in tangent space around the
  31716. * sample direction, rotated per-pixel using Interleaved Gradient Noise (IGN).
  31717. *
  31718. * @method
  31719. * @param {Object} inputs - The input parameter object.
  31720. * @param {CubeDepthTexture} inputs.depthTexture - A reference to the shadow cube map.
  31721. * @param {Node<vec3>} inputs.bd3D - The normalized direction from light to fragment.
  31722. * @param {Node<float>} inputs.dp - The depth value to compare against.
  31723. * @param {LightShadow} inputs.shadow - The light shadow.
  31724. * @return {Node<float>} The filtering result.
  31725. */
  31726. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, shadow } ) => {
  31727. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  31728. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  31729. const texelSize = radius.div( mapSize.x );
  31730. // Build a tangent-space coordinate system for applying offsets
  31731. const absDir = abs( bd3D );
  31732. const tangent = normalize( cross( bd3D, absDir.x.greaterThan( absDir.z ).select( vec3( 0, 1, 0 ), vec3( 1, 0, 0 ) ) ) );
  31733. const bitangent = cross( bd3D, tangent );
  31734. // Use IGN to rotate sampling pattern per pixel (phi = IGN * 2π)
  31735. const phi = interleavedGradientNoise( screenCoordinate.xy ).mul( 6.28318530718 );
  31736. // 5 samples using Vogel disk distribution in tangent space
  31737. const sample0 = vogelDiskSample( 0, 5, phi );
  31738. const sample1 = vogelDiskSample( 1, 5, phi );
  31739. const sample2 = vogelDiskSample( 2, 5, phi );
  31740. const sample3 = vogelDiskSample( 3, 5, phi );
  31741. const sample4 = vogelDiskSample( 4, 5, phi );
  31742. return cubeTexture( depthTexture, bd3D.add( tangent.mul( sample0.x ).add( bitangent.mul( sample0.y ) ).mul( texelSize ) ) ).compare( dp )
  31743. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample1.x ).add( bitangent.mul( sample1.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31744. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample2.x ).add( bitangent.mul( sample2.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31745. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample3.x ).add( bitangent.mul( sample3.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31746. .add( cubeTexture( depthTexture, bd3D.add( tangent.mul( sample4.x ).add( bitangent.mul( sample4.y ) ).mul( texelSize ) ) ).compare( dp ) )
  31747. .mul( 1.0 / 5.0 );
  31748. } );
  31749. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  31750. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  31751. // the vector from the light to the world-space position of the fragment.
  31752. const shadowPosition = shadowCoord.xyz.toConst();
  31753. const shadowPositionAbs = shadowPosition.abs().toConst();
  31754. const viewZ = shadowPositionAbs.x.max( shadowPositionAbs.y ).max( shadowPositionAbs.z );
  31755. const shadowCameraNear = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  31756. const shadowCameraFar = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  31757. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  31758. const result = float( 1.0 ).toVar();
  31759. If( viewZ.sub( shadowCameraFar ).lessThanEqual( 0.0 ).and( viewZ.sub( shadowCameraNear ).greaterThanEqual( 0.0 ) ), () => {
  31760. const dp = viewZToPerspectiveDepth( viewZ.negate(), shadowCameraNear, shadowCameraFar );
  31761. dp.addAssign( bias );
  31762. // bd3D = base direction 3D (direction from light to fragment)
  31763. const bd3D = shadowPosition.normalize();
  31764. // percentage-closer filtering using cube texture sampling
  31765. result.assign( filterFn( { depthTexture, bd3D, dp, shadow } ) );
  31766. } );
  31767. return result;
  31768. } );
  31769. /**
  31770. * Represents the shadow implementation for point light nodes.
  31771. *
  31772. * @augments ShadowNode
  31773. */
  31774. class PointShadowNode extends ShadowNode {
  31775. static get type() {
  31776. return 'PointShadowNode';
  31777. }
  31778. /**
  31779. * Constructs a new point shadow node.
  31780. *
  31781. * @param {PointLight} light - The shadow casting point light.
  31782. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31783. */
  31784. constructor( light, shadow = null ) {
  31785. super( light, shadow );
  31786. }
  31787. /**
  31788. * Overwrites the default implementation to return point light shadow specific
  31789. * filtering functions.
  31790. *
  31791. * @param {number} type - The shadow type.
  31792. * @return {Function} The filtering function.
  31793. */
  31794. getShadowFilterFn( type ) {
  31795. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  31796. }
  31797. /**
  31798. * Overwrites the default implementation so the unaltered shadow position is used.
  31799. *
  31800. * @param {NodeBuilder} builder - A reference to the current node builder.
  31801. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  31802. * @return {Node<vec3>} The shadow coordinates.
  31803. */
  31804. setupShadowCoord( builder, shadowPosition ) {
  31805. return shadowPosition;
  31806. }
  31807. /**
  31808. * Overwrites the default implementation to only use point light specific
  31809. * shadow filter functions.
  31810. *
  31811. * @param {NodeBuilder} builder - A reference to the current node builder.
  31812. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  31813. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  31814. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's depth texture.
  31815. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  31816. * @param {LightShadow} inputs.shadow - The light shadow.
  31817. * @return {Node<float>} The result node of the shadow filtering.
  31818. */
  31819. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  31820. return pointShadowFilter( { filterFn, depthTexture, shadowCoord, shadow } );
  31821. }
  31822. /**
  31823. * Overwrites the default implementation to create a CubeRenderTarget with CubeDepthTexture.
  31824. *
  31825. * @param {LightShadow} shadow - The light shadow object.
  31826. * @param {NodeBuilder} builder - A reference to the current node builder.
  31827. * @return {Object} An object containing the shadow map and depth texture.
  31828. */
  31829. setupRenderTarget( shadow, builder ) {
  31830. const depthTexture = new CubeDepthTexture( shadow.mapSize.width );
  31831. depthTexture.name = 'PointShadowDepthTexture';
  31832. depthTexture.compareFunction = LessEqualCompare;
  31833. const shadowMap = builder.createCubeRenderTarget( shadow.mapSize.width );
  31834. shadowMap.texture.name = 'PointShadowMap';
  31835. shadowMap.depthTexture = depthTexture;
  31836. return { shadowMap, depthTexture };
  31837. }
  31838. /**
  31839. * Overwrites the default implementation with point light specific
  31840. * rendering code.
  31841. *
  31842. * @param {NodeFrame} frame - A reference to the current node frame.
  31843. */
  31844. renderShadow( frame ) {
  31845. const { shadow, shadowMap, light } = this;
  31846. const { renderer, scene } = frame;
  31847. const camera = shadow.camera;
  31848. const shadowMatrix = shadow.matrix;
  31849. // Select cube directions/ups based on coordinate system
  31850. const isWebGPU = renderer.coordinateSystem === WebGPUCoordinateSystem;
  31851. const cubeDirections = isWebGPU ? _cubeDirectionsWebGPU : _cubeDirectionsWebGL;
  31852. const cubeUps = isWebGPU ? _cubeUpsWebGPU : _cubeUpsWebGL;
  31853. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.width );
  31854. //
  31855. const previousAutoClear = renderer.autoClear;
  31856. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  31857. const previousClearAlpha = renderer.getClearAlpha();
  31858. renderer.autoClear = false;
  31859. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  31860. // Render each cube face
  31861. for ( let face = 0; face < 6; face ++ ) {
  31862. // Set render target to the specific cube face
  31863. renderer.setRenderTarget( shadowMap, face );
  31864. renderer.clear();
  31865. // Update shadow camera matrices for this face
  31866. const far = light.distance || camera.far;
  31867. if ( far !== camera.far ) {
  31868. camera.far = far;
  31869. camera.updateProjectionMatrix();
  31870. }
  31871. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  31872. camera.position.copy( _lightPositionWorld );
  31873. _lookTarget.copy( camera.position );
  31874. _lookTarget.add( cubeDirections[ face ] );
  31875. camera.up.copy( cubeUps[ face ] );
  31876. camera.lookAt( _lookTarget );
  31877. camera.updateMatrixWorld();
  31878. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  31879. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  31880. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix$1, camera.coordinateSystem, camera.reversedDepth );
  31881. //
  31882. const currentSceneName = scene.name;
  31883. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ face + 1 }`;
  31884. renderer.render( scene, camera );
  31885. scene.name = currentSceneName;
  31886. }
  31887. //
  31888. renderer.autoClear = previousAutoClear;
  31889. renderer.setClearColor( previousClearColor, previousClearAlpha );
  31890. }
  31891. }
  31892. /**
  31893. * TSL function for creating an instance of `PointShadowNode`.
  31894. *
  31895. * @tsl
  31896. * @function
  31897. * @param {PointLight} light - The shadow casting point light.
  31898. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  31899. * @return {PointShadowNode} The created point shadow node.
  31900. */
  31901. const pointShadow = ( light, shadow ) => new PointShadowNode( light, shadow );
  31902. /**
  31903. * Base class for analytic light nodes.
  31904. *
  31905. * @augments LightingNode
  31906. */
  31907. class AnalyticLightNode extends LightingNode {
  31908. static get type() {
  31909. return 'AnalyticLightNode';
  31910. }
  31911. /**
  31912. * Constructs a new analytic light node.
  31913. *
  31914. * @param {?Light} [light=null] - The light source.
  31915. */
  31916. constructor( light = null ) {
  31917. super();
  31918. /**
  31919. * The light source.
  31920. *
  31921. * @type {?Light}
  31922. * @default null
  31923. */
  31924. this.light = light;
  31925. /**
  31926. * The light's color value.
  31927. *
  31928. * @type {Color}
  31929. */
  31930. this.color = new Color();
  31931. /**
  31932. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  31933. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  31934. *
  31935. * @type {Node}
  31936. */
  31937. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  31938. /**
  31939. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  31940. * The final color node is represented by a different node when using shadows.
  31941. *
  31942. * @type {?Node}
  31943. * @default null
  31944. */
  31945. this.baseColorNode = null;
  31946. /**
  31947. * Represents the light's shadow.
  31948. *
  31949. * @type {?ShadowNode}
  31950. * @default null
  31951. */
  31952. this.shadowNode = null;
  31953. /**
  31954. * Represents the light's shadow color.
  31955. *
  31956. * @type {?Node}
  31957. * @default null
  31958. */
  31959. this.shadowColorNode = null;
  31960. /**
  31961. * This flag can be used for type testing.
  31962. *
  31963. * @type {boolean}
  31964. * @readonly
  31965. * @default true
  31966. */
  31967. this.isAnalyticLightNode = true;
  31968. /**
  31969. * Overwritten since analytic light nodes are updated
  31970. * once per frame.
  31971. *
  31972. * @type {string}
  31973. * @default 'frame'
  31974. */
  31975. this.updateType = NodeUpdateType.FRAME;
  31976. if ( light && light.shadow ) {
  31977. this._shadowDisposeListener = () => {
  31978. this.disposeShadow();
  31979. };
  31980. light.addEventListener( 'dispose', this._shadowDisposeListener );
  31981. }
  31982. }
  31983. dispose() {
  31984. if ( this._shadowDisposeListener ) {
  31985. this.light.removeEventListener( 'dispose', this._shadowDisposeListener );
  31986. }
  31987. super.dispose();
  31988. }
  31989. /**
  31990. * Frees internal resources related to shadows.
  31991. */
  31992. disposeShadow() {
  31993. if ( this.shadowNode !== null ) {
  31994. this.shadowNode.dispose();
  31995. this.shadowNode = null;
  31996. }
  31997. this.shadowColorNode = null;
  31998. if ( this.baseColorNode !== null ) {
  31999. this.colorNode = this.baseColorNode;
  32000. this.baseColorNode = null;
  32001. }
  32002. }
  32003. getHash() {
  32004. return this.light.uuid;
  32005. }
  32006. /**
  32007. * Returns a node representing a direction vector which points from the current
  32008. * position in view space to the light's position in view space.
  32009. *
  32010. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32011. * @return {Node<vec3>} The light vector node.
  32012. */
  32013. getLightVector( builder ) {
  32014. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  32015. }
  32016. /**
  32017. * Sets up the direct lighting for the analytic light node.
  32018. *
  32019. * @abstract
  32020. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32021. * @return {Object|undefined} The direct light data (color and direction).
  32022. */
  32023. setupDirect( /*builder*/ ) { }
  32024. /**
  32025. * Sets up the direct rect area lighting for the analytic light node.
  32026. *
  32027. * @abstract
  32028. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  32029. * @return {Object|undefined} The direct rect area light data.
  32030. */
  32031. setupDirectRectArea( /*builder*/ ) { }
  32032. /**
  32033. * Setups the shadow node for this light. The method exists so concrete light classes
  32034. * can setup different types of shadow nodes.
  32035. *
  32036. * @return {ShadowNode} The created shadow node.
  32037. */
  32038. setupShadowNode() {
  32039. return shadow( this.light );
  32040. }
  32041. /**
  32042. * Setups the shadow for this light. This method is only executed if the light
  32043. * cast shadows and the current build object receives shadows. It incorporates
  32044. * shadows into the lighting computation.
  32045. *
  32046. * @param {NodeBuilder} builder - The current node builder.
  32047. */
  32048. setupShadow( builder ) {
  32049. const { renderer } = builder;
  32050. if ( renderer.shadowMap.enabled === false ) return;
  32051. let shadowColorNode = this.shadowColorNode;
  32052. if ( shadowColorNode === null ) {
  32053. const customShadowNode = this.light.shadow.shadowNode;
  32054. let shadowNode;
  32055. if ( customShadowNode !== undefined ) {
  32056. shadowNode = nodeObject( customShadowNode );
  32057. } else {
  32058. shadowNode = this.setupShadowNode();
  32059. }
  32060. this.shadowNode = shadowNode;
  32061. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  32062. this.baseColorNode = this.colorNode;
  32063. }
  32064. //
  32065. if ( builder.context.getShadow ) {
  32066. shadowColorNode = builder.context.getShadow( this, builder );
  32067. }
  32068. this.colorNode = shadowColorNode;
  32069. }
  32070. /**
  32071. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  32072. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  32073. * invocate the respective interface methods.
  32074. *
  32075. * @param {NodeBuilder} builder - The current node builder.
  32076. */
  32077. setup( builder ) {
  32078. this.colorNode = this.baseColorNode || this.colorNode;
  32079. if ( this.light.castShadow ) {
  32080. if ( builder.object.receiveShadow ) {
  32081. this.setupShadow( builder );
  32082. }
  32083. } else if ( this.shadowNode !== null ) {
  32084. this.shadowNode.dispose();
  32085. this.shadowNode = null;
  32086. this.shadowColorNode = null;
  32087. }
  32088. const directLightData = this.setupDirect( builder );
  32089. const directRectAreaLightData = this.setupDirectRectArea( builder );
  32090. if ( directLightData ) {
  32091. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  32092. }
  32093. if ( directRectAreaLightData ) {
  32094. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  32095. }
  32096. }
  32097. /**
  32098. * The update method is used to update light uniforms per frame.
  32099. * Potentially overwritten in concrete light nodes to update light
  32100. * specific uniforms.
  32101. *
  32102. * @param {NodeFrame} frame - A reference to the current node frame.
  32103. */
  32104. update( /*frame*/ ) {
  32105. const { light } = this;
  32106. this.color.copy( light.color ).multiplyScalar( light.intensity );
  32107. }
  32108. }
  32109. /**
  32110. * Represents a `discard` shader operation in TSL.
  32111. *
  32112. * @method
  32113. * @param {Object} inputs - The input parameter object.
  32114. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  32115. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  32116. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  32117. * @return {Node<float>} The distance falloff.
  32118. */
  32119. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  32120. // based upon Frostbite 3 Moving to Physically-based Rendering
  32121. // page 32, equation 26: E[window1]
  32122. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32123. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32124. return cutoffDistance.greaterThan( 0 ).select(
  32125. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32126. distanceFalloff
  32127. );
  32128. } ); // validated
  32129. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  32130. const lightDirection = lightVector.normalize();
  32131. const lightDistance = lightVector.length();
  32132. const attenuation = getDistanceAttenuation( {
  32133. lightDistance,
  32134. cutoffDistance,
  32135. decayExponent
  32136. } );
  32137. const lightColor = color.mul( attenuation );
  32138. return { lightDirection, lightColor };
  32139. };
  32140. /**
  32141. * Module for representing point lights as nodes.
  32142. *
  32143. * @augments AnalyticLightNode
  32144. */
  32145. class PointLightNode extends AnalyticLightNode {
  32146. static get type() {
  32147. return 'PointLightNode';
  32148. }
  32149. /**
  32150. * Constructs a new point light node.
  32151. *
  32152. * @param {?PointLight} [light=null] - The point light source.
  32153. */
  32154. constructor( light = null ) {
  32155. super( light );
  32156. /**
  32157. * Uniform node representing the cutoff distance.
  32158. *
  32159. * @type {UniformNode<float>}
  32160. */
  32161. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32162. /**
  32163. * Uniform node representing the decay exponent.
  32164. *
  32165. * @type {UniformNode<float>}
  32166. */
  32167. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  32168. }
  32169. /**
  32170. * Overwritten to updated point light specific uniforms.
  32171. *
  32172. * @param {NodeFrame} frame - A reference to the current node frame.
  32173. */
  32174. update( frame ) {
  32175. const { light } = this;
  32176. super.update( frame );
  32177. this.cutoffDistanceNode.value = light.distance;
  32178. this.decayExponentNode.value = light.decay;
  32179. }
  32180. /**
  32181. * Overwritten to setup point light specific shadow.
  32182. *
  32183. * @return {PointShadowNode}
  32184. */
  32185. setupShadowNode() {
  32186. return pointShadow( this.light );
  32187. }
  32188. setupDirect( builder ) {
  32189. return directPointLight( {
  32190. color: this.colorNode,
  32191. lightVector: this.getLightVector( builder ),
  32192. cutoffDistance: this.cutoffDistanceNode,
  32193. decayExponent: this.decayExponentNode
  32194. } );
  32195. }
  32196. }
  32197. /**
  32198. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  32199. *
  32200. * @tsl
  32201. * @function
  32202. * @param {Node<vec2>} coord - The uv coordinates.
  32203. * @return {Node<float>} The result data.
  32204. */
  32205. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  32206. const uv = coord.mul( 2.0 );
  32207. const cx = uv.x.floor();
  32208. const cy = uv.y.floor();
  32209. const result = cx.add( cy ).mod( 2.0 );
  32210. return result.sign();
  32211. } );
  32212. /**
  32213. * Generates a circle based on the uv coordinates.
  32214. *
  32215. * @tsl
  32216. * @function
  32217. * @param {Node<vec2>} coord - The uv to generate the circle.
  32218. * @return {Node<float>} The circle shape.
  32219. */
  32220. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  32221. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  32222. let alpha;
  32223. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  32224. const dlen = float( len2.fwidth() ).toVar();
  32225. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  32226. } else {
  32227. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  32228. }
  32229. return alpha;
  32230. } );
  32231. // Three.js Transpiler
  32232. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  32233. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  32234. const f = float( f_immutable ).toVar();
  32235. const t = float( t_immutable ).toVar();
  32236. const b = bool( b_immutable ).toVar();
  32237. return select( b, t, f );
  32238. } ).setLayout( {
  32239. name: 'mx_select',
  32240. type: 'float',
  32241. inputs: [
  32242. { name: 'b', type: 'bool' },
  32243. { name: 't', type: 'float' },
  32244. { name: 'f', type: 'float' }
  32245. ]
  32246. } );
  32247. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  32248. const b = bool( b_immutable ).toVar();
  32249. const val = float( val_immutable ).toVar();
  32250. return select( b, val.negate(), val );
  32251. } ).setLayout( {
  32252. name: 'mx_negate_if',
  32253. type: 'float',
  32254. inputs: [
  32255. { name: 'val', type: 'float' },
  32256. { name: 'b', type: 'bool' }
  32257. ]
  32258. } );
  32259. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32260. const x = float( x_immutable ).toVar();
  32261. return int( floor( x ) );
  32262. } ).setLayout( {
  32263. name: 'mx_floor',
  32264. type: 'int',
  32265. inputs: [
  32266. { name: 'x', type: 'float' }
  32267. ]
  32268. } );
  32269. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  32270. const x = float( x_immutable ).toVar();
  32271. i.assign( mx_floor( x ) );
  32272. return x.sub( float( i ) );
  32273. } );
  32274. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32275. const t = float( t_immutable ).toVar();
  32276. const s = float( s_immutable ).toVar();
  32277. const v3 = float( v3_immutable ).toVar();
  32278. const v2 = float( v2_immutable ).toVar();
  32279. const v1 = float( v1_immutable ).toVar();
  32280. const v0 = float( v0_immutable ).toVar();
  32281. const s1 = float( sub( 1.0, s ) ).toVar();
  32282. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32283. } ).setLayout( {
  32284. name: 'mx_bilerp_0',
  32285. type: 'float',
  32286. inputs: [
  32287. { name: 'v0', type: 'float' },
  32288. { name: 'v1', type: 'float' },
  32289. { name: 'v2', type: 'float' },
  32290. { name: 'v3', type: 'float' },
  32291. { name: 's', type: 'float' },
  32292. { name: 't', type: 'float' }
  32293. ]
  32294. } );
  32295. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  32296. const t = float( t_immutable ).toVar();
  32297. const s = float( s_immutable ).toVar();
  32298. const v3 = vec3( v3_immutable ).toVar();
  32299. const v2 = vec3( v2_immutable ).toVar();
  32300. const v1 = vec3( v1_immutable ).toVar();
  32301. const v0 = vec3( v0_immutable ).toVar();
  32302. const s1 = float( sub( 1.0, s ) ).toVar();
  32303. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  32304. } ).setLayout( {
  32305. name: 'mx_bilerp_1',
  32306. type: 'vec3',
  32307. inputs: [
  32308. { name: 'v0', type: 'vec3' },
  32309. { name: 'v1', type: 'vec3' },
  32310. { name: 'v2', type: 'vec3' },
  32311. { name: 'v3', type: 'vec3' },
  32312. { name: 's', type: 'float' },
  32313. { name: 't', type: 'float' }
  32314. ]
  32315. } );
  32316. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  32317. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  32318. const r = float( r_immutable ).toVar();
  32319. const t = float( t_immutable ).toVar();
  32320. const s = float( s_immutable ).toVar();
  32321. const v7 = float( v7_immutable ).toVar();
  32322. const v6 = float( v6_immutable ).toVar();
  32323. const v5 = float( v5_immutable ).toVar();
  32324. const v4 = float( v4_immutable ).toVar();
  32325. const v3 = float( v3_immutable ).toVar();
  32326. const v2 = float( v2_immutable ).toVar();
  32327. const v1 = float( v1_immutable ).toVar();
  32328. const v0 = float( v0_immutable ).toVar();
  32329. const s1 = float( sub( 1.0, s ) ).toVar();
  32330. const t1 = float( sub( 1.0, t ) ).toVar();
  32331. const r1 = float( sub( 1.0, r ) ).toVar();
  32332. 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 ) ) ) ) ) );
  32333. } ).setLayout( {
  32334. name: 'mx_trilerp_0',
  32335. type: 'float',
  32336. inputs: [
  32337. { name: 'v0', type: 'float' },
  32338. { name: 'v1', type: 'float' },
  32339. { name: 'v2', type: 'float' },
  32340. { name: 'v3', type: 'float' },
  32341. { name: 'v4', type: 'float' },
  32342. { name: 'v5', type: 'float' },
  32343. { name: 'v6', type: 'float' },
  32344. { name: 'v7', type: 'float' },
  32345. { name: 's', type: 'float' },
  32346. { name: 't', type: 'float' },
  32347. { name: 'r', type: 'float' }
  32348. ]
  32349. } );
  32350. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  32351. const r = float( r_immutable ).toVar();
  32352. const t = float( t_immutable ).toVar();
  32353. const s = float( s_immutable ).toVar();
  32354. const v7 = vec3( v7_immutable ).toVar();
  32355. const v6 = vec3( v6_immutable ).toVar();
  32356. const v5 = vec3( v5_immutable ).toVar();
  32357. const v4 = vec3( v4_immutable ).toVar();
  32358. const v3 = vec3( v3_immutable ).toVar();
  32359. const v2 = vec3( v2_immutable ).toVar();
  32360. const v1 = vec3( v1_immutable ).toVar();
  32361. const v0 = vec3( v0_immutable ).toVar();
  32362. const s1 = float( sub( 1.0, s ) ).toVar();
  32363. const t1 = float( sub( 1.0, t ) ).toVar();
  32364. const r1 = float( sub( 1.0, r ) ).toVar();
  32365. 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 ) ) ) ) ) );
  32366. } ).setLayout( {
  32367. name: 'mx_trilerp_1',
  32368. type: 'vec3',
  32369. inputs: [
  32370. { name: 'v0', type: 'vec3' },
  32371. { name: 'v1', type: 'vec3' },
  32372. { name: 'v2', type: 'vec3' },
  32373. { name: 'v3', type: 'vec3' },
  32374. { name: 'v4', type: 'vec3' },
  32375. { name: 'v5', type: 'vec3' },
  32376. { name: 'v6', type: 'vec3' },
  32377. { name: 'v7', type: 'vec3' },
  32378. { name: 's', type: 'float' },
  32379. { name: 't', type: 'float' },
  32380. { name: 'r', type: 'float' }
  32381. ]
  32382. } );
  32383. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  32384. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32385. const y = float( y_immutable ).toVar();
  32386. const x = float( x_immutable ).toVar();
  32387. const hash = uint( hash_immutable ).toVar();
  32388. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  32389. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  32390. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  32391. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32392. } ).setLayout( {
  32393. name: 'mx_gradient_float_0',
  32394. type: 'float',
  32395. inputs: [
  32396. { name: 'hash', type: 'uint' },
  32397. { name: 'x', type: 'float' },
  32398. { name: 'y', type: 'float' }
  32399. ]
  32400. } );
  32401. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32402. const z = float( z_immutable ).toVar();
  32403. const y = float( y_immutable ).toVar();
  32404. const x = float( x_immutable ).toVar();
  32405. const hash = uint( hash_immutable ).toVar();
  32406. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  32407. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  32408. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  32409. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  32410. } ).setLayout( {
  32411. name: 'mx_gradient_float_1',
  32412. type: 'float',
  32413. inputs: [
  32414. { name: 'hash', type: 'uint' },
  32415. { name: 'x', type: 'float' },
  32416. { name: 'y', type: 'float' },
  32417. { name: 'z', type: 'float' }
  32418. ]
  32419. } );
  32420. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  32421. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  32422. const y = float( y_immutable ).toVar();
  32423. const x = float( x_immutable ).toVar();
  32424. const hash = uvec3( hash_immutable ).toVar();
  32425. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  32426. } ).setLayout( {
  32427. name: 'mx_gradient_vec3_0',
  32428. type: 'vec3',
  32429. inputs: [
  32430. { name: 'hash', type: 'uvec3' },
  32431. { name: 'x', type: 'float' },
  32432. { name: 'y', type: 'float' }
  32433. ]
  32434. } );
  32435. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  32436. const z = float( z_immutable ).toVar();
  32437. const y = float( y_immutable ).toVar();
  32438. const x = float( x_immutable ).toVar();
  32439. const hash = uvec3( hash_immutable ).toVar();
  32440. 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 ) );
  32441. } ).setLayout( {
  32442. name: 'mx_gradient_vec3_1',
  32443. type: 'vec3',
  32444. inputs: [
  32445. { name: 'hash', type: 'uvec3' },
  32446. { name: 'x', type: 'float' },
  32447. { name: 'y', type: 'float' },
  32448. { name: 'z', type: 'float' }
  32449. ]
  32450. } );
  32451. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  32452. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32453. const v = float( v_immutable ).toVar();
  32454. return mul( 0.6616, v );
  32455. } ).setLayout( {
  32456. name: 'mx_gradient_scale2d_0',
  32457. type: 'float',
  32458. inputs: [
  32459. { name: 'v', type: 'float' }
  32460. ]
  32461. } );
  32462. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32463. const v = float( v_immutable ).toVar();
  32464. return mul( 0.9820, v );
  32465. } ).setLayout( {
  32466. name: 'mx_gradient_scale3d_0',
  32467. type: 'float',
  32468. inputs: [
  32469. { name: 'v', type: 'float' }
  32470. ]
  32471. } );
  32472. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32473. const v = vec3( v_immutable ).toVar();
  32474. return mul( 0.6616, v );
  32475. } ).setLayout( {
  32476. name: 'mx_gradient_scale2d_1',
  32477. type: 'vec3',
  32478. inputs: [
  32479. { name: 'v', type: 'vec3' }
  32480. ]
  32481. } );
  32482. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  32483. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  32484. const v = vec3( v_immutable ).toVar();
  32485. return mul( 0.9820, v );
  32486. } ).setLayout( {
  32487. name: 'mx_gradient_scale3d_1',
  32488. type: 'vec3',
  32489. inputs: [
  32490. { name: 'v', type: 'vec3' }
  32491. ]
  32492. } );
  32493. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  32494. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  32495. const k = int( k_immutable ).toVar();
  32496. const x = uint( x_immutable ).toVar();
  32497. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  32498. } ).setLayout( {
  32499. name: 'mx_rotl32',
  32500. type: 'uint',
  32501. inputs: [
  32502. { name: 'x', type: 'uint' },
  32503. { name: 'k', type: 'int' }
  32504. ]
  32505. } );
  32506. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  32507. a.subAssign( c );
  32508. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  32509. c.addAssign( b );
  32510. b.subAssign( a );
  32511. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  32512. a.addAssign( c );
  32513. c.subAssign( b );
  32514. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  32515. b.addAssign( a );
  32516. a.subAssign( c );
  32517. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  32518. c.addAssign( b );
  32519. b.subAssign( a );
  32520. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  32521. a.addAssign( c );
  32522. c.subAssign( b );
  32523. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  32524. b.addAssign( a );
  32525. } );
  32526. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  32527. const c = uint( c_immutable ).toVar();
  32528. const b = uint( b_immutable ).toVar();
  32529. const a = uint( a_immutable ).toVar();
  32530. c.bitXorAssign( b );
  32531. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  32532. a.bitXorAssign( c );
  32533. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  32534. b.bitXorAssign( a );
  32535. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  32536. c.bitXorAssign( b );
  32537. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  32538. a.bitXorAssign( c );
  32539. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  32540. b.bitXorAssign( a );
  32541. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  32542. c.bitXorAssign( b );
  32543. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  32544. return c;
  32545. } ).setLayout( {
  32546. name: 'mx_bjfinal',
  32547. type: 'uint',
  32548. inputs: [
  32549. { name: 'a', type: 'uint' },
  32550. { name: 'b', type: 'uint' },
  32551. { name: 'c', type: 'uint' }
  32552. ]
  32553. } );
  32554. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  32555. const bits = uint( bits_immutable ).toVar();
  32556. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  32557. } ).setLayout( {
  32558. name: 'mx_bits_to_01',
  32559. type: 'float',
  32560. inputs: [
  32561. { name: 'bits', type: 'uint' }
  32562. ]
  32563. } );
  32564. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  32565. const t = float( t_immutable ).toVar();
  32566. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  32567. } ).setLayout( {
  32568. name: 'mx_fade',
  32569. type: 'float',
  32570. inputs: [
  32571. { name: 't', type: 'float' }
  32572. ]
  32573. } );
  32574. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32575. const x = int( x_immutable ).toVar();
  32576. const len = uint( uint( 1 ) ).toVar();
  32577. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  32578. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  32579. } ).setLayout( {
  32580. name: 'mx_hash_int_0',
  32581. type: 'uint',
  32582. inputs: [
  32583. { name: 'x', type: 'int' }
  32584. ]
  32585. } );
  32586. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32587. const y = int( y_immutable ).toVar();
  32588. const x = int( x_immutable ).toVar();
  32589. const len = uint( uint( 2 ) ).toVar();
  32590. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32591. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32592. a.addAssign( uint( x ) );
  32593. b.addAssign( uint( y ) );
  32594. return mx_bjfinal( a, b, c );
  32595. } ).setLayout( {
  32596. name: 'mx_hash_int_1',
  32597. type: 'uint',
  32598. inputs: [
  32599. { name: 'x', type: 'int' },
  32600. { name: 'y', type: 'int' }
  32601. ]
  32602. } );
  32603. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32604. const z = int( z_immutable ).toVar();
  32605. const y = int( y_immutable ).toVar();
  32606. const x = int( x_immutable ).toVar();
  32607. const len = uint( uint( 3 ) ).toVar();
  32608. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32609. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32610. a.addAssign( uint( x ) );
  32611. b.addAssign( uint( y ) );
  32612. c.addAssign( uint( z ) );
  32613. return mx_bjfinal( a, b, c );
  32614. } ).setLayout( {
  32615. name: 'mx_hash_int_2',
  32616. type: 'uint',
  32617. inputs: [
  32618. { name: 'x', type: 'int' },
  32619. { name: 'y', type: 'int' },
  32620. { name: 'z', type: 'int' }
  32621. ]
  32622. } );
  32623. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  32624. const xx = int( xx_immutable ).toVar();
  32625. const z = int( z_immutable ).toVar();
  32626. const y = int( y_immutable ).toVar();
  32627. const x = int( x_immutable ).toVar();
  32628. const len = uint( uint( 4 ) ).toVar();
  32629. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32630. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32631. a.addAssign( uint( x ) );
  32632. b.addAssign( uint( y ) );
  32633. c.addAssign( uint( z ) );
  32634. mx_bjmix( a, b, c );
  32635. a.addAssign( uint( xx ) );
  32636. return mx_bjfinal( a, b, c );
  32637. } ).setLayout( {
  32638. name: 'mx_hash_int_3',
  32639. type: 'uint',
  32640. inputs: [
  32641. { name: 'x', type: 'int' },
  32642. { name: 'y', type: 'int' },
  32643. { name: 'z', type: 'int' },
  32644. { name: 'xx', type: 'int' }
  32645. ]
  32646. } );
  32647. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  32648. const yy = int( yy_immutable ).toVar();
  32649. const xx = int( xx_immutable ).toVar();
  32650. const z = int( z_immutable ).toVar();
  32651. const y = int( y_immutable ).toVar();
  32652. const x = int( x_immutable ).toVar();
  32653. const len = uint( uint( 5 ) ).toVar();
  32654. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  32655. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  32656. a.addAssign( uint( x ) );
  32657. b.addAssign( uint( y ) );
  32658. c.addAssign( uint( z ) );
  32659. mx_bjmix( a, b, c );
  32660. a.addAssign( uint( xx ) );
  32661. b.addAssign( uint( yy ) );
  32662. return mx_bjfinal( a, b, c );
  32663. } ).setLayout( {
  32664. name: 'mx_hash_int_4',
  32665. type: 'uint',
  32666. inputs: [
  32667. { name: 'x', type: 'int' },
  32668. { name: 'y', type: 'int' },
  32669. { name: 'z', type: 'int' },
  32670. { name: 'xx', type: 'int' },
  32671. { name: 'yy', type: 'int' }
  32672. ]
  32673. } );
  32674. 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 ] );
  32675. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  32676. const y = int( y_immutable ).toVar();
  32677. const x = int( x_immutable ).toVar();
  32678. const h = uint( mx_hash_int( x, y ) ).toVar();
  32679. const result = uvec3().toVar();
  32680. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32681. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32682. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32683. return result;
  32684. } ).setLayout( {
  32685. name: 'mx_hash_vec3_0',
  32686. type: 'uvec3',
  32687. inputs: [
  32688. { name: 'x', type: 'int' },
  32689. { name: 'y', type: 'int' }
  32690. ]
  32691. } );
  32692. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  32693. const z = int( z_immutable ).toVar();
  32694. const y = int( y_immutable ).toVar();
  32695. const x = int( x_immutable ).toVar();
  32696. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  32697. const result = uvec3().toVar();
  32698. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  32699. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  32700. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  32701. return result;
  32702. } ).setLayout( {
  32703. name: 'mx_hash_vec3_1',
  32704. type: 'uvec3',
  32705. inputs: [
  32706. { name: 'x', type: 'int' },
  32707. { name: 'y', type: 'int' },
  32708. { name: 'z', type: 'int' }
  32709. ]
  32710. } );
  32711. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  32712. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32713. const p = vec2( p_immutable ).toVar();
  32714. const X = int().toVar(), Y = int().toVar();
  32715. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32716. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32717. const u = float( mx_fade( fx ) ).toVar();
  32718. const v = float( mx_fade( fy ) ).toVar();
  32719. 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();
  32720. return mx_gradient_scale2d( result );
  32721. } ).setLayout( {
  32722. name: 'mx_perlin_noise_float_0',
  32723. type: 'float',
  32724. inputs: [
  32725. { name: 'p', type: 'vec2' }
  32726. ]
  32727. } );
  32728. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32729. const p = vec3( p_immutable ).toVar();
  32730. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32731. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32732. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32733. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32734. const u = float( mx_fade( fx ) ).toVar();
  32735. const v = float( mx_fade( fy ) ).toVar();
  32736. const w = float( mx_fade( fz ) ).toVar();
  32737. 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();
  32738. return mx_gradient_scale3d( result );
  32739. } ).setLayout( {
  32740. name: 'mx_perlin_noise_float_1',
  32741. type: 'float',
  32742. inputs: [
  32743. { name: 'p', type: 'vec3' }
  32744. ]
  32745. } );
  32746. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  32747. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32748. const p = vec2( p_immutable ).toVar();
  32749. const X = int().toVar(), Y = int().toVar();
  32750. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32751. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32752. const u = float( mx_fade( fx ) ).toVar();
  32753. const v = float( mx_fade( fy ) ).toVar();
  32754. 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();
  32755. return mx_gradient_scale2d( result );
  32756. } ).setLayout( {
  32757. name: 'mx_perlin_noise_vec3_0',
  32758. type: 'vec3',
  32759. inputs: [
  32760. { name: 'p', type: 'vec2' }
  32761. ]
  32762. } );
  32763. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32764. const p = vec3( p_immutable ).toVar();
  32765. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  32766. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  32767. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  32768. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  32769. const u = float( mx_fade( fx ) ).toVar();
  32770. const v = float( mx_fade( fy ) ).toVar();
  32771. const w = float( mx_fade( fz ) ).toVar();
  32772. 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();
  32773. return mx_gradient_scale3d( result );
  32774. } ).setLayout( {
  32775. name: 'mx_perlin_noise_vec3_1',
  32776. type: 'vec3',
  32777. inputs: [
  32778. { name: 'p', type: 'vec3' }
  32779. ]
  32780. } );
  32781. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  32782. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32783. const p = float( p_immutable ).toVar();
  32784. const ix = int( mx_floor( p ) ).toVar();
  32785. return mx_bits_to_01( mx_hash_int( ix ) );
  32786. } ).setLayout( {
  32787. name: 'mx_cell_noise_float_0',
  32788. type: 'float',
  32789. inputs: [
  32790. { name: 'p', type: 'float' }
  32791. ]
  32792. } );
  32793. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32794. const p = vec2( p_immutable ).toVar();
  32795. const ix = int( mx_floor( p.x ) ).toVar();
  32796. const iy = int( mx_floor( p.y ) ).toVar();
  32797. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  32798. } ).setLayout( {
  32799. name: 'mx_cell_noise_float_1',
  32800. type: 'float',
  32801. inputs: [
  32802. { name: 'p', type: 'vec2' }
  32803. ]
  32804. } );
  32805. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32806. const p = vec3( p_immutable ).toVar();
  32807. const ix = int( mx_floor( p.x ) ).toVar();
  32808. const iy = int( mx_floor( p.y ) ).toVar();
  32809. const iz = int( mx_floor( p.z ) ).toVar();
  32810. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  32811. } ).setLayout( {
  32812. name: 'mx_cell_noise_float_2',
  32813. type: 'float',
  32814. inputs: [
  32815. { name: 'p', type: 'vec3' }
  32816. ]
  32817. } );
  32818. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32819. const p = vec4( p_immutable ).toVar();
  32820. const ix = int( mx_floor( p.x ) ).toVar();
  32821. const iy = int( mx_floor( p.y ) ).toVar();
  32822. const iz = int( mx_floor( p.z ) ).toVar();
  32823. const iw = int( mx_floor( p.w ) ).toVar();
  32824. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  32825. } ).setLayout( {
  32826. name: 'mx_cell_noise_float_3',
  32827. type: 'float',
  32828. inputs: [
  32829. { name: 'p', type: 'vec4' }
  32830. ]
  32831. } );
  32832. 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 ] );
  32833. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32834. const p = float( p_immutable ).toVar();
  32835. const ix = int( mx_floor( p ) ).toVar();
  32836. 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 ) ) ) );
  32837. } ).setLayout( {
  32838. name: 'mx_cell_noise_vec3_0',
  32839. type: 'vec3',
  32840. inputs: [
  32841. { name: 'p', type: 'float' }
  32842. ]
  32843. } );
  32844. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32845. const p = vec2( p_immutable ).toVar();
  32846. const ix = int( mx_floor( p.x ) ).toVar();
  32847. const iy = int( mx_floor( p.y ) ).toVar();
  32848. 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 ) ) ) );
  32849. } ).setLayout( {
  32850. name: 'mx_cell_noise_vec3_1',
  32851. type: 'vec3',
  32852. inputs: [
  32853. { name: 'p', type: 'vec2' }
  32854. ]
  32855. } );
  32856. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32857. const p = vec3( p_immutable ).toVar();
  32858. const ix = int( mx_floor( p.x ) ).toVar();
  32859. const iy = int( mx_floor( p.y ) ).toVar();
  32860. const iz = int( mx_floor( p.z ) ).toVar();
  32861. 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 ) ) ) );
  32862. } ).setLayout( {
  32863. name: 'mx_cell_noise_vec3_2',
  32864. type: 'vec3',
  32865. inputs: [
  32866. { name: 'p', type: 'vec3' }
  32867. ]
  32868. } );
  32869. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  32870. const p = vec4( p_immutable ).toVar();
  32871. const ix = int( mx_floor( p.x ) ).toVar();
  32872. const iy = int( mx_floor( p.y ) ).toVar();
  32873. const iz = int( mx_floor( p.z ) ).toVar();
  32874. const iw = int( mx_floor( p.w ) ).toVar();
  32875. 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 ) ) ) );
  32876. } ).setLayout( {
  32877. name: 'mx_cell_noise_vec3_3',
  32878. type: 'vec3',
  32879. inputs: [
  32880. { name: 'p', type: 'vec4' }
  32881. ]
  32882. } );
  32883. 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 ] );
  32884. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32885. const diminish = float( diminish_immutable ).toVar();
  32886. const lacunarity = float( lacunarity_immutable ).toVar();
  32887. const octaves = int( octaves_immutable ).toVar();
  32888. const p = vec3( p_immutable ).toVar();
  32889. const result = float( 0.0 ).toVar();
  32890. const amplitude = float( 1.0 ).toVar();
  32891. Loop( octaves, () => {
  32892. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  32893. amplitude.mulAssign( diminish );
  32894. p.mulAssign( lacunarity );
  32895. } );
  32896. return result;
  32897. } ).setLayout( {
  32898. name: 'mx_fractal_noise_float',
  32899. type: 'float',
  32900. inputs: [
  32901. { name: 'p', type: 'vec3' },
  32902. { name: 'octaves', type: 'int' },
  32903. { name: 'lacunarity', type: 'float' },
  32904. { name: 'diminish', type: 'float' }
  32905. ]
  32906. } );
  32907. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32908. const diminish = float( diminish_immutable ).toVar();
  32909. const lacunarity = float( lacunarity_immutable ).toVar();
  32910. const octaves = int( octaves_immutable ).toVar();
  32911. const p = vec3( p_immutable ).toVar();
  32912. const result = vec3( 0.0 ).toVar();
  32913. const amplitude = float( 1.0 ).toVar();
  32914. Loop( octaves, () => {
  32915. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  32916. amplitude.mulAssign( diminish );
  32917. p.mulAssign( lacunarity );
  32918. } );
  32919. return result;
  32920. } ).setLayout( {
  32921. name: 'mx_fractal_noise_vec3',
  32922. type: 'vec3',
  32923. inputs: [
  32924. { name: 'p', type: 'vec3' },
  32925. { name: 'octaves', type: 'int' },
  32926. { name: 'lacunarity', type: 'float' },
  32927. { name: 'diminish', type: 'float' }
  32928. ]
  32929. } );
  32930. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32931. const diminish = float( diminish_immutable ).toVar();
  32932. const lacunarity = float( lacunarity_immutable ).toVar();
  32933. const octaves = int( octaves_immutable ).toVar();
  32934. const p = vec3( p_immutable ).toVar();
  32935. 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 ) );
  32936. } ).setLayout( {
  32937. name: 'mx_fractal_noise_vec2',
  32938. type: 'vec2',
  32939. inputs: [
  32940. { name: 'p', type: 'vec3' },
  32941. { name: 'octaves', type: 'int' },
  32942. { name: 'lacunarity', type: 'float' },
  32943. { name: 'diminish', type: 'float' }
  32944. ]
  32945. } );
  32946. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  32947. const diminish = float( diminish_immutable ).toVar();
  32948. const lacunarity = float( lacunarity_immutable ).toVar();
  32949. const octaves = int( octaves_immutable ).toVar();
  32950. const p = vec3( p_immutable ).toVar();
  32951. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  32952. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  32953. return vec4( c, f );
  32954. } ).setLayout( {
  32955. name: 'mx_fractal_noise_vec4',
  32956. type: 'vec4',
  32957. inputs: [
  32958. { name: 'p', type: 'vec3' },
  32959. { name: 'octaves', type: 'int' },
  32960. { name: 'lacunarity', type: 'float' },
  32961. { name: 'diminish', type: 'float' }
  32962. ]
  32963. } );
  32964. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  32965. const metric = int( metric_immutable ).toVar();
  32966. const jitter = float( jitter_immutable ).toVar();
  32967. const yoff = int( yoff_immutable ).toVar();
  32968. const xoff = int( xoff_immutable ).toVar();
  32969. const y = int( y_immutable ).toVar();
  32970. const x = int( x_immutable ).toVar();
  32971. const p = vec2( p_immutable ).toVar();
  32972. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  32973. const off = vec2( tmp.x, tmp.y ).toVar();
  32974. off.subAssign( 0.5 );
  32975. off.mulAssign( jitter );
  32976. off.addAssign( 0.5 );
  32977. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  32978. const diff = vec2( cellpos.sub( p ) ).toVar();
  32979. If( metric.equal( int( 2 ) ), () => {
  32980. return abs( diff.x ).add( abs( diff.y ) );
  32981. } );
  32982. If( metric.equal( int( 3 ) ), () => {
  32983. return max$1( abs( diff.x ), abs( diff.y ) );
  32984. } );
  32985. return dot( diff, diff );
  32986. } ).setLayout( {
  32987. name: 'mx_worley_distance_0',
  32988. type: 'float',
  32989. inputs: [
  32990. { name: 'p', type: 'vec2' },
  32991. { name: 'x', type: 'int' },
  32992. { name: 'y', type: 'int' },
  32993. { name: 'xoff', type: 'int' },
  32994. { name: 'yoff', type: 'int' },
  32995. { name: 'jitter', type: 'float' },
  32996. { name: 'metric', type: 'int' }
  32997. ]
  32998. } );
  32999. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  33000. const metric = int( metric_immutable ).toVar();
  33001. const jitter = float( jitter_immutable ).toVar();
  33002. const zoff = int( zoff_immutable ).toVar();
  33003. const yoff = int( yoff_immutable ).toVar();
  33004. const xoff = int( xoff_immutable ).toVar();
  33005. const z = int( z_immutable ).toVar();
  33006. const y = int( y_immutable ).toVar();
  33007. const x = int( x_immutable ).toVar();
  33008. const p = vec3( p_immutable ).toVar();
  33009. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  33010. off.subAssign( 0.5 );
  33011. off.mulAssign( jitter );
  33012. off.addAssign( 0.5 );
  33013. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  33014. const diff = vec3( cellpos.sub( p ) ).toVar();
  33015. If( metric.equal( int( 2 ) ), () => {
  33016. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  33017. } );
  33018. If( metric.equal( int( 3 ) ), () => {
  33019. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  33020. } );
  33021. return dot( diff, diff );
  33022. } ).setLayout( {
  33023. name: 'mx_worley_distance_1',
  33024. type: 'float',
  33025. inputs: [
  33026. { name: 'p', type: 'vec3' },
  33027. { name: 'x', type: 'int' },
  33028. { name: 'y', type: 'int' },
  33029. { name: 'z', type: 'int' },
  33030. { name: 'xoff', type: 'int' },
  33031. { name: 'yoff', type: 'int' },
  33032. { name: 'zoff', type: 'int' },
  33033. { name: 'jitter', type: 'float' },
  33034. { name: 'metric', type: 'int' }
  33035. ]
  33036. } );
  33037. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  33038. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33039. const metric = int( metric_immutable ).toVar();
  33040. const jitter = float( jitter_immutable ).toVar();
  33041. const p = vec2( p_immutable ).toVar();
  33042. const X = int().toVar(), Y = int().toVar();
  33043. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33044. const sqdist = float( 1e6 ).toVar();
  33045. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33046. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33047. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33048. sqdist.assign( min$1( sqdist, dist ) );
  33049. } );
  33050. } );
  33051. If( metric.equal( int( 0 ) ), () => {
  33052. sqdist.assign( sqrt( sqdist ) );
  33053. } );
  33054. return sqdist;
  33055. } ).setLayout( {
  33056. name: 'mx_worley_noise_float_0',
  33057. type: 'float',
  33058. inputs: [
  33059. { name: 'p', type: 'vec2' },
  33060. { name: 'jitter', type: 'float' },
  33061. { name: 'metric', type: 'int' }
  33062. ]
  33063. } );
  33064. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33065. const metric = int( metric_immutable ).toVar();
  33066. const jitter = float( jitter_immutable ).toVar();
  33067. const p = vec2( p_immutable ).toVar();
  33068. const X = int().toVar(), Y = int().toVar();
  33069. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33070. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33071. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33072. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33073. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33074. If( dist.lessThan( sqdist.x ), () => {
  33075. sqdist.y.assign( sqdist.x );
  33076. sqdist.x.assign( dist );
  33077. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33078. sqdist.y.assign( dist );
  33079. } );
  33080. } );
  33081. } );
  33082. If( metric.equal( int( 0 ) ), () => {
  33083. sqdist.assign( sqrt( sqdist ) );
  33084. } );
  33085. return sqdist;
  33086. } ).setLayout( {
  33087. name: 'mx_worley_noise_vec2_0',
  33088. type: 'vec2',
  33089. inputs: [
  33090. { name: 'p', type: 'vec2' },
  33091. { name: 'jitter', type: 'float' },
  33092. { name: 'metric', type: 'int' }
  33093. ]
  33094. } );
  33095. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33096. const metric = int( metric_immutable ).toVar();
  33097. const jitter = float( jitter_immutable ).toVar();
  33098. const p = vec2( p_immutable ).toVar();
  33099. const X = int().toVar(), Y = int().toVar();
  33100. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  33101. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33102. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33103. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33104. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  33105. If( dist.lessThan( sqdist.x ), () => {
  33106. sqdist.z.assign( sqdist.y );
  33107. sqdist.y.assign( sqdist.x );
  33108. sqdist.x.assign( dist );
  33109. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33110. sqdist.z.assign( sqdist.y );
  33111. sqdist.y.assign( dist );
  33112. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33113. sqdist.z.assign( dist );
  33114. } );
  33115. } );
  33116. } );
  33117. If( metric.equal( int( 0 ) ), () => {
  33118. sqdist.assign( sqrt( sqdist ) );
  33119. } );
  33120. return sqdist;
  33121. } ).setLayout( {
  33122. name: 'mx_worley_noise_vec3_0',
  33123. type: 'vec3',
  33124. inputs: [
  33125. { name: 'p', type: 'vec2' },
  33126. { name: 'jitter', type: 'float' },
  33127. { name: 'metric', type: 'int' }
  33128. ]
  33129. } );
  33130. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33131. const metric = int( metric_immutable ).toVar();
  33132. const jitter = float( jitter_immutable ).toVar();
  33133. const p = vec3( p_immutable ).toVar();
  33134. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33135. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33136. const sqdist = float( 1e6 ).toVar();
  33137. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33138. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33139. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33140. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33141. sqdist.assign( min$1( sqdist, dist ) );
  33142. } );
  33143. } );
  33144. } );
  33145. If( metric.equal( int( 0 ) ), () => {
  33146. sqdist.assign( sqrt( sqdist ) );
  33147. } );
  33148. return sqdist;
  33149. } ).setLayout( {
  33150. name: 'mx_worley_noise_float_1',
  33151. type: 'float',
  33152. inputs: [
  33153. { name: 'p', type: 'vec3' },
  33154. { name: 'jitter', type: 'float' },
  33155. { name: 'metric', type: 'int' }
  33156. ]
  33157. } );
  33158. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  33159. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33160. const metric = int( metric_immutable ).toVar();
  33161. const jitter = float( jitter_immutable ).toVar();
  33162. const p = vec3( p_immutable ).toVar();
  33163. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33164. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33165. const sqdist = vec2( 1e6, 1e6 ).toVar();
  33166. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33167. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33168. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33169. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33170. If( dist.lessThan( sqdist.x ), () => {
  33171. sqdist.y.assign( sqdist.x );
  33172. sqdist.x.assign( dist );
  33173. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33174. sqdist.y.assign( dist );
  33175. } );
  33176. } );
  33177. } );
  33178. } );
  33179. If( metric.equal( int( 0 ) ), () => {
  33180. sqdist.assign( sqrt( sqdist ) );
  33181. } );
  33182. return sqdist;
  33183. } ).setLayout( {
  33184. name: 'mx_worley_noise_vec2_1',
  33185. type: 'vec2',
  33186. inputs: [
  33187. { name: 'p', type: 'vec3' },
  33188. { name: 'jitter', type: 'float' },
  33189. { name: 'metric', type: 'int' }
  33190. ]
  33191. } );
  33192. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  33193. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  33194. const metric = int( metric_immutable ).toVar();
  33195. const jitter = float( jitter_immutable ).toVar();
  33196. const p = vec3( p_immutable ).toVar();
  33197. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  33198. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  33199. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  33200. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  33201. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  33202. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  33203. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  33204. If( dist.lessThan( sqdist.x ), () => {
  33205. sqdist.z.assign( sqdist.y );
  33206. sqdist.y.assign( sqdist.x );
  33207. sqdist.x.assign( dist );
  33208. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  33209. sqdist.z.assign( sqdist.y );
  33210. sqdist.y.assign( dist );
  33211. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  33212. sqdist.z.assign( dist );
  33213. } );
  33214. } );
  33215. } );
  33216. } );
  33217. If( metric.equal( int( 0 ) ), () => {
  33218. sqdist.assign( sqrt( sqdist ) );
  33219. } );
  33220. return sqdist;
  33221. } ).setLayout( {
  33222. name: 'mx_worley_noise_vec3_1',
  33223. type: 'vec3',
  33224. inputs: [
  33225. { name: 'p', type: 'vec3' },
  33226. { name: 'jitter', type: 'float' },
  33227. { name: 'metric', type: 'int' }
  33228. ]
  33229. } );
  33230. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  33231. // Unified Noise 2D
  33232. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  33233. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  33234. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33235. octaves_immutable, lacunarity_immutable, diminish_immutable
  33236. ] ) => {
  33237. const noiseType = int( noiseType_immutable ).toVar();
  33238. const texcoord = vec2( texcoord_immutable ).toVar();
  33239. const freq = vec2( freq_immutable ).toVar();
  33240. const offset = vec2( offset_immutable ).toVar();
  33241. const jitter = float( jitter_immutable ).toVar();
  33242. const outmin = float( outmin_immutable ).toVar();
  33243. const outmax = float( outmax_immutable ).toVar();
  33244. const clampoutput = bool( clampoutput_immutable ).toVar();
  33245. const octaves = int( octaves_immutable ).toVar();
  33246. const lacunarity = float( lacunarity_immutable ).toVar();
  33247. const diminish = float( diminish_immutable ).toVar();
  33248. // Compute input position
  33249. const p = texcoord.mul( freq ).add( offset );
  33250. const result = float( 0.0 ).toVar();
  33251. // Perlin
  33252. If( noiseType.equal( int( 0 ) ), () => {
  33253. result.assign( mx_perlin_noise_vec3( p ) );
  33254. } );
  33255. // Cell
  33256. If( noiseType.equal( int( 1 ) ), () => {
  33257. result.assign( mx_cell_noise_vec3( p ) );
  33258. } );
  33259. // Worley (metric=0 = euclidean)
  33260. If( noiseType.equal( int( 2 ) ), () => {
  33261. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33262. } );
  33263. // Fractal (use vec3(p, 0.0) for 2D input)
  33264. If( noiseType.equal( int( 3 ) ), () => {
  33265. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  33266. } );
  33267. // Remap output to [outmin, outmax]
  33268. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33269. // Clamp if requested
  33270. If( clampoutput, () => {
  33271. result.assign( clamp( result, outmin, outmax ) );
  33272. } );
  33273. return result;
  33274. } ).setLayout( {
  33275. name: 'mx_unifiednoise2d',
  33276. type: 'float',
  33277. inputs: [
  33278. { name: 'noiseType', type: 'int' },
  33279. { name: 'texcoord', type: 'vec2' },
  33280. { name: 'freq', type: 'vec2' },
  33281. { name: 'offset', type: 'vec2' },
  33282. { name: 'jitter', type: 'float' },
  33283. { name: 'outmin', type: 'float' },
  33284. { name: 'outmax', type: 'float' },
  33285. { name: 'clampoutput', type: 'bool' },
  33286. { name: 'octaves', type: 'int' },
  33287. { name: 'lacunarity', type: 'float' },
  33288. { name: 'diminish', type: 'float' }
  33289. ]
  33290. } );
  33291. // Unified Noise 3D
  33292. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  33293. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  33294. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  33295. octaves_immutable, lacunarity_immutable, diminish_immutable
  33296. ] ) => {
  33297. const noiseType = int( noiseType_immutable ).toVar();
  33298. const position = vec3( position_immutable ).toVar();
  33299. const freq = vec3( freq_immutable ).toVar();
  33300. const offset = vec3( offset_immutable ).toVar();
  33301. const jitter = float( jitter_immutable ).toVar();
  33302. const outmin = float( outmin_immutable ).toVar();
  33303. const outmax = float( outmax_immutable ).toVar();
  33304. const clampoutput = bool( clampoutput_immutable ).toVar();
  33305. const octaves = int( octaves_immutable ).toVar();
  33306. const lacunarity = float( lacunarity_immutable ).toVar();
  33307. const diminish = float( diminish_immutable ).toVar();
  33308. // Compute input position
  33309. const p = position.mul( freq ).add( offset );
  33310. const result = float( 0.0 ).toVar();
  33311. // Perlin
  33312. If( noiseType.equal( int( 0 ) ), () => {
  33313. result.assign( mx_perlin_noise_vec3( p ) );
  33314. } );
  33315. // Cell
  33316. If( noiseType.equal( int( 1 ) ), () => {
  33317. result.assign( mx_cell_noise_vec3( p ) );
  33318. } );
  33319. // Worley (metric=0 = euclidean)
  33320. If( noiseType.equal( int( 2 ) ), () => {
  33321. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  33322. } );
  33323. // Fractal
  33324. If( noiseType.equal( int( 3 ) ), () => {
  33325. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  33326. } );
  33327. // Remap output to [outmin, outmax]
  33328. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  33329. // Clamp if requested
  33330. If( clampoutput, () => {
  33331. result.assign( clamp( result, outmin, outmax ) );
  33332. } );
  33333. return result;
  33334. } ).setLayout( {
  33335. name: 'mx_unifiednoise3d',
  33336. type: 'float',
  33337. inputs: [
  33338. { name: 'noiseType', type: 'int' },
  33339. { name: 'position', type: 'vec3' },
  33340. { name: 'freq', type: 'vec3' },
  33341. { name: 'offset', type: 'vec3' },
  33342. { name: 'jitter', type: 'float' },
  33343. { name: 'outmin', type: 'float' },
  33344. { name: 'outmax', type: 'float' },
  33345. { name: 'clampoutput', type: 'bool' },
  33346. { name: 'octaves', type: 'int' },
  33347. { name: 'lacunarity', type: 'float' },
  33348. { name: 'diminish', type: 'float' }
  33349. ]
  33350. } );
  33351. // Three.js Transpiler
  33352. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  33353. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  33354. const s = hsv.y;
  33355. const v = hsv.z;
  33356. const result = vec3().toVar();
  33357. If( s.lessThan( 0.0001 ), () => {
  33358. result.assign( vec3( v, v, v ) );
  33359. } ).Else( () => {
  33360. let h = hsv.x;
  33361. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  33362. const hi = int( trunc( h ) );
  33363. const f = h.sub( float( hi ) );
  33364. const p = v.mul( s.oneMinus() );
  33365. const q = v.mul( s.mul( f ).oneMinus() );
  33366. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  33367. If( hi.equal( int( 0 ) ), () => {
  33368. result.assign( vec3( v, t, p ) );
  33369. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  33370. result.assign( vec3( q, v, p ) );
  33371. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  33372. result.assign( vec3( p, v, t ) );
  33373. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  33374. result.assign( vec3( p, q, v ) );
  33375. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  33376. result.assign( vec3( t, p, v ) );
  33377. } ).Else( () => {
  33378. result.assign( vec3( v, p, q ) );
  33379. } );
  33380. } );
  33381. return result;
  33382. } ).setLayout( {
  33383. name: 'mx_hsvtorgb',
  33384. type: 'vec3',
  33385. inputs: [
  33386. { name: 'hsv', type: 'vec3' }
  33387. ]
  33388. } );
  33389. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  33390. const c = vec3( c_immutable ).toVar();
  33391. const r = float( c.x ).toVar();
  33392. const g = float( c.y ).toVar();
  33393. const b = float( c.z ).toVar();
  33394. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  33395. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  33396. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  33397. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  33398. v.assign( maxcomp );
  33399. If( maxcomp.greaterThan( 0.0 ), () => {
  33400. s.assign( delta.div( maxcomp ) );
  33401. } ).Else( () => {
  33402. s.assign( 0.0 );
  33403. } );
  33404. If( s.lessThanEqual( 0.0 ), () => {
  33405. h.assign( 0.0 );
  33406. } ).Else( () => {
  33407. If( r.greaterThanEqual( maxcomp ), () => {
  33408. h.assign( g.sub( b ).div( delta ) );
  33409. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  33410. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  33411. } ).Else( () => {
  33412. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  33413. } );
  33414. h.mulAssign( 1.0 / 6.0 );
  33415. If( h.lessThan( 0.0 ), () => {
  33416. h.addAssign( 1.0 );
  33417. } );
  33418. } );
  33419. return vec3( h, s, v );
  33420. } ).setLayout( {
  33421. name: 'mx_rgbtohsv',
  33422. type: 'vec3',
  33423. inputs: [
  33424. { name: 'c', type: 'vec3' }
  33425. ]
  33426. } );
  33427. // Three.js Transpiler
  33428. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  33429. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  33430. const color = vec3( color_immutable ).toVar();
  33431. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  33432. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  33433. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  33434. return mix( linSeg, powSeg, isAbove );
  33435. } ).setLayout( {
  33436. name: 'mx_srgb_texture_to_lin_rec709',
  33437. type: 'vec3',
  33438. inputs: [
  33439. { name: 'color', type: 'vec3' }
  33440. ]
  33441. } );
  33442. const mx_aastep = ( threshold, value ) => {
  33443. threshold = float( threshold );
  33444. value = float( value );
  33445. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  33446. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  33447. };
  33448. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  33449. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  33450. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  33451. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  33452. const mx_ramp4 = (
  33453. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  33454. ) => {
  33455. const u = texcoord.x.clamp();
  33456. const v = texcoord.y.clamp();
  33457. const top = mix( valuetl, valuetr, u );
  33458. const bottom = mix( valuebl, valuebr, u );
  33459. return mix( top, bottom, v );
  33460. };
  33461. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  33462. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  33463. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  33464. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  33465. const mx_safepower = ( in1, in2 = 1 ) => {
  33466. in1 = float( in1 );
  33467. return in1.abs().pow( in2 ).mul( in1.sign() );
  33468. };
  33469. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  33470. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33471. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33472. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  33473. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  33474. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  33475. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  33476. return noise_vec4.mul( amplitude ).add( pivot );
  33477. };
  33478. const mx_unifiednoise2d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise2d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  33479. const mx_unifiednoise3d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise3d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  33480. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33481. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33482. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  33483. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  33484. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33485. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33486. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33487. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  33488. // === Moved from MaterialXLoader.js ===
  33489. // Math ops
  33490. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  33491. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  33492. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  33493. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  33494. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  33495. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  33496. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  33497. const mx_timer = () => time;
  33498. const mx_frame = () => frameId;
  33499. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  33500. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  33501. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  33502. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  33503. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  33504. const mx_separate = ( in1, channelOrOut = null ) => {
  33505. if ( typeof channelOrOut === 'string' ) {
  33506. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33507. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  33508. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  33509. }
  33510. if ( typeof channelOrOut === 'number' ) {
  33511. return in1.element( channelOrOut );
  33512. }
  33513. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  33514. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  33515. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  33516. }
  33517. return in1;
  33518. };
  33519. const mx_place2d = (
  33520. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  33521. ) => {
  33522. let uv = texcoord;
  33523. if ( pivot ) uv = uv.sub( pivot );
  33524. if ( scale ) uv = uv.mul( scale );
  33525. if ( rotate ) {
  33526. const rad = rotate.mul( Math.PI / 180.0 );
  33527. const cosR = rad.cos();
  33528. const sinR = rad.sin();
  33529. uv = vec2(
  33530. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  33531. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  33532. );
  33533. }
  33534. if ( pivot ) uv = uv.add( pivot );
  33535. if ( offset ) uv = uv.add( offset );
  33536. return uv;
  33537. };
  33538. const mx_rotate2d = ( input, amount ) => {
  33539. input = vec2( input );
  33540. amount = float( amount );
  33541. const radians = amount.mul( Math.PI / 180.0 );
  33542. return rotate( input, radians );
  33543. };
  33544. const mx_rotate3d = ( input, amount, axis ) => {
  33545. input = vec3( input );
  33546. amount = float( amount );
  33547. axis = vec3( axis );
  33548. const radians = amount.mul( Math.PI / 180.0 );
  33549. const nAxis = axis.normalize();
  33550. const cosA = radians.cos();
  33551. const sinA = radians.sin();
  33552. const oneMinusCosA = float( 1 ).sub( cosA );
  33553. const rot =
  33554. input.mul( cosA )
  33555. .add( nAxis.cross( input ).mul( sinA ) )
  33556. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  33557. return rot;
  33558. };
  33559. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  33560. input = vec3( input );
  33561. scale = float( scale );
  33562. return bumpMap( input, scale );
  33563. };
  33564. /**
  33565. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  33566. *
  33567. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  33568. *
  33569. * ```js
  33570. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  33571. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  33572. * ```
  33573. *
  33574. * @tsl
  33575. * @function
  33576. * @param {Node<vec3>} normal - The normal to correct.
  33577. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  33578. * @param {Node<vec3>} cubePos - The cube position.
  33579. * @return {Node<vec3>} The parallax corrected normal.
  33580. */
  33581. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  33582. const nDir = normalize( normal ).toVar();
  33583. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33584. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  33585. const rbminmax = vec3().toVar();
  33586. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  33587. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  33588. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  33589. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  33590. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  33591. return boxIntersection.sub( cubePos );
  33592. } );
  33593. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  33594. // normal is assumed to have unit length
  33595. const x = normal.x, y = normal.y, z = normal.z;
  33596. // band 0
  33597. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  33598. // band 1
  33599. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  33600. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  33601. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  33602. // band 2
  33603. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  33604. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  33605. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  33606. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  33607. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  33608. return result;
  33609. } );
  33610. // constants
  33611. var TSL = /*#__PURE__*/Object.freeze({
  33612. __proto__: null,
  33613. BRDF_GGX: BRDF_GGX,
  33614. BRDF_Lambert: BRDF_Lambert,
  33615. BasicPointShadowFilter: BasicPointShadowFilter,
  33616. BasicShadowFilter: BasicShadowFilter,
  33617. Break: Break,
  33618. Const: Const,
  33619. Continue: Continue,
  33620. DFGLUT: DFGLUT,
  33621. D_GGX: D_GGX,
  33622. Discard: Discard,
  33623. EPSILON: EPSILON,
  33624. F_Schlick: F_Schlick,
  33625. Fn: Fn,
  33626. HALF_PI: HALF_PI,
  33627. INFINITY: INFINITY,
  33628. If: If,
  33629. Loop: Loop,
  33630. NodeAccess: NodeAccess,
  33631. NodeShaderStage: NodeShaderStage,
  33632. NodeType: NodeType,
  33633. NodeUpdateType: NodeUpdateType,
  33634. OnBeforeMaterialUpdate: OnBeforeMaterialUpdate,
  33635. OnBeforeObjectUpdate: OnBeforeObjectUpdate,
  33636. OnMaterialUpdate: OnMaterialUpdate,
  33637. OnObjectUpdate: OnObjectUpdate,
  33638. PCFShadowFilter: PCFShadowFilter,
  33639. PCFSoftShadowFilter: PCFSoftShadowFilter,
  33640. PI: PI,
  33641. PI2: PI2,
  33642. PointShadowFilter: PointShadowFilter,
  33643. Return: Return,
  33644. Schlick_to_F0: Schlick_to_F0,
  33645. ScriptableNodeResources: ScriptableNodeResources,
  33646. ShaderNode: ShaderNode,
  33647. Stack: Stack,
  33648. Switch: Switch,
  33649. TBNViewMatrix: TBNViewMatrix,
  33650. TWO_PI: TWO_PI,
  33651. VSMShadowFilter: VSMShadowFilter,
  33652. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  33653. Var: Var,
  33654. VarIntent: VarIntent,
  33655. abs: abs,
  33656. acesFilmicToneMapping: acesFilmicToneMapping,
  33657. acos: acos,
  33658. add: add,
  33659. addMethodChaining: addMethodChaining,
  33660. addNodeElement: addNodeElement,
  33661. agxToneMapping: agxToneMapping,
  33662. all: all,
  33663. alphaT: alphaT,
  33664. and: and,
  33665. anisotropy: anisotropy,
  33666. anisotropyB: anisotropyB,
  33667. anisotropyT: anisotropyT,
  33668. any: any,
  33669. append: append,
  33670. array: array,
  33671. arrayBuffer: arrayBuffer,
  33672. asin: asin,
  33673. assign: assign,
  33674. atan: atan,
  33675. atomicAdd: atomicAdd,
  33676. atomicAnd: atomicAnd,
  33677. atomicFunc: atomicFunc,
  33678. atomicLoad: atomicLoad,
  33679. atomicMax: atomicMax,
  33680. atomicMin: atomicMin,
  33681. atomicOr: atomicOr,
  33682. atomicStore: atomicStore,
  33683. atomicSub: atomicSub,
  33684. atomicXor: atomicXor,
  33685. attenuationColor: attenuationColor,
  33686. attenuationDistance: attenuationDistance,
  33687. attribute: attribute,
  33688. attributeArray: attributeArray,
  33689. backgroundBlurriness: backgroundBlurriness,
  33690. backgroundIntensity: backgroundIntensity,
  33691. backgroundRotation: backgroundRotation,
  33692. batch: batch,
  33693. bentNormalView: bentNormalView,
  33694. billboarding: billboarding,
  33695. bitAnd: bitAnd,
  33696. bitNot: bitNot,
  33697. bitOr: bitOr,
  33698. bitXor: bitXor,
  33699. bitangentGeometry: bitangentGeometry,
  33700. bitangentLocal: bitangentLocal,
  33701. bitangentView: bitangentView,
  33702. bitangentWorld: bitangentWorld,
  33703. bitcast: bitcast,
  33704. blendBurn: blendBurn,
  33705. blendColor: blendColor,
  33706. blendDodge: blendDodge,
  33707. blendOverlay: blendOverlay,
  33708. blendScreen: blendScreen,
  33709. blur: blur,
  33710. bool: bool,
  33711. buffer: buffer,
  33712. bufferAttribute: bufferAttribute,
  33713. builtin: builtin,
  33714. builtinAOContext: builtinAOContext,
  33715. builtinShadowContext: builtinShadowContext,
  33716. bumpMap: bumpMap,
  33717. bvec2: bvec2,
  33718. bvec3: bvec3,
  33719. bvec4: bvec4,
  33720. bypass: bypass,
  33721. cache: cache,
  33722. call: call,
  33723. cameraFar: cameraFar,
  33724. cameraIndex: cameraIndex,
  33725. cameraNear: cameraNear,
  33726. cameraNormalMatrix: cameraNormalMatrix,
  33727. cameraPosition: cameraPosition,
  33728. cameraProjectionMatrix: cameraProjectionMatrix,
  33729. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  33730. cameraViewMatrix: cameraViewMatrix,
  33731. cameraViewport: cameraViewport,
  33732. cameraWorldMatrix: cameraWorldMatrix,
  33733. cbrt: cbrt,
  33734. cdl: cdl,
  33735. ceil: ceil,
  33736. checker: checker,
  33737. cineonToneMapping: cineonToneMapping,
  33738. clamp: clamp,
  33739. clearcoat: clearcoat,
  33740. clearcoatNormalView: clearcoatNormalView,
  33741. clearcoatRoughness: clearcoatRoughness,
  33742. clipSpace: clipSpace,
  33743. code: code,
  33744. color: color,
  33745. colorSpaceToWorking: colorSpaceToWorking,
  33746. colorToDirection: colorToDirection,
  33747. compute: compute,
  33748. computeKernel: computeKernel,
  33749. computeSkinning: computeSkinning,
  33750. context: context,
  33751. convert: convert,
  33752. convertColorSpace: convertColorSpace,
  33753. convertToTexture: convertToTexture,
  33754. cos: cos,
  33755. countLeadingZeros: countLeadingZeros,
  33756. countOneBits: countOneBits,
  33757. countTrailingZeros: countTrailingZeros,
  33758. cross: cross,
  33759. cubeTexture: cubeTexture,
  33760. cubeTextureBase: cubeTextureBase,
  33761. dFdx: dFdx,
  33762. dFdy: dFdy,
  33763. dashSize: dashSize,
  33764. debug: debug,
  33765. decrement: decrement,
  33766. decrementBefore: decrementBefore,
  33767. defaultBuildStages: defaultBuildStages,
  33768. defaultShaderStages: defaultShaderStages,
  33769. defined: defined,
  33770. degrees: degrees,
  33771. deltaTime: deltaTime,
  33772. densityFogFactor: densityFogFactor,
  33773. depth: depth,
  33774. depthPass: depthPass,
  33775. determinant: determinant,
  33776. difference: difference,
  33777. diffuseColor: diffuseColor,
  33778. diffuseContribution: diffuseContribution,
  33779. directPointLight: directPointLight,
  33780. directionToColor: directionToColor,
  33781. directionToFaceDirection: directionToFaceDirection,
  33782. dispersion: dispersion,
  33783. disposeShadowMaterial: disposeShadowMaterial,
  33784. distance: distance,
  33785. div: div,
  33786. dot: dot,
  33787. drawIndex: drawIndex,
  33788. dynamicBufferAttribute: dynamicBufferAttribute,
  33789. element: element,
  33790. emissive: emissive,
  33791. equal: equal,
  33792. equirectUV: equirectUV,
  33793. exp: exp,
  33794. exp2: exp2,
  33795. exponentialHeightFogFactor: exponentialHeightFogFactor,
  33796. expression: expression,
  33797. faceDirection: faceDirection,
  33798. faceForward: faceForward,
  33799. faceforward: faceforward,
  33800. float: float,
  33801. floatBitsToInt: floatBitsToInt,
  33802. floatBitsToUint: floatBitsToUint,
  33803. floor: floor,
  33804. fog: fog,
  33805. fract: fract,
  33806. frameGroup: frameGroup,
  33807. frameId: frameId,
  33808. frontFacing: frontFacing,
  33809. fwidth: fwidth,
  33810. gain: gain,
  33811. gapSize: gapSize,
  33812. getConstNodeType: getConstNodeType,
  33813. getCurrentStack: getCurrentStack,
  33814. getDirection: getDirection,
  33815. getDistanceAttenuation: getDistanceAttenuation,
  33816. getGeometryRoughness: getGeometryRoughness,
  33817. getNormalFromDepth: getNormalFromDepth,
  33818. getParallaxCorrectNormal: getParallaxCorrectNormal,
  33819. getRoughness: getRoughness,
  33820. getScreenPosition: getScreenPosition,
  33821. getShIrradianceAt: getShIrradianceAt,
  33822. getShadowMaterial: getShadowMaterial,
  33823. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  33824. getTextureIndex: getTextureIndex,
  33825. getViewPosition: getViewPosition,
  33826. ggxConvolution: ggxConvolution,
  33827. globalId: globalId,
  33828. glsl: glsl,
  33829. glslFn: glslFn,
  33830. grayscale: grayscale,
  33831. greaterThan: greaterThan,
  33832. greaterThanEqual: greaterThanEqual,
  33833. hash: hash,
  33834. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  33835. highpModelViewMatrix: highpModelViewMatrix,
  33836. hue: hue,
  33837. increment: increment,
  33838. incrementBefore: incrementBefore,
  33839. inspector: inspector,
  33840. instance: instance,
  33841. instanceIndex: instanceIndex,
  33842. instancedArray: instancedArray,
  33843. instancedBufferAttribute: instancedBufferAttribute,
  33844. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  33845. instancedMesh: instancedMesh,
  33846. int: int,
  33847. intBitsToFloat: intBitsToFloat,
  33848. interleavedGradientNoise: interleavedGradientNoise,
  33849. inverse: inverse,
  33850. inverseSqrt: inverseSqrt,
  33851. inversesqrt: inversesqrt,
  33852. invocationLocalIndex: invocationLocalIndex,
  33853. invocationSubgroupIndex: invocationSubgroupIndex,
  33854. ior: ior,
  33855. iridescence: iridescence,
  33856. iridescenceIOR: iridescenceIOR,
  33857. iridescenceThickness: iridescenceThickness,
  33858. isolate: isolate,
  33859. ivec2: ivec2,
  33860. ivec3: ivec3,
  33861. ivec4: ivec4,
  33862. js: js,
  33863. label: label,
  33864. length: length,
  33865. lengthSq: lengthSq,
  33866. lessThan: lessThan,
  33867. lessThanEqual: lessThanEqual,
  33868. lightPosition: lightPosition,
  33869. lightProjectionUV: lightProjectionUV,
  33870. lightShadowMatrix: lightShadowMatrix,
  33871. lightTargetDirection: lightTargetDirection,
  33872. lightTargetPosition: lightTargetPosition,
  33873. lightViewPosition: lightViewPosition,
  33874. lightingContext: lightingContext,
  33875. lights: lights,
  33876. linearDepth: linearDepth,
  33877. linearToneMapping: linearToneMapping,
  33878. localId: localId,
  33879. log: log,
  33880. log2: log2,
  33881. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  33882. luminance: luminance,
  33883. mat2: mat2,
  33884. mat3: mat3,
  33885. mat4: mat4,
  33886. matcapUV: matcapUV,
  33887. materialAO: materialAO,
  33888. materialAlphaTest: materialAlphaTest,
  33889. materialAnisotropy: materialAnisotropy,
  33890. materialAnisotropyVector: materialAnisotropyVector,
  33891. materialAttenuationColor: materialAttenuationColor,
  33892. materialAttenuationDistance: materialAttenuationDistance,
  33893. materialClearcoat: materialClearcoat,
  33894. materialClearcoatNormal: materialClearcoatNormal,
  33895. materialClearcoatRoughness: materialClearcoatRoughness,
  33896. materialColor: materialColor,
  33897. materialDispersion: materialDispersion,
  33898. materialEmissive: materialEmissive,
  33899. materialEnvIntensity: materialEnvIntensity,
  33900. materialEnvRotation: materialEnvRotation,
  33901. materialIOR: materialIOR,
  33902. materialIridescence: materialIridescence,
  33903. materialIridescenceIOR: materialIridescenceIOR,
  33904. materialIridescenceThickness: materialIridescenceThickness,
  33905. materialLightMap: materialLightMap,
  33906. materialLineDashOffset: materialLineDashOffset,
  33907. materialLineDashSize: materialLineDashSize,
  33908. materialLineGapSize: materialLineGapSize,
  33909. materialLineScale: materialLineScale,
  33910. materialLineWidth: materialLineWidth,
  33911. materialMetalness: materialMetalness,
  33912. materialNormal: materialNormal,
  33913. materialOpacity: materialOpacity,
  33914. materialPointSize: materialPointSize,
  33915. materialReference: materialReference,
  33916. materialReflectivity: materialReflectivity,
  33917. materialRefractionRatio: materialRefractionRatio,
  33918. materialRotation: materialRotation,
  33919. materialRoughness: materialRoughness,
  33920. materialSheen: materialSheen,
  33921. materialSheenRoughness: materialSheenRoughness,
  33922. materialShininess: materialShininess,
  33923. materialSpecular: materialSpecular,
  33924. materialSpecularColor: materialSpecularColor,
  33925. materialSpecularIntensity: materialSpecularIntensity,
  33926. materialSpecularStrength: materialSpecularStrength,
  33927. materialThickness: materialThickness,
  33928. materialTransmission: materialTransmission,
  33929. max: max$1,
  33930. maxMipLevel: maxMipLevel,
  33931. mediumpModelViewMatrix: mediumpModelViewMatrix,
  33932. metalness: metalness,
  33933. min: min$1,
  33934. mix: mix,
  33935. mixElement: mixElement,
  33936. mod: mod,
  33937. modInt: modInt,
  33938. modelDirection: modelDirection,
  33939. modelNormalMatrix: modelNormalMatrix,
  33940. modelPosition: modelPosition,
  33941. modelRadius: modelRadius,
  33942. modelScale: modelScale,
  33943. modelViewMatrix: modelViewMatrix,
  33944. modelViewPosition: modelViewPosition,
  33945. modelViewProjection: modelViewProjection,
  33946. modelWorldMatrix: modelWorldMatrix,
  33947. modelWorldMatrixInverse: modelWorldMatrixInverse,
  33948. morphReference: morphReference,
  33949. mrt: mrt,
  33950. mul: mul,
  33951. mx_aastep: mx_aastep,
  33952. mx_add: mx_add,
  33953. mx_atan2: mx_atan2,
  33954. mx_cell_noise_float: mx_cell_noise_float,
  33955. mx_contrast: mx_contrast,
  33956. mx_divide: mx_divide,
  33957. mx_fractal_noise_float: mx_fractal_noise_float,
  33958. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  33959. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  33960. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  33961. mx_frame: mx_frame,
  33962. mx_heighttonormal: mx_heighttonormal,
  33963. mx_hsvtorgb: mx_hsvtorgb,
  33964. mx_ifequal: mx_ifequal,
  33965. mx_ifgreater: mx_ifgreater,
  33966. mx_ifgreatereq: mx_ifgreatereq,
  33967. mx_invert: mx_invert,
  33968. mx_modulo: mx_modulo,
  33969. mx_multiply: mx_multiply,
  33970. mx_noise_float: mx_noise_float,
  33971. mx_noise_vec3: mx_noise_vec3,
  33972. mx_noise_vec4: mx_noise_vec4,
  33973. mx_place2d: mx_place2d,
  33974. mx_power: mx_power,
  33975. mx_ramp4: mx_ramp4,
  33976. mx_ramplr: mx_ramplr,
  33977. mx_ramptb: mx_ramptb,
  33978. mx_rgbtohsv: mx_rgbtohsv,
  33979. mx_rotate2d: mx_rotate2d,
  33980. mx_rotate3d: mx_rotate3d,
  33981. mx_safepower: mx_safepower,
  33982. mx_separate: mx_separate,
  33983. mx_splitlr: mx_splitlr,
  33984. mx_splittb: mx_splittb,
  33985. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  33986. mx_subtract: mx_subtract,
  33987. mx_timer: mx_timer,
  33988. mx_transform_uv: mx_transform_uv,
  33989. mx_unifiednoise2d: mx_unifiednoise2d,
  33990. mx_unifiednoise3d: mx_unifiednoise3d,
  33991. mx_worley_noise_float: mx_worley_noise_float,
  33992. mx_worley_noise_vec2: mx_worley_noise_vec2,
  33993. mx_worley_noise_vec3: mx_worley_noise_vec3,
  33994. negate: negate,
  33995. neutralToneMapping: neutralToneMapping,
  33996. nodeArray: nodeArray,
  33997. nodeImmutable: nodeImmutable,
  33998. nodeObject: nodeObject,
  33999. nodeObjectIntent: nodeObjectIntent,
  34000. nodeObjects: nodeObjects,
  34001. nodeProxy: nodeProxy,
  34002. nodeProxyIntent: nodeProxyIntent,
  34003. normalFlat: normalFlat,
  34004. normalGeometry: normalGeometry,
  34005. normalLocal: normalLocal,
  34006. normalMap: normalMap,
  34007. normalView: normalView,
  34008. normalViewGeometry: normalViewGeometry,
  34009. normalWorld: normalWorld,
  34010. normalWorldGeometry: normalWorldGeometry,
  34011. normalize: normalize,
  34012. not: not,
  34013. notEqual: notEqual,
  34014. numWorkgroups: numWorkgroups,
  34015. objectDirection: objectDirection,
  34016. objectGroup: objectGroup,
  34017. objectPosition: objectPosition,
  34018. objectRadius: objectRadius,
  34019. objectScale: objectScale,
  34020. objectViewPosition: objectViewPosition,
  34021. objectWorldMatrix: objectWorldMatrix,
  34022. oneMinus: oneMinus,
  34023. or: or,
  34024. orthographicDepthToViewZ: orthographicDepthToViewZ,
  34025. oscSawtooth: oscSawtooth,
  34026. oscSine: oscSine,
  34027. oscSquare: oscSquare,
  34028. oscTriangle: oscTriangle,
  34029. output: output,
  34030. outputStruct: outputStruct,
  34031. overloadingFn: overloadingFn,
  34032. packHalf2x16: packHalf2x16,
  34033. packSnorm2x16: packSnorm2x16,
  34034. packUnorm2x16: packUnorm2x16,
  34035. parabola: parabola,
  34036. parallaxDirection: parallaxDirection,
  34037. parallaxUV: parallaxUV,
  34038. parameter: parameter,
  34039. pass: pass,
  34040. passTexture: passTexture,
  34041. pcurve: pcurve,
  34042. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  34043. pmremTexture: pmremTexture,
  34044. pointShadow: pointShadow,
  34045. pointUV: pointUV,
  34046. pointWidth: pointWidth,
  34047. positionGeometry: positionGeometry,
  34048. positionLocal: positionLocal,
  34049. positionPrevious: positionPrevious,
  34050. positionView: positionView,
  34051. positionViewDirection: positionViewDirection,
  34052. positionWorld: positionWorld,
  34053. positionWorldDirection: positionWorldDirection,
  34054. posterize: posterize,
  34055. pow: pow,
  34056. pow2: pow2,
  34057. pow3: pow3,
  34058. pow4: pow4,
  34059. premultiplyAlpha: premultiplyAlpha,
  34060. property: property,
  34061. quadBroadcast: quadBroadcast,
  34062. quadSwapDiagonal: quadSwapDiagonal,
  34063. quadSwapX: quadSwapX,
  34064. quadSwapY: quadSwapY,
  34065. radians: radians,
  34066. rand: rand,
  34067. range: range,
  34068. rangeFogFactor: rangeFogFactor,
  34069. reciprocal: reciprocal,
  34070. reference: reference,
  34071. referenceBuffer: referenceBuffer,
  34072. reflect: reflect,
  34073. reflectVector: reflectVector,
  34074. reflectView: reflectView,
  34075. reflector: reflector,
  34076. refract: refract,
  34077. refractVector: refractVector,
  34078. refractView: refractView,
  34079. reinhardToneMapping: reinhardToneMapping,
  34080. remap: remap,
  34081. remapClamp: remapClamp,
  34082. renderGroup: renderGroup,
  34083. renderOutput: renderOutput,
  34084. rendererReference: rendererReference,
  34085. replaceDefaultUV: replaceDefaultUV,
  34086. rotate: rotate,
  34087. rotateUV: rotateUV,
  34088. roughness: roughness,
  34089. round: round,
  34090. rtt: rtt,
  34091. sRGBTransferEOTF: sRGBTransferEOTF,
  34092. sRGBTransferOETF: sRGBTransferOETF,
  34093. sample: sample,
  34094. sampler: sampler,
  34095. samplerComparison: samplerComparison,
  34096. saturate: saturate,
  34097. saturation: saturation,
  34098. screenCoordinate: screenCoordinate,
  34099. screenDPR: screenDPR,
  34100. screenSize: screenSize,
  34101. screenUV: screenUV,
  34102. scriptable: scriptable,
  34103. scriptableValue: scriptableValue,
  34104. select: select,
  34105. setCurrentStack: setCurrentStack,
  34106. setName: setName,
  34107. shaderStages: shaderStages,
  34108. shadow: shadow,
  34109. shadowPositionWorld: shadowPositionWorld,
  34110. shapeCircle: shapeCircle,
  34111. sharedUniformGroup: sharedUniformGroup,
  34112. sheen: sheen,
  34113. sheenRoughness: sheenRoughness,
  34114. shiftLeft: shiftLeft,
  34115. shiftRight: shiftRight,
  34116. shininess: shininess,
  34117. sign: sign,
  34118. sin: sin,
  34119. sinc: sinc,
  34120. skinning: skinning,
  34121. smoothstep: smoothstep,
  34122. smoothstepElement: smoothstepElement,
  34123. specularColor: specularColor,
  34124. specularColorBlended: specularColorBlended,
  34125. specularF90: specularF90,
  34126. spherizeUV: spherizeUV,
  34127. split: split,
  34128. spritesheetUV: spritesheetUV,
  34129. sqrt: sqrt,
  34130. stack: stack,
  34131. step: step,
  34132. stepElement: stepElement,
  34133. storage: storage,
  34134. storageBarrier: storageBarrier,
  34135. storageTexture: storageTexture,
  34136. string: string,
  34137. struct: struct,
  34138. sub: sub,
  34139. subBuild: subBuild,
  34140. subgroupAdd: subgroupAdd,
  34141. subgroupAll: subgroupAll,
  34142. subgroupAnd: subgroupAnd,
  34143. subgroupAny: subgroupAny,
  34144. subgroupBallot: subgroupBallot,
  34145. subgroupBroadcast: subgroupBroadcast,
  34146. subgroupBroadcastFirst: subgroupBroadcastFirst,
  34147. subgroupElect: subgroupElect,
  34148. subgroupExclusiveAdd: subgroupExclusiveAdd,
  34149. subgroupExclusiveMul: subgroupExclusiveMul,
  34150. subgroupInclusiveAdd: subgroupInclusiveAdd,
  34151. subgroupInclusiveMul: subgroupInclusiveMul,
  34152. subgroupIndex: subgroupIndex,
  34153. subgroupMax: subgroupMax,
  34154. subgroupMin: subgroupMin,
  34155. subgroupMul: subgroupMul,
  34156. subgroupOr: subgroupOr,
  34157. subgroupShuffle: subgroupShuffle,
  34158. subgroupShuffleDown: subgroupShuffleDown,
  34159. subgroupShuffleUp: subgroupShuffleUp,
  34160. subgroupShuffleXor: subgroupShuffleXor,
  34161. subgroupSize: subgroupSize,
  34162. subgroupXor: subgroupXor,
  34163. tan: tan,
  34164. tangentGeometry: tangentGeometry,
  34165. tangentLocal: tangentLocal,
  34166. tangentView: tangentView,
  34167. tangentWorld: tangentWorld,
  34168. texture: texture,
  34169. texture3D: texture3D,
  34170. texture3DLevel: texture3DLevel,
  34171. texture3DLoad: texture3DLoad,
  34172. textureBarrier: textureBarrier,
  34173. textureBicubic: textureBicubic,
  34174. textureBicubicLevel: textureBicubicLevel,
  34175. textureCubeUV: textureCubeUV,
  34176. textureLevel: textureLevel,
  34177. textureLoad: textureLoad,
  34178. textureSize: textureSize,
  34179. textureStore: textureStore,
  34180. thickness: thickness,
  34181. time: time,
  34182. toneMapping: toneMapping,
  34183. toneMappingExposure: toneMappingExposure,
  34184. toonOutlinePass: toonOutlinePass,
  34185. transformDirection: transformDirection,
  34186. transformNormal: transformNormal,
  34187. transformNormalToView: transformNormalToView,
  34188. transformedClearcoatNormalView: transformedClearcoatNormalView,
  34189. transformedNormalView: transformedNormalView,
  34190. transformedNormalWorld: transformedNormalWorld,
  34191. transmission: transmission,
  34192. transpose: transpose,
  34193. triNoise3D: triNoise3D,
  34194. triplanarTexture: triplanarTexture,
  34195. triplanarTextures: triplanarTextures,
  34196. trunc: trunc,
  34197. uint: uint,
  34198. uintBitsToFloat: uintBitsToFloat,
  34199. uniform: uniform,
  34200. uniformArray: uniformArray,
  34201. uniformCubeTexture: uniformCubeTexture,
  34202. uniformFlow: uniformFlow,
  34203. uniformGroup: uniformGroup,
  34204. uniformTexture: uniformTexture,
  34205. unpackHalf2x16: unpackHalf2x16,
  34206. unpackNormal: unpackNormal,
  34207. unpackSnorm2x16: unpackSnorm2x16,
  34208. unpackUnorm2x16: unpackUnorm2x16,
  34209. unpremultiplyAlpha: unpremultiplyAlpha,
  34210. userData: userData,
  34211. uv: uv$1,
  34212. uvec2: uvec2,
  34213. uvec3: uvec3,
  34214. uvec4: uvec4,
  34215. varying: varying,
  34216. varyingProperty: varyingProperty,
  34217. vec2: vec2,
  34218. vec3: vec3,
  34219. vec4: vec4,
  34220. vectorComponents: vectorComponents,
  34221. velocity: velocity,
  34222. vertexColor: vertexColor,
  34223. vertexIndex: vertexIndex,
  34224. vertexStage: vertexStage,
  34225. vibrance: vibrance,
  34226. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  34227. viewZToOrthographicDepth: viewZToOrthographicDepth,
  34228. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  34229. viewport: viewport,
  34230. viewportCoordinate: viewportCoordinate,
  34231. viewportDepthTexture: viewportDepthTexture,
  34232. viewportLinearDepth: viewportLinearDepth,
  34233. viewportMipTexture: viewportMipTexture,
  34234. viewportOpaqueMipTexture: viewportOpaqueMipTexture,
  34235. viewportResolution: viewportResolution,
  34236. viewportSafeUV: viewportSafeUV,
  34237. viewportSharedTexture: viewportSharedTexture,
  34238. viewportSize: viewportSize,
  34239. viewportTexture: viewportTexture,
  34240. viewportUV: viewportUV,
  34241. vogelDiskSample: vogelDiskSample,
  34242. wgsl: wgsl,
  34243. wgslFn: wgslFn,
  34244. workgroupArray: workgroupArray,
  34245. workgroupBarrier: workgroupBarrier,
  34246. workgroupId: workgroupId,
  34247. workingToColorSpace: workingToColorSpace,
  34248. xor: xor
  34249. });
  34250. const _clearColor = /*@__PURE__*/ new Color4();
  34251. /**
  34252. * This renderer module manages the background.
  34253. *
  34254. * @private
  34255. * @augments DataMap
  34256. */
  34257. class Background extends DataMap {
  34258. /**
  34259. * Constructs a new background management component.
  34260. *
  34261. * @param {Renderer} renderer - The renderer.
  34262. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  34263. */
  34264. constructor( renderer, nodes ) {
  34265. super();
  34266. /**
  34267. * The renderer.
  34268. *
  34269. * @type {Renderer}
  34270. */
  34271. this.renderer = renderer;
  34272. /**
  34273. * Renderer component for managing nodes related logic.
  34274. *
  34275. * @type {Nodes}
  34276. */
  34277. this.nodes = nodes;
  34278. }
  34279. /**
  34280. * Updates the background for the given scene. Depending on how `Scene.background`
  34281. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  34282. * or add a mesh to the render list for rendering the background as a textured plane
  34283. * or skybox.
  34284. *
  34285. * @param {Scene} scene - The scene.
  34286. * @param {RenderList} renderList - The current render list.
  34287. * @param {RenderContext} renderContext - The current render context.
  34288. */
  34289. update( scene, renderList, renderContext ) {
  34290. const renderer = this.renderer;
  34291. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34292. let forceClear = false;
  34293. if ( background === null ) {
  34294. // no background settings, use clear color configuration from the renderer
  34295. renderer._clearColor.getRGB( _clearColor );
  34296. _clearColor.a = renderer._clearColor.a;
  34297. } else if ( background.isColor === true ) {
  34298. // background is an opaque color
  34299. background.getRGB( _clearColor );
  34300. _clearColor.a = 1;
  34301. forceClear = true;
  34302. } else if ( background.isNode === true ) {
  34303. const sceneData = this.get( scene );
  34304. const backgroundNode = background;
  34305. _clearColor.copy( renderer._clearColor );
  34306. let backgroundMesh = sceneData.backgroundMesh;
  34307. if ( backgroundMesh === undefined ) {
  34308. const backgroundMeshNode = vec4( backgroundNode ).mul( backgroundIntensity ).context( {
  34309. // @TODO: Add Texture2D support using node context
  34310. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  34311. getTextureLevel: () => backgroundBlurriness
  34312. } );
  34313. // when using orthographic cameras, we must scale the skybox sphere
  34314. // up to exceed the dimensions of the camera's viewing box.
  34315. const isOrtho = cameraProjectionMatrix.element( 3 ).element( 3 ).equal( 1.0 );
  34316. // calculate the orthographic scale
  34317. // projectionMatrix[1][1] is (1 / top). Invert it to get the height and multiply by 3.0
  34318. // (an arbitrary safety factor) to ensure the skybox is large enough to cover the corners
  34319. // of the rectangular screen
  34320. const orthoScale = div( 1.0, cameraProjectionMatrix.element( 1 ).element( 1 ) ).mul( 3.0 );
  34321. // compute vertex position
  34322. const modifiedPosition = isOrtho.select( positionLocal.mul( orthoScale ), positionLocal );
  34323. // by using a w component of 0, the skybox will not translate when the camera moves through the scene
  34324. const viewPosition = modelViewMatrix.mul( vec4( modifiedPosition, 0.0 ) );
  34325. // we force w=1.0 here to prevent the w_clip=0 divide-by-zero error for ortho cameras.
  34326. let viewProj = cameraProjectionMatrix.mul( vec4( viewPosition.xyz, 1.0 ) );
  34327. // force background to far plane so it does not occlude objects
  34328. viewProj = viewProj.setZ( viewProj.w );
  34329. const nodeMaterial = new NodeMaterial();
  34330. nodeMaterial.name = 'Background.material';
  34331. nodeMaterial.side = BackSide;
  34332. nodeMaterial.depthTest = false;
  34333. nodeMaterial.depthWrite = false;
  34334. nodeMaterial.allowOverride = false;
  34335. nodeMaterial.fog = false;
  34336. nodeMaterial.lights = false;
  34337. nodeMaterial.vertexNode = viewProj;
  34338. nodeMaterial.colorNode = backgroundMeshNode;
  34339. sceneData.backgroundMeshNode = backgroundMeshNode;
  34340. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34341. backgroundMesh.frustumCulled = false;
  34342. backgroundMesh.name = 'Background.mesh';
  34343. function onBackgroundDispose() {
  34344. background.removeEventListener( 'dispose', onBackgroundDispose );
  34345. backgroundMesh.material.dispose();
  34346. backgroundMesh.geometry.dispose();
  34347. }
  34348. background.addEventListener( 'dispose', onBackgroundDispose );
  34349. }
  34350. const backgroundCacheKey = backgroundNode.getCacheKey();
  34351. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34352. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34353. sceneData.backgroundMeshNode.needsUpdate = true;
  34354. backgroundMesh.material.needsUpdate = true;
  34355. sceneData.backgroundCacheKey = backgroundCacheKey;
  34356. }
  34357. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34358. } else {
  34359. error( 'Renderer: Unsupported background configuration.', background );
  34360. }
  34361. //
  34362. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  34363. if ( environmentBlendMode === 'additive' ) {
  34364. _clearColor.set( 0, 0, 0, 1 );
  34365. } else if ( environmentBlendMode === 'alpha-blend' ) {
  34366. _clearColor.set( 0, 0, 0, 0 );
  34367. }
  34368. //
  34369. if ( renderer.autoClear === true || forceClear === true ) {
  34370. const clearColorValue = renderContext.clearColorValue;
  34371. clearColorValue.r = _clearColor.r;
  34372. clearColorValue.g = _clearColor.g;
  34373. clearColorValue.b = _clearColor.b;
  34374. clearColorValue.a = _clearColor.a;
  34375. // premultiply alpha
  34376. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34377. clearColorValue.r *= clearColorValue.a;
  34378. clearColorValue.g *= clearColorValue.a;
  34379. clearColorValue.b *= clearColorValue.a;
  34380. }
  34381. //
  34382. renderContext.depthClearValue = renderer._clearDepth;
  34383. renderContext.stencilClearValue = renderer._clearStencil;
  34384. renderContext.clearColor = renderer.autoClearColor === true;
  34385. renderContext.clearDepth = renderer.autoClearDepth === true;
  34386. renderContext.clearStencil = renderer.autoClearStencil === true;
  34387. } else {
  34388. renderContext.clearColor = false;
  34389. renderContext.clearDepth = false;
  34390. renderContext.clearStencil = false;
  34391. }
  34392. }
  34393. }
  34394. let _id$7 = 0;
  34395. /**
  34396. * A bind group represents a collection of bindings and thus a collection
  34397. * or resources. Bind groups are assigned to pipelines to provide them
  34398. * with the required resources (like uniform buffers or textures).
  34399. *
  34400. * @private
  34401. */
  34402. class BindGroup {
  34403. /**
  34404. * Constructs a new bind group.
  34405. *
  34406. * @param {string} name - The bind group's name.
  34407. * @param {Array<Binding>} bindings - An array of bindings.
  34408. * @param {number} index - The group index.
  34409. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  34410. */
  34411. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  34412. /**
  34413. * The bind group's name.
  34414. *
  34415. * @type {string}
  34416. */
  34417. this.name = name;
  34418. /**
  34419. * An array of bindings.
  34420. *
  34421. * @type {Array<Binding>}
  34422. */
  34423. this.bindings = bindings;
  34424. /**
  34425. * The group index.
  34426. *
  34427. * @type {number}
  34428. */
  34429. this.index = index;
  34430. /**
  34431. * An array of reference bindings.
  34432. *
  34433. * @type {Array<Binding>}
  34434. */
  34435. this.bindingsReference = bindingsReference;
  34436. /**
  34437. * The group's ID.
  34438. *
  34439. * @type {number}
  34440. */
  34441. this.id = _id$7 ++;
  34442. }
  34443. }
  34444. /**
  34445. * This module represents the state of a node builder after it was
  34446. * used to build the nodes for a render object. The state holds the
  34447. * results of the build for further processing in the renderer.
  34448. *
  34449. * Render objects with identical cache keys share the same node builder state.
  34450. *
  34451. * @private
  34452. */
  34453. class NodeBuilderState {
  34454. /**
  34455. * Constructs a new node builder state.
  34456. *
  34457. * @param {string} vertexShader - The native vertex shader code.
  34458. * @param {string} fragmentShader - The native fragment shader code.
  34459. * @param {string} computeShader - The native compute shader code.
  34460. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  34461. * @param {Array<BindGroup>} bindings - An array of bind groups.
  34462. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  34463. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  34464. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  34465. * @param {NodeMaterialObserver} observer - A node material observer.
  34466. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  34467. */
  34468. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  34469. /**
  34470. * The native vertex shader code.
  34471. *
  34472. * @type {string}
  34473. */
  34474. this.vertexShader = vertexShader;
  34475. /**
  34476. * The native fragment shader code.
  34477. *
  34478. * @type {string}
  34479. */
  34480. this.fragmentShader = fragmentShader;
  34481. /**
  34482. * The native compute shader code.
  34483. *
  34484. * @type {string}
  34485. */
  34486. this.computeShader = computeShader;
  34487. /**
  34488. * An array with transform attribute objects.
  34489. * Only relevant when using compute shaders with WebGL 2.
  34490. *
  34491. * @type {Array<Object>}
  34492. */
  34493. this.transforms = transforms;
  34494. /**
  34495. * An array of node attributes representing
  34496. * the attributes of the shaders.
  34497. *
  34498. * @type {Array<NodeAttribute>}
  34499. */
  34500. this.nodeAttributes = nodeAttributes;
  34501. /**
  34502. * An array of bind groups representing the uniform or storage
  34503. * buffers, texture or samplers of the shader.
  34504. *
  34505. * @type {Array<BindGroup>}
  34506. */
  34507. this.bindings = bindings;
  34508. /**
  34509. * An array of nodes that implement their `update()` method.
  34510. *
  34511. * @type {Array<Node>}
  34512. */
  34513. this.updateNodes = updateNodes;
  34514. /**
  34515. * An array of nodes that implement their `updateBefore()` method.
  34516. *
  34517. * @type {Array<Node>}
  34518. */
  34519. this.updateBeforeNodes = updateBeforeNodes;
  34520. /**
  34521. * An array of nodes that implement their `updateAfter()` method.
  34522. *
  34523. * @type {Array<Node>}
  34524. */
  34525. this.updateAfterNodes = updateAfterNodes;
  34526. /**
  34527. * A node material observer.
  34528. *
  34529. * @type {NodeMaterialObserver}
  34530. */
  34531. this.observer = observer;
  34532. /**
  34533. * How often this state is used by render objects.
  34534. *
  34535. * @type {number}
  34536. */
  34537. this.usedTimes = 0;
  34538. }
  34539. /**
  34540. * This method is used to create a array of bind groups based
  34541. * on the existing bind groups of this state. Shared groups are
  34542. * not cloned.
  34543. *
  34544. * @return {Array<BindGroup>} A array of bind groups.
  34545. */
  34546. createBindings() {
  34547. const bindings = [];
  34548. for ( const instanceGroup of this.bindings ) {
  34549. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  34550. if ( shared !== true ) {
  34551. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  34552. bindings.push( bindingsGroup );
  34553. for ( const instanceBinding of instanceGroup.bindings ) {
  34554. bindingsGroup.bindings.push( instanceBinding.clone() );
  34555. }
  34556. } else {
  34557. bindings.push( instanceGroup );
  34558. }
  34559. }
  34560. return bindings;
  34561. }
  34562. }
  34563. /**
  34564. * {@link NodeBuilder} is going to create instances of this class during the build process
  34565. * of nodes. They represent the final shader attributes that are going to be generated
  34566. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  34567. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  34568. */
  34569. class NodeAttribute {
  34570. /**
  34571. * Constructs a new node attribute.
  34572. *
  34573. * @param {string} name - The name of the attribute.
  34574. * @param {string} type - The type of the attribute.
  34575. * @param {?Node} node - An optional reference to the node.
  34576. */
  34577. constructor( name, type, node = null ) {
  34578. /**
  34579. * This flag can be used for type testing.
  34580. *
  34581. * @type {boolean}
  34582. * @readonly
  34583. * @default true
  34584. */
  34585. this.isNodeAttribute = true;
  34586. /**
  34587. * The name of the attribute.
  34588. *
  34589. * @type {string}
  34590. */
  34591. this.name = name;
  34592. /**
  34593. * The type of the attribute.
  34594. *
  34595. * @type {string}
  34596. */
  34597. this.type = type;
  34598. /**
  34599. * An optional reference to the node.
  34600. *
  34601. * @type {?Node}
  34602. * @default null
  34603. */
  34604. this.node = node;
  34605. }
  34606. }
  34607. /**
  34608. * {@link NodeBuilder} is going to create instances of this class during the build process
  34609. * of nodes. They represent the final shader uniforms that are going to be generated
  34610. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  34611. * for this purpose.
  34612. */
  34613. class NodeUniform {
  34614. /**
  34615. * Constructs a new node uniform.
  34616. *
  34617. * @param {string} name - The name of the uniform.
  34618. * @param {string} type - The type of the uniform.
  34619. * @param {UniformNode} node - An reference to the node.
  34620. */
  34621. constructor( name, type, node ) {
  34622. /**
  34623. * This flag can be used for type testing.
  34624. *
  34625. * @type {boolean}
  34626. * @readonly
  34627. * @default true
  34628. */
  34629. this.isNodeUniform = true;
  34630. /**
  34631. * The name of the uniform.
  34632. *
  34633. * @type {string}
  34634. */
  34635. this.name = name;
  34636. /**
  34637. * The type of the uniform.
  34638. *
  34639. * @type {string}
  34640. */
  34641. this.type = type;
  34642. /**
  34643. * An reference to the node.
  34644. *
  34645. * @type {UniformNode}
  34646. */
  34647. this.node = node;
  34648. }
  34649. /**
  34650. * The value of the uniform node.
  34651. *
  34652. * @type {any}
  34653. */
  34654. get value() {
  34655. return this.node.value;
  34656. }
  34657. set value( val ) {
  34658. this.node.value = val;
  34659. }
  34660. /**
  34661. * The id of the uniform node.
  34662. *
  34663. * @type {number}
  34664. */
  34665. get id() {
  34666. return this.node.id;
  34667. }
  34668. /**
  34669. * The uniform node's group.
  34670. *
  34671. * @type {UniformGroupNode}
  34672. */
  34673. get groupNode() {
  34674. return this.node.groupNode;
  34675. }
  34676. }
  34677. /**
  34678. * {@link NodeBuilder} is going to create instances of this class during the build process
  34679. * of nodes. They represent the final shader variables that are going to be generated
  34680. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  34681. * this purpose.
  34682. */
  34683. class NodeVar {
  34684. /**
  34685. * Constructs a new node variable.
  34686. *
  34687. * @param {string} name - The name of the variable.
  34688. * @param {string} type - The type of the variable.
  34689. * @param {boolean} [readOnly=false] - The read-only flag.
  34690. * @param {?number} [count=null] - The size.
  34691. */
  34692. constructor( name, type, readOnly = false, count = null ) {
  34693. /**
  34694. * This flag can be used for type testing.
  34695. *
  34696. * @type {boolean}
  34697. * @readonly
  34698. * @default true
  34699. */
  34700. this.isNodeVar = true;
  34701. /**
  34702. * The name of the variable.
  34703. *
  34704. * @type {string}
  34705. */
  34706. this.name = name;
  34707. /**
  34708. * The type of the variable.
  34709. *
  34710. * @type {string}
  34711. */
  34712. this.type = type;
  34713. /**
  34714. * The read-only flag.
  34715. *
  34716. * @type {boolean}
  34717. */
  34718. this.readOnly = readOnly;
  34719. /**
  34720. * The size.
  34721. *
  34722. * @type {?number}
  34723. */
  34724. this.count = count;
  34725. }
  34726. }
  34727. /**
  34728. * {@link NodeBuilder} is going to create instances of this class during the build process
  34729. * of nodes. They represent the final shader varyings that are going to be generated
  34730. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  34731. * this purpose.
  34732. *
  34733. * @augments NodeVar
  34734. */
  34735. class NodeVarying extends NodeVar {
  34736. /**
  34737. * Constructs a new node varying.
  34738. *
  34739. * @param {string} name - The name of the varying.
  34740. * @param {string} type - The type of the varying.
  34741. * @param {?string} interpolationType - The interpolation type of the varying.
  34742. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34743. */
  34744. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  34745. super( name, type );
  34746. /**
  34747. * Whether this varying requires interpolation or not. This property can be used
  34748. * to check if the varying can be optimized for a variable.
  34749. *
  34750. * @type {boolean}
  34751. * @default false
  34752. */
  34753. this.needsInterpolation = false;
  34754. /**
  34755. * This flag can be used for type testing.
  34756. *
  34757. * @type {boolean}
  34758. * @readonly
  34759. * @default true
  34760. */
  34761. this.isNodeVarying = true;
  34762. /**
  34763. * The interpolation type of the varying data.
  34764. *
  34765. * @type {?string}
  34766. * @default null
  34767. */
  34768. this.interpolationType = interpolationType;
  34769. /**
  34770. * The interpolation sampling type of varying data.
  34771. *
  34772. * @type {?string}
  34773. * @default null
  34774. */
  34775. this.interpolationSampling = interpolationSampling;
  34776. }
  34777. }
  34778. /**
  34779. * {@link NodeBuilder} is going to create instances of this class during the build process
  34780. * of nodes. They represent user-defined, native shader code portions that are going to be
  34781. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  34782. * for this purpose.
  34783. */
  34784. class NodeCode {
  34785. /**
  34786. * Constructs a new code node.
  34787. *
  34788. * @param {string} name - The name of the code.
  34789. * @param {string} type - The node type.
  34790. * @param {string} [code=''] - The native shader code.
  34791. */
  34792. constructor( name, type, code = '' ) {
  34793. /**
  34794. * The name of the code.
  34795. *
  34796. * @type {string}
  34797. */
  34798. this.name = name;
  34799. /**
  34800. * The node type.
  34801. *
  34802. * @type {string}
  34803. */
  34804. this.type = type;
  34805. /**
  34806. * The native shader code.
  34807. *
  34808. * @type {string}
  34809. * @default ''
  34810. */
  34811. this.code = code;
  34812. Object.defineProperty( this, 'isNodeCode', { value: true } );
  34813. }
  34814. }
  34815. let _id$6 = 0;
  34816. /**
  34817. * This utility class is used in {@link NodeBuilder} as an internal
  34818. * cache data structure for node data.
  34819. */
  34820. class NodeCache {
  34821. /**
  34822. * Constructs a new node cache.
  34823. *
  34824. * @param {?NodeCache} parent - A reference to a parent cache.
  34825. */
  34826. constructor( parent = null ) {
  34827. /**
  34828. * The id of the cache.
  34829. *
  34830. * @type {number}
  34831. * @readonly
  34832. */
  34833. this.id = _id$6 ++;
  34834. /**
  34835. * A weak map for managing node data.
  34836. *
  34837. * @type {WeakMap<Node, Object>}
  34838. */
  34839. this.nodesData = new WeakMap();
  34840. /**
  34841. * Reference to a parent node cache.
  34842. *
  34843. * @type {?NodeCache}
  34844. * @default null
  34845. */
  34846. this.parent = parent;
  34847. }
  34848. /**
  34849. * Returns the data for the given node.
  34850. *
  34851. * @param {Node} node - The node.
  34852. * @return {?Object} The data for the node.
  34853. */
  34854. getData( node ) {
  34855. let data = this.nodesData.get( node );
  34856. if ( data === undefined && this.parent !== null ) {
  34857. data = this.parent.getData( node );
  34858. }
  34859. return data;
  34860. }
  34861. /**
  34862. * Sets the data for a given node.
  34863. *
  34864. * @param {Node} node - The node.
  34865. * @param {Object} data - The data that should be cached.
  34866. */
  34867. setData( node, data ) {
  34868. this.nodesData.set( node, data );
  34869. }
  34870. }
  34871. class StructType {
  34872. constructor( name, members ) {
  34873. this.name = name;
  34874. this.members = members;
  34875. this.output = false;
  34876. }
  34877. }
  34878. /**
  34879. * Abstract base class for uniforms.
  34880. *
  34881. * @abstract
  34882. * @private
  34883. */
  34884. class Uniform {
  34885. /**
  34886. * Constructs a new uniform.
  34887. *
  34888. * @param {string} name - The uniform's name.
  34889. * @param {any} value - The uniform's value.
  34890. */
  34891. constructor( name, value ) {
  34892. /**
  34893. * The uniform's name.
  34894. *
  34895. * @type {string}
  34896. */
  34897. this.name = name;
  34898. /**
  34899. * The uniform's value.
  34900. *
  34901. * @type {any}
  34902. */
  34903. this.value = value;
  34904. /**
  34905. * Used to build the uniform buffer according to the STD140 layout.
  34906. * Derived uniforms will set this property to a data type specific
  34907. * value.
  34908. *
  34909. * @type {number}
  34910. */
  34911. this.boundary = 0;
  34912. /**
  34913. * The item size. Derived uniforms will set this property to a data
  34914. * type specific value.
  34915. *
  34916. * @type {number}
  34917. */
  34918. this.itemSize = 0;
  34919. /**
  34920. * This property is set by {@link UniformsGroup} and marks
  34921. * the start position in the uniform buffer.
  34922. *
  34923. * @type {number}
  34924. */
  34925. this.offset = 0;
  34926. /**
  34927. * This property is set by {@link UniformsGroup} and marks
  34928. * the index position in the uniform array.
  34929. *
  34930. * @type {number}
  34931. */
  34932. this.index = -1;
  34933. }
  34934. /**
  34935. * Sets the uniform's value.
  34936. *
  34937. * @param {any} value - The value to set.
  34938. */
  34939. setValue( value ) {
  34940. this.value = value;
  34941. }
  34942. /**
  34943. * Returns the uniform's value.
  34944. *
  34945. * @return {any} The value.
  34946. */
  34947. getValue() {
  34948. return this.value;
  34949. }
  34950. }
  34951. /**
  34952. * Represents a Number uniform.
  34953. *
  34954. * @private
  34955. * @augments Uniform
  34956. */
  34957. class NumberUniform extends Uniform {
  34958. /**
  34959. * Constructs a new Number uniform.
  34960. *
  34961. * @param {string} name - The uniform's name.
  34962. * @param {number} value - The uniform's value.
  34963. */
  34964. constructor( name, value = 0 ) {
  34965. super( name, value );
  34966. /**
  34967. * This flag can be used for type testing.
  34968. *
  34969. * @type {boolean}
  34970. * @readonly
  34971. * @default true
  34972. */
  34973. this.isNumberUniform = true;
  34974. this.boundary = 4;
  34975. this.itemSize = 1;
  34976. }
  34977. }
  34978. /**
  34979. * Represents a Vector2 uniform.
  34980. *
  34981. * @private
  34982. * @augments Uniform
  34983. */
  34984. class Vector2Uniform extends Uniform {
  34985. /**
  34986. * Constructs a new Number uniform.
  34987. *
  34988. * @param {string} name - The uniform's name.
  34989. * @param {Vector2} value - The uniform's value.
  34990. */
  34991. constructor( name, value = new Vector2() ) {
  34992. super( name, value );
  34993. /**
  34994. * This flag can be used for type testing.
  34995. *
  34996. * @type {boolean}
  34997. * @readonly
  34998. * @default true
  34999. */
  35000. this.isVector2Uniform = true;
  35001. this.boundary = 8;
  35002. this.itemSize = 2;
  35003. }
  35004. }
  35005. /**
  35006. * Represents a Vector3 uniform.
  35007. *
  35008. * @private
  35009. * @augments Uniform
  35010. */
  35011. class Vector3Uniform extends Uniform {
  35012. /**
  35013. * Constructs a new Number uniform.
  35014. *
  35015. * @param {string} name - The uniform's name.
  35016. * @param {Vector3} value - The uniform's value.
  35017. */
  35018. constructor( name, value = new Vector3() ) {
  35019. super( name, value );
  35020. /**
  35021. * This flag can be used for type testing.
  35022. *
  35023. * @type {boolean}
  35024. * @readonly
  35025. * @default true
  35026. */
  35027. this.isVector3Uniform = true;
  35028. this.boundary = 16;
  35029. this.itemSize = 3;
  35030. }
  35031. }
  35032. /**
  35033. * Represents a Vector4 uniform.
  35034. *
  35035. * @private
  35036. * @augments Uniform
  35037. */
  35038. class Vector4Uniform extends Uniform {
  35039. /**
  35040. * Constructs a new Number uniform.
  35041. *
  35042. * @param {string} name - The uniform's name.
  35043. * @param {Vector4} value - The uniform's value.
  35044. */
  35045. constructor( name, value = new Vector4() ) {
  35046. super( name, value );
  35047. /**
  35048. * This flag can be used for type testing.
  35049. *
  35050. * @type {boolean}
  35051. * @readonly
  35052. * @default true
  35053. */
  35054. this.isVector4Uniform = true;
  35055. this.boundary = 16;
  35056. this.itemSize = 4;
  35057. }
  35058. }
  35059. /**
  35060. * Represents a Color uniform.
  35061. *
  35062. * @private
  35063. * @augments Uniform
  35064. */
  35065. class ColorUniform extends Uniform {
  35066. /**
  35067. * Constructs a new Number uniform.
  35068. *
  35069. * @param {string} name - The uniform's name.
  35070. * @param {Color} value - The uniform's value.
  35071. */
  35072. constructor( name, value = new Color() ) {
  35073. super( name, value );
  35074. /**
  35075. * This flag can be used for type testing.
  35076. *
  35077. * @type {boolean}
  35078. * @readonly
  35079. * @default true
  35080. */
  35081. this.isColorUniform = true;
  35082. this.boundary = 16;
  35083. this.itemSize = 3;
  35084. }
  35085. }
  35086. /**
  35087. * Represents a Matrix2 uniform.
  35088. *
  35089. * @private
  35090. * @augments Uniform
  35091. */
  35092. class Matrix2Uniform extends Uniform {
  35093. /**
  35094. * Constructs a new Number uniform.
  35095. *
  35096. * @param {string} name - The uniform's name.
  35097. * @param {Matrix2} value - The uniform's value.
  35098. */
  35099. constructor( name, value = new Matrix2() ) {
  35100. super( name, value );
  35101. /**
  35102. * This flag can be used for type testing.
  35103. *
  35104. * @type {boolean}
  35105. * @readonly
  35106. * @default true
  35107. */
  35108. this.isMatrix2Uniform = true;
  35109. this.boundary = 8;
  35110. this.itemSize = 4;
  35111. }
  35112. }
  35113. /**
  35114. * Represents a Matrix3 uniform.
  35115. *
  35116. * @private
  35117. * @augments Uniform
  35118. */
  35119. class Matrix3Uniform extends Uniform {
  35120. /**
  35121. * Constructs a new Number uniform.
  35122. *
  35123. * @param {string} name - The uniform's name.
  35124. * @param {Matrix3} value - The uniform's value.
  35125. */
  35126. constructor( name, value = new Matrix3() ) {
  35127. super( name, value );
  35128. /**
  35129. * This flag can be used for type testing.
  35130. *
  35131. * @type {boolean}
  35132. * @readonly
  35133. * @default true
  35134. */
  35135. this.isMatrix3Uniform = true;
  35136. this.boundary = 48;
  35137. this.itemSize = 12;
  35138. }
  35139. }
  35140. /**
  35141. * Represents a Matrix4 uniform.
  35142. *
  35143. * @private
  35144. * @augments Uniform
  35145. */
  35146. class Matrix4Uniform extends Uniform {
  35147. /**
  35148. * Constructs a new Number uniform.
  35149. *
  35150. * @param {string} name - The uniform's name.
  35151. * @param {Matrix4} value - The uniform's value.
  35152. */
  35153. constructor( name, value = new Matrix4() ) {
  35154. super( name, value );
  35155. /**
  35156. * This flag can be used for type testing.
  35157. *
  35158. * @type {boolean}
  35159. * @readonly
  35160. * @default true
  35161. */
  35162. this.isMatrix4Uniform = true;
  35163. this.boundary = 64;
  35164. this.itemSize = 16;
  35165. }
  35166. }
  35167. /**
  35168. * A special form of Number uniform binding type.
  35169. * It's value is managed by a node object.
  35170. *
  35171. * @private
  35172. * @augments NumberUniform
  35173. */
  35174. class NumberNodeUniform extends NumberUniform {
  35175. /**
  35176. * Constructs a new node-based Number uniform.
  35177. *
  35178. * @param {NodeUniform} nodeUniform - The node uniform.
  35179. */
  35180. constructor( nodeUniform ) {
  35181. super( nodeUniform.name, nodeUniform.value );
  35182. /**
  35183. * The node uniform.
  35184. *
  35185. * @type {NodeUniform}
  35186. */
  35187. this.nodeUniform = nodeUniform;
  35188. }
  35189. /**
  35190. * Overwritten to return the value of the node uniform.
  35191. *
  35192. * @return {number} The value.
  35193. */
  35194. getValue() {
  35195. return this.nodeUniform.value;
  35196. }
  35197. /**
  35198. * Returns the node uniform data type.
  35199. *
  35200. * @return {string} The data type.
  35201. */
  35202. getType() {
  35203. return this.nodeUniform.type;
  35204. }
  35205. }
  35206. /**
  35207. * A special form of Vector2 uniform binding type.
  35208. * It's value is managed by a node object.
  35209. *
  35210. * @private
  35211. * @augments Vector2Uniform
  35212. */
  35213. class Vector2NodeUniform extends Vector2Uniform {
  35214. /**
  35215. * Constructs a new node-based Vector2 uniform.
  35216. *
  35217. * @param {NodeUniform} nodeUniform - The node uniform.
  35218. */
  35219. constructor( nodeUniform ) {
  35220. super( nodeUniform.name, nodeUniform.value );
  35221. /**
  35222. * The node uniform.
  35223. *
  35224. * @type {NodeUniform}
  35225. */
  35226. this.nodeUniform = nodeUniform;
  35227. }
  35228. /**
  35229. * Overwritten to return the value of the node uniform.
  35230. *
  35231. * @return {Vector2} The value.
  35232. */
  35233. getValue() {
  35234. return this.nodeUniform.value;
  35235. }
  35236. /**
  35237. * Returns the node uniform data type.
  35238. *
  35239. * @return {string} The data type.
  35240. */
  35241. getType() {
  35242. return this.nodeUniform.type;
  35243. }
  35244. }
  35245. /**
  35246. * A special form of Vector3 uniform binding type.
  35247. * It's value is managed by a node object.
  35248. *
  35249. * @private
  35250. * @augments Vector3Uniform
  35251. */
  35252. class Vector3NodeUniform extends Vector3Uniform {
  35253. /**
  35254. * Constructs a new node-based Vector3 uniform.
  35255. *
  35256. * @param {NodeUniform} nodeUniform - The node uniform.
  35257. */
  35258. constructor( nodeUniform ) {
  35259. super( nodeUniform.name, nodeUniform.value );
  35260. /**
  35261. * The node uniform.
  35262. *
  35263. * @type {NodeUniform}
  35264. */
  35265. this.nodeUniform = nodeUniform;
  35266. }
  35267. /**
  35268. * Overwritten to return the value of the node uniform.
  35269. *
  35270. * @return {Vector3} The value.
  35271. */
  35272. getValue() {
  35273. return this.nodeUniform.value;
  35274. }
  35275. /**
  35276. * Returns the node uniform data type.
  35277. *
  35278. * @return {string} The data type.
  35279. */
  35280. getType() {
  35281. return this.nodeUniform.type;
  35282. }
  35283. }
  35284. /**
  35285. * A special form of Vector4 uniform binding type.
  35286. * It's value is managed by a node object.
  35287. *
  35288. * @private
  35289. * @augments Vector4Uniform
  35290. */
  35291. class Vector4NodeUniform extends Vector4Uniform {
  35292. /**
  35293. * Constructs a new node-based Vector4 uniform.
  35294. *
  35295. * @param {NodeUniform} nodeUniform - The node uniform.
  35296. */
  35297. constructor( nodeUniform ) {
  35298. super( nodeUniform.name, nodeUniform.value );
  35299. /**
  35300. * The node uniform.
  35301. *
  35302. * @type {NodeUniform}
  35303. */
  35304. this.nodeUniform = nodeUniform;
  35305. }
  35306. /**
  35307. * Overwritten to return the value of the node uniform.
  35308. *
  35309. * @return {Vector4} The value.
  35310. */
  35311. getValue() {
  35312. return this.nodeUniform.value;
  35313. }
  35314. /**
  35315. * Returns the node uniform data type.
  35316. *
  35317. * @return {string} The data type.
  35318. */
  35319. getType() {
  35320. return this.nodeUniform.type;
  35321. }
  35322. }
  35323. /**
  35324. * A special form of Color uniform binding type.
  35325. * It's value is managed by a node object.
  35326. *
  35327. * @private
  35328. * @augments ColorUniform
  35329. */
  35330. class ColorNodeUniform extends ColorUniform {
  35331. /**
  35332. * Constructs a new node-based Color uniform.
  35333. *
  35334. * @param {NodeUniform} nodeUniform - The node uniform.
  35335. */
  35336. constructor( nodeUniform ) {
  35337. super( nodeUniform.name, nodeUniform.value );
  35338. /**
  35339. * The node uniform.
  35340. *
  35341. * @type {NodeUniform}
  35342. */
  35343. this.nodeUniform = nodeUniform;
  35344. }
  35345. /**
  35346. * Overwritten to return the value of the node uniform.
  35347. *
  35348. * @return {Color} The value.
  35349. */
  35350. getValue() {
  35351. return this.nodeUniform.value;
  35352. }
  35353. /**
  35354. * Returns the node uniform data type.
  35355. *
  35356. * @return {string} The data type.
  35357. */
  35358. getType() {
  35359. return this.nodeUniform.type;
  35360. }
  35361. }
  35362. /**
  35363. * A special form of Matrix2 uniform binding type.
  35364. * It's value is managed by a node object.
  35365. *
  35366. * @private
  35367. * @augments Matrix2Uniform
  35368. */
  35369. class Matrix2NodeUniform extends Matrix2Uniform {
  35370. /**
  35371. * Constructs a new node-based Matrix2 uniform.
  35372. *
  35373. * @param {NodeUniform} nodeUniform - The node uniform.
  35374. */
  35375. constructor( nodeUniform ) {
  35376. super( nodeUniform.name, nodeUniform.value );
  35377. /**
  35378. * The node uniform.
  35379. *
  35380. * @type {NodeUniform}
  35381. */
  35382. this.nodeUniform = nodeUniform;
  35383. }
  35384. /**
  35385. * Overwritten to return the value of the node uniform.
  35386. *
  35387. * @return {Matrix2} The value.
  35388. */
  35389. getValue() {
  35390. return this.nodeUniform.value;
  35391. }
  35392. /**
  35393. * Returns the node uniform data type.
  35394. *
  35395. * @return {string} The data type.
  35396. */
  35397. getType() {
  35398. return this.nodeUniform.type;
  35399. }
  35400. }
  35401. /**
  35402. * A special form of Matrix3 uniform binding type.
  35403. * It's value is managed by a node object.
  35404. *
  35405. * @private
  35406. * @augments Matrix3Uniform
  35407. */
  35408. class Matrix3NodeUniform extends Matrix3Uniform {
  35409. /**
  35410. * Constructs a new node-based Matrix3 uniform.
  35411. *
  35412. * @param {NodeUniform} nodeUniform - The node uniform.
  35413. */
  35414. constructor( nodeUniform ) {
  35415. super( nodeUniform.name, nodeUniform.value );
  35416. /**
  35417. * The node uniform.
  35418. *
  35419. * @type {NodeUniform}
  35420. */
  35421. this.nodeUniform = nodeUniform;
  35422. }
  35423. /**
  35424. * Overwritten to return the value of the node uniform.
  35425. *
  35426. * @return {Matrix3} The value.
  35427. */
  35428. getValue() {
  35429. return this.nodeUniform.value;
  35430. }
  35431. /**
  35432. * Returns the node uniform data type.
  35433. *
  35434. * @return {string} The data type.
  35435. */
  35436. getType() {
  35437. return this.nodeUniform.type;
  35438. }
  35439. }
  35440. /**
  35441. * A special form of Matrix4 uniform binding type.
  35442. * It's value is managed by a node object.
  35443. *
  35444. * @private
  35445. * @augments Matrix4Uniform
  35446. */
  35447. class Matrix4NodeUniform extends Matrix4Uniform {
  35448. /**
  35449. * Constructs a new node-based Matrix4 uniform.
  35450. *
  35451. * @param {NodeUniform} nodeUniform - The node uniform.
  35452. */
  35453. constructor( nodeUniform ) {
  35454. super( nodeUniform.name, nodeUniform.value );
  35455. /**
  35456. * The node uniform.
  35457. *
  35458. * @type {NodeUniform}
  35459. */
  35460. this.nodeUniform = nodeUniform;
  35461. }
  35462. /**
  35463. * Overwritten to return the value of the node uniform.
  35464. *
  35465. * @return {Matrix4} The value.
  35466. */
  35467. getValue() {
  35468. return this.nodeUniform.value;
  35469. }
  35470. /**
  35471. * Returns the node uniform data type.
  35472. *
  35473. * @return {string} The data type.
  35474. */
  35475. getType() {
  35476. return this.nodeUniform.type;
  35477. }
  35478. }
  35479. let _id$5 = 0;
  35480. const sharedNodeData = new WeakMap();
  35481. const rendererCache = new WeakMap();
  35482. const typeFromArray = new Map( [
  35483. [ Int8Array, 'int' ],
  35484. [ Int16Array, 'int' ],
  35485. [ Int32Array, 'int' ],
  35486. [ Uint8Array, 'uint' ],
  35487. [ Uint16Array, 'uint' ],
  35488. [ Uint32Array, 'uint' ],
  35489. [ Float32Array, 'float' ]
  35490. ] );
  35491. const toFloat = ( value ) => {
  35492. if ( /e/g.test( value ) ) {
  35493. return String( value ).replace( /\+/g, '' );
  35494. } else {
  35495. value = Number( value );
  35496. return value + ( value % 1 ? '' : '.0' );
  35497. }
  35498. };
  35499. /**
  35500. * Base class for builders which generate a shader program based
  35501. * on a 3D object and its node material definition.
  35502. */
  35503. class NodeBuilder {
  35504. /**
  35505. * Constructs a new node builder.
  35506. *
  35507. * @param {Object3D} object - The 3D object.
  35508. * @param {Renderer} renderer - The current renderer.
  35509. * @param {NodeParser} parser - A reference to a node parser.
  35510. */
  35511. constructor( object, renderer, parser ) {
  35512. /**
  35513. * The 3D object.
  35514. *
  35515. * @type {Object3D}
  35516. */
  35517. this.object = object;
  35518. /**
  35519. * The material of the 3D object.
  35520. *
  35521. * @type {?Material}
  35522. */
  35523. this.material = ( object && object.material ) || null;
  35524. /**
  35525. * The geometry of the 3D object.
  35526. *
  35527. * @type {?BufferGeometry}
  35528. */
  35529. this.geometry = ( object && object.geometry ) || null;
  35530. /**
  35531. * The current renderer.
  35532. *
  35533. * @type {Renderer}
  35534. */
  35535. this.renderer = renderer;
  35536. /**
  35537. * A reference to a node parser.
  35538. *
  35539. * @type {NodeParser}
  35540. */
  35541. this.parser = parser;
  35542. /**
  35543. * The scene the 3D object belongs to.
  35544. *
  35545. * @type {?Scene}
  35546. * @default null
  35547. */
  35548. this.scene = null;
  35549. /**
  35550. * The camera the 3D object is rendered with.
  35551. *
  35552. * @type {?Camera}
  35553. * @default null
  35554. */
  35555. this.camera = null;
  35556. /**
  35557. * A list of all nodes the builder is processing
  35558. * for this 3D object.
  35559. *
  35560. * @type {Array<Node>}
  35561. */
  35562. this.nodes = [];
  35563. /**
  35564. * A list of all sequential nodes.
  35565. *
  35566. * @type {Array<Node>}
  35567. */
  35568. this.sequentialNodes = [];
  35569. /**
  35570. * A list of all nodes which {@link Node#update} method should be executed.
  35571. *
  35572. * @type {Array<Node>}
  35573. */
  35574. this.updateNodes = [];
  35575. /**
  35576. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  35577. *
  35578. * @type {Array<Node>}
  35579. */
  35580. this.updateBeforeNodes = [];
  35581. /**
  35582. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  35583. *
  35584. * @type {Array<Node>}
  35585. */
  35586. this.updateAfterNodes = [];
  35587. /**
  35588. * A dictionary that assigns each node to a unique hash.
  35589. *
  35590. * @type {Object<number,Node>}
  35591. */
  35592. this.hashNodes = {};
  35593. /**
  35594. * A reference to a node material observer.
  35595. *
  35596. * @type {?NodeMaterialObserver}
  35597. * @default null
  35598. */
  35599. this.observer = null;
  35600. /**
  35601. * A reference to the current lights node.
  35602. *
  35603. * @type {?LightsNode}
  35604. * @default null
  35605. */
  35606. this.lightsNode = null;
  35607. /**
  35608. * A reference to the current environment node.
  35609. *
  35610. * @type {?Node}
  35611. * @default null
  35612. */
  35613. this.environmentNode = null;
  35614. /**
  35615. * A reference to the current fog node.
  35616. *
  35617. * @type {?Node}
  35618. * @default null
  35619. */
  35620. this.fogNode = null;
  35621. /**
  35622. * The current clipping context.
  35623. *
  35624. * @type {?ClippingContext}
  35625. */
  35626. this.clippingContext = null;
  35627. /**
  35628. * The generated vertex shader.
  35629. *
  35630. * @type {?string}
  35631. */
  35632. this.vertexShader = null;
  35633. /**
  35634. * The generated fragment shader.
  35635. *
  35636. * @type {?string}
  35637. */
  35638. this.fragmentShader = null;
  35639. /**
  35640. * The generated compute shader.
  35641. *
  35642. * @type {?string}
  35643. */
  35644. this.computeShader = null;
  35645. /**
  35646. * Nodes used in the primary flow of code generation.
  35647. *
  35648. * @type {Object<string,Array<Node>>}
  35649. */
  35650. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35651. /**
  35652. * Nodes code from `.flowNodes`.
  35653. *
  35654. * @type {Object<string,string>}
  35655. */
  35656. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35657. /**
  35658. * This dictionary holds the node uniforms of the builder.
  35659. * The uniforms are maintained in an array for each shader stage.
  35660. *
  35661. * @type {Object}
  35662. */
  35663. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35664. /**
  35665. * This dictionary holds the output structs of the builder.
  35666. * The structs are maintained in an array for each shader stage.
  35667. *
  35668. * @type {Object}
  35669. */
  35670. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35671. /**
  35672. * This dictionary holds the types of the builder.
  35673. *
  35674. * @type {Object}
  35675. */
  35676. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  35677. /**
  35678. * This dictionary holds the bindings for each shader stage.
  35679. *
  35680. * @type {Object}
  35681. */
  35682. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35683. /**
  35684. * This dictionary maintains the binding indices per bind group.
  35685. *
  35686. * @type {Object}
  35687. */
  35688. this.bindingsIndexes = {};
  35689. /**
  35690. * Reference to the array of bind groups.
  35691. *
  35692. * @type {?Array<BindGroup>}
  35693. */
  35694. this.bindGroups = null;
  35695. /**
  35696. * This array holds the node attributes of this builder
  35697. * created via {@link AttributeNode}.
  35698. *
  35699. * @type {Array<NodeAttribute>}
  35700. */
  35701. this.attributes = [];
  35702. /**
  35703. * This array holds the node attributes of this builder
  35704. * created via {@link BufferAttributeNode}.
  35705. *
  35706. * @type {Array<NodeAttribute>}
  35707. */
  35708. this.bufferAttributes = [];
  35709. /**
  35710. * This array holds the node varyings of this builder.
  35711. *
  35712. * @type {Array<NodeVarying>}
  35713. */
  35714. this.varyings = [];
  35715. /**
  35716. * This dictionary holds the (native) node codes of this builder.
  35717. * The codes are maintained in an array for each shader stage.
  35718. *
  35719. * @type {Object<string,Array<NodeCode>>}
  35720. */
  35721. this.codes = {};
  35722. /**
  35723. * This dictionary holds the node variables of this builder.
  35724. * The variables are maintained in an array for each shader stage.
  35725. * This dictionary is also used to count the number of variables
  35726. * according to their type (const, vars).
  35727. *
  35728. * @type {Object<string,Array<NodeVar>|number>}
  35729. */
  35730. this.vars = {};
  35731. /**
  35732. * This dictionary holds the declarations for each shader stage.
  35733. *
  35734. * @type {Object}
  35735. */
  35736. this.declarations = {};
  35737. /**
  35738. * Current code flow.
  35739. * All code generated in this stack will be stored in `.flow`.
  35740. *
  35741. * @type {{code: string}}
  35742. */
  35743. this.flow = { code: '' };
  35744. /**
  35745. * A chain of nodes.
  35746. * Used to check recursive calls in node-graph.
  35747. *
  35748. * @type {Array<Node>}
  35749. */
  35750. this.chaining = [];
  35751. /**
  35752. * The current stack.
  35753. * This reflects the current process in the code block hierarchy,
  35754. * it is useful to know if the current process is inside a conditional for example.
  35755. *
  35756. * @type {StackNode}
  35757. */
  35758. this.stack = stack();
  35759. /**
  35760. * List of stack nodes.
  35761. * The current stack hierarchy is stored in an array.
  35762. *
  35763. * @type {Array<StackNode>}
  35764. */
  35765. this.stacks = [];
  35766. /**
  35767. * A tab value. Used for shader string generation.
  35768. *
  35769. * @type {string}
  35770. * @default '\t'
  35771. */
  35772. this.tab = '\t';
  35773. /**
  35774. * Reference to the current function node.
  35775. *
  35776. * @type {?FunctionNode}
  35777. * @default null
  35778. */
  35779. this.currentFunctionNode = null;
  35780. /**
  35781. * The builder's context.
  35782. *
  35783. * @type {Object}
  35784. */
  35785. this.context = {
  35786. material: this.material
  35787. };
  35788. /**
  35789. * The builder's cache.
  35790. *
  35791. * @type {NodeCache}
  35792. */
  35793. this.cache = new NodeCache();
  35794. /**
  35795. * Since the {@link NodeBuilder#cache} might be temporarily
  35796. * overwritten by other caches, this member retains the reference
  35797. * to the builder's own cache.
  35798. *
  35799. * @type {NodeCache}
  35800. * @default this.cache
  35801. */
  35802. this.globalCache = this.cache;
  35803. this.flowsData = new WeakMap();
  35804. /**
  35805. * The current shader stage.
  35806. *
  35807. * @type {?('vertex'|'fragment'|'compute'|'any')}
  35808. */
  35809. this.shaderStage = null;
  35810. /**
  35811. * The current build stage.
  35812. *
  35813. * @type {?('setup'|'analyze'|'generate')}
  35814. */
  35815. this.buildStage = null;
  35816. /**
  35817. * The sub-build layers.
  35818. *
  35819. * @type {Array<SubBuildNode>}
  35820. * @default []
  35821. */
  35822. this.subBuildLayers = [];
  35823. /**
  35824. * The active stack nodes.
  35825. *
  35826. * @type {Array<StackNode>}
  35827. */
  35828. this.activeStacks = [];
  35829. /**
  35830. * The current sub-build TSL function(Fn).
  35831. *
  35832. * @type {?string}
  35833. * @default null
  35834. */
  35835. this.subBuildFn = null;
  35836. /**
  35837. * The current TSL function(Fn) call node.
  35838. *
  35839. * @type {?Node}
  35840. * @default null
  35841. */
  35842. this.fnCall = null;
  35843. Object.defineProperty( this, 'id', { value: _id$5 ++ } );
  35844. }
  35845. /**
  35846. * Whether the material is using flat shading or not.
  35847. *
  35848. * @returns {boolean} Whether the material is using flat shading or not.
  35849. */
  35850. isFlatShading() {
  35851. return this.material.flatShading === true || this.geometry.hasAttribute( 'normal' ) === false;
  35852. }
  35853. /**
  35854. * Whether the material is opaque or not.
  35855. *
  35856. * @return {boolean} Whether the material is opaque or not.
  35857. */
  35858. isOpaque() {
  35859. const material = this.material;
  35860. return material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false;
  35861. }
  35862. /**
  35863. * Returns the bind groups of the current renderer.
  35864. *
  35865. * @return {ChainMap} The cache.
  35866. */
  35867. getBindGroupsCache() {
  35868. let bindGroupsCache = rendererCache.get( this.renderer );
  35869. if ( bindGroupsCache === undefined ) {
  35870. bindGroupsCache = new ChainMap();
  35871. rendererCache.set( this.renderer, bindGroupsCache );
  35872. }
  35873. return bindGroupsCache;
  35874. }
  35875. /**
  35876. * Factory method for creating an instance of {@link RenderTarget} with the given
  35877. * dimensions and options.
  35878. *
  35879. * @param {number} width - The width of the render target.
  35880. * @param {number} height - The height of the render target.
  35881. * @param {Object} options - The options of the render target.
  35882. * @return {RenderTarget} The render target.
  35883. */
  35884. createRenderTarget( width, height, options ) {
  35885. return new RenderTarget( width, height, options );
  35886. }
  35887. /**
  35888. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  35889. * dimensions and options.
  35890. *
  35891. * @param {number} size - The size of the cube render target.
  35892. * @param {Object} options - The options of the cube render target.
  35893. * @return {CubeRenderTarget} The cube render target.
  35894. */
  35895. createCubeRenderTarget( size, options ) {
  35896. return new CubeRenderTarget( size, options );
  35897. }
  35898. /**
  35899. * Whether the given node is included in the internal array of nodes or not.
  35900. *
  35901. * @param {Node} node - The node to test.
  35902. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  35903. */
  35904. includes( node ) {
  35905. return this.nodes.includes( node );
  35906. }
  35907. /**
  35908. * Returns the output struct name which is required by
  35909. * {@link OutputStructNode}.
  35910. *
  35911. * @abstract
  35912. * @return {string} The name of the output struct.
  35913. */
  35914. getOutputStructName() {}
  35915. /**
  35916. * Returns a bind group for the given group name and binding.
  35917. *
  35918. * @private
  35919. * @param {string} groupName - The group name.
  35920. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  35921. * @return {BindGroup} The bind group
  35922. */
  35923. _getBindGroup( groupName, bindings ) {
  35924. const bindGroupsCache = this.getBindGroupsCache();
  35925. //
  35926. const bindingsArray = [];
  35927. let sharedGroup = true;
  35928. for ( const binding of bindings ) {
  35929. bindingsArray.push( binding );
  35930. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35931. }
  35932. //
  35933. let bindGroup;
  35934. if ( sharedGroup ) {
  35935. bindGroup = bindGroupsCache.get( bindingsArray );
  35936. if ( bindGroup === undefined ) {
  35937. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35938. bindGroupsCache.set( bindingsArray, bindGroup );
  35939. }
  35940. } else {
  35941. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35942. }
  35943. return bindGroup;
  35944. }
  35945. /**
  35946. * Returns an array of node uniform groups for the given group name and shader stage.
  35947. *
  35948. * @param {string} groupName - The group name.
  35949. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35950. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  35951. */
  35952. getBindGroupArray( groupName, shaderStage ) {
  35953. const bindings = this.bindings[ shaderStage ];
  35954. let bindGroup = bindings[ groupName ];
  35955. if ( bindGroup === undefined ) {
  35956. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35957. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35958. }
  35959. bindings[ groupName ] = bindGroup = [];
  35960. }
  35961. return bindGroup;
  35962. }
  35963. /**
  35964. * Returns a list bindings of all shader stages separated by groups.
  35965. *
  35966. * @return {Array<BindGroup>} The list of bindings.
  35967. */
  35968. getBindings() {
  35969. let bindingsGroups = this.bindGroups;
  35970. if ( bindingsGroups === null ) {
  35971. const groups = {};
  35972. const bindings = this.bindings;
  35973. for ( const shaderStage of shaderStages ) {
  35974. for ( const groupName in bindings[ shaderStage ] ) {
  35975. const uniforms = bindings[ shaderStage ][ groupName ];
  35976. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35977. for ( const uniform of uniforms ) {
  35978. if ( groupUniforms.includes( uniform ) === false ) {
  35979. groupUniforms.push( uniform );
  35980. }
  35981. }
  35982. }
  35983. }
  35984. bindingsGroups = [];
  35985. for ( const groupName in groups ) {
  35986. const group = groups[ groupName ];
  35987. const bindingsGroup = this._getBindGroup( groupName, group );
  35988. bindingsGroups.push( bindingsGroup );
  35989. }
  35990. this.bindGroups = bindingsGroups;
  35991. }
  35992. return bindingsGroups;
  35993. }
  35994. /**
  35995. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  35996. */
  35997. sortBindingGroups() {
  35998. const bindingsGroups = this.getBindings();
  35999. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36000. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36001. const bindingGroup = bindingsGroups[ i ];
  36002. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36003. bindingGroup.index = i;
  36004. }
  36005. }
  36006. /**
  36007. * The builder maintains each node in a hash-based dictionary.
  36008. * This method sets the given node (value) with the given hash (key) into this dictionary.
  36009. *
  36010. * @param {Node} node - The node to add.
  36011. * @param {number} hash - The hash of the node.
  36012. */
  36013. setHashNode( node, hash ) {
  36014. this.hashNodes[ hash ] = node;
  36015. }
  36016. /**
  36017. * Adds a node to this builder.
  36018. *
  36019. * @param {Node} node - The node to add.
  36020. */
  36021. addNode( node ) {
  36022. if ( this.nodes.includes( node ) === false ) {
  36023. this.nodes.push( node );
  36024. this.setHashNode( node, node.getHash( this ) );
  36025. }
  36026. }
  36027. /**
  36028. * It is used to add Nodes that will be used as FRAME and RENDER events,
  36029. * and need to follow a certain sequence in the calls to work correctly.
  36030. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  36031. *
  36032. * @param {Node} node - The node to add.
  36033. */
  36034. addSequentialNode( node ) {
  36035. if ( this.sequentialNodes.includes( node ) === false ) {
  36036. this.sequentialNodes.push( node );
  36037. }
  36038. }
  36039. /**
  36040. * Checks the update types of nodes
  36041. */
  36042. buildUpdateNodes() {
  36043. for ( const node of this.nodes ) {
  36044. const updateType = node.getUpdateType();
  36045. if ( updateType !== NodeUpdateType.NONE ) {
  36046. this.updateNodes.push( node );
  36047. }
  36048. }
  36049. for ( const node of this.sequentialNodes ) {
  36050. const updateBeforeType = node.getUpdateBeforeType();
  36051. const updateAfterType = node.getUpdateAfterType();
  36052. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36053. this.updateBeforeNodes.push( node );
  36054. }
  36055. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36056. this.updateAfterNodes.push( node );
  36057. }
  36058. }
  36059. }
  36060. /**
  36061. * A reference the current node which is the
  36062. * last node in the chain of nodes.
  36063. *
  36064. * @type {Node}
  36065. */
  36066. get currentNode() {
  36067. return this.chaining[ this.chaining.length - 1 ];
  36068. }
  36069. /**
  36070. * Whether the given texture is filtered or not.
  36071. *
  36072. * @param {Texture} texture - The texture to check.
  36073. * @return {boolean} Whether the given texture is filtered or not.
  36074. */
  36075. isFilteredTexture( texture ) {
  36076. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36077. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36078. }
  36079. /**
  36080. * Adds the given node to the internal node chain.
  36081. * This is used to check recursive calls in node-graph.
  36082. *
  36083. * @param {Node} node - The node to add.
  36084. */
  36085. addChain( node ) {
  36086. /*
  36087. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36088. warn( 'Recursive node: ', node );
  36089. }
  36090. */
  36091. this.chaining.push( node );
  36092. }
  36093. /**
  36094. * Removes the given node from the internal node chain.
  36095. *
  36096. * @param {Node} node - The node to remove.
  36097. */
  36098. removeChain( node ) {
  36099. const lastChain = this.chaining.pop();
  36100. if ( lastChain !== node ) {
  36101. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36102. }
  36103. }
  36104. /**
  36105. * Returns the native shader method name for a given generic name. E.g.
  36106. * the method name `textureDimensions` matches the WGSL name but must be
  36107. * resolved to `textureSize` in GLSL.
  36108. *
  36109. * @abstract
  36110. * @param {string} method - The method name to resolve.
  36111. * @return {string} The resolved method name.
  36112. */
  36113. getMethod( method ) {
  36114. return method;
  36115. }
  36116. /**
  36117. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  36118. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  36119. *
  36120. * @abstract
  36121. * @param {string} condSnippet - The condition determining which expression gets resolved.
  36122. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  36123. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  36124. * @return {string} The resolved method name.
  36125. */
  36126. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  36127. return null;
  36128. }
  36129. /**
  36130. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  36131. *
  36132. * @param {number} hash - The hash of the node.
  36133. * @return {Node} The found node.
  36134. */
  36135. getNodeFromHash( hash ) {
  36136. return this.hashNodes[ hash ];
  36137. }
  36138. /**
  36139. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  36140. *
  36141. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  36142. * @param {Node} node - The node to add.
  36143. * @return {Node} The node.
  36144. */
  36145. addFlow( shaderStage, node ) {
  36146. this.flowNodes[ shaderStage ].push( node );
  36147. return node;
  36148. }
  36149. /**
  36150. * Sets builder's context.
  36151. *
  36152. * @param {Object} context - The context to set.
  36153. */
  36154. setContext( context ) {
  36155. this.context = context;
  36156. }
  36157. /**
  36158. * Returns the builder's current context.
  36159. *
  36160. * @return {Object} The builder's current context.
  36161. */
  36162. getContext() {
  36163. return this.context;
  36164. }
  36165. /**
  36166. * Adds context data to the builder's current context.
  36167. *
  36168. * @param {Object} context - The context to add.
  36169. * @return {Object} The previous context.
  36170. */
  36171. addContext( context ) {
  36172. const previousContext = this.getContext();
  36173. this.setContext( { ...this.context, ...context } );
  36174. return previousContext;
  36175. }
  36176. /**
  36177. * Gets a context used in shader construction that can be shared across different materials.
  36178. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  36179. *
  36180. * @return {Object} The builder's current context without material.
  36181. */
  36182. getSharedContext() {
  36183. const context = { ...this.context };
  36184. delete context.material;
  36185. delete context.getUV;
  36186. delete context.getOutput;
  36187. delete context.getTextureLevel;
  36188. delete context.getAO;
  36189. delete context.getShadow;
  36190. return context;
  36191. }
  36192. /**
  36193. * Sets builder's cache.
  36194. *
  36195. * @param {NodeCache} cache - The cache to set.
  36196. */
  36197. setCache( cache ) {
  36198. this.cache = cache;
  36199. }
  36200. /**
  36201. * Returns the builder's current cache.
  36202. *
  36203. * @return {NodeCache} The builder's current cache.
  36204. */
  36205. getCache() {
  36206. return this.cache;
  36207. }
  36208. /**
  36209. * Returns a cache for the given node.
  36210. *
  36211. * @param {Node} node - The node.
  36212. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  36213. * @return {NodeCache} The cache.
  36214. */
  36215. getCacheFromNode( node, parent = true ) {
  36216. const data = this.getDataFromNode( node );
  36217. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36218. return data.cache;
  36219. }
  36220. /**
  36221. * Whether the requested feature is available or not.
  36222. *
  36223. * @abstract
  36224. * @param {string} name - The requested feature.
  36225. * @return {boolean} Whether the requested feature is supported or not.
  36226. */
  36227. isAvailable( /*name*/ ) {
  36228. return false;
  36229. }
  36230. /**
  36231. * Returns the vertexIndex input variable as a native shader string.
  36232. *
  36233. * @abstract
  36234. * @return {string} The instanceIndex shader string.
  36235. */
  36236. getVertexIndex() {
  36237. warn( 'Abstract function.' );
  36238. }
  36239. /**
  36240. * Contextually returns either the vertex stage instance index builtin
  36241. * or the linearized index of an compute invocation within a grid of workgroups.
  36242. *
  36243. * @abstract
  36244. * @return {string} The instanceIndex shader string.
  36245. */
  36246. getInstanceIndex() {
  36247. warn( 'Abstract function.' );
  36248. }
  36249. /**
  36250. * Returns the drawIndex input variable as a native shader string.
  36251. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  36252. *
  36253. * @abstract
  36254. * @return {?string} The drawIndex shader string.
  36255. */
  36256. getDrawIndex() {
  36257. warn( 'Abstract function.' );
  36258. }
  36259. /**
  36260. * Returns the frontFacing input variable as a native shader string.
  36261. *
  36262. * @abstract
  36263. * @return {string} The frontFacing shader string.
  36264. */
  36265. getFrontFacing() {
  36266. warn( 'Abstract function.' );
  36267. }
  36268. /**
  36269. * Returns the fragCoord input variable as a native shader string.
  36270. *
  36271. * @abstract
  36272. * @return {string} The fragCoord shader string.
  36273. */
  36274. getFragCoord() {
  36275. warn( 'Abstract function.' );
  36276. }
  36277. /**
  36278. * Whether to flip texture data along its vertical axis or not. WebGL needs
  36279. * this method evaluate to `true`, WebGPU to `false`.
  36280. *
  36281. * @abstract
  36282. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  36283. */
  36284. isFlipY() {
  36285. return false;
  36286. }
  36287. /**
  36288. * Calling this method increases the usage count for the given node by one.
  36289. *
  36290. * @param {Node} node - The node to increase the usage count for.
  36291. * @return {number} The updated usage count.
  36292. */
  36293. increaseUsage( node ) {
  36294. const nodeData = this.getDataFromNode( node );
  36295. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36296. return nodeData.usageCount;
  36297. }
  36298. /**
  36299. * Generates a texture sample shader string for the given texture data.
  36300. *
  36301. * @abstract
  36302. * @param {Texture} texture - The texture.
  36303. * @param {string} textureProperty - The texture property name.
  36304. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36305. * @return {string} The generated shader string.
  36306. */
  36307. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36308. warn( 'Abstract function.' );
  36309. }
  36310. /**
  36311. * Generates a texture LOD shader string for the given texture data.
  36312. *
  36313. * @abstract
  36314. * @param {Texture} texture - The texture.
  36315. * @param {string} textureProperty - The texture property name.
  36316. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  36317. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  36318. * @param {string} levelSnippet - Snippet defining the mip level.
  36319. * @return {string} The generated shader string.
  36320. */
  36321. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  36322. warn( 'Abstract function.' );
  36323. }
  36324. /**
  36325. * Generates the array declaration string.
  36326. *
  36327. * @param {string} type - The type.
  36328. * @param {?number} [count] - The count.
  36329. * @return {string} The generated value as a shader string.
  36330. */
  36331. generateArrayDeclaration( type, count ) {
  36332. return this.getType( type ) + '[ ' + count + ' ]';
  36333. }
  36334. /**
  36335. * Generates the array shader string for the given type and value.
  36336. *
  36337. * @param {string} type - The type.
  36338. * @param {?number} [count] - The count.
  36339. * @param {?Array<Node>} [values=null] - The default values.
  36340. * @return {string} The generated value as a shader string.
  36341. */
  36342. generateArray( type, count, values = null ) {
  36343. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  36344. for ( let i = 0; i < count; i ++ ) {
  36345. const value = values ? values[ i ] : null;
  36346. if ( value !== null ) {
  36347. snippet += value.build( this, type );
  36348. } else {
  36349. snippet += this.generateConst( type );
  36350. }
  36351. if ( i < count - 1 ) snippet += ', ';
  36352. }
  36353. snippet += ' )';
  36354. return snippet;
  36355. }
  36356. /**
  36357. * Generates the struct shader string.
  36358. *
  36359. * @param {string} type - The type.
  36360. * @param {Array<Object>} [membersLayout] - The count.
  36361. * @param {?Array<Node>} [values=null] - The default values.
  36362. * @return {string} The generated value as a shader string.
  36363. */
  36364. generateStruct( type, membersLayout, values = null ) {
  36365. const snippets = [];
  36366. for ( const member of membersLayout ) {
  36367. const { name, type } = member;
  36368. if ( values && values[ name ] && values[ name ].isNode ) {
  36369. snippets.push( values[ name ].build( this, type ) );
  36370. } else {
  36371. snippets.push( this.generateConst( type ) );
  36372. }
  36373. }
  36374. return type + '( ' + snippets.join( ', ' ) + ' )';
  36375. }
  36376. /**
  36377. * Generates the shader string for the given type and value.
  36378. *
  36379. * @param {string} type - The type.
  36380. * @param {?any} [value=null] - The value.
  36381. * @return {string} The generated value as a shader string.
  36382. */
  36383. generateConst( type, value = null ) {
  36384. if ( value === null ) {
  36385. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36386. else if ( type === 'bool' ) value = false;
  36387. else if ( type === 'color' ) value = new Color();
  36388. else if ( type === 'vec2' || type === 'uvec2' || type === 'ivec2' ) value = new Vector2();
  36389. else if ( type === 'vec3' || type === 'uvec3' || type === 'ivec3' ) value = new Vector3();
  36390. else if ( type === 'vec4' || type === 'uvec4' || type === 'ivec4' ) value = new Vector4();
  36391. }
  36392. if ( type === 'float' ) return toFloat( value );
  36393. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36394. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36395. if ( type === 'bool' ) return value ? 'true' : 'false';
  36396. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36397. const typeLength = this.getTypeLength( type );
  36398. const componentType = this.getComponentType( type );
  36399. const generateConst = value => this.generateConst( componentType, value );
  36400. if ( typeLength === 2 ) {
  36401. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36402. } else if ( typeLength === 3 ) {
  36403. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36404. } else if ( typeLength === 4 && type !== 'mat2' ) {
  36405. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36406. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  36407. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36408. } else if ( typeLength > 4 ) {
  36409. return `${ this.getType( type ) }()`;
  36410. }
  36411. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36412. }
  36413. /**
  36414. * It might be necessary to convert certain data types to different ones
  36415. * so this method can be used to hide the conversion.
  36416. *
  36417. * @param {string} type - The type.
  36418. * @return {string} The updated type.
  36419. */
  36420. getType( type ) {
  36421. if ( type === 'color' ) return 'vec3';
  36422. return type;
  36423. }
  36424. /**
  36425. * Whether the given attribute name is defined in the geometry or not.
  36426. *
  36427. * @param {string} name - The attribute name.
  36428. * @return {boolean} Whether the given attribute name is defined in the geometry.
  36429. */
  36430. hasGeometryAttribute( name ) {
  36431. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36432. }
  36433. /**
  36434. * Returns a node attribute for the given name and type.
  36435. *
  36436. * @param {string} name - The attribute's name.
  36437. * @param {string} type - The attribute's type.
  36438. * @return {NodeAttribute} The node attribute.
  36439. */
  36440. getAttribute( name, type ) {
  36441. const attributes = this.attributes;
  36442. // find attribute
  36443. for ( const attribute of attributes ) {
  36444. if ( attribute.name === name ) {
  36445. return attribute;
  36446. }
  36447. }
  36448. // create a new if no exist
  36449. const attribute = new NodeAttribute( name, type );
  36450. this.registerDeclaration( attribute );
  36451. attributes.push( attribute );
  36452. return attribute;
  36453. }
  36454. /**
  36455. * Returns for the given node and shader stage the property name for the shader.
  36456. *
  36457. * @param {Node} node - The node.
  36458. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  36459. * @return {string} The property name.
  36460. */
  36461. getPropertyName( node/*, shaderStage*/ ) {
  36462. return node.name;
  36463. }
  36464. /**
  36465. * Whether the given type is a vector type or not.
  36466. *
  36467. * @param {string} type - The type to check.
  36468. * @return {boolean} Whether the given type is a vector type or not.
  36469. */
  36470. isVector( type ) {
  36471. return /vec\d/.test( type );
  36472. }
  36473. /**
  36474. * Whether the given type is a matrix type or not.
  36475. *
  36476. * @param {string} type - The type to check.
  36477. * @return {boolean} Whether the given type is a matrix type or not.
  36478. */
  36479. isMatrix( type ) {
  36480. return /mat\d/.test( type );
  36481. }
  36482. /**
  36483. * Whether the given type is a reference type or not.
  36484. *
  36485. * @param {string} type - The type to check.
  36486. * @return {boolean} Whether the given type is a reference type or not.
  36487. */
  36488. isReference( type ) {
  36489. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36490. }
  36491. /**
  36492. * Checks if the given texture requires a manual conversion to the working color space.
  36493. *
  36494. * @abstract
  36495. * @param {Texture} texture - The texture to check.
  36496. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  36497. */
  36498. needsToWorkingColorSpace( /*texture*/ ) {
  36499. return false;
  36500. }
  36501. /**
  36502. * Returns the component type of a given texture.
  36503. *
  36504. * @param {Texture} texture - The texture.
  36505. * @return {string} The component type.
  36506. */
  36507. getComponentTypeFromTexture( texture ) {
  36508. const type = texture.type;
  36509. if ( texture.isDataTexture ) {
  36510. if ( type === IntType ) return 'int';
  36511. if ( type === UnsignedIntType ) return 'uint';
  36512. }
  36513. return 'float';
  36514. }
  36515. /**
  36516. * Returns the element type for a given type.
  36517. *
  36518. * @param {string} type - The type.
  36519. * @return {string} The element type.
  36520. */
  36521. getElementType( type ) {
  36522. if ( type === 'mat2' ) return 'vec2';
  36523. if ( type === 'mat3' ) return 'vec3';
  36524. if ( type === 'mat4' ) return 'vec4';
  36525. return this.getComponentType( type );
  36526. }
  36527. /**
  36528. * Returns the component type for a given type.
  36529. *
  36530. * @param {string} type - The type.
  36531. * @return {string} The component type.
  36532. */
  36533. getComponentType( type ) {
  36534. type = this.getVectorType( type );
  36535. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36536. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36537. if ( componentType === null ) return null;
  36538. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36539. if ( componentType[ 1 ] === 'i' ) return 'int';
  36540. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36541. return 'float';
  36542. }
  36543. /**
  36544. * Returns the vector type for a given type.
  36545. *
  36546. * @param {string} type - The type.
  36547. * @return {string} The vector type.
  36548. */
  36549. getVectorType( type ) {
  36550. if ( type === 'color' ) return 'vec3';
  36551. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36552. return type;
  36553. }
  36554. /**
  36555. * Returns the data type for the given the length and component type.
  36556. *
  36557. * @param {number} length - The length.
  36558. * @param {string} [componentType='float'] - The component type.
  36559. * @return {string} The type.
  36560. */
  36561. getTypeFromLength( length, componentType = 'float' ) {
  36562. if ( length === 1 ) return componentType;
  36563. let baseType = getTypeFromLength( length );
  36564. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36565. // fix edge case for mat2x2 being same size as vec4
  36566. if ( /mat2/.test( componentType ) === true ) {
  36567. baseType = baseType.replace( 'vec', 'mat' );
  36568. }
  36569. return prefix + baseType;
  36570. }
  36571. /**
  36572. * Returns the type for a given typed array.
  36573. *
  36574. * @param {TypedArray} array - The typed array.
  36575. * @return {string} The type.
  36576. */
  36577. getTypeFromArray( array ) {
  36578. return typeFromArray.get( array.constructor );
  36579. }
  36580. /**
  36581. * Returns the type is an integer type.
  36582. *
  36583. * @param {string} type - The type.
  36584. * @return {boolean} Whether the type is an integer type or not.
  36585. */
  36586. isInteger( type ) {
  36587. return /int|uint|(i|u)vec/.test( type );
  36588. }
  36589. /**
  36590. * Returns the type for a given buffer attribute.
  36591. *
  36592. * @param {BufferAttribute} attribute - The buffer attribute.
  36593. * @return {string} The type.
  36594. */
  36595. getTypeFromAttribute( attribute ) {
  36596. let dataAttribute = attribute;
  36597. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36598. const array = dataAttribute.array;
  36599. const itemSize = attribute.itemSize;
  36600. const normalized = attribute.normalized;
  36601. let arrayType;
  36602. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36603. arrayType = this.getTypeFromArray( array );
  36604. }
  36605. return this.getTypeFromLength( itemSize, arrayType );
  36606. }
  36607. /**
  36608. * Returns the length for the given data type.
  36609. *
  36610. * @param {string} type - The data type.
  36611. * @return {number} The length.
  36612. */
  36613. getTypeLength( type ) {
  36614. const vecType = this.getVectorType( type );
  36615. const vecNum = /vec([2-4])/.exec( vecType );
  36616. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36617. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36618. if ( /mat2/.test( type ) === true ) return 4;
  36619. if ( /mat3/.test( type ) === true ) return 9;
  36620. if ( /mat4/.test( type ) === true ) return 16;
  36621. return 0;
  36622. }
  36623. /**
  36624. * Returns the vector type for a given matrix type.
  36625. *
  36626. * @param {string} type - The matrix type.
  36627. * @return {string} The vector type.
  36628. */
  36629. getVectorFromMatrix( type ) {
  36630. return type.replace( 'mat', 'vec' );
  36631. }
  36632. /**
  36633. * For a given type this method changes the component type to the
  36634. * given value. E.g. `vec4` should be changed to the new component type
  36635. * `uint` which results in `uvec4`.
  36636. *
  36637. * @param {string} type - The type.
  36638. * @param {string} newComponentType - The new component type.
  36639. * @return {string} The new type.
  36640. */
  36641. changeComponentType( type, newComponentType ) {
  36642. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36643. }
  36644. /**
  36645. * Returns the integer type pendant for the given type.
  36646. *
  36647. * @param {string} type - The type.
  36648. * @return {string} The integer type.
  36649. */
  36650. getIntegerType( type ) {
  36651. const componentType = this.getComponentType( type );
  36652. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36653. return this.changeComponentType( type, 'int' );
  36654. }
  36655. /**
  36656. * Adds an active stack to the internal stack.
  36657. *
  36658. * @param {StackNode} stack - The stack node to add.
  36659. */
  36660. setActiveStack( stack ) {
  36661. this.activeStacks.push( stack );
  36662. }
  36663. /**
  36664. * Removes the active stack from the internal stack.
  36665. *
  36666. * @param {StackNode} stack - The stack node to remove.
  36667. */
  36668. removeActiveStack( stack ) {
  36669. if ( this.activeStacks[ this.activeStacks.length - 1 ] === stack ) {
  36670. this.activeStacks.pop();
  36671. } else {
  36672. throw new Error( 'NodeBuilder: Invalid active stack removal.' );
  36673. }
  36674. }
  36675. /**
  36676. * Returns the active stack.
  36677. *
  36678. * @return {StackNode} The active stack.
  36679. */
  36680. getActiveStack() {
  36681. return this.activeStacks[ this.activeStacks.length - 1 ];
  36682. }
  36683. /**
  36684. * Returns the base stack.
  36685. *
  36686. * @return {StackNode} The base stack.
  36687. */
  36688. getBaseStack() {
  36689. return this.activeStacks[ 0 ];
  36690. }
  36691. /**
  36692. * Adds a stack node to the internal stack.
  36693. *
  36694. * @return {StackNode} The added stack node.
  36695. */
  36696. addStack() {
  36697. this.stack = stack( this.stack );
  36698. const previousStack = getCurrentStack();
  36699. this.stacks.push( previousStack );
  36700. setCurrentStack( this.stack );
  36701. return this.stack;
  36702. }
  36703. /**
  36704. * Removes the last stack node from the internal stack.
  36705. *
  36706. * @return {StackNode} The removed stack node.
  36707. */
  36708. removeStack() {
  36709. const lastStack = this.stack;
  36710. for ( const node of lastStack.nodes ) {
  36711. const nodeData = this.getDataFromNode( node );
  36712. nodeData.stack = lastStack;
  36713. }
  36714. this.stack = lastStack.parent;
  36715. setCurrentStack( this.stacks.pop() );
  36716. return lastStack;
  36717. }
  36718. /**
  36719. * The builder maintains (cached) data for each node during the building process. This method
  36720. * can be used to get these data for a specific shader stage and cache.
  36721. *
  36722. * @param {Node} node - The node to get the data for.
  36723. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36724. * @param {?NodeCache} cache - An optional cache.
  36725. * @return {Object} The node data.
  36726. */
  36727. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36728. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36729. let nodeData = cache.getData( node );
  36730. if ( nodeData === undefined ) {
  36731. nodeData = {};
  36732. cache.setData( node, nodeData );
  36733. }
  36734. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36735. //
  36736. let data = nodeData[ shaderStage ];
  36737. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  36738. const subBuild = this.getClosestSubBuild( subBuilds );
  36739. if ( subBuild ) {
  36740. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  36741. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  36742. data.subBuilds = subBuilds;
  36743. }
  36744. return data;
  36745. }
  36746. /**
  36747. * Returns the properties for the given node and shader stage.
  36748. *
  36749. * Properties are typically used within a build stage to reference a node's
  36750. * child node or nodes manually assigned to the properties in a separate build stage.
  36751. * A typical usage pattern for defining nodes manually would be assigning dependency nodes
  36752. * to the current node's properties in the setup stage and building those properties in the generate stage.
  36753. *
  36754. * @param {Node} node - The node to get the properties for.
  36755. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  36756. * @return {Object} The node properties.
  36757. */
  36758. getNodeProperties( node, shaderStage = 'any' ) {
  36759. const nodeData = this.getDataFromNode( node, shaderStage );
  36760. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36761. }
  36762. /**
  36763. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  36764. *
  36765. * @param {BufferAttributeNode} node - The buffer attribute node.
  36766. * @param {string} type - The node type.
  36767. * @return {NodeAttribute} The node attribute.
  36768. */
  36769. getBufferAttributeFromNode( node, type ) {
  36770. const nodeData = this.getDataFromNode( node, 'vertex' );
  36771. let bufferAttribute = nodeData.bufferAttribute;
  36772. if ( bufferAttribute === undefined ) {
  36773. const index = this.uniforms.index ++;
  36774. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36775. this.bufferAttributes.push( bufferAttribute );
  36776. nodeData.bufferAttribute = bufferAttribute;
  36777. }
  36778. return bufferAttribute;
  36779. }
  36780. /**
  36781. * Returns an instance of {@link StructType} for the given struct name and shader stage
  36782. * or null if not found.
  36783. *
  36784. * @param {string} name - The name of the struct.
  36785. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36786. * @return {?StructType} The struct type or null if not found.
  36787. */
  36788. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  36789. return this.types[ shaderStage ][ name ] || null;
  36790. }
  36791. /**
  36792. * Returns an instance of {@link StructType} for the given output struct node.
  36793. *
  36794. * @param {OutputStructNode} node - The output struct node.
  36795. * @param {Array<Object>} membersLayout - The output struct types.
  36796. * @param {?string} [name=null] - The name of the struct.
  36797. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36798. * @return {StructType} The struct type attribute.
  36799. */
  36800. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  36801. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36802. let structType = nodeData.structType;
  36803. if ( structType === undefined ) {
  36804. const index = this.structs.index ++;
  36805. if ( name === null ) name = 'StructType' + index;
  36806. structType = new StructType( name, membersLayout );
  36807. this.structs[ shaderStage ].push( structType );
  36808. this.types[ shaderStage ][ name ] = node;
  36809. nodeData.structType = structType;
  36810. }
  36811. return structType;
  36812. }
  36813. /**
  36814. * Returns an instance of {@link StructType} for the given output struct node.
  36815. *
  36816. * @param {OutputStructNode} node - The output struct node.
  36817. * @param {Array<Object>} membersLayout - The output struct types.
  36818. * @return {StructType} The struct type attribute.
  36819. */
  36820. getOutputStructTypeFromNode( node, membersLayout ) {
  36821. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  36822. structType.output = true;
  36823. return structType;
  36824. }
  36825. /**
  36826. * Returns an instance of {@link NodeUniform} for the given uniform node.
  36827. *
  36828. * @param {UniformNode} node - The uniform node.
  36829. * @param {string} type - The uniform type.
  36830. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36831. * @param {?string} name - The name of the uniform.
  36832. * @return {NodeUniform} The node uniform.
  36833. */
  36834. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36835. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36836. let nodeUniform = nodeData.uniform;
  36837. if ( nodeUniform === undefined ) {
  36838. const index = this.uniforms.index ++;
  36839. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36840. this.uniforms[ shaderStage ].push( nodeUniform );
  36841. this.registerDeclaration( nodeUniform );
  36842. nodeData.uniform = nodeUniform;
  36843. }
  36844. return nodeUniform;
  36845. }
  36846. /**
  36847. * Returns an instance of {@link NodeVar} for the given variable node.
  36848. *
  36849. * @param {VarNode} node - The variable node.
  36850. * @param {?string} name - The variable's name.
  36851. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  36852. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36853. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  36854. *
  36855. * @return {NodeVar} The node variable.
  36856. */
  36857. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  36858. const nodeData = this.getDataFromNode( node, shaderStage );
  36859. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  36860. let nodeVar = nodeData[ subBuildVariable ];
  36861. if ( nodeVar === undefined ) {
  36862. const idNS = readOnly ? '_const' : '_var';
  36863. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36864. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  36865. if ( name === null ) {
  36866. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  36867. this.vars[ idNS ] ++;
  36868. }
  36869. //
  36870. if ( subBuildVariable !== 'variable' ) {
  36871. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36872. }
  36873. //
  36874. const count = node.getArrayCount( this );
  36875. nodeVar = new NodeVar( name, type, readOnly, count );
  36876. if ( ! readOnly ) {
  36877. vars.push( nodeVar );
  36878. }
  36879. this.registerDeclaration( nodeVar );
  36880. nodeData[ subBuildVariable ] = nodeVar;
  36881. }
  36882. return nodeVar;
  36883. }
  36884. /**
  36885. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  36886. *
  36887. * @param {Node} node - The varying node.
  36888. * @return {boolean} Returns true if deterministic.
  36889. */
  36890. isDeterministic( node ) {
  36891. if ( node.isMathNode ) {
  36892. return this.isDeterministic( node.aNode ) &&
  36893. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  36894. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  36895. } else if ( node.isOperatorNode ) {
  36896. return this.isDeterministic( node.aNode ) &&
  36897. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  36898. } else if ( node.isArrayNode ) {
  36899. if ( node.values !== null ) {
  36900. for ( const n of node.values ) {
  36901. if ( ! this.isDeterministic( n ) ) {
  36902. return false;
  36903. }
  36904. }
  36905. }
  36906. return true;
  36907. } else if ( node.isConstNode ) {
  36908. return true;
  36909. }
  36910. return false;
  36911. }
  36912. /**
  36913. * Returns an instance of {@link NodeVarying} for the given varying node.
  36914. *
  36915. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  36916. * @param {?string} name - The varying's name.
  36917. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  36918. * @param {?string} interpolationType - The interpolation type of the varying.
  36919. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  36920. * @return {NodeVar} The node varying.
  36921. */
  36922. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  36923. const nodeData = this.getDataFromNode( node, 'any' );
  36924. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  36925. let nodeVarying = nodeData[ subBuildVarying ];
  36926. if ( nodeVarying === undefined ) {
  36927. const varyings = this.varyings;
  36928. const index = varyings.length;
  36929. if ( name === null ) name = 'nodeVarying' + index;
  36930. //
  36931. if ( subBuildVarying !== 'varying' ) {
  36932. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  36933. }
  36934. //
  36935. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  36936. varyings.push( nodeVarying );
  36937. this.registerDeclaration( nodeVarying );
  36938. nodeData[ subBuildVarying ] = nodeVarying;
  36939. }
  36940. return nodeVarying;
  36941. }
  36942. /**
  36943. * Registers a node declaration in the current shader stage.
  36944. *
  36945. * @param {Object} node - The node to be registered.
  36946. */
  36947. registerDeclaration( node ) {
  36948. const shaderStage = this.shaderStage;
  36949. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  36950. const property = this.getPropertyName( node );
  36951. let index = 1;
  36952. let name = property;
  36953. // Automatically renames the property if the name is already in use.
  36954. while ( declarations[ name ] !== undefined ) {
  36955. name = property + '_' + index ++;
  36956. }
  36957. if ( index > 1 ) {
  36958. node.name = name;
  36959. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  36960. }
  36961. declarations[ name ] = node;
  36962. }
  36963. /**
  36964. * Returns an instance of {@link NodeCode} for the given code node.
  36965. *
  36966. * @param {CodeNode} node - The code node.
  36967. * @param {string} type - The node type.
  36968. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  36969. * @return {NodeCode} The node code.
  36970. */
  36971. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36972. const nodeData = this.getDataFromNode( node );
  36973. let nodeCode = nodeData.code;
  36974. if ( nodeCode === undefined ) {
  36975. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36976. const index = codes.length;
  36977. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36978. codes.push( nodeCode );
  36979. nodeData.code = nodeCode;
  36980. }
  36981. return nodeCode;
  36982. }
  36983. /**
  36984. * Adds a code flow based on the code-block hierarchy.
  36985. * This is used so that code-blocks like If,Else create their variables locally if the Node
  36986. * is only used inside one of these conditionals in the current shader stage.
  36987. *
  36988. * @param {Node} node - The node to add.
  36989. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  36990. */
  36991. addFlowCodeHierarchy( node, nodeBlock ) {
  36992. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36993. let needsFlowCode = true;
  36994. let nodeBlockHierarchy = nodeBlock;
  36995. while ( nodeBlockHierarchy ) {
  36996. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36997. needsFlowCode = false;
  36998. break;
  36999. }
  37000. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  37001. }
  37002. if ( needsFlowCode ) {
  37003. for ( const flowCode of flowCodes ) {
  37004. this.addLineFlowCode( flowCode );
  37005. }
  37006. }
  37007. }
  37008. /**
  37009. * Add a inline-code to the current flow code-block.
  37010. *
  37011. * @param {Node} node - The node to add.
  37012. * @param {string} code - The code to add.
  37013. * @param {Node} nodeBlock - Current ConditionalNode
  37014. */
  37015. addLineFlowCodeBlock( node, code, nodeBlock ) {
  37016. const nodeData = this.getDataFromNode( node );
  37017. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  37018. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  37019. flowCodes.push( code );
  37020. codeBlock.set( nodeBlock, true );
  37021. }
  37022. /**
  37023. * Add a inline-code to the current flow.
  37024. *
  37025. * @param {string} code - The code to add.
  37026. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  37027. * @return {NodeBuilder} A reference to this node builder.
  37028. */
  37029. addLineFlowCode( code, node = null ) {
  37030. if ( code === '' ) return this;
  37031. if ( node !== null && this.context.nodeBlock ) {
  37032. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  37033. }
  37034. code = this.tab + code;
  37035. if ( ! /;\s*$/.test( code ) ) {
  37036. code = code + ';\n';
  37037. }
  37038. this.flow.code += code;
  37039. return this;
  37040. }
  37041. /**
  37042. * Adds a code to the current code flow.
  37043. *
  37044. * @param {string} code - Shader code.
  37045. * @return {NodeBuilder} A reference to this node builder.
  37046. */
  37047. addFlowCode( code ) {
  37048. this.flow.code += code;
  37049. return this;
  37050. }
  37051. /**
  37052. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  37053. * Typically used in codes with If,Else.
  37054. *
  37055. * @return {NodeBuilder} A reference to this node builder.
  37056. */
  37057. addFlowTab() {
  37058. this.tab += '\t';
  37059. return this;
  37060. }
  37061. /**
  37062. * Removes a tab.
  37063. *
  37064. * @return {NodeBuilder} A reference to this node builder.
  37065. */
  37066. removeFlowTab() {
  37067. this.tab = this.tab.slice( 0, -1 );
  37068. return this;
  37069. }
  37070. /**
  37071. * Gets the current flow data based on a Node.
  37072. *
  37073. * @param {Node} node - Node that the flow was started.
  37074. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37075. * @return {Object} The flow data.
  37076. */
  37077. getFlowData( node/*, shaderStage*/ ) {
  37078. return this.flowsData.get( node );
  37079. }
  37080. /**
  37081. * Executes the node flow based on a root node to generate the final shader code.
  37082. *
  37083. * @param {Node} node - The node to execute.
  37084. * @return {Object} The code flow.
  37085. */
  37086. flowNode( node ) {
  37087. const output = node.getNodeType( this );
  37088. const flowData = this.flowChildNode( node, output );
  37089. this.flowsData.set( node, flowData );
  37090. return flowData;
  37091. }
  37092. /**
  37093. * Includes a node in the current function node.
  37094. *
  37095. * @param {Node} node - The node to include.
  37096. * @returns {void}
  37097. */
  37098. addInclude( node ) {
  37099. if ( this.currentFunctionNode !== null ) {
  37100. this.currentFunctionNode.includes.push( node );
  37101. }
  37102. }
  37103. /**
  37104. * Returns the native shader operator name for a given generic name.
  37105. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37106. *
  37107. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  37108. * @return {FunctionNode} The build function node.
  37109. */
  37110. buildFunctionNode( shaderNode ) {
  37111. const fn = new FunctionNode();
  37112. const previous = this.currentFunctionNode;
  37113. this.currentFunctionNode = fn;
  37114. fn.code = this.buildFunctionCode( shaderNode );
  37115. this.currentFunctionNode = previous;
  37116. return fn;
  37117. }
  37118. /**
  37119. * Generates a code flow based on a TSL function: Fn().
  37120. *
  37121. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  37122. * @return {Object}
  37123. */
  37124. flowShaderNode( shaderNode ) {
  37125. const layout = shaderNode.layout;
  37126. const inputs = {
  37127. [ Symbol.iterator ]() {
  37128. let index = 0;
  37129. const values = Object.values( this );
  37130. return {
  37131. next: () => ( {
  37132. value: values[ index ],
  37133. done: index ++ >= values.length
  37134. } )
  37135. };
  37136. }
  37137. };
  37138. for ( const input of layout.inputs ) {
  37139. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  37140. }
  37141. //
  37142. shaderNode.layout = null;
  37143. const callNode = shaderNode.call( inputs );
  37144. const flowData = this.flowStagesNode( callNode, layout.type );
  37145. shaderNode.layout = layout;
  37146. return flowData;
  37147. }
  37148. /**
  37149. * Executes the node in a specific build stage.
  37150. *
  37151. * This function can be used to arbitrarily execute the specified build stage
  37152. * outside of the standard build process. For instance, if a node's type depends
  37153. * on properties created by the 'setup' stage, then flowBuildStage(node, 'setup')
  37154. * can be used to execute the setup build stage and access its generated nodes
  37155. * before the standard build process begins.
  37156. *
  37157. * @param {Node} node - The node to execute.
  37158. * @param {string} buildStage - The build stage to execute the node in.
  37159. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  37160. * @return {?(Node|string)} The result of the node build.
  37161. */
  37162. flowBuildStage( node, buildStage, output = null ) {
  37163. const previousBuildStage = this.getBuildStage();
  37164. this.setBuildStage( buildStage );
  37165. const result = node.build( this, output );
  37166. this.setBuildStage( previousBuildStage );
  37167. return result;
  37168. }
  37169. /**
  37170. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  37171. *
  37172. * @param {Node} node - The node to execute.
  37173. * @param {?string} output - Expected output type. For example 'vec3'.
  37174. * @return {Object}
  37175. */
  37176. flowStagesNode( node, output = null ) {
  37177. const previousFlow = this.flow;
  37178. const previousVars = this.vars;
  37179. const previousDeclarations = this.declarations;
  37180. const previousCache = this.cache;
  37181. const previousBuildStage = this.buildStage;
  37182. const previousStack = this.stack;
  37183. const flow = {
  37184. code: ''
  37185. };
  37186. this.flow = flow;
  37187. this.vars = {};
  37188. this.declarations = {};
  37189. this.cache = new NodeCache();
  37190. this.stack = stack();
  37191. for ( const buildStage of defaultBuildStages ) {
  37192. this.setBuildStage( buildStage );
  37193. flow.result = node.build( this, output );
  37194. }
  37195. flow.vars = this.getVars( this.shaderStage );
  37196. this.flow = previousFlow;
  37197. this.vars = previousVars;
  37198. this.declarations = previousDeclarations;
  37199. this.cache = previousCache;
  37200. this.stack = previousStack;
  37201. this.setBuildStage( previousBuildStage );
  37202. return flow;
  37203. }
  37204. /**
  37205. * Returns the native shader operator name for a given generic name.
  37206. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  37207. *
  37208. * @abstract
  37209. * @param {string} op - The operator name to resolve.
  37210. * @return {?string} The resolved operator name.
  37211. */
  37212. getFunctionOperator( /* op */ ) {
  37213. return null;
  37214. }
  37215. /**
  37216. * Builds the given shader node.
  37217. *
  37218. * @abstract
  37219. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37220. * @return {string} The function code.
  37221. */
  37222. buildFunctionCode( /* shaderNode */ ) {
  37223. warn( 'Abstract function.' );
  37224. }
  37225. /**
  37226. * Generates a code flow based on a child Node.
  37227. *
  37228. * @param {Node} node - The node to execute.
  37229. * @param {?string} output - Expected output type. For example 'vec3'.
  37230. * @return {Object} The code flow.
  37231. */
  37232. flowChildNode( node, output = null ) {
  37233. const previousFlow = this.flow;
  37234. const flow = {
  37235. code: ''
  37236. };
  37237. this.flow = flow;
  37238. flow.result = node.build( this, output );
  37239. this.flow = previousFlow;
  37240. return flow;
  37241. }
  37242. /**
  37243. * Executes a flow of code in a different stage.
  37244. *
  37245. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  37246. * return the value in fragment-stage even if it is being executed in an input fragment.
  37247. *
  37248. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37249. * @param {Node} node - The node to execute.
  37250. * @param {?string} output - Expected output type. For example 'vec3'.
  37251. * @param {?string} propertyName - The property name to assign the result.
  37252. * @return {?(Object|Node)} The code flow or node.build() result.
  37253. */
  37254. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  37255. const previousTab = this.tab;
  37256. const previousCache = this.cache;
  37257. const previousShaderStage = this.shaderStage;
  37258. const previousContext = this.context;
  37259. this.setShaderStage( shaderStage );
  37260. const context = { ...this.context };
  37261. delete context.nodeBlock;
  37262. this.cache = this.globalCache;
  37263. this.tab = '\t';
  37264. this.context = context;
  37265. let result = null;
  37266. if ( this.buildStage === 'generate' ) {
  37267. const flowData = this.flowChildNode( node, output );
  37268. if ( propertyName !== null ) {
  37269. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  37270. }
  37271. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  37272. result = flowData;
  37273. } else {
  37274. result = node.build( this );
  37275. }
  37276. this.setShaderStage( previousShaderStage );
  37277. this.cache = previousCache;
  37278. this.tab = previousTab;
  37279. this.context = previousContext;
  37280. return result;
  37281. }
  37282. /**
  37283. * Returns an array holding all node attributes of this node builder.
  37284. *
  37285. * @return {Array<NodeAttribute>} The node attributes of this builder.
  37286. */
  37287. getAttributesArray() {
  37288. return this.attributes.concat( this.bufferAttributes );
  37289. }
  37290. /**
  37291. * Returns the attribute definitions as a shader string for the given shader stage.
  37292. *
  37293. * @abstract
  37294. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37295. * @return {string} The attribute code section.
  37296. */
  37297. getAttributes( /*shaderStage*/ ) {
  37298. warn( 'Abstract function.' );
  37299. }
  37300. /**
  37301. * Returns the varying definitions as a shader string for the given shader stage.
  37302. *
  37303. * @abstract
  37304. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37305. * @return {string} The varying code section.
  37306. */
  37307. getVaryings( /*shaderStage*/ ) {
  37308. warn( 'Abstract function.' );
  37309. }
  37310. /**
  37311. * Returns a single variable definition as a shader string for the given variable type and name.
  37312. *
  37313. * @param {string} type - The variable's type.
  37314. * @param {string} name - The variable's name.
  37315. * @param {?number} [count=null] - The array length.
  37316. * @return {string} The shader string.
  37317. */
  37318. getVar( type, name, count = null ) {
  37319. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  37320. }
  37321. /**
  37322. * Returns the variable definitions as a shader string for the given shader stage.
  37323. *
  37324. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37325. * @return {string} The variable code section.
  37326. */
  37327. getVars( shaderStage ) {
  37328. let snippet = '';
  37329. const vars = this.vars[ shaderStage ];
  37330. if ( vars !== undefined ) {
  37331. for ( const variable of vars ) {
  37332. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  37333. }
  37334. }
  37335. return snippet;
  37336. }
  37337. /**
  37338. * Returns the uniform definitions as a shader string for the given shader stage.
  37339. *
  37340. * @abstract
  37341. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37342. * @return {string} The uniform code section.
  37343. */
  37344. getUniforms( /*shaderStage*/ ) {
  37345. warn( 'Abstract function.' );
  37346. }
  37347. /**
  37348. * Returns the native code definitions as a shader string for the given shader stage.
  37349. *
  37350. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  37351. * @return {string} The native code section.
  37352. */
  37353. getCodes( shaderStage ) {
  37354. const codes = this.codes[ shaderStage ];
  37355. let code = '';
  37356. if ( codes !== undefined ) {
  37357. for ( const nodeCode of codes ) {
  37358. code += nodeCode.code + '\n';
  37359. }
  37360. }
  37361. return code;
  37362. }
  37363. /**
  37364. * Returns the hash of this node builder.
  37365. *
  37366. * @return {string} The hash.
  37367. */
  37368. getHash() {
  37369. return this.vertexShader + this.fragmentShader + this.computeShader;
  37370. }
  37371. /**
  37372. * Sets the current shader stage.
  37373. *
  37374. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  37375. */
  37376. setShaderStage( shaderStage ) {
  37377. this.shaderStage = shaderStage;
  37378. }
  37379. /**
  37380. * Returns the current shader stage.
  37381. *
  37382. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  37383. */
  37384. getShaderStage() {
  37385. return this.shaderStage;
  37386. }
  37387. /**
  37388. * Sets the current build stage.
  37389. *
  37390. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  37391. */
  37392. setBuildStage( buildStage ) {
  37393. this.buildStage = buildStage;
  37394. }
  37395. /**
  37396. * Returns the current build stage.
  37397. *
  37398. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  37399. */
  37400. getBuildStage() {
  37401. return this.buildStage;
  37402. }
  37403. /**
  37404. * Controls the code build of the shader stages.
  37405. *
  37406. * @abstract
  37407. */
  37408. buildCode() {
  37409. warn( 'Abstract function.' );
  37410. }
  37411. /**
  37412. * Returns the current sub-build layer.
  37413. *
  37414. * @return {SubBuildNode} The current sub-build layers.
  37415. */
  37416. get subBuild() {
  37417. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  37418. }
  37419. /**
  37420. * Adds a sub-build layer to the node builder.
  37421. *
  37422. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  37423. */
  37424. addSubBuild( subBuild ) {
  37425. this.subBuildLayers.push( subBuild );
  37426. }
  37427. /**
  37428. * Removes the last sub-build layer from the node builder.
  37429. *
  37430. * @return {SubBuildNode} The removed sub-build layer.
  37431. */
  37432. removeSubBuild() {
  37433. return this.subBuildLayers.pop();
  37434. }
  37435. /**
  37436. * Returns the closest sub-build layer for the given data.
  37437. *
  37438. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  37439. * @return {?string} The closest sub-build name or null if none found.
  37440. */
  37441. getClosestSubBuild( data ) {
  37442. let subBuilds;
  37443. if ( data && data.isNode ) {
  37444. if ( data.isShaderCallNodeInternal ) {
  37445. subBuilds = data.shaderNode.subBuilds;
  37446. } else if ( data.isStackNode ) {
  37447. subBuilds = [ data.subBuild ];
  37448. } else {
  37449. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  37450. }
  37451. } else if ( data instanceof Set ) {
  37452. subBuilds = [ ...data ];
  37453. } else {
  37454. subBuilds = data;
  37455. }
  37456. if ( ! subBuilds ) return null;
  37457. const subBuildLayers = this.subBuildLayers;
  37458. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  37459. const subBuild = subBuilds[ i ];
  37460. if ( subBuildLayers.includes( subBuild ) ) {
  37461. return subBuild;
  37462. }
  37463. }
  37464. return null;
  37465. }
  37466. /**
  37467. * Returns the output node of a sub-build layer.
  37468. *
  37469. * @param {Node} node - The node to get the output from.
  37470. * @return {string} The output node name.
  37471. */
  37472. getSubBuildOutput( node ) {
  37473. return this.getSubBuildProperty( 'outputNode', node );
  37474. }
  37475. /**
  37476. * Returns the sub-build property name for the given property and node.
  37477. *
  37478. * @param {string} [property=''] - The property name.
  37479. * @param {?Node} [node=null] - The node to get the sub-build from.
  37480. * @return {string} The sub-build property name.
  37481. */
  37482. getSubBuildProperty( property = '', node = null ) {
  37483. let subBuild;
  37484. if ( node !== null ) {
  37485. subBuild = this.getClosestSubBuild( node );
  37486. } else {
  37487. subBuild = this.subBuildFn;
  37488. }
  37489. let result;
  37490. if ( subBuild ) {
  37491. result = property ? ( subBuild + '_' + property ) : subBuild;
  37492. } else {
  37493. result = property;
  37494. }
  37495. return result;
  37496. }
  37497. /**
  37498. * Central build method which controls the build for the given object.
  37499. *
  37500. * @return {NodeBuilder} A reference to this node builder.
  37501. */
  37502. build() {
  37503. const { object, material, renderer } = this;
  37504. if ( material !== null ) {
  37505. let nodeMaterial = renderer.library.fromMaterial( material );
  37506. if ( nodeMaterial === null ) {
  37507. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  37508. nodeMaterial = new NodeMaterial();
  37509. }
  37510. nodeMaterial.build( this );
  37511. } else {
  37512. this.addFlow( 'compute', object );
  37513. }
  37514. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  37515. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  37516. // generate() -> stage 3: generate shader
  37517. for ( const buildStage of defaultBuildStages ) {
  37518. this.setBuildStage( buildStage );
  37519. if ( this.context.position && this.context.position.isNode ) {
  37520. this.flowNodeFromShaderStage( 'vertex', this.context.position );
  37521. }
  37522. for ( const shaderStage of shaderStages ) {
  37523. this.setShaderStage( shaderStage );
  37524. const flowNodes = this.flowNodes[ shaderStage ];
  37525. for ( const node of flowNodes ) {
  37526. if ( buildStage === 'generate' ) {
  37527. this.flowNode( node );
  37528. } else {
  37529. node.build( this );
  37530. }
  37531. }
  37532. }
  37533. }
  37534. this.setBuildStage( null );
  37535. this.setShaderStage( null );
  37536. // stage 4: build code for a specific output
  37537. this.buildCode();
  37538. this.buildUpdateNodes();
  37539. return this;
  37540. }
  37541. /**
  37542. * Returns shared data object for the given node.
  37543. *
  37544. * @param {Node} node - The node to get shared data from.
  37545. * @return {Object} The shared data.
  37546. */
  37547. getSharedDataFromNode( node ) {
  37548. let data = sharedNodeData.get( node );
  37549. if ( data === undefined ) {
  37550. data = {};
  37551. }
  37552. return data;
  37553. }
  37554. /**
  37555. * Returns a uniform representation which is later used for UBO generation and rendering.
  37556. *
  37557. * @param {NodeUniform} uniformNode - The uniform node.
  37558. * @param {string} type - The requested type.
  37559. * @return {Uniform} The uniform.
  37560. */
  37561. getNodeUniform( uniformNode, type ) {
  37562. const nodeData = this.getSharedDataFromNode( uniformNode );
  37563. let node = nodeData.cache;
  37564. if ( node === undefined ) {
  37565. if ( type === 'float' || type === 'int' || type === 'uint' ) node = new NumberNodeUniform( uniformNode );
  37566. else if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) node = new Vector2NodeUniform( uniformNode );
  37567. else if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) node = new Vector3NodeUniform( uniformNode );
  37568. else if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) node = new Vector4NodeUniform( uniformNode );
  37569. else if ( type === 'color' ) node = new ColorNodeUniform( uniformNode );
  37570. else if ( type === 'mat2' ) node = new Matrix2NodeUniform( uniformNode );
  37571. else if ( type === 'mat3' ) node = new Matrix3NodeUniform( uniformNode );
  37572. else if ( type === 'mat4' ) node = new Matrix4NodeUniform( uniformNode );
  37573. else {
  37574. throw new Error( `Uniform "${ type }" not implemented.` );
  37575. }
  37576. nodeData.cache = node;
  37577. }
  37578. return node;
  37579. }
  37580. /**
  37581. * Formats the given shader snippet from a given type into another one. E.g.
  37582. * this method might be used to convert a simple float string `"1.0"` into a
  37583. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  37584. *
  37585. * @param {string} snippet - The shader snippet.
  37586. * @param {string} fromType - The source type.
  37587. * @param {string} toType - The target type.
  37588. * @return {string} The updated shader string.
  37589. */
  37590. format( snippet, fromType, toType ) {
  37591. fromType = this.getVectorType( fromType );
  37592. toType = this.getVectorType( toType );
  37593. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  37594. return snippet;
  37595. }
  37596. const fromTypeLength = this.getTypeLength( fromType );
  37597. const toTypeLength = this.getTypeLength( toType );
  37598. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  37599. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  37600. }
  37601. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  37602. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  37603. }
  37604. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  37605. // @TODO: ignore for now
  37606. return snippet;
  37607. }
  37608. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  37609. // @TODO: ignore for now
  37610. return snippet;
  37611. }
  37612. if ( fromTypeLength === toTypeLength ) {
  37613. return `${ this.getType( toType ) }( ${ snippet } )`;
  37614. }
  37615. if ( fromTypeLength > toTypeLength ) {
  37616. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  37617. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  37618. }
  37619. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  37620. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  37621. }
  37622. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  37623. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  37624. }
  37625. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  37626. // convert a number value to vector type, e.g:
  37627. // vec3( 1u ) -> vec3( float( 1u ) )
  37628. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  37629. }
  37630. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  37631. }
  37632. /**
  37633. * Returns a signature with the engine's current revision.
  37634. *
  37635. * @return {string} The signature.
  37636. */
  37637. getSignature() {
  37638. return `// Three.js r${ REVISION } - Node System\n`;
  37639. }
  37640. /**
  37641. * Returns `true` if data from the previous frame are required. Relevant
  37642. * when computing motion vectors with {@link VelocityNode}.
  37643. *
  37644. * @return {boolean} Whether data from the previous frame are required or not.
  37645. */
  37646. needsPreviousData() {
  37647. const mrt = this.renderer.getMRT();
  37648. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( this.object ).useVelocity === true;
  37649. }
  37650. }
  37651. /**
  37652. * Management class for updating nodes. The module tracks metrics like
  37653. * the elapsed time, delta time, the render and frame ID to correctly
  37654. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  37655. * and {@link Node#updateAfter} depending on the node's configuration.
  37656. */
  37657. class NodeFrame {
  37658. /**
  37659. * Constructs a new node fame.
  37660. */
  37661. constructor() {
  37662. /**
  37663. * The elapsed time in seconds.
  37664. *
  37665. * @type {number}
  37666. * @default 0
  37667. */
  37668. this.time = 0;
  37669. /**
  37670. * The delta time in seconds.
  37671. *
  37672. * @type {number}
  37673. * @default 0
  37674. */
  37675. this.deltaTime = 0;
  37676. /**
  37677. * The frame ID.
  37678. *
  37679. * @type {number}
  37680. * @default 0
  37681. */
  37682. this.frameId = 0;
  37683. /**
  37684. * The render ID.
  37685. *
  37686. * @type {number}
  37687. * @default 0
  37688. */
  37689. this.renderId = 0;
  37690. /**
  37691. * Used to control the {@link Node#update} call.
  37692. *
  37693. * @type {WeakMap<Node, Object>}
  37694. */
  37695. this.updateMap = new WeakMap();
  37696. /**
  37697. * Used to control the {@link Node#updateBefore} call.
  37698. *
  37699. * @type {WeakMap<Node, Object>}
  37700. */
  37701. this.updateBeforeMap = new WeakMap();
  37702. /**
  37703. * Used to control the {@link Node#updateAfter} call.
  37704. *
  37705. * @type {WeakMap<Node, Object>}
  37706. */
  37707. this.updateAfterMap = new WeakMap();
  37708. /**
  37709. * A reference to the current renderer.
  37710. *
  37711. * @type {?Renderer}
  37712. * @default null
  37713. */
  37714. this.renderer = null;
  37715. /**
  37716. * A reference to the current material.
  37717. *
  37718. * @type {?Material}
  37719. * @default null
  37720. */
  37721. this.material = null;
  37722. /**
  37723. * A reference to the current camera.
  37724. *
  37725. * @type {?Camera}
  37726. * @default null
  37727. */
  37728. this.camera = null;
  37729. /**
  37730. * A reference to the current 3D object.
  37731. *
  37732. * @type {?Object3D}
  37733. * @default null
  37734. */
  37735. this.object = null;
  37736. /**
  37737. * A reference to the current scene.
  37738. *
  37739. * @type {?Scene}
  37740. * @default null
  37741. */
  37742. this.scene = null;
  37743. }
  37744. /**
  37745. * Returns a dictionary for a given node and update map which
  37746. * is used to correctly call node update methods per frame or render.
  37747. *
  37748. * @private
  37749. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  37750. * @param {Node} nodeRef - The reference to the current node.
  37751. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  37752. */
  37753. _getMaps( referenceMap, nodeRef ) {
  37754. let maps = referenceMap.get( nodeRef );
  37755. if ( maps === undefined ) {
  37756. maps = {
  37757. renderId: 0,
  37758. frameId: 0,
  37759. };
  37760. referenceMap.set( nodeRef, maps );
  37761. }
  37762. return maps;
  37763. }
  37764. /**
  37765. * This method executes the {@link Node#updateBefore} for the given node.
  37766. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  37767. * is only executed once per frame, render or object depending on the update
  37768. * type.
  37769. *
  37770. * @param {Node} node - The node that should be updated.
  37771. */
  37772. updateBeforeNode( node ) {
  37773. const updateType = node.getUpdateBeforeType();
  37774. const reference = node.updateReference( this );
  37775. if ( updateType === NodeUpdateType.FRAME ) {
  37776. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37777. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  37778. const previousFrameId = nodeUpdateBeforeMap.frameId;
  37779. nodeUpdateBeforeMap.frameId = this.frameId;
  37780. if ( node.updateBefore( this ) === false ) {
  37781. nodeUpdateBeforeMap.frameId = previousFrameId;
  37782. }
  37783. }
  37784. } else if ( updateType === NodeUpdateType.RENDER ) {
  37785. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  37786. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  37787. const previousRenderId = nodeUpdateBeforeMap.renderId;
  37788. nodeUpdateBeforeMap.renderId = this.renderId;
  37789. if ( node.updateBefore( this ) === false ) {
  37790. nodeUpdateBeforeMap.renderId = previousRenderId;
  37791. }
  37792. }
  37793. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37794. node.updateBefore( this );
  37795. }
  37796. }
  37797. /**
  37798. * This method executes the {@link Node#updateAfter} for the given node.
  37799. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  37800. * is only executed once per frame, render or object depending on the update
  37801. * type.
  37802. *
  37803. * @param {Node} node - The node that should be updated.
  37804. */
  37805. updateAfterNode( node ) {
  37806. const updateType = node.getUpdateAfterType();
  37807. const reference = node.updateReference( this );
  37808. if ( updateType === NodeUpdateType.FRAME ) {
  37809. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37810. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  37811. if ( node.updateAfter( this ) !== false ) {
  37812. nodeUpdateAfterMap.frameId = this.frameId;
  37813. }
  37814. }
  37815. } else if ( updateType === NodeUpdateType.RENDER ) {
  37816. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  37817. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  37818. if ( node.updateAfter( this ) !== false ) {
  37819. nodeUpdateAfterMap.renderId = this.renderId;
  37820. }
  37821. }
  37822. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37823. node.updateAfter( this );
  37824. }
  37825. }
  37826. /**
  37827. * This method executes the {@link Node#update} for the given node.
  37828. * It makes sure {@link Node#updateType} is honored meaning the update
  37829. * is only executed once per frame, render or object depending on the update
  37830. * type.
  37831. *
  37832. * @param {Node} node - The node that should be updated.
  37833. */
  37834. updateNode( node ) {
  37835. const updateType = node.getUpdateType();
  37836. const reference = node.updateReference( this );
  37837. if ( updateType === NodeUpdateType.FRAME ) {
  37838. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37839. if ( nodeUpdateMap.frameId !== this.frameId ) {
  37840. if ( node.update( this ) !== false ) {
  37841. nodeUpdateMap.frameId = this.frameId;
  37842. }
  37843. }
  37844. } else if ( updateType === NodeUpdateType.RENDER ) {
  37845. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  37846. if ( nodeUpdateMap.renderId !== this.renderId ) {
  37847. if ( node.update( this ) !== false ) {
  37848. nodeUpdateMap.renderId = this.renderId;
  37849. }
  37850. }
  37851. } else if ( updateType === NodeUpdateType.OBJECT ) {
  37852. node.update( this );
  37853. }
  37854. }
  37855. /**
  37856. * Updates the internal state of the node frame. This method is
  37857. * called by the renderer in its internal animation loop.
  37858. */
  37859. update() {
  37860. this.frameId ++;
  37861. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  37862. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  37863. this.lastTime = performance.now();
  37864. this.time += this.deltaTime;
  37865. }
  37866. }
  37867. /**
  37868. * Describes the input of a {@link NodeFunction}.
  37869. */
  37870. class NodeFunctionInput {
  37871. /**
  37872. * Constructs a new node function input.
  37873. *
  37874. * @param {string} type - The input type.
  37875. * @param {string} name - The input name.
  37876. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  37877. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  37878. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  37879. */
  37880. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  37881. /**
  37882. * The input type.
  37883. *
  37884. * @type {string}
  37885. */
  37886. this.type = type;
  37887. /**
  37888. * The input name.
  37889. *
  37890. * @type {string}
  37891. */
  37892. this.name = name;
  37893. /**
  37894. * If the input is an Array, count will be the length.
  37895. *
  37896. * @type {?number}
  37897. * @default null
  37898. */
  37899. this.count = count;
  37900. /**
  37901. *The parameter qualifier (only relevant for GLSL).
  37902. *
  37903. * @type {('in'|'out'|'inout')}
  37904. * @default ''
  37905. */
  37906. this.qualifier = qualifier;
  37907. /**
  37908. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  37909. *
  37910. * @type {boolean}
  37911. * @default false
  37912. */
  37913. this.isConst = isConst;
  37914. }
  37915. }
  37916. NodeFunctionInput.isNodeFunctionInput = true;
  37917. /**
  37918. * Module for representing ambient lights as nodes.
  37919. *
  37920. * @augments AnalyticLightNode
  37921. */
  37922. class AmbientLightNode extends AnalyticLightNode {
  37923. static get type() {
  37924. return 'AmbientLightNode';
  37925. }
  37926. /**
  37927. * Constructs a new ambient light node.
  37928. *
  37929. * @param {?AmbientLight} [light=null] - The ambient light source.
  37930. */
  37931. constructor( light = null ) {
  37932. super( light );
  37933. }
  37934. setup( { context } ) {
  37935. context.irradiance.addAssign( this.colorNode );
  37936. }
  37937. }
  37938. /**
  37939. * Module for representing directional lights as nodes.
  37940. *
  37941. * @augments AnalyticLightNode
  37942. */
  37943. class DirectionalLightNode extends AnalyticLightNode {
  37944. static get type() {
  37945. return 'DirectionalLightNode';
  37946. }
  37947. /**
  37948. * Constructs a new directional light node.
  37949. *
  37950. * @param {?DirectionalLight} [light=null] - The directional light source.
  37951. */
  37952. constructor( light = null ) {
  37953. super( light );
  37954. }
  37955. setupDirect() {
  37956. const lightColor = this.colorNode;
  37957. const lightDirection = lightTargetDirection( this.light );
  37958. return { lightDirection, lightColor };
  37959. }
  37960. }
  37961. /**
  37962. * Module for representing hemisphere lights as nodes.
  37963. *
  37964. * @augments AnalyticLightNode
  37965. */
  37966. class HemisphereLightNode extends AnalyticLightNode {
  37967. static get type() {
  37968. return 'HemisphereLightNode';
  37969. }
  37970. /**
  37971. * Constructs a new hemisphere light node.
  37972. *
  37973. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  37974. */
  37975. constructor( light = null ) {
  37976. super( light );
  37977. /**
  37978. * Uniform node representing the light's position.
  37979. *
  37980. * @type {UniformNode<vec3>}
  37981. */
  37982. this.lightPositionNode = lightPosition( light );
  37983. /**
  37984. * A node representing the light's direction.
  37985. *
  37986. * @type {Node<vec3>}
  37987. */
  37988. this.lightDirectionNode = this.lightPositionNode.normalize();
  37989. /**
  37990. * Uniform node representing the light's ground color.
  37991. *
  37992. * @type {UniformNode<vec3>}
  37993. */
  37994. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37995. }
  37996. /**
  37997. * Overwritten to updated hemisphere light specific uniforms.
  37998. *
  37999. * @param {NodeFrame} frame - A reference to the current node frame.
  38000. */
  38001. update( frame ) {
  38002. const { light } = this;
  38003. super.update( frame );
  38004. this.lightPositionNode.object3d = light;
  38005. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  38006. }
  38007. setup( builder ) {
  38008. const { colorNode, groundColorNode, lightDirectionNode } = this;
  38009. const dotNL = normalWorld.dot( lightDirectionNode );
  38010. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  38011. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  38012. builder.context.irradiance.addAssign( irradiance );
  38013. }
  38014. }
  38015. /**
  38016. * Module for representing spot lights as nodes.
  38017. *
  38018. * @augments AnalyticLightNode
  38019. */
  38020. class SpotLightNode extends AnalyticLightNode {
  38021. static get type() {
  38022. return 'SpotLightNode';
  38023. }
  38024. /**
  38025. * Constructs a new spot light node.
  38026. *
  38027. * @param {?SpotLight} [light=null] - The spot light source.
  38028. */
  38029. constructor( light = null ) {
  38030. super( light );
  38031. /**
  38032. * Uniform node representing the cone cosine.
  38033. *
  38034. * @type {UniformNode<float>}
  38035. */
  38036. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  38037. /**
  38038. * Uniform node representing the penumbra cosine.
  38039. *
  38040. * @type {UniformNode<float>}
  38041. */
  38042. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  38043. /**
  38044. * Uniform node representing the cutoff distance.
  38045. *
  38046. * @type {UniformNode<float>}
  38047. */
  38048. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  38049. /**
  38050. * Uniform node representing the decay exponent.
  38051. *
  38052. * @type {UniformNode<float>}
  38053. */
  38054. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  38055. /**
  38056. * Uniform node representing the light color.
  38057. *
  38058. * @type {UniformNode<Color>}
  38059. */
  38060. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  38061. }
  38062. /**
  38063. * Overwritten to updated spot light specific uniforms.
  38064. *
  38065. * @param {NodeFrame} frame - A reference to the current node frame.
  38066. */
  38067. update( frame ) {
  38068. super.update( frame );
  38069. const { light } = this;
  38070. this.coneCosNode.value = Math.cos( light.angle );
  38071. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  38072. this.cutoffDistanceNode.value = light.distance;
  38073. this.decayExponentNode.value = light.decay;
  38074. }
  38075. /**
  38076. * Computes the spot attenuation for the given angle.
  38077. *
  38078. * @param {NodeBuilder} builder - The node builder.
  38079. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38080. * @return {Node<float>} The spot attenuation.
  38081. */
  38082. getSpotAttenuation( builder, angleCosine ) {
  38083. const { coneCosNode, penumbraCosNode } = this;
  38084. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  38085. }
  38086. getLightCoord( builder ) {
  38087. const properties = builder.getNodeProperties( this );
  38088. let projectionUV = properties.projectionUV;
  38089. if ( projectionUV === undefined ) {
  38090. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  38091. properties.projectionUV = projectionUV;
  38092. }
  38093. return projectionUV;
  38094. }
  38095. setupDirect( builder ) {
  38096. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  38097. const lightVector = this.getLightVector( builder );
  38098. const lightDirection = lightVector.normalize();
  38099. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  38100. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  38101. const lightDistance = lightVector.length();
  38102. const lightAttenuation = getDistanceAttenuation( {
  38103. lightDistance,
  38104. cutoffDistance: cutoffDistanceNode,
  38105. decayExponent: decayExponentNode
  38106. } );
  38107. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  38108. let projected, lightCoord;
  38109. if ( light.colorNode ) {
  38110. lightCoord = this.getLightCoord( builder );
  38111. projected = light.colorNode( lightCoord );
  38112. } else if ( light.map ) {
  38113. lightCoord = this.getLightCoord( builder );
  38114. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  38115. }
  38116. if ( projected ) {
  38117. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  38118. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  38119. }
  38120. return { lightColor, lightDirection };
  38121. }
  38122. }
  38123. /**
  38124. * An IES version of the default spot light node.
  38125. *
  38126. * @augments SpotLightNode
  38127. */
  38128. class IESSpotLightNode extends SpotLightNode {
  38129. static get type() {
  38130. return 'IESSpotLightNode';
  38131. }
  38132. /**
  38133. * Overwrites the default implementation to compute an IES conform spot attenuation.
  38134. *
  38135. * @param {NodeBuilder} builder - The node builder.
  38136. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  38137. * @return {Node<float>} The spot attenuation.
  38138. */
  38139. getSpotAttenuation( builder, angleCosine ) {
  38140. const iesMap = this.light.iesMap;
  38141. let spotAttenuation = null;
  38142. if ( iesMap && iesMap.isTexture === true ) {
  38143. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  38144. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  38145. } else {
  38146. spotAttenuation = super.getSpotAttenuation( angleCosine );
  38147. }
  38148. return spotAttenuation;
  38149. }
  38150. }
  38151. /**
  38152. * Module for representing light probes as nodes.
  38153. *
  38154. * @augments AnalyticLightNode
  38155. */
  38156. class LightProbeNode extends AnalyticLightNode {
  38157. static get type() {
  38158. return 'LightProbeNode';
  38159. }
  38160. /**
  38161. * Constructs a new light probe node.
  38162. *
  38163. * @param {?LightProbe} [light=null] - The light probe.
  38164. */
  38165. constructor( light = null ) {
  38166. super( light );
  38167. const array = [];
  38168. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  38169. /**
  38170. * Light probe represented as a uniform of spherical harmonics.
  38171. *
  38172. * @type {UniformArrayNode}
  38173. */
  38174. this.lightProbe = uniformArray( array );
  38175. }
  38176. /**
  38177. * Overwritten to updated light probe specific uniforms.
  38178. *
  38179. * @param {NodeFrame} frame - A reference to the current node frame.
  38180. */
  38181. update( frame ) {
  38182. const { light } = this;
  38183. super.update( frame );
  38184. //
  38185. for ( let i = 0; i < 9; i ++ ) {
  38186. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  38187. }
  38188. }
  38189. setup( builder ) {
  38190. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  38191. builder.context.irradiance.addAssign( irradiance );
  38192. }
  38193. }
  38194. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  38195. const d = p.abs().sub( b );
  38196. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  38197. } );
  38198. /**
  38199. * An implementation of a projector light node.
  38200. *
  38201. * @augments SpotLightNode
  38202. */
  38203. class ProjectorLightNode extends SpotLightNode {
  38204. static get type() {
  38205. return 'ProjectorLightNode';
  38206. }
  38207. update( frame ) {
  38208. super.update( frame );
  38209. const light = this.light;
  38210. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  38211. if ( light.aspect === null ) {
  38212. let aspect = 1;
  38213. if ( light.map !== null ) {
  38214. aspect = light.map.width / light.map.height;
  38215. }
  38216. light.shadow.aspect = aspect;
  38217. } else {
  38218. light.shadow.aspect = light.aspect;
  38219. }
  38220. }
  38221. /**
  38222. * Overwrites the default implementation to compute projection attenuation.
  38223. *
  38224. * @param {NodeBuilder} builder - The node builder.
  38225. * @return {Node<float>} The spot attenuation.
  38226. */
  38227. getSpotAttenuation( builder ) {
  38228. const attenuation = float( 0 );
  38229. const penumbraCos = this.penumbraCosNode;
  38230. // compute the fragment's position in the light's clip space
  38231. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  38232. // the sign of w determines whether the current fragment is in front or behind the light.
  38233. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  38234. If( spotLightCoord.w.greaterThan( 0 ), () => {
  38235. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  38236. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  38237. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  38238. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  38239. } );
  38240. return attenuation;
  38241. }
  38242. }
  38243. const _matrix41 = /*@__PURE__*/ new Matrix4();
  38244. const _matrix42 = /*@__PURE__*/ new Matrix4();
  38245. let _ltcLib = null;
  38246. /**
  38247. * Module for representing rect area lights as nodes.
  38248. *
  38249. * @augments AnalyticLightNode
  38250. */
  38251. class RectAreaLightNode extends AnalyticLightNode {
  38252. static get type() {
  38253. return 'RectAreaLightNode';
  38254. }
  38255. /**
  38256. * Constructs a new rect area light node.
  38257. *
  38258. * @param {?RectAreaLight} [light=null] - The rect area light source.
  38259. */
  38260. constructor( light = null ) {
  38261. super( light );
  38262. /**
  38263. * Uniform node representing the half height of the are light.
  38264. *
  38265. * @type {UniformNode<vec3>}
  38266. */
  38267. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  38268. /**
  38269. * Uniform node representing the half width of the are light.
  38270. *
  38271. * @type {UniformNode<vec3>}
  38272. */
  38273. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  38274. /**
  38275. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  38276. * relies on `viewMatrix` which might vary per render call.
  38277. *
  38278. * @type {string}
  38279. * @default 'render'
  38280. */
  38281. this.updateType = NodeUpdateType.RENDER;
  38282. }
  38283. /**
  38284. * Overwritten to updated rect area light specific uniforms.
  38285. *
  38286. * @param {NodeFrame} frame - A reference to the current node frame.
  38287. */
  38288. update( frame ) {
  38289. super.update( frame );
  38290. const { light } = this;
  38291. const viewMatrix = frame.camera.matrixWorldInverse;
  38292. _matrix42.identity();
  38293. _matrix41.copy( light.matrixWorld );
  38294. _matrix41.premultiply( viewMatrix );
  38295. _matrix42.extractRotation( _matrix41 );
  38296. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  38297. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  38298. this.halfWidth.value.applyMatrix4( _matrix42 );
  38299. this.halfHeight.value.applyMatrix4( _matrix42 );
  38300. }
  38301. setupDirectRectArea( builder ) {
  38302. let ltc_1, ltc_2;
  38303. if ( builder.isAvailable( 'float32Filterable' ) ) {
  38304. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  38305. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  38306. } else {
  38307. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  38308. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  38309. }
  38310. const { colorNode, light } = this;
  38311. const lightPosition = lightViewPosition( light );
  38312. return {
  38313. lightColor: colorNode,
  38314. lightPosition,
  38315. halfWidth: this.halfWidth,
  38316. halfHeight: this.halfHeight,
  38317. ltc_1,
  38318. ltc_2
  38319. };
  38320. }
  38321. /**
  38322. * Used to configure the internal BRDF approximation texture data.
  38323. *
  38324. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  38325. */
  38326. static setLTC( ltc ) {
  38327. _ltcLib = ltc;
  38328. }
  38329. }
  38330. /**
  38331. * Base class for node parsers. A derived parser must be implemented
  38332. * for each supported native shader language.
  38333. */
  38334. class NodeParser {
  38335. /**
  38336. * The method parses the given native code an returns a node function.
  38337. *
  38338. * @abstract
  38339. * @param {string} source - The native shader code.
  38340. * @return {NodeFunction} A node function.
  38341. */
  38342. parseFunction( /*source*/ ) {
  38343. warn( 'Abstract function.' );
  38344. }
  38345. }
  38346. /**
  38347. * Base class for node functions. A derived module must be implemented
  38348. * for each supported native shader language. Similar to other `Node*` modules,
  38349. * this class is only relevant during the building process and not used
  38350. * in user-level code.
  38351. */
  38352. class NodeFunction {
  38353. /**
  38354. * Constructs a new node function.
  38355. *
  38356. * @param {string} type - The node type. This type is the return type of the node function.
  38357. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  38358. * @param {string} [name=''] - The function's name.
  38359. * @param {string} [precision=''] - The precision qualifier.
  38360. */
  38361. constructor( type, inputs, name = '', precision = '' ) {
  38362. /**
  38363. * The node type. This type is the return type of the node function.
  38364. *
  38365. * @type {string}
  38366. */
  38367. this.type = type;
  38368. /**
  38369. * The function's inputs.
  38370. *
  38371. * @type {Array<NodeFunctionInput>}
  38372. */
  38373. this.inputs = inputs;
  38374. /**
  38375. * The name of the uniform.
  38376. *
  38377. * @type {string}
  38378. * @default ''
  38379. */
  38380. this.name = name;
  38381. /**
  38382. * The precision qualifier.
  38383. *
  38384. * @type {string}
  38385. * @default ''
  38386. */
  38387. this.precision = precision;
  38388. }
  38389. /**
  38390. * This method returns the native code of the node function.
  38391. *
  38392. * @abstract
  38393. * @param {string} name - The function's name.
  38394. * @return {string} A shader code.
  38395. */
  38396. getCode( /*name = this.name*/ ) {
  38397. warn( 'Abstract function.' );
  38398. }
  38399. }
  38400. NodeFunction.isNodeFunction = true;
  38401. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  38402. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  38403. const pragmaMain = '#pragma main';
  38404. const parse$1 = ( source ) => {
  38405. source = source.trim();
  38406. const pragmaMainIndex = source.indexOf( pragmaMain );
  38407. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  38408. const declaration = mainCode.match( declarationRegexp$1 );
  38409. if ( declaration !== null && declaration.length === 5 ) {
  38410. // tokenizer
  38411. const inputsCode = declaration[ 4 ];
  38412. const propsMatches = [];
  38413. let nameMatch = null;
  38414. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  38415. propsMatches.push( nameMatch );
  38416. }
  38417. // parser
  38418. const inputs = [];
  38419. let i = 0;
  38420. while ( i < propsMatches.length ) {
  38421. const isConst = propsMatches[ i ][ 0 ] === 'const';
  38422. if ( isConst === true ) {
  38423. i ++;
  38424. }
  38425. let qualifier = propsMatches[ i ][ 0 ];
  38426. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  38427. i ++;
  38428. } else {
  38429. qualifier = '';
  38430. }
  38431. const type = propsMatches[ i ++ ][ 0 ];
  38432. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  38433. if ( Number.isNaN( count ) === false ) i ++;
  38434. else count = null;
  38435. const name = propsMatches[ i ++ ][ 0 ];
  38436. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  38437. }
  38438. //
  38439. const blockCode = mainCode.substring( declaration[ 0 ].length );
  38440. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  38441. const type = declaration[ 2 ];
  38442. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  38443. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  38444. return {
  38445. type,
  38446. inputs,
  38447. name,
  38448. precision,
  38449. inputsCode,
  38450. blockCode,
  38451. headerCode
  38452. };
  38453. } else {
  38454. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  38455. }
  38456. };
  38457. /**
  38458. * This class represents a GLSL node function.
  38459. *
  38460. * @augments NodeFunction
  38461. */
  38462. class GLSLNodeFunction extends NodeFunction {
  38463. /**
  38464. * Constructs a new GLSL node function.
  38465. *
  38466. * @param {string} source - The GLSL source.
  38467. */
  38468. constructor( source ) {
  38469. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  38470. super( type, inputs, name, precision );
  38471. this.inputsCode = inputsCode;
  38472. this.blockCode = blockCode;
  38473. this.headerCode = headerCode;
  38474. }
  38475. /**
  38476. * This method returns the GLSL code of the node function.
  38477. *
  38478. * @param {string} [name=this.name] - The function's name.
  38479. * @return {string} The shader code.
  38480. */
  38481. getCode( name = this.name ) {
  38482. let code;
  38483. const blockCode = this.blockCode;
  38484. if ( blockCode !== '' ) {
  38485. const { type, inputsCode, headerCode, precision } = this;
  38486. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  38487. if ( precision !== '' ) {
  38488. declarationCode = `${ precision } ${ declarationCode }`;
  38489. }
  38490. code = headerCode + declarationCode + blockCode;
  38491. } else {
  38492. // interface function
  38493. code = '';
  38494. }
  38495. return code;
  38496. }
  38497. }
  38498. /**
  38499. * A GLSL node parser.
  38500. *
  38501. * @augments NodeParser
  38502. */
  38503. class GLSLNodeParser extends NodeParser {
  38504. /**
  38505. * The method parses the given GLSL code an returns a node function.
  38506. *
  38507. * @param {string} source - The GLSL code.
  38508. * @return {GLSLNodeFunction} A node function.
  38509. */
  38510. parseFunction( source ) {
  38511. return new GLSLNodeFunction( source );
  38512. }
  38513. }
  38514. const _outputNodeMap = new WeakMap();
  38515. const _chainKeys$1 = [];
  38516. const _cacheKeyValues = [];
  38517. /**
  38518. * This renderer module manages node-related objects and is the
  38519. * primary interface between the renderer and the node system.
  38520. *
  38521. * @private
  38522. * @augments DataMap
  38523. */
  38524. class NodeManager extends DataMap {
  38525. /**
  38526. * Constructs a new nodes management component.
  38527. *
  38528. * @param {Renderer} renderer - The renderer.
  38529. * @param {Backend} backend - The renderer's backend.
  38530. */
  38531. constructor( renderer, backend ) {
  38532. super();
  38533. /**
  38534. * The renderer.
  38535. *
  38536. * @type {Renderer}
  38537. */
  38538. this.renderer = renderer;
  38539. /**
  38540. * The renderer's backend.
  38541. *
  38542. * @type {Backend}
  38543. */
  38544. this.backend = backend;
  38545. /**
  38546. * The node frame.
  38547. *
  38548. * @type {Renderer}
  38549. */
  38550. this.nodeFrame = new NodeFrame();
  38551. /**
  38552. * A cache for managing node builder states.
  38553. *
  38554. * @type {Map<number,NodeBuilderState>}
  38555. */
  38556. this.nodeBuilderCache = new Map();
  38557. /**
  38558. * A cache for managing data cache key data.
  38559. *
  38560. * @type {ChainMap}
  38561. */
  38562. this.callHashCache = new ChainMap();
  38563. /**
  38564. * A cache for managing node uniforms group data.
  38565. *
  38566. * @type {ChainMap}
  38567. */
  38568. this.groupsData = new ChainMap();
  38569. /**
  38570. * A cache for managing node objects of
  38571. * scene properties like fog or environments.
  38572. *
  38573. * @type {Object<string,WeakMap>}
  38574. */
  38575. this.cacheLib = {};
  38576. }
  38577. /**
  38578. * Returns `true` if the given node uniforms group must be updated or not.
  38579. *
  38580. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  38581. * @return {boolean} Whether the node uniforms group requires an update or not.
  38582. */
  38583. updateGroup( nodeUniformsGroup ) {
  38584. const groupNode = nodeUniformsGroup.groupNode;
  38585. const name = groupNode.name;
  38586. // objectGroup is always updated
  38587. if ( name === objectGroup.name ) return true;
  38588. // renderGroup is updated once per render/compute call
  38589. if ( name === renderGroup.name ) {
  38590. const uniformsGroupData = this.get( nodeUniformsGroup );
  38591. const renderId = this.nodeFrame.renderId;
  38592. if ( uniformsGroupData.renderId !== renderId ) {
  38593. uniformsGroupData.renderId = renderId;
  38594. return true;
  38595. }
  38596. return false;
  38597. }
  38598. // frameGroup is updated once per frame
  38599. if ( name === frameGroup.name ) {
  38600. const uniformsGroupData = this.get( nodeUniformsGroup );
  38601. const frameId = this.nodeFrame.frameId;
  38602. if ( uniformsGroupData.frameId !== frameId ) {
  38603. uniformsGroupData.frameId = frameId;
  38604. return true;
  38605. }
  38606. return false;
  38607. }
  38608. // other groups are updated just when groupNode.needsUpdate is true
  38609. _chainKeys$1[ 0 ] = groupNode;
  38610. _chainKeys$1[ 1 ] = nodeUniformsGroup;
  38611. let groupData = this.groupsData.get( _chainKeys$1 );
  38612. if ( groupData === undefined ) this.groupsData.set( _chainKeys$1, groupData = {} );
  38613. _chainKeys$1[ 0 ] = null;
  38614. _chainKeys$1[ 1 ] = null;
  38615. if ( groupData.version !== groupNode.version ) {
  38616. groupData.version = groupNode.version;
  38617. return true;
  38618. }
  38619. return false;
  38620. }
  38621. /**
  38622. * Returns the cache key for the given render object.
  38623. *
  38624. * @param {RenderObject} renderObject - The render object.
  38625. * @return {number} The cache key.
  38626. */
  38627. getForRenderCacheKey( renderObject ) {
  38628. return renderObject.initialCacheKey;
  38629. }
  38630. /**
  38631. * Returns a node builder state for the given render object.
  38632. *
  38633. * @param {RenderObject} renderObject - The render object.
  38634. * @return {NodeBuilderState} The node builder state.
  38635. */
  38636. getForRender( renderObject ) {
  38637. const renderObjectData = this.get( renderObject );
  38638. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38639. if ( nodeBuilderState === undefined ) {
  38640. const { nodeBuilderCache } = this;
  38641. const cacheKey = this.getForRenderCacheKey( renderObject );
  38642. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38643. if ( nodeBuilderState === undefined ) {
  38644. const createNodeBuilder = ( material ) => {
  38645. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38646. nodeBuilder.scene = renderObject.scene;
  38647. nodeBuilder.material = material;
  38648. nodeBuilder.camera = renderObject.camera;
  38649. nodeBuilder.context.material = material;
  38650. nodeBuilder.lightsNode = renderObject.lightsNode;
  38651. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38652. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38653. nodeBuilder.clippingContext = renderObject.clippingContext;
  38654. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  38655. nodeBuilder.enableMultiview();
  38656. }
  38657. return nodeBuilder;
  38658. };
  38659. let nodeBuilder = createNodeBuilder( renderObject.material );
  38660. try {
  38661. nodeBuilder.build();
  38662. } catch ( e ) {
  38663. nodeBuilder = createNodeBuilder( new NodeMaterial() );
  38664. nodeBuilder.build();
  38665. error( 'TSL: ' + e );
  38666. }
  38667. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38668. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38669. }
  38670. nodeBuilderState.usedTimes ++;
  38671. renderObjectData.nodeBuilderState = nodeBuilderState;
  38672. }
  38673. return nodeBuilderState;
  38674. }
  38675. /**
  38676. * Deletes the given object from the internal data map
  38677. *
  38678. * @param {any} object - The object to delete.
  38679. * @return {?Object} The deleted dictionary.
  38680. */
  38681. delete( object ) {
  38682. if ( object.isRenderObject ) {
  38683. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38684. nodeBuilderState.usedTimes --;
  38685. if ( nodeBuilderState.usedTimes === 0 ) {
  38686. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38687. }
  38688. }
  38689. return super.delete( object );
  38690. }
  38691. /**
  38692. * Returns a node builder state for the given compute node.
  38693. *
  38694. * @param {Node} computeNode - The compute node.
  38695. * @return {NodeBuilderState} The node builder state.
  38696. */
  38697. getForCompute( computeNode ) {
  38698. const computeData = this.get( computeNode );
  38699. let nodeBuilderState = computeData.nodeBuilderState;
  38700. if ( nodeBuilderState === undefined ) {
  38701. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38702. nodeBuilder.build();
  38703. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38704. computeData.nodeBuilderState = nodeBuilderState;
  38705. }
  38706. return nodeBuilderState;
  38707. }
  38708. /**
  38709. * Creates a node builder state for the given node builder.
  38710. *
  38711. * @private
  38712. * @param {NodeBuilder} nodeBuilder - The node builder.
  38713. * @return {NodeBuilderState} The node builder state.
  38714. */
  38715. _createNodeBuilderState( nodeBuilder ) {
  38716. return new NodeBuilderState(
  38717. nodeBuilder.vertexShader,
  38718. nodeBuilder.fragmentShader,
  38719. nodeBuilder.computeShader,
  38720. nodeBuilder.getAttributesArray(),
  38721. nodeBuilder.getBindings(),
  38722. nodeBuilder.updateNodes,
  38723. nodeBuilder.updateBeforeNodes,
  38724. nodeBuilder.updateAfterNodes,
  38725. nodeBuilder.observer,
  38726. nodeBuilder.transforms
  38727. );
  38728. }
  38729. /**
  38730. * Returns an environment node for the current configured
  38731. * scene environment.
  38732. *
  38733. * @param {Scene} scene - The scene.
  38734. * @return {Node} A node representing the current scene environment.
  38735. */
  38736. getEnvironmentNode( scene ) {
  38737. this.updateEnvironment( scene );
  38738. let environmentNode = null;
  38739. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  38740. environmentNode = scene.environmentNode;
  38741. } else {
  38742. const sceneData = this.get( scene );
  38743. if ( sceneData.environmentNode ) {
  38744. environmentNode = sceneData.environmentNode;
  38745. }
  38746. }
  38747. return environmentNode;
  38748. }
  38749. /**
  38750. * Returns a background node for the current configured
  38751. * scene background.
  38752. *
  38753. * @param {Scene} scene - The scene.
  38754. * @return {Node} A node representing the current scene background.
  38755. */
  38756. getBackgroundNode( scene ) {
  38757. this.updateBackground( scene );
  38758. let backgroundNode = null;
  38759. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  38760. backgroundNode = scene.backgroundNode;
  38761. } else {
  38762. const sceneData = this.get( scene );
  38763. if ( sceneData.backgroundNode ) {
  38764. backgroundNode = sceneData.backgroundNode;
  38765. }
  38766. }
  38767. return backgroundNode;
  38768. }
  38769. /**
  38770. * Returns a fog node for the current configured scene fog.
  38771. *
  38772. * @param {Scene} scene - The scene.
  38773. * @return {Node} A node representing the current scene fog.
  38774. */
  38775. getFogNode( scene ) {
  38776. this.updateFog( scene );
  38777. return scene.fogNode || this.get( scene ).fogNode || null;
  38778. }
  38779. /**
  38780. * Returns a cache key for the given scene and lights node.
  38781. * This key is used by `RenderObject` as a part of the dynamic
  38782. * cache key (a key that must be checked every time the render
  38783. * objects is drawn).
  38784. *
  38785. * @param {Scene} scene - The scene.
  38786. * @param {LightsNode} lightsNode - The lights node.
  38787. * @return {number} The cache key.
  38788. */
  38789. getCacheKey( scene, lightsNode ) {
  38790. _chainKeys$1[ 0 ] = scene;
  38791. _chainKeys$1[ 1 ] = lightsNode;
  38792. const callId = this.renderer.info.calls;
  38793. const cacheKeyData = this.callHashCache.get( _chainKeys$1 ) || {};
  38794. if ( cacheKeyData.callId !== callId ) {
  38795. const environmentNode = this.getEnvironmentNode( scene );
  38796. const fogNode = this.getFogNode( scene );
  38797. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  38798. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  38799. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  38800. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  38801. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  38802. _cacheKeyValues.push( this.renderer.shadowMap.type );
  38803. cacheKeyData.callId = callId;
  38804. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  38805. this.callHashCache.set( _chainKeys$1, cacheKeyData );
  38806. _cacheKeyValues.length = 0;
  38807. }
  38808. _chainKeys$1[ 0 ] = null;
  38809. _chainKeys$1[ 1 ] = null;
  38810. return cacheKeyData.cacheKey;
  38811. }
  38812. /**
  38813. * A boolean that indicates whether tone mapping should be enabled
  38814. * or not.
  38815. *
  38816. * @type {boolean}
  38817. */
  38818. get isToneMappingState() {
  38819. return this.renderer.getRenderTarget() ? false : true;
  38820. }
  38821. /**
  38822. * If a scene background is configured, this method makes sure to
  38823. * represent the background with a corresponding node-based implementation.
  38824. *
  38825. * @param {Scene} scene - The scene.
  38826. */
  38827. updateBackground( scene ) {
  38828. const sceneData = this.get( scene );
  38829. const background = scene.background;
  38830. if ( background ) {
  38831. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38832. if ( sceneData.background !== background || forceUpdate ) {
  38833. const backgroundNode = this.getCacheNode( 'background', background, () => {
  38834. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38835. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38836. return pmremTexture( background );
  38837. } else {
  38838. let envMap;
  38839. if ( background.isCubeTexture === true ) {
  38840. envMap = cubeTexture( background );
  38841. } else {
  38842. envMap = texture( background );
  38843. }
  38844. return cubeMapNode( envMap );
  38845. }
  38846. } else if ( background.isTexture === true ) {
  38847. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38848. } else if ( background.isColor !== true ) {
  38849. error( 'WebGPUNodes: Unsupported background configuration.', background );
  38850. }
  38851. }, forceUpdate );
  38852. sceneData.backgroundNode = backgroundNode;
  38853. sceneData.background = background;
  38854. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38855. }
  38856. } else if ( sceneData.backgroundNode ) {
  38857. delete sceneData.backgroundNode;
  38858. delete sceneData.background;
  38859. }
  38860. }
  38861. /**
  38862. * This method is part of the caching of nodes which are used to represents the
  38863. * scene's background, fog or environment.
  38864. *
  38865. * @param {string} type - The type of object to cache.
  38866. * @param {Object} object - The object.
  38867. * @param {Function} callback - A callback that produces a node representation for the given object.
  38868. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  38869. * @return {Node} The node representation.
  38870. */
  38871. getCacheNode( type, object, callback, forceUpdate = false ) {
  38872. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  38873. let node = nodeCache.get( object );
  38874. if ( node === undefined || forceUpdate ) {
  38875. node = callback();
  38876. nodeCache.set( object, node );
  38877. }
  38878. return node;
  38879. }
  38880. /**
  38881. * If a scene fog is configured, this method makes sure to
  38882. * represent the fog with a corresponding node-based implementation.
  38883. *
  38884. * @param {Scene} scene - The scene.
  38885. */
  38886. updateFog( scene ) {
  38887. const sceneData = this.get( scene );
  38888. const sceneFog = scene.fog;
  38889. if ( sceneFog ) {
  38890. if ( sceneData.fog !== sceneFog ) {
  38891. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  38892. if ( sceneFog.isFogExp2 ) {
  38893. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38894. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  38895. return fog( color, densityFogFactor( density ) );
  38896. } else if ( sceneFog.isFog ) {
  38897. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  38898. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  38899. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  38900. return fog( color, rangeFogFactor( near, far ) );
  38901. } else {
  38902. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  38903. }
  38904. } );
  38905. sceneData.fogNode = fogNode;
  38906. sceneData.fog = sceneFog;
  38907. }
  38908. } else {
  38909. delete sceneData.fogNode;
  38910. delete sceneData.fog;
  38911. }
  38912. }
  38913. /**
  38914. * If a scene environment is configured, this method makes sure to
  38915. * represent the environment with a corresponding node-based implementation.
  38916. *
  38917. * @param {Scene} scene - The scene.
  38918. */
  38919. updateEnvironment( scene ) {
  38920. const sceneData = this.get( scene );
  38921. const environment = scene.environment;
  38922. if ( environment ) {
  38923. if ( sceneData.environment !== environment ) {
  38924. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  38925. if ( environment.isCubeTexture === true ) {
  38926. return cubeTexture( environment );
  38927. } else if ( environment.isTexture === true ) {
  38928. return texture( environment );
  38929. } else {
  38930. error( 'Nodes: Unsupported environment configuration.', environment );
  38931. }
  38932. } );
  38933. sceneData.environmentNode = environmentNode;
  38934. sceneData.environment = environment;
  38935. }
  38936. } else if ( sceneData.environmentNode ) {
  38937. delete sceneData.environmentNode;
  38938. delete sceneData.environment;
  38939. }
  38940. }
  38941. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38942. const nodeFrame = this.nodeFrame;
  38943. nodeFrame.renderer = renderer;
  38944. nodeFrame.scene = scene;
  38945. nodeFrame.object = object;
  38946. nodeFrame.camera = camera;
  38947. nodeFrame.material = material;
  38948. return nodeFrame;
  38949. }
  38950. getNodeFrameForRender( renderObject ) {
  38951. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38952. }
  38953. /**
  38954. * Returns the current output cache key.
  38955. *
  38956. * @return {string} The output cache key.
  38957. */
  38958. getOutputCacheKey() {
  38959. const renderer = this.renderer;
  38960. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  38961. }
  38962. /**
  38963. * Checks if the output configuration (tone mapping and color space) for
  38964. * the given target has changed.
  38965. *
  38966. * @param {Texture} outputTarget - The output target.
  38967. * @return {boolean} Whether the output configuration has changed or not.
  38968. */
  38969. hasOutputChange( outputTarget ) {
  38970. const cacheKey = _outputNodeMap.get( outputTarget );
  38971. return cacheKey !== this.getOutputCacheKey();
  38972. }
  38973. /**
  38974. * Returns a node that represents the output configuration (tone mapping and
  38975. * color space) for the current target.
  38976. *
  38977. * @param {Texture} outputTarget - The output target.
  38978. * @return {Node} The output node.
  38979. */
  38980. getOutputNode( outputTarget ) {
  38981. const renderer = this.renderer;
  38982. const cacheKey = this.getOutputCacheKey();
  38983. const output = outputTarget.isArrayTexture ?
  38984. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  38985. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38986. _outputNodeMap.set( outputTarget, cacheKey );
  38987. return output;
  38988. }
  38989. /**
  38990. * Triggers the call of `updateBefore()` methods
  38991. * for all nodes of the given render object.
  38992. *
  38993. * @param {RenderObject} renderObject - The render object.
  38994. */
  38995. updateBefore( renderObject ) {
  38996. const nodeBuilder = renderObject.getNodeBuilderState();
  38997. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38998. // update frame state for each node
  38999. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  39000. }
  39001. }
  39002. /**
  39003. * Triggers the call of `updateAfter()` methods
  39004. * for all nodes of the given render object.
  39005. *
  39006. * @param {RenderObject} renderObject - The render object.
  39007. */
  39008. updateAfter( renderObject ) {
  39009. const nodeBuilder = renderObject.getNodeBuilderState();
  39010. for ( const node of nodeBuilder.updateAfterNodes ) {
  39011. // update frame state for each node
  39012. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  39013. }
  39014. }
  39015. /**
  39016. * Triggers the call of `update()` methods
  39017. * for all nodes of the given compute node.
  39018. *
  39019. * @param {Node} computeNode - The compute node.
  39020. */
  39021. updateForCompute( computeNode ) {
  39022. const nodeFrame = this.getNodeFrame();
  39023. const nodeBuilder = this.getForCompute( computeNode );
  39024. for ( const node of nodeBuilder.updateNodes ) {
  39025. nodeFrame.updateNode( node );
  39026. }
  39027. }
  39028. /**
  39029. * Triggers the call of `update()` methods
  39030. * for all nodes of the given compute node.
  39031. *
  39032. * @param {RenderObject} renderObject - The render object.
  39033. */
  39034. updateForRender( renderObject ) {
  39035. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39036. const nodeBuilder = renderObject.getNodeBuilderState();
  39037. for ( const node of nodeBuilder.updateNodes ) {
  39038. nodeFrame.updateNode( node );
  39039. }
  39040. }
  39041. /**
  39042. * Returns `true` if the given render object requires a refresh.
  39043. *
  39044. * @param {RenderObject} renderObject - The render object.
  39045. * @return {boolean} Whether the given render object requires a refresh or not.
  39046. */
  39047. needsRefresh( renderObject ) {
  39048. const nodeFrame = this.getNodeFrameForRender( renderObject );
  39049. const monitor = renderObject.getMonitor();
  39050. return monitor.needsRefresh( renderObject, nodeFrame );
  39051. }
  39052. /**
  39053. * Frees the internal resources.
  39054. */
  39055. dispose() {
  39056. super.dispose();
  39057. this.nodeFrame = new NodeFrame();
  39058. this.nodeBuilderCache = new Map();
  39059. this.cacheLib = {};
  39060. }
  39061. }
  39062. const _plane = /*@__PURE__*/ new Plane();
  39063. /**
  39064. * Represents the state that is used to perform clipping via clipping planes.
  39065. * There is a default clipping context for each render context. When the
  39066. * scene holds instances of `ClippingGroup`, there will be a context for each
  39067. * group.
  39068. *
  39069. * @private
  39070. */
  39071. class ClippingContext {
  39072. /**
  39073. * Constructs a new clipping context.
  39074. *
  39075. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  39076. */
  39077. constructor( parentContext = null ) {
  39078. /**
  39079. * The clipping context's version.
  39080. *
  39081. * @type {number}
  39082. * @readonly
  39083. */
  39084. this.version = 0;
  39085. /**
  39086. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  39087. *
  39088. * @type {?boolean}
  39089. * @default null
  39090. */
  39091. this.clipIntersection = null;
  39092. /**
  39093. * The clipping context's cache key.
  39094. *
  39095. * @type {string}
  39096. */
  39097. this.cacheKey = '';
  39098. /**
  39099. * Whether the shadow pass is active or not.
  39100. *
  39101. * @type {boolean}
  39102. * @default false
  39103. */
  39104. this.shadowPass = false;
  39105. /**
  39106. * The view normal matrix.
  39107. *
  39108. * @type {Matrix3}
  39109. */
  39110. this.viewNormalMatrix = new Matrix3();
  39111. /**
  39112. * Internal cache for maintaining clipping contexts.
  39113. *
  39114. * @type {WeakMap<ClippingGroup,ClippingContext>}
  39115. */
  39116. this.clippingGroupContexts = new WeakMap();
  39117. /**
  39118. * The intersection planes.
  39119. *
  39120. * @type {Array<Vector4>}
  39121. */
  39122. this.intersectionPlanes = [];
  39123. /**
  39124. * The intersection planes.
  39125. *
  39126. * @type {Array<Vector4>}
  39127. */
  39128. this.unionPlanes = [];
  39129. /**
  39130. * The version of the clipping context's parent context.
  39131. *
  39132. * @type {?number}
  39133. * @readonly
  39134. */
  39135. this.parentVersion = null;
  39136. if ( parentContext !== null ) {
  39137. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  39138. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  39139. this.shadowPass = parentContext.shadowPass;
  39140. this.viewMatrix = parentContext.viewMatrix;
  39141. }
  39142. }
  39143. /**
  39144. * Projects the given source clipping planes and writes the result into the
  39145. * destination array.
  39146. *
  39147. * @param {Array<Plane>} source - The source clipping planes.
  39148. * @param {Array<Vector4>} destination - The destination.
  39149. * @param {number} offset - The offset.
  39150. */
  39151. projectPlanes( source, destination, offset ) {
  39152. const l = source.length;
  39153. for ( let i = 0; i < l; i ++ ) {
  39154. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  39155. const v = destination[ offset + i ];
  39156. const normal = _plane.normal;
  39157. v.x = - normal.x;
  39158. v.y = - normal.y;
  39159. v.z = - normal.z;
  39160. v.w = _plane.constant;
  39161. }
  39162. }
  39163. /**
  39164. * Updates the root clipping context of a scene.
  39165. *
  39166. * @param {Scene} scene - The scene.
  39167. * @param {Camera} camera - The camera that is used to render the scene.
  39168. */
  39169. updateGlobal( scene, camera ) {
  39170. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  39171. this.viewMatrix = camera.matrixWorldInverse;
  39172. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  39173. }
  39174. /**
  39175. * Updates the clipping context.
  39176. *
  39177. * @param {ClippingContext} parentContext - The parent context.
  39178. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  39179. */
  39180. update( parentContext, clippingGroup ) {
  39181. let update = false;
  39182. if ( parentContext.version !== this.parentVersion ) {
  39183. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  39184. this.unionPlanes = Array.from( parentContext.unionPlanes );
  39185. this.parentVersion = parentContext.version;
  39186. }
  39187. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  39188. this.clipIntersection = clippingGroup.clipIntersection;
  39189. if ( this.clipIntersection ) {
  39190. this.unionPlanes.length = parentContext.unionPlanes.length;
  39191. } else {
  39192. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  39193. }
  39194. }
  39195. const srcClippingPlanes = clippingGroup.clippingPlanes;
  39196. const l = srcClippingPlanes.length;
  39197. let dstClippingPlanes;
  39198. let offset;
  39199. if ( this.clipIntersection ) {
  39200. dstClippingPlanes = this.intersectionPlanes;
  39201. offset = parentContext.intersectionPlanes.length;
  39202. } else {
  39203. dstClippingPlanes = this.unionPlanes;
  39204. offset = parentContext.unionPlanes.length;
  39205. }
  39206. if ( dstClippingPlanes.length !== offset + l ) {
  39207. dstClippingPlanes.length = offset + l;
  39208. for ( let i = 0; i < l; i ++ ) {
  39209. dstClippingPlanes[ offset + i ] = new Vector4();
  39210. }
  39211. update = true;
  39212. }
  39213. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  39214. if ( update ) {
  39215. this.version ++;
  39216. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  39217. }
  39218. }
  39219. /**
  39220. * Returns a clipping context for the given clipping group.
  39221. *
  39222. * @param {ClippingGroup} clippingGroup - The clipping group.
  39223. * @return {ClippingContext} The clipping context.
  39224. */
  39225. getGroupContext( clippingGroup ) {
  39226. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  39227. let context = this.clippingGroupContexts.get( clippingGroup );
  39228. if ( context === undefined ) {
  39229. context = new ClippingContext( this );
  39230. this.clippingGroupContexts.set( clippingGroup, context );
  39231. }
  39232. context.update( this, clippingGroup );
  39233. return context;
  39234. }
  39235. /**
  39236. * The count of union clipping planes.
  39237. *
  39238. * @type {number}
  39239. * @readonly
  39240. */
  39241. get unionClippingCount() {
  39242. return this.unionPlanes.length;
  39243. }
  39244. }
  39245. /**
  39246. * This module is used to represent render bundles inside the renderer
  39247. * for further processing.
  39248. *
  39249. * @private
  39250. */
  39251. class RenderBundle {
  39252. /**
  39253. * Constructs a new bundle group.
  39254. *
  39255. * @param {BundleGroup} bundleGroup - The bundle group.
  39256. * @param {Camera} camera - The camera the bundle group is rendered with.
  39257. */
  39258. constructor( bundleGroup, camera ) {
  39259. this.bundleGroup = bundleGroup;
  39260. this.camera = camera;
  39261. }
  39262. }
  39263. const _chainKeys = [];
  39264. /**
  39265. * This renderer module manages render bundles.
  39266. *
  39267. * @private
  39268. */
  39269. class RenderBundles {
  39270. /**
  39271. * Constructs a new render bundle management component.
  39272. */
  39273. constructor() {
  39274. /**
  39275. * A chain map for maintaining the render bundles.
  39276. *
  39277. * @type {ChainMap}
  39278. */
  39279. this.bundles = new ChainMap();
  39280. }
  39281. /**
  39282. * Returns a render bundle for the given bundle group and camera.
  39283. *
  39284. * @param {BundleGroup} bundleGroup - The bundle group.
  39285. * @param {Camera} camera - The camera the bundle group is rendered with.
  39286. * @return {RenderBundle} The render bundle.
  39287. */
  39288. get( bundleGroup, camera ) {
  39289. const bundles = this.bundles;
  39290. _chainKeys[ 0 ] = bundleGroup;
  39291. _chainKeys[ 1 ] = camera;
  39292. let bundle = bundles.get( _chainKeys );
  39293. if ( bundle === undefined ) {
  39294. bundle = new RenderBundle( bundleGroup, camera );
  39295. bundles.set( _chainKeys, bundle );
  39296. }
  39297. _chainKeys[ 0 ] = null;
  39298. _chainKeys[ 1 ] = null;
  39299. return bundle;
  39300. }
  39301. /**
  39302. * Frees all internal resources.
  39303. */
  39304. dispose() {
  39305. this.bundles = new ChainMap();
  39306. }
  39307. }
  39308. /**
  39309. * The purpose of a node library is to assign node implementations
  39310. * to existing library features. In `WebGPURenderer` lights, materials
  39311. * which are not based on `NodeMaterial` as well as tone mapping techniques
  39312. * are implemented with node-based modules.
  39313. *
  39314. * @private
  39315. */
  39316. class NodeLibrary {
  39317. /**
  39318. * Constructs a new node library.
  39319. */
  39320. constructor() {
  39321. /**
  39322. * A weak map that maps lights to light nodes.
  39323. *
  39324. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  39325. */
  39326. this.lightNodes = new WeakMap();
  39327. /**
  39328. * A map that maps materials to node materials.
  39329. *
  39330. * @type {Map<string,NodeMaterial.constructor>}
  39331. */
  39332. this.materialNodes = new Map();
  39333. /**
  39334. * A map that maps tone mapping techniques (constants)
  39335. * to tone mapping node functions.
  39336. *
  39337. * @type {Map<number,Function>}
  39338. */
  39339. this.toneMappingNodes = new Map();
  39340. }
  39341. /**
  39342. * Returns a matching node material instance for the given material object.
  39343. *
  39344. * This method also assigns/copies the properties of the given material object
  39345. * to the node material. This is done to make sure the current material
  39346. * configuration carries over to the node version.
  39347. *
  39348. * @param {Material} material - A material.
  39349. * @return {NodeMaterial} The corresponding node material.
  39350. */
  39351. fromMaterial( material ) {
  39352. if ( material.isNodeMaterial ) return material;
  39353. let nodeMaterial = null;
  39354. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  39355. if ( nodeMaterialClass !== null ) {
  39356. nodeMaterial = new nodeMaterialClass();
  39357. for ( const key in material ) {
  39358. nodeMaterial[ key ] = material[ key ];
  39359. }
  39360. }
  39361. return nodeMaterial;
  39362. }
  39363. /**
  39364. * Adds a tone mapping node function for a tone mapping technique (constant).
  39365. *
  39366. * @param {Function} toneMappingNode - The tone mapping node function.
  39367. * @param {number} toneMapping - The tone mapping.
  39368. */
  39369. addToneMapping( toneMappingNode, toneMapping ) {
  39370. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  39371. }
  39372. /**
  39373. * Returns a tone mapping node function for a tone mapping technique (constant).
  39374. *
  39375. * @param {number} toneMapping - The tone mapping.
  39376. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  39377. */
  39378. getToneMappingFunction( toneMapping ) {
  39379. return this.toneMappingNodes.get( toneMapping ) || null;
  39380. }
  39381. /**
  39382. * Returns a node material class definition for a material type.
  39383. *
  39384. * @param {string} materialType - The material type.
  39385. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  39386. */
  39387. getMaterialNodeClass( materialType ) {
  39388. return this.materialNodes.get( materialType ) || null;
  39389. }
  39390. /**
  39391. * Adds a node material class definition for a given material type.
  39392. *
  39393. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  39394. * @param {string} materialClassType - The material type.
  39395. */
  39396. addMaterial( materialNodeClass, materialClassType ) {
  39397. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  39398. }
  39399. /**
  39400. * Returns a light node class definition for a light class definition.
  39401. *
  39402. * @param {Light.constructor} light - The light class definition.
  39403. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  39404. */
  39405. getLightNodeClass( light ) {
  39406. return this.lightNodes.get( light ) || null;
  39407. }
  39408. /**
  39409. * Adds a light node class definition for a given light class definition.
  39410. *
  39411. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  39412. * @param {Light.constructor} lightClass - The light class definition.
  39413. */
  39414. addLight( lightNodeClass, lightClass ) {
  39415. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  39416. }
  39417. /**
  39418. * Adds a node class definition for the given type to the provided type library.
  39419. *
  39420. * @param {Node.constructor} nodeClass - The node class definition.
  39421. * @param {number|string} type - The object type.
  39422. * @param {Map<number|string,Node.constructor>} library - The type library.
  39423. */
  39424. addType( nodeClass, type, library ) {
  39425. if ( library.has( type ) ) {
  39426. warn( `Redefinition of node ${ type }` );
  39427. return;
  39428. }
  39429. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39430. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  39431. library.set( type, nodeClass );
  39432. }
  39433. /**
  39434. * Adds a node class definition for the given class definition to the provided type library.
  39435. *
  39436. * @param {Node.constructor} nodeClass - The node class definition.
  39437. * @param {Node.constructor} baseClass - The class definition.
  39438. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  39439. */
  39440. addClass( nodeClass, baseClass, library ) {
  39441. if ( library.has( baseClass ) ) {
  39442. warn( `Redefinition of node ${ baseClass.name }` );
  39443. return;
  39444. }
  39445. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  39446. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  39447. library.set( baseClass, nodeClass );
  39448. }
  39449. }
  39450. const _defaultLights = /*@__PURE__*/ new LightsNode();
  39451. const _weakMap = /*@__PURE__*/ new WeakMap();
  39452. /**
  39453. * This renderer module manages the lights nodes which are unique
  39454. * per scene and camera combination.
  39455. *
  39456. * The lights node itself is later configured in the render list
  39457. * with the actual lights from the scene.
  39458. *
  39459. * @private
  39460. */
  39461. class Lighting {
  39462. /**
  39463. * Creates a new lights node for the given array of lights.
  39464. *
  39465. * @param {Array<Light>} lights - The render object.
  39466. * @return {LightsNode} The lights node.
  39467. */
  39468. createNode( lights = [] ) {
  39469. return new LightsNode().setLights( lights );
  39470. }
  39471. /**
  39472. * Returns a lights node for the given scene and camera.
  39473. *
  39474. * @param {Scene} scene - The scene.
  39475. * @param {Camera} camera - The camera.
  39476. * @return {LightsNode} The lights node.
  39477. */
  39478. getNode( scene ) {
  39479. // ignore post-processing
  39480. if ( scene.isQuadMesh ) return _defaultLights;
  39481. let node = _weakMap.get( scene );
  39482. if ( node === undefined ) {
  39483. node = this.createNode();
  39484. _weakMap.set( scene, node );
  39485. }
  39486. return node;
  39487. }
  39488. }
  39489. /**
  39490. * A special type of render target that is used when rendering
  39491. * with the WebXR Device API.
  39492. *
  39493. * @private
  39494. * @augments RenderTarget
  39495. */
  39496. class XRRenderTarget extends RenderTarget {
  39497. /**
  39498. * Constructs a new XR render target.
  39499. *
  39500. * @param {number} [width=1] - The width of the render target.
  39501. * @param {number} [height=1] - The height of the render target.
  39502. * @param {Object} [options={}] - The configuration options.
  39503. */
  39504. constructor( width = 1, height = 1, options = {} ) {
  39505. super( width, height, options );
  39506. /**
  39507. * This flag can be used for type testing.
  39508. *
  39509. * @type {boolean}
  39510. * @readonly
  39511. * @default true
  39512. */
  39513. this.isXRRenderTarget = true;
  39514. /**
  39515. * Whether the attachments of the render target
  39516. * are defined by external textures. This flag is
  39517. * set to `true` when using the WebXR Layers API.
  39518. *
  39519. * @private
  39520. * @type {boolean}
  39521. * @default false
  39522. */
  39523. this._hasExternalTextures = false;
  39524. /**
  39525. * Whether a depth buffer should automatically be allocated
  39526. * for this XR render target or not.
  39527. *
  39528. * Allocating a depth buffer is the default behavior of XR render
  39529. * targets. However, when using the WebXR Layers API, this flag
  39530. * must be set to `false` when the `ignoreDepthValues` property of
  39531. * the projection layers evaluates to `false`.
  39532. *
  39533. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  39534. *
  39535. * @private
  39536. * @type {boolean}
  39537. * @default true
  39538. */
  39539. this._autoAllocateDepthBuffer = true;
  39540. /**
  39541. * Whether this render target is associated with a XRWebGLLayer.
  39542. *
  39543. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  39544. * this means that you don't have access to its bound color,
  39545. * stencil and depth buffers. We need to handle this framebuffer
  39546. * differently since its textures are always bound.
  39547. *
  39548. * @private
  39549. * @type {boolean}
  39550. * @default false
  39551. * */
  39552. this._isOpaqueFramebuffer = false;
  39553. }
  39554. copy( source ) {
  39555. super.copy( source );
  39556. this._hasExternalTextures = source._hasExternalTextures;
  39557. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  39558. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  39559. return this;
  39560. }
  39561. }
  39562. const _cameraLPos = /*@__PURE__*/ new Vector3();
  39563. const _cameraRPos = /*@__PURE__*/ new Vector3();
  39564. /**
  39565. * The XR manager is built on top of the WebXR Device API to
  39566. * manage XR sessions with `WebGPURenderer`.
  39567. *
  39568. * XR is currently only supported with a WebGL 2 backend.
  39569. *
  39570. * @augments EventDispatcher
  39571. */
  39572. class XRManager extends EventDispatcher {
  39573. /**
  39574. * Constructs a new XR manager.
  39575. *
  39576. * @param {Renderer} renderer - The renderer.
  39577. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  39578. */
  39579. constructor( renderer, multiview = false ) {
  39580. super();
  39581. /**
  39582. * This flag globally enables XR rendering.
  39583. *
  39584. * @type {boolean}
  39585. * @default false
  39586. */
  39587. this.enabled = false;
  39588. /**
  39589. * Whether the XR device is currently presenting or not.
  39590. *
  39591. * @type {boolean}
  39592. * @default false
  39593. * @readonly
  39594. */
  39595. this.isPresenting = false;
  39596. /**
  39597. * Whether the XR camera should automatically be updated or not.
  39598. *
  39599. * @type {boolean}
  39600. * @default true
  39601. */
  39602. this.cameraAutoUpdate = true;
  39603. /**
  39604. * The renderer.
  39605. *
  39606. * @private
  39607. * @type {Renderer}
  39608. */
  39609. this._renderer = renderer;
  39610. // camera
  39611. /**
  39612. * Represents the camera for the left eye.
  39613. *
  39614. * @private
  39615. * @type {PerspectiveCamera}
  39616. */
  39617. this._cameraL = new PerspectiveCamera();
  39618. this._cameraL.viewport = new Vector4();
  39619. /**
  39620. * Represents the camera for the right eye.
  39621. *
  39622. * @private
  39623. * @type {PerspectiveCamera}
  39624. */
  39625. this._cameraR = new PerspectiveCamera();
  39626. this._cameraR.viewport = new Vector4();
  39627. /**
  39628. * A list of cameras used for rendering the XR views.
  39629. *
  39630. * @private
  39631. * @type {Array<Camera>}
  39632. */
  39633. this._cameras = [ this._cameraL, this._cameraR ];
  39634. /**
  39635. * The main XR camera.
  39636. *
  39637. * @private
  39638. * @type {ArrayCamera}
  39639. */
  39640. this._cameraXR = new ArrayCamera();
  39641. /**
  39642. * The current near value of the XR camera.
  39643. *
  39644. * @private
  39645. * @type {?number}
  39646. * @default null
  39647. */
  39648. this._currentDepthNear = null;
  39649. /**
  39650. * The current far value of the XR camera.
  39651. *
  39652. * @private
  39653. * @type {?number}
  39654. * @default null
  39655. */
  39656. this._currentDepthFar = null;
  39657. /**
  39658. * A list of WebXR controllers requested by the application.
  39659. *
  39660. * @private
  39661. * @type {Array<WebXRController>}
  39662. */
  39663. this._controllers = [];
  39664. /**
  39665. * A list of XR input source. Each input source belongs to
  39666. * an instance of WebXRController.
  39667. *
  39668. * @private
  39669. * @type {Array<XRInputSource?>}
  39670. */
  39671. this._controllerInputSources = [];
  39672. /**
  39673. * The XR render target that represents the rendering destination
  39674. * during an active XR session.
  39675. *
  39676. * @private
  39677. * @type {?RenderTarget}
  39678. * @default null
  39679. */
  39680. this._xrRenderTarget = null;
  39681. /**
  39682. * An array holding all the non-projection layers
  39683. *
  39684. * @private
  39685. * @type {Array<Object>}
  39686. * @default []
  39687. */
  39688. this._layers = [];
  39689. /**
  39690. * Whether the XR session uses layers.
  39691. *
  39692. * @private
  39693. * @type {boolean}
  39694. * @default false
  39695. */
  39696. this._sessionUsesLayers = false;
  39697. /**
  39698. * Whether the device supports binding gl objects.
  39699. *
  39700. * @private
  39701. * @type {boolean}
  39702. * @readonly
  39703. */
  39704. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  39705. this._frameBufferTargets = null;
  39706. /**
  39707. * Helper function to create native WebXR Layer.
  39708. *
  39709. * @private
  39710. * @type {Function}
  39711. */
  39712. this._createXRLayer = createXRLayer.bind( this );
  39713. /**
  39714. * The current WebGL context.
  39715. *
  39716. * @private
  39717. * @type {?WebGL2RenderingContext}
  39718. * @default null
  39719. */
  39720. this._gl = null;
  39721. /**
  39722. * The current animation context.
  39723. *
  39724. * @private
  39725. * @type {?Window}
  39726. * @default null
  39727. */
  39728. this._currentAnimationContext = null;
  39729. /**
  39730. * The current animation loop.
  39731. *
  39732. * @private
  39733. * @type {?Function}
  39734. * @default null
  39735. */
  39736. this._currentAnimationLoop = null;
  39737. /**
  39738. * The current pixel ratio.
  39739. *
  39740. * @private
  39741. * @type {?number}
  39742. * @default null
  39743. */
  39744. this._currentPixelRatio = null;
  39745. /**
  39746. * The current size of the renderer's canvas
  39747. * in logical pixel unit.
  39748. *
  39749. * @private
  39750. * @type {Vector2}
  39751. */
  39752. this._currentSize = new Vector2();
  39753. /**
  39754. * The default event listener for handling events inside a XR session.
  39755. *
  39756. * @private
  39757. * @type {Function}
  39758. */
  39759. this._onSessionEvent = onSessionEvent.bind( this );
  39760. /**
  39761. * The event listener for handling the end of a XR session.
  39762. *
  39763. * @private
  39764. * @type {Function}
  39765. */
  39766. this._onSessionEnd = onSessionEnd.bind( this );
  39767. /**
  39768. * The event listener for handling the `inputsourceschange` event.
  39769. *
  39770. * @private
  39771. * @type {Function}
  39772. */
  39773. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  39774. /**
  39775. * The animation loop which is used as a replacement for the default
  39776. * animation loop of the application. It is only used when a XR session
  39777. * is active.
  39778. *
  39779. * @private
  39780. * @type {Function}
  39781. */
  39782. this._onAnimationFrame = onAnimationFrame.bind( this );
  39783. /**
  39784. * The current XR reference space.
  39785. *
  39786. * @private
  39787. * @type {?XRReferenceSpace}
  39788. * @default null
  39789. */
  39790. this._referenceSpace = null;
  39791. /**
  39792. * The current XR reference space type.
  39793. *
  39794. * @private
  39795. * @type {XRReferenceSpaceType}
  39796. * @default 'local-floor'
  39797. */
  39798. this._referenceSpaceType = 'local-floor';
  39799. /**
  39800. * A custom reference space defined by the application.
  39801. *
  39802. * @private
  39803. * @type {?XRReferenceSpace}
  39804. * @default null
  39805. */
  39806. this._customReferenceSpace = null;
  39807. /**
  39808. * The framebuffer scale factor.
  39809. *
  39810. * @private
  39811. * @type {number}
  39812. * @default 1
  39813. */
  39814. this._framebufferScaleFactor = 1;
  39815. /**
  39816. * The foveation factor.
  39817. *
  39818. * @private
  39819. * @type {number}
  39820. * @default 1
  39821. */
  39822. this._foveation = 1.0;
  39823. /**
  39824. * A reference to the current XR session.
  39825. *
  39826. * @private
  39827. * @type {?XRSession}
  39828. * @default null
  39829. */
  39830. this._session = null;
  39831. /**
  39832. * A reference to the current XR base layer.
  39833. *
  39834. * @private
  39835. * @type {?XRWebGLLayer}
  39836. * @default null
  39837. */
  39838. this._glBaseLayer = null;
  39839. /**
  39840. * A reference to the current XR binding.
  39841. *
  39842. * @private
  39843. * @type {?XRWebGLBinding}
  39844. * @default null
  39845. */
  39846. this._glBinding = null;
  39847. /**
  39848. * A reference to the current XR projection layer.
  39849. *
  39850. * @private
  39851. * @type {?XRProjectionLayer}
  39852. * @default null
  39853. */
  39854. this._glProjLayer = null;
  39855. /**
  39856. * A reference to the current XR frame.
  39857. *
  39858. * @private
  39859. * @type {?XRFrame}
  39860. * @default null
  39861. */
  39862. this._xrFrame = null;
  39863. /**
  39864. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  39865. *
  39866. * Note: this does not represent XRSession explicitly requesting
  39867. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  39868. *
  39869. * @private
  39870. * @type {boolean}
  39871. * @readonly
  39872. */
  39873. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  39874. /**
  39875. * Whether the usage of multiview has been requested by the application or not.
  39876. *
  39877. * @private
  39878. * @type {boolean}
  39879. * @default false
  39880. * @readonly
  39881. */
  39882. this._useMultiviewIfPossible = multiview;
  39883. /**
  39884. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  39885. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  39886. *
  39887. * @private
  39888. * @type {boolean}
  39889. * @readonly
  39890. */
  39891. this._useMultiview = false;
  39892. }
  39893. /**
  39894. * Returns an instance of `THREE.Group` that represents the transformation
  39895. * of a XR controller in target ray space. The requested controller is defined
  39896. * by the given index.
  39897. *
  39898. * @param {number} index - The index of the XR controller.
  39899. * @return {Group} A group that represents the controller's transformation.
  39900. */
  39901. getController( index ) {
  39902. const controller = this._getController( index );
  39903. return controller.getTargetRaySpace();
  39904. }
  39905. /**
  39906. * Returns an instance of `THREE.Group` that represents the transformation
  39907. * of a XR controller in grip space. The requested controller is defined
  39908. * by the given index.
  39909. *
  39910. * @param {number} index - The index of the XR controller.
  39911. * @return {Group} A group that represents the controller's transformation.
  39912. */
  39913. getControllerGrip( index ) {
  39914. const controller = this._getController( index );
  39915. return controller.getGripSpace();
  39916. }
  39917. /**
  39918. * Returns an instance of `THREE.Group` that represents the transformation
  39919. * of a XR controller in hand space. The requested controller is defined
  39920. * by the given index.
  39921. *
  39922. * @param {number} index - The index of the XR controller.
  39923. * @return {Group} A group that represents the controller's transformation.
  39924. */
  39925. getHand( index ) {
  39926. const controller = this._getController( index );
  39927. return controller.getHandSpace();
  39928. }
  39929. /**
  39930. * Returns the foveation value.
  39931. *
  39932. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  39933. */
  39934. getFoveation() {
  39935. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  39936. return undefined;
  39937. }
  39938. return this._foveation;
  39939. }
  39940. /**
  39941. * Sets the foveation value.
  39942. *
  39943. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  39944. * and `1` means maximum foveation (the edges render at lower resolution).
  39945. */
  39946. setFoveation( foveation ) {
  39947. this._foveation = foveation;
  39948. if ( this._glProjLayer !== null ) {
  39949. this._glProjLayer.fixedFoveation = foveation;
  39950. }
  39951. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  39952. this._glBaseLayer.fixedFoveation = foveation;
  39953. }
  39954. }
  39955. /**
  39956. * Returns the framebuffer scale factor.
  39957. *
  39958. * @return {number} The framebuffer scale factor.
  39959. */
  39960. getFramebufferScaleFactor() {
  39961. return this._framebufferScaleFactor;
  39962. }
  39963. /**
  39964. * Sets the framebuffer scale factor.
  39965. *
  39966. * This method can not be used during a XR session.
  39967. *
  39968. * @param {number} factor - The framebuffer scale factor.
  39969. */
  39970. setFramebufferScaleFactor( factor ) {
  39971. this._framebufferScaleFactor = factor;
  39972. if ( this.isPresenting === true ) {
  39973. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  39974. }
  39975. }
  39976. /**
  39977. * Returns the reference space type.
  39978. *
  39979. * @return {XRReferenceSpaceType} The reference space type.
  39980. */
  39981. getReferenceSpaceType() {
  39982. return this._referenceSpaceType;
  39983. }
  39984. /**
  39985. * Sets the reference space type.
  39986. *
  39987. * This method can not be used during a XR session.
  39988. *
  39989. * @param {XRReferenceSpaceType} type - The reference space type.
  39990. */
  39991. setReferenceSpaceType( type ) {
  39992. this._referenceSpaceType = type;
  39993. if ( this.isPresenting === true ) {
  39994. warn( 'XRManager: Cannot change reference space type while presenting.' );
  39995. }
  39996. }
  39997. /**
  39998. * Returns the XR reference space.
  39999. *
  40000. * @return {XRReferenceSpace} The XR reference space.
  40001. */
  40002. getReferenceSpace() {
  40003. return this._customReferenceSpace || this._referenceSpace;
  40004. }
  40005. /**
  40006. * Sets a custom XR reference space.
  40007. *
  40008. * @param {XRReferenceSpace} space - The XR reference space.
  40009. */
  40010. setReferenceSpace( space ) {
  40011. this._customReferenceSpace = space;
  40012. }
  40013. /**
  40014. * Returns the XR camera.
  40015. *
  40016. * @return {ArrayCamera} The XR camera.
  40017. */
  40018. getCamera() {
  40019. return this._cameraXR;
  40020. }
  40021. /**
  40022. * Returns the environment blend mode from the current XR session.
  40023. *
  40024. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  40025. */
  40026. getEnvironmentBlendMode() {
  40027. if ( this._session !== null ) {
  40028. return this._session.environmentBlendMode;
  40029. }
  40030. }
  40031. /**
  40032. * Returns the current XR binding.
  40033. *
  40034. * Creates a new binding if needed and the browser is
  40035. * capable of doing so.
  40036. *
  40037. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  40038. */
  40039. getBinding() {
  40040. if ( this._glBinding === null && this._supportsGlBinding ) {
  40041. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  40042. }
  40043. return this._glBinding;
  40044. }
  40045. /**
  40046. * Returns the current XR frame.
  40047. *
  40048. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  40049. */
  40050. getFrame() {
  40051. return this._xrFrame;
  40052. }
  40053. /**
  40054. * Returns `true` if the engine renders to a multiview target.
  40055. *
  40056. * @return {boolean} Whether the engine renders to a multiview render target or not.
  40057. */
  40058. useMultiview() {
  40059. return this._useMultiview;
  40060. }
  40061. /**
  40062. * This method can be used in XR applications to create a quadratic layer that presents a separate
  40063. * rendered scene.
  40064. *
  40065. * @param {number} width - The width of the layer plane in world units.
  40066. * @param {number} height - The height of the layer plane in world units.
  40067. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40068. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40069. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40070. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40071. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40072. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40073. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40074. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  40075. */
  40076. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40077. const geometry = new PlaneGeometry( width, height );
  40078. const renderTarget = new XRRenderTarget(
  40079. pixelwidth,
  40080. pixelheight,
  40081. {
  40082. format: RGBAFormat,
  40083. type: UnsignedByteType,
  40084. depthTexture: new DepthTexture(
  40085. pixelwidth,
  40086. pixelheight,
  40087. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40088. undefined,
  40089. undefined,
  40090. undefined,
  40091. undefined,
  40092. undefined,
  40093. undefined,
  40094. attributes.stencil ? DepthStencilFormat : DepthFormat
  40095. ),
  40096. stencilBuffer: attributes.stencil,
  40097. resolveDepthBuffer: false,
  40098. resolveStencilBuffer: false
  40099. } );
  40100. renderTarget._autoAllocateDepthBuffer = true;
  40101. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40102. material.map = renderTarget.texture;
  40103. material.map.offset.y = 1;
  40104. material.map.repeat.y = -1;
  40105. const plane = new Mesh( geometry, material );
  40106. plane.position.copy( translation );
  40107. plane.quaternion.copy( quaternion );
  40108. const layer = {
  40109. type: 'quad',
  40110. width: width,
  40111. height: height,
  40112. translation: translation,
  40113. quaternion: quaternion,
  40114. pixelwidth: pixelwidth,
  40115. pixelheight: pixelheight,
  40116. plane: plane,
  40117. material: material,
  40118. rendercall: rendercall,
  40119. renderTarget: renderTarget };
  40120. this._layers.push( layer );
  40121. if ( this._session !== null ) {
  40122. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  40123. layer.plane.material.blending = CustomBlending;
  40124. layer.plane.material.blendEquation = AddEquation;
  40125. layer.plane.material.blendSrc = ZeroFactor;
  40126. layer.plane.material.blendDst = ZeroFactor;
  40127. layer.xrlayer = this._createXRLayer( layer );
  40128. const xrlayers = this._session.renderState.layers;
  40129. xrlayers.unshift( layer.xrlayer );
  40130. this._session.updateRenderState( { layers: xrlayers } );
  40131. } else {
  40132. renderTarget.isXRRenderTarget = false;
  40133. }
  40134. return plane;
  40135. }
  40136. /**
  40137. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  40138. * rendered scene.
  40139. *
  40140. * @param {number} radius - The radius of the cylinder in world units.
  40141. * @param {number} centralAngle - The central angle of the cylinder in radians.
  40142. * @param {number} aspectratio - The aspect ratio.
  40143. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  40144. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  40145. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  40146. * @param {number} pixelheight - The height of the layer's render target in pixels.
  40147. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  40148. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  40149. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  40150. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  40151. */
  40152. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  40153. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  40154. const renderTarget = new XRRenderTarget(
  40155. pixelwidth,
  40156. pixelheight,
  40157. {
  40158. format: RGBAFormat,
  40159. type: UnsignedByteType,
  40160. depthTexture: new DepthTexture(
  40161. pixelwidth,
  40162. pixelheight,
  40163. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  40164. undefined,
  40165. undefined,
  40166. undefined,
  40167. undefined,
  40168. undefined,
  40169. undefined,
  40170. attributes.stencil ? DepthStencilFormat : DepthFormat
  40171. ),
  40172. stencilBuffer: attributes.stencil,
  40173. resolveDepthBuffer: false,
  40174. resolveStencilBuffer: false
  40175. } );
  40176. renderTarget._autoAllocateDepthBuffer = true;
  40177. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40178. material.map = renderTarget.texture;
  40179. material.map.offset.y = 1;
  40180. material.map.repeat.y = -1;
  40181. const plane = new Mesh( geometry, material );
  40182. plane.position.copy( translation );
  40183. plane.quaternion.copy( quaternion );
  40184. const layer = {
  40185. type: 'cylinder',
  40186. radius: radius,
  40187. centralAngle: centralAngle,
  40188. aspectratio: aspectratio,
  40189. translation: translation,
  40190. quaternion: quaternion,
  40191. pixelwidth: pixelwidth,
  40192. pixelheight: pixelheight,
  40193. plane: plane,
  40194. material: material,
  40195. rendercall: rendercall,
  40196. renderTarget: renderTarget };
  40197. this._layers.push( layer );
  40198. if ( this._session !== null ) {
  40199. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  40200. layer.plane.material.blending = CustomBlending;
  40201. layer.plane.material.blendEquation = AddEquation;
  40202. layer.plane.material.blendSrc = ZeroFactor;
  40203. layer.plane.material.blendDst = ZeroFactor;
  40204. layer.xrlayer = this._createXRLayer( layer );
  40205. const xrlayers = this._session.renderState.layers;
  40206. xrlayers.unshift( layer.xrlayer );
  40207. this._session.updateRenderState( { layers: xrlayers } );
  40208. } else {
  40209. renderTarget.isXRRenderTarget = false;
  40210. }
  40211. return plane;
  40212. }
  40213. /**
  40214. * Renders the XR layers that have been previously added to the scene.
  40215. *
  40216. * This method is usually called in your animation loop before rendering
  40217. * the actual scene via `renderer.render( scene, camera );`.
  40218. */
  40219. renderLayers( ) {
  40220. const translationObject = new Vector3();
  40221. const quaternionObject = new Quaternion();
  40222. const renderer = this._renderer;
  40223. const wasPresenting = this.isPresenting;
  40224. const rendererOutputTarget = renderer.getOutputRenderTarget();
  40225. const rendererFramebufferTarget = renderer._frameBufferTarget;
  40226. this.isPresenting = false;
  40227. const rendererSize = new Vector2();
  40228. renderer.getSize( rendererSize );
  40229. const rendererQuad = renderer._quad;
  40230. for ( const layer of this._layers ) {
  40231. layer.renderTarget.isXRRenderTarget = this._session !== null;
  40232. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  40233. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  40234. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  40235. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  40236. renderer.backend.setXRRenderTargetTextures(
  40237. layer.renderTarget,
  40238. glSubImage.colorTexture,
  40239. undefined );
  40240. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  40241. renderer.setOutputRenderTarget( layer.renderTarget );
  40242. renderer.setRenderTarget( null );
  40243. renderer._frameBufferTarget = null;
  40244. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  40245. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  40246. if ( ! frameBufferTarget ) {
  40247. renderer._quad = new QuadMesh( new NodeMaterial() );
  40248. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  40249. } else {
  40250. renderer._frameBufferTarget = frameBufferTarget;
  40251. renderer._quad = quad;
  40252. }
  40253. layer.rendercall();
  40254. renderer._frameBufferTarget = null;
  40255. } else {
  40256. renderer.setRenderTarget( layer.renderTarget );
  40257. layer.rendercall();
  40258. }
  40259. }
  40260. renderer.setRenderTarget( null );
  40261. renderer.setOutputRenderTarget( rendererOutputTarget );
  40262. renderer._frameBufferTarget = rendererFramebufferTarget;
  40263. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  40264. renderer._quad = rendererQuad;
  40265. this.isPresenting = wasPresenting;
  40266. }
  40267. /**
  40268. * Returns the current XR session.
  40269. *
  40270. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  40271. */
  40272. getSession() {
  40273. return this._session;
  40274. }
  40275. /**
  40276. * After a XR session has been requested usually with one of the `*Button` modules, it
  40277. * is injected into the renderer with this method. This method triggers the start of
  40278. * the actual XR rendering.
  40279. *
  40280. * @async
  40281. * @param {XRSession} session - The XR session to set.
  40282. * @return {Promise} A Promise that resolves when the session has been set.
  40283. */
  40284. async setSession( session ) {
  40285. const renderer = this._renderer;
  40286. const backend = renderer.backend;
  40287. this._gl = renderer.getContext();
  40288. const gl = this._gl;
  40289. const attributes = gl.getContextAttributes();
  40290. this._session = session;
  40291. if ( session !== null ) {
  40292. if ( backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  40293. session.addEventListener( 'select', this._onSessionEvent );
  40294. session.addEventListener( 'selectstart', this._onSessionEvent );
  40295. session.addEventListener( 'selectend', this._onSessionEvent );
  40296. session.addEventListener( 'squeeze', this._onSessionEvent );
  40297. session.addEventListener( 'squeezestart', this._onSessionEvent );
  40298. session.addEventListener( 'squeezeend', this._onSessionEvent );
  40299. session.addEventListener( 'end', this._onSessionEnd );
  40300. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40301. await backend.makeXRCompatible();
  40302. this._currentPixelRatio = renderer.getPixelRatio();
  40303. renderer.getSize( this._currentSize );
  40304. this._currentAnimationContext = renderer._animation.getContext();
  40305. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  40306. renderer._animation.stop();
  40307. //
  40308. if ( this._supportsLayers === true ) {
  40309. // default path using XRProjectionLayer
  40310. let depthFormat = null;
  40311. let depthType = null;
  40312. let glDepthFormat = null;
  40313. if ( renderer.depth ) {
  40314. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40315. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  40316. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  40317. }
  40318. const projectionlayerInit = {
  40319. colorFormat: gl.RGBA8,
  40320. depthFormat: glDepthFormat,
  40321. scaleFactor: this._framebufferScaleFactor,
  40322. clearOnAccess: false
  40323. };
  40324. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  40325. projectionlayerInit.textureType = 'texture-array';
  40326. this._useMultiview = true;
  40327. }
  40328. this._glBinding = this.getBinding();
  40329. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  40330. const layersArray = [ glProjLayer ];
  40331. this._glProjLayer = glProjLayer;
  40332. renderer.setPixelRatio( 1 );
  40333. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  40334. const depth = this._useMultiview ? 2 : 1;
  40335. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  40336. this._xrRenderTarget = new XRRenderTarget(
  40337. glProjLayer.textureWidth,
  40338. glProjLayer.textureHeight,
  40339. {
  40340. format: RGBAFormat,
  40341. type: UnsignedByteType,
  40342. colorSpace: renderer.outputColorSpace,
  40343. depthTexture: depthTexture,
  40344. stencilBuffer: renderer.stencil,
  40345. samples: attributes.antialias ? 4 : 0,
  40346. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40347. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  40348. depth: this._useMultiview ? 2 : 1,
  40349. multiview: this._useMultiview
  40350. } );
  40351. this._xrRenderTarget._hasExternalTextures = true;
  40352. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  40353. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  40354. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40355. if ( this._sessionUsesLayers ) {
  40356. // switch layers to native
  40357. for ( const layer of this._layers ) {
  40358. // change material so it "punches" out a hole to show the XR Layer.
  40359. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  40360. layer.plane.material.blending = CustomBlending;
  40361. layer.plane.material.blendEquation = AddEquation;
  40362. layer.plane.material.blendSrc = ZeroFactor;
  40363. layer.plane.material.blendDst = ZeroFactor;
  40364. layer.xrlayer = this._createXRLayer( layer );
  40365. layersArray.unshift( layer.xrlayer );
  40366. }
  40367. }
  40368. session.updateRenderState( { layers: layersArray } );
  40369. } else {
  40370. // fallback to XRWebGLLayer
  40371. const layerInit = {
  40372. antialias: renderer.currentSamples > 0,
  40373. alpha: true,
  40374. depth: renderer.depth,
  40375. stencil: renderer.stencil,
  40376. framebufferScaleFactor: this.getFramebufferScaleFactor()
  40377. };
  40378. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  40379. this._glBaseLayer = glBaseLayer;
  40380. session.updateRenderState( { baseLayer: glBaseLayer } );
  40381. renderer.setPixelRatio( 1 );
  40382. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  40383. this._xrRenderTarget = new XRRenderTarget(
  40384. glBaseLayer.framebufferWidth,
  40385. glBaseLayer.framebufferHeight,
  40386. {
  40387. format: RGBAFormat,
  40388. type: UnsignedByteType,
  40389. colorSpace: renderer.outputColorSpace,
  40390. stencilBuffer: renderer.stencil,
  40391. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40392. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  40393. }
  40394. );
  40395. this._xrRenderTarget._isOpaqueFramebuffer = true;
  40396. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  40397. }
  40398. //
  40399. this.setFoveation( this.getFoveation() );
  40400. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  40401. renderer._animation.setContext( session );
  40402. renderer._animation.start();
  40403. this.isPresenting = true;
  40404. this.dispatchEvent( { type: 'sessionstart' } );
  40405. }
  40406. }
  40407. /**
  40408. * This method is called by the renderer per frame and updates the XR camera
  40409. * and it sub cameras based on the given camera. The given camera is the "user"
  40410. * camera created on application level and used for non-XR rendering.
  40411. *
  40412. * @param {PerspectiveCamera} camera - The camera.
  40413. */
  40414. updateCamera( camera ) {
  40415. const session = this._session;
  40416. if ( session === null ) return;
  40417. const depthNear = camera.near;
  40418. const depthFar = camera.far;
  40419. const cameraXR = this._cameraXR;
  40420. const cameraL = this._cameraL;
  40421. const cameraR = this._cameraR;
  40422. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  40423. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  40424. cameraXR.isMultiViewCamera = this._useMultiview;
  40425. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  40426. // Note that the new renderState won't apply until the next frame. See #18320
  40427. session.updateRenderState( {
  40428. depthNear: cameraXR.near,
  40429. depthFar: cameraXR.far
  40430. } );
  40431. this._currentDepthNear = cameraXR.near;
  40432. this._currentDepthFar = cameraXR.far;
  40433. }
  40434. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  40435. cameraXR.layers.mask = camera.layers.mask | 0b110;
  40436. cameraL.layers.mask = cameraXR.layers.mask & -5;
  40437. cameraR.layers.mask = cameraXR.layers.mask & -3;
  40438. const parent = camera.parent;
  40439. const cameras = cameraXR.cameras;
  40440. updateCamera( cameraXR, parent );
  40441. for ( let i = 0; i < cameras.length; i ++ ) {
  40442. updateCamera( cameras[ i ], parent );
  40443. }
  40444. // update projection matrix for proper view frustum culling
  40445. if ( cameras.length === 2 ) {
  40446. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  40447. } else {
  40448. // assume single camera setup (AR)
  40449. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  40450. }
  40451. // update user camera and its children
  40452. updateUserCamera( camera, cameraXR, parent );
  40453. }
  40454. /**
  40455. * Returns a WebXR controller for the given controller index.
  40456. *
  40457. * @private
  40458. * @param {number} index - The controller index.
  40459. * @return {WebXRController} The XR controller.
  40460. */
  40461. _getController( index ) {
  40462. let controller = this._controllers[ index ];
  40463. if ( controller === undefined ) {
  40464. controller = new WebXRController();
  40465. this._controllers[ index ] = controller;
  40466. }
  40467. return controller;
  40468. }
  40469. }
  40470. /**
  40471. * Assumes 2 cameras that are parallel and share an X-axis, and that
  40472. * the cameras' projection and world matrices have already been set.
  40473. * And that near and far planes are identical for both cameras.
  40474. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  40475. *
  40476. * @param {ArrayCamera} camera - The camera to update.
  40477. * @param {PerspectiveCamera} cameraL - The left camera.
  40478. * @param {PerspectiveCamera} cameraR - The right camera.
  40479. */
  40480. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  40481. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  40482. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  40483. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  40484. const projL = cameraL.projectionMatrix.elements;
  40485. const projR = cameraR.projectionMatrix.elements;
  40486. // VR systems will have identical far and near planes, and
  40487. // most likely identical top and bottom frustum extents.
  40488. // Use the left camera for these values.
  40489. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  40490. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  40491. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  40492. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  40493. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  40494. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  40495. const left = near * leftFov;
  40496. const right = near * rightFov;
  40497. // Calculate the new camera's position offset from the
  40498. // left camera. xOffset should be roughly half `ipd`.
  40499. const zOffset = ipd / ( - leftFov + rightFov );
  40500. const xOffset = zOffset * - leftFov;
  40501. // TODO: Better way to apply this offset?
  40502. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  40503. camera.translateX( xOffset );
  40504. camera.translateZ( zOffset );
  40505. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  40506. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40507. // Check if the projection uses an infinite far plane.
  40508. if ( projL[ 10 ] === -1 ) {
  40509. // Use the projection matrix from the left eye.
  40510. // The camera offset is sufficient to include the view volumes
  40511. // of both eyes (assuming symmetric projections).
  40512. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  40513. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  40514. } else {
  40515. // Find the union of the frustum values of the cameras and scale
  40516. // the values so that the near plane's position does not change in world space,
  40517. // although must now be relative to the new union camera.
  40518. const near2 = near + zOffset;
  40519. const far2 = far + zOffset;
  40520. const left2 = left - xOffset;
  40521. const right2 = right + ( ipd - xOffset );
  40522. const top2 = topFov * far / far2 * near2;
  40523. const bottom2 = bottomFov * far / far2 * near2;
  40524. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  40525. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40526. }
  40527. }
  40528. /**
  40529. * Updates the world matrices for the given camera based on the parent 3D object.
  40530. *
  40531. * @inner
  40532. * @param {Camera} camera - The camera to update.
  40533. * @param {Object3D} parent - The parent 3D object.
  40534. */
  40535. function updateCamera( camera, parent ) {
  40536. if ( parent === null ) {
  40537. camera.matrixWorld.copy( camera.matrix );
  40538. } else {
  40539. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  40540. }
  40541. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  40542. }
  40543. /**
  40544. * Updates the given camera with the transformation of the XR camera and parent object.
  40545. *
  40546. * @inner
  40547. * @param {Camera} camera - The camera to update.
  40548. * @param {ArrayCamera} cameraXR - The XR camera.
  40549. * @param {Object3D} parent - The parent 3D object.
  40550. */
  40551. function updateUserCamera( camera, cameraXR, parent ) {
  40552. if ( parent === null ) {
  40553. camera.matrix.copy( cameraXR.matrixWorld );
  40554. } else {
  40555. camera.matrix.copy( parent.matrixWorld );
  40556. camera.matrix.invert();
  40557. camera.matrix.multiply( cameraXR.matrixWorld );
  40558. }
  40559. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40560. camera.updateMatrixWorld( true );
  40561. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  40562. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  40563. if ( camera.isPerspectiveCamera ) {
  40564. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  40565. camera.zoom = 1;
  40566. }
  40567. }
  40568. function onSessionEvent( event ) {
  40569. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  40570. if ( controllerIndex === -1 ) {
  40571. return;
  40572. }
  40573. const controller = this._controllers[ controllerIndex ];
  40574. if ( controller !== undefined ) {
  40575. const referenceSpace = this.getReferenceSpace();
  40576. controller.update( event.inputSource, event.frame, referenceSpace );
  40577. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  40578. }
  40579. }
  40580. function onSessionEnd() {
  40581. const session = this._session;
  40582. const renderer = this._renderer;
  40583. session.removeEventListener( 'select', this._onSessionEvent );
  40584. session.removeEventListener( 'selectstart', this._onSessionEvent );
  40585. session.removeEventListener( 'selectend', this._onSessionEvent );
  40586. session.removeEventListener( 'squeeze', this._onSessionEvent );
  40587. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  40588. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  40589. session.removeEventListener( 'end', this._onSessionEnd );
  40590. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  40591. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40592. const inputSource = this._controllerInputSources[ i ];
  40593. if ( inputSource === null ) continue;
  40594. this._controllerInputSources[ i ] = null;
  40595. this._controllers[ i ].disconnect( inputSource );
  40596. }
  40597. this._currentDepthNear = null;
  40598. this._currentDepthFar = null;
  40599. // restore framebuffer/rendering state
  40600. renderer._resetXRState();
  40601. this._session = null;
  40602. this._xrRenderTarget = null;
  40603. this._glBinding = null;
  40604. this._glBaseLayer = null;
  40605. this._glProjLayer = null;
  40606. // switch layers back to emulated
  40607. if ( this._sessionUsesLayers === true ) {
  40608. for ( const layer of this._layers ) {
  40609. // Recreate layer render target to reset state
  40610. layer.renderTarget = new XRRenderTarget(
  40611. layer.pixelwidth,
  40612. layer.pixelheight,
  40613. {
  40614. format: RGBAFormat,
  40615. type: UnsignedByteType,
  40616. depthTexture: new DepthTexture(
  40617. layer.pixelwidth,
  40618. layer.pixelheight,
  40619. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  40620. undefined,
  40621. undefined,
  40622. undefined,
  40623. undefined,
  40624. undefined,
  40625. undefined,
  40626. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  40627. ),
  40628. stencilBuffer: layer.stencilBuffer,
  40629. resolveDepthBuffer: false,
  40630. resolveStencilBuffer: false
  40631. } );
  40632. layer.renderTarget.isXRRenderTarget = false;
  40633. layer.plane.material = layer.material;
  40634. layer.material.map = layer.renderTarget.texture;
  40635. layer.material.map.offset.y = 1;
  40636. layer.material.map.repeat.y = -1;
  40637. delete layer.xrlayer;
  40638. }
  40639. }
  40640. //
  40641. this.isPresenting = false;
  40642. this._useMultiview = false;
  40643. renderer._animation.stop();
  40644. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  40645. renderer._animation.setContext( this._currentAnimationContext );
  40646. renderer._animation.start();
  40647. renderer.setPixelRatio( this._currentPixelRatio );
  40648. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  40649. this.dispatchEvent( { type: 'sessionend' } );
  40650. }
  40651. function onInputSourcesChange( event ) {
  40652. const controllers = this._controllers;
  40653. const controllerInputSources = this._controllerInputSources;
  40654. // Notify disconnected
  40655. for ( let i = 0; i < event.removed.length; i ++ ) {
  40656. const inputSource = event.removed[ i ];
  40657. const index = controllerInputSources.indexOf( inputSource );
  40658. if ( index >= 0 ) {
  40659. controllerInputSources[ index ] = null;
  40660. controllers[ index ].disconnect( inputSource );
  40661. }
  40662. }
  40663. // Notify connected
  40664. for ( let i = 0; i < event.added.length; i ++ ) {
  40665. const inputSource = event.added[ i ];
  40666. let controllerIndex = controllerInputSources.indexOf( inputSource );
  40667. if ( controllerIndex === -1 ) {
  40668. // Assign input source a controller that currently has no input source
  40669. for ( let i = 0; i < controllers.length; i ++ ) {
  40670. if ( i >= controllerInputSources.length ) {
  40671. controllerInputSources.push( inputSource );
  40672. controllerIndex = i;
  40673. break;
  40674. } else if ( controllerInputSources[ i ] === null ) {
  40675. controllerInputSources[ i ] = inputSource;
  40676. controllerIndex = i;
  40677. break;
  40678. }
  40679. }
  40680. // If all controllers do currently receive input we ignore new ones
  40681. if ( controllerIndex === -1 ) break;
  40682. }
  40683. const controller = controllers[ controllerIndex ];
  40684. if ( controller ) {
  40685. controller.connect( inputSource );
  40686. }
  40687. }
  40688. }
  40689. // Creation method for native WebXR layers
  40690. function createXRLayer( layer ) {
  40691. if ( layer.type === 'quad' ) {
  40692. return this._glBinding.createQuadLayer( {
  40693. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40694. width: layer.width / 2,
  40695. height: layer.height / 2,
  40696. space: this._referenceSpace,
  40697. viewPixelWidth: layer.pixelwidth,
  40698. viewPixelHeight: layer.pixelheight,
  40699. clearOnAccess: false
  40700. } );
  40701. } else {
  40702. return this._glBinding.createCylinderLayer( {
  40703. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  40704. radius: layer.radius,
  40705. centralAngle: layer.centralAngle,
  40706. aspectRatio: layer.aspectRatio,
  40707. space: this._referenceSpace,
  40708. viewPixelWidth: layer.pixelwidth,
  40709. viewPixelHeight: layer.pixelheight,
  40710. clearOnAccess: false
  40711. } );
  40712. }
  40713. }
  40714. // Animation Loop
  40715. function onAnimationFrame( time, frame ) {
  40716. if ( frame === undefined ) return;
  40717. const cameraXR = this._cameraXR;
  40718. const renderer = this._renderer;
  40719. const backend = renderer.backend;
  40720. const glBaseLayer = this._glBaseLayer;
  40721. const referenceSpace = this.getReferenceSpace();
  40722. const pose = frame.getViewerPose( referenceSpace );
  40723. this._xrFrame = frame;
  40724. if ( pose !== null ) {
  40725. const views = pose.views;
  40726. if ( this._glBaseLayer !== null ) {
  40727. backend.setXRTarget( glBaseLayer.framebuffer );
  40728. }
  40729. let cameraXRNeedsUpdate = false;
  40730. // check if it's necessary to rebuild cameraXR's camera list
  40731. if ( views.length !== cameraXR.cameras.length ) {
  40732. cameraXR.cameras.length = 0;
  40733. cameraXRNeedsUpdate = true;
  40734. }
  40735. for ( let i = 0; i < views.length; i ++ ) {
  40736. const view = views[ i ];
  40737. let viewport;
  40738. if ( this._supportsLayers === true ) {
  40739. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  40740. viewport = glSubImage.viewport;
  40741. // For side-by-side projection, we only produce a single texture for both eyes.
  40742. if ( i === 0 ) {
  40743. backend.setXRRenderTargetTextures(
  40744. this._xrRenderTarget,
  40745. glSubImage.colorTexture,
  40746. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  40747. );
  40748. }
  40749. } else {
  40750. viewport = glBaseLayer.getViewport( view );
  40751. }
  40752. let camera = this._cameras[ i ];
  40753. if ( camera === undefined ) {
  40754. camera = new PerspectiveCamera();
  40755. camera.layers.enable( i );
  40756. camera.viewport = new Vector4();
  40757. this._cameras[ i ] = camera;
  40758. }
  40759. camera.matrix.fromArray( view.transform.matrix );
  40760. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  40761. camera.projectionMatrix.fromArray( view.projectionMatrix );
  40762. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  40763. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  40764. if ( i === 0 ) {
  40765. cameraXR.matrix.copy( camera.matrix );
  40766. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  40767. }
  40768. if ( cameraXRNeedsUpdate === true ) {
  40769. cameraXR.cameras.push( camera );
  40770. }
  40771. }
  40772. renderer.setOutputRenderTarget( this._xrRenderTarget );
  40773. }
  40774. //
  40775. for ( let i = 0; i < this._controllers.length; i ++ ) {
  40776. const inputSource = this._controllerInputSources[ i ];
  40777. const controller = this._controllers[ i ];
  40778. if ( inputSource !== null && controller !== undefined ) {
  40779. controller.update( inputSource, frame, referenceSpace );
  40780. }
  40781. }
  40782. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  40783. if ( frame.detectedPlanes ) {
  40784. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  40785. }
  40786. this._xrFrame = null;
  40787. }
  40788. /**
  40789. * CanvasTarget is a class that represents the final output destination of the renderer.
  40790. *
  40791. * @augments EventDispatcher
  40792. */
  40793. class CanvasTarget extends EventDispatcher {
  40794. /**
  40795. * Constructs a new CanvasTarget.
  40796. *
  40797. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  40798. */
  40799. constructor( domElement ) {
  40800. super();
  40801. /**
  40802. * A reference to the canvas element the renderer is drawing to.
  40803. * This value of this property will automatically be created by
  40804. * the renderer.
  40805. *
  40806. * @type {HTMLCanvasElement|OffscreenCanvas}
  40807. */
  40808. this.domElement = domElement;
  40809. /**
  40810. * The renderer's pixel ratio.
  40811. *
  40812. * @private
  40813. * @type {number}
  40814. * @default 1
  40815. */
  40816. this._pixelRatio = 1;
  40817. /**
  40818. * The width of the renderer's default framebuffer in logical pixel unit.
  40819. *
  40820. * @private
  40821. * @type {number}
  40822. */
  40823. this._width = this.domElement.width;
  40824. /**
  40825. * The height of the renderer's default framebuffer in logical pixel unit.
  40826. *
  40827. * @private
  40828. * @type {number}
  40829. */
  40830. this._height = this.domElement.height;
  40831. /**
  40832. * The viewport of the renderer in logical pixel unit.
  40833. *
  40834. * @private
  40835. * @type {Vector4}
  40836. */
  40837. this._viewport = new Vector4( 0, 0, this._width, this._height );
  40838. /**
  40839. * The scissor rectangle of the renderer in logical pixel unit.
  40840. *
  40841. * @private
  40842. * @type {Vector4}
  40843. */
  40844. this._scissor = new Vector4( 0, 0, this._width, this._height );
  40845. /**
  40846. * Whether the scissor test should be enabled or not.
  40847. *
  40848. * @private
  40849. * @type {boolean}
  40850. */
  40851. this._scissorTest = false;
  40852. /**
  40853. * The color texture of the default framebuffer.
  40854. *
  40855. * @type {FramebufferTexture}
  40856. */
  40857. this.colorTexture = new FramebufferTexture();
  40858. /**
  40859. * The depth texture of the default framebuffer.
  40860. *
  40861. * @type {DepthTexture}
  40862. */
  40863. this.depthTexture = new DepthTexture();
  40864. }
  40865. /**
  40866. * Returns the pixel ratio.
  40867. *
  40868. * @return {number} The pixel ratio.
  40869. */
  40870. getPixelRatio() {
  40871. return this._pixelRatio;
  40872. }
  40873. /**
  40874. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40875. *
  40876. * @param {Vector2} target - The method writes the result in this target object.
  40877. * @return {Vector2} The drawing buffer size.
  40878. */
  40879. getDrawingBufferSize( target ) {
  40880. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  40881. }
  40882. /**
  40883. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40884. *
  40885. * @param {Vector2} target - The method writes the result in this target object.
  40886. * @return {Vector2} The renderer's size in logical pixels.
  40887. */
  40888. getSize( target ) {
  40889. return target.set( this._width, this._height );
  40890. }
  40891. /**
  40892. * Sets the given pixel ratio and resizes the canvas if necessary.
  40893. *
  40894. * @param {number} [value=1] - The pixel ratio.
  40895. */
  40896. setPixelRatio( value = 1 ) {
  40897. if ( this._pixelRatio === value ) return;
  40898. this._pixelRatio = value;
  40899. this.setSize( this._width, this._height, false );
  40900. }
  40901. /**
  40902. * This method allows to define the drawing buffer size by specifying
  40903. * width, height and pixel ratio all at once. The size of the drawing
  40904. * buffer is computed with this formula:
  40905. * ```js
  40906. * size.x = width * pixelRatio;
  40907. * size.y = height * pixelRatio;
  40908. * ```
  40909. *
  40910. * @param {number} width - The width in logical pixels.
  40911. * @param {number} height - The height in logical pixels.
  40912. * @param {number} pixelRatio - The pixel ratio.
  40913. */
  40914. setDrawingBufferSize( width, height, pixelRatio ) {
  40915. // Renderer can't be resized while presenting in XR.
  40916. if ( this.xr && this.xr.isPresenting ) return;
  40917. this._width = width;
  40918. this._height = height;
  40919. this._pixelRatio = pixelRatio;
  40920. this.domElement.width = Math.floor( width * pixelRatio );
  40921. this.domElement.height = Math.floor( height * pixelRatio );
  40922. this.setViewport( 0, 0, width, height );
  40923. this._dispatchResize();
  40924. }
  40925. /**
  40926. * Sets the size of the renderer.
  40927. *
  40928. * @param {number} width - The width in logical pixels.
  40929. * @param {number} height - The height in logical pixels.
  40930. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40931. */
  40932. setSize( width, height, updateStyle = true ) {
  40933. // Renderer can't be resized while presenting in XR.
  40934. if ( this.xr && this.xr.isPresenting ) return;
  40935. this._width = width;
  40936. this._height = height;
  40937. this.domElement.width = Math.floor( width * this._pixelRatio );
  40938. this.domElement.height = Math.floor( height * this._pixelRatio );
  40939. if ( updateStyle === true ) {
  40940. this.domElement.style.width = width + 'px';
  40941. this.domElement.style.height = height + 'px';
  40942. }
  40943. this.setViewport( 0, 0, width, height );
  40944. this._dispatchResize();
  40945. }
  40946. /**
  40947. * Returns the scissor rectangle.
  40948. *
  40949. * @param {Vector4} target - The method writes the result in this target object.
  40950. * @return {Vector4} The scissor rectangle.
  40951. */
  40952. getScissor( target ) {
  40953. const scissor = this._scissor;
  40954. target.x = scissor.x;
  40955. target.y = scissor.y;
  40956. target.width = scissor.width;
  40957. target.height = scissor.height;
  40958. return target;
  40959. }
  40960. /**
  40961. * Defines the scissor rectangle.
  40962. *
  40963. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40964. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40965. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40966. * @param {number} width - The width of the scissor box in logical pixel unit.
  40967. * @param {number} height - The height of the scissor box in logical pixel unit.
  40968. */
  40969. setScissor( x, y, width, height ) {
  40970. const scissor = this._scissor;
  40971. if ( x.isVector4 ) {
  40972. scissor.copy( x );
  40973. } else {
  40974. scissor.set( x, y, width, height );
  40975. }
  40976. }
  40977. /**
  40978. * Returns the scissor test value.
  40979. *
  40980. * @return {boolean} Whether the scissor test should be enabled or not.
  40981. */
  40982. getScissorTest() {
  40983. return this._scissorTest;
  40984. }
  40985. /**
  40986. * Defines the scissor test.
  40987. *
  40988. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40989. */
  40990. setScissorTest( boolean ) {
  40991. this._scissorTest = boolean;
  40992. }
  40993. /**
  40994. * Returns the viewport definition.
  40995. *
  40996. * @param {Vector4} target - The method writes the result in this target object.
  40997. * @return {Vector4} The viewport definition.
  40998. */
  40999. getViewport( target ) {
  41000. return target.copy( this._viewport );
  41001. }
  41002. /**
  41003. * Defines the viewport.
  41004. *
  41005. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41006. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  41007. * @param {number} width - The width of the viewport in logical pixel unit.
  41008. * @param {number} height - The height of the viewport in logical pixel unit.
  41009. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  41010. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  41011. */
  41012. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  41013. const viewport = this._viewport;
  41014. if ( x.isVector4 ) {
  41015. viewport.copy( x );
  41016. } else {
  41017. viewport.set( x, y, width, height );
  41018. }
  41019. viewport.minDepth = minDepth;
  41020. viewport.maxDepth = maxDepth;
  41021. }
  41022. /**
  41023. * Dispatches the resize event.
  41024. *
  41025. * @private
  41026. */
  41027. _dispatchResize() {
  41028. this.dispatchEvent( { type: 'resize' } );
  41029. }
  41030. /**
  41031. * Frees the GPU-related resources allocated by this instance. Call this
  41032. * method whenever this instance is no longer used in your app.
  41033. *
  41034. * @fires RenderTarget#dispose
  41035. */
  41036. dispose() {
  41037. this.dispatchEvent( { type: 'dispose' } );
  41038. }
  41039. }
  41040. const _scene = /*@__PURE__*/ new Scene();
  41041. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  41042. const _screen = /*@__PURE__*/ new Vector4();
  41043. const _frustum = /*@__PURE__*/ new Frustum();
  41044. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  41045. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  41046. const _vector4 = /*@__PURE__*/ new Vector4();
  41047. const _shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  41048. /**
  41049. * Base class for renderers.
  41050. */
  41051. class Renderer {
  41052. /**
  41053. * Renderer options.
  41054. *
  41055. * @typedef {Object} Renderer~Options
  41056. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  41057. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  41058. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  41059. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  41060. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  41061. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  41062. * to overwrite the default.
  41063. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41064. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  41065. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  41066. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  41067. */
  41068. /**
  41069. * Constructs a new renderer.
  41070. *
  41071. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  41072. * @param {Renderer~Options} [parameters] - The configuration parameter.
  41073. */
  41074. constructor( backend, parameters = {} ) {
  41075. /**
  41076. * This flag can be used for type testing.
  41077. *
  41078. * @type {boolean}
  41079. * @readonly
  41080. * @default true
  41081. */
  41082. this.isRenderer = true;
  41083. //
  41084. const {
  41085. logarithmicDepthBuffer = false,
  41086. alpha = true,
  41087. depth = true,
  41088. stencil = false,
  41089. antialias = false,
  41090. samples = 0,
  41091. getFallback = null,
  41092. outputBufferType = HalfFloatType,
  41093. multiview = false
  41094. } = parameters;
  41095. /**
  41096. * A reference to the current backend.
  41097. *
  41098. * @type {Backend}
  41099. */
  41100. this.backend = backend;
  41101. /**
  41102. * Whether the renderer should automatically clear the current rendering target
  41103. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  41104. * or the current bound render target (custom framebuffer).
  41105. *
  41106. * @type {boolean}
  41107. * @default true
  41108. */
  41109. this.autoClear = true;
  41110. /**
  41111. * When `autoClear` is set to `true`, this property defines whether the renderer
  41112. * should clear the color buffer.
  41113. *
  41114. * @type {boolean}
  41115. * @default true
  41116. */
  41117. this.autoClearColor = true;
  41118. /**
  41119. * When `autoClear` is set to `true`, this property defines whether the renderer
  41120. * should clear the depth buffer.
  41121. *
  41122. * @type {boolean}
  41123. * @default true
  41124. */
  41125. this.autoClearDepth = true;
  41126. /**
  41127. * When `autoClear` is set to `true`, this property defines whether the renderer
  41128. * should clear the stencil buffer.
  41129. *
  41130. * @type {boolean}
  41131. * @default true
  41132. */
  41133. this.autoClearStencil = true;
  41134. /**
  41135. * Whether the default framebuffer should be transparent or opaque.
  41136. *
  41137. * @type {boolean}
  41138. * @default true
  41139. */
  41140. this.alpha = alpha;
  41141. /**
  41142. * Whether logarithmic depth buffer is enabled or not.
  41143. *
  41144. * @type {boolean}
  41145. * @default false
  41146. */
  41147. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  41148. /**
  41149. * Defines the output color space of the renderer.
  41150. *
  41151. * @type {string}
  41152. * @default SRGBColorSpace
  41153. */
  41154. this.outputColorSpace = SRGBColorSpace;
  41155. /**
  41156. * Defines the tone mapping of the renderer.
  41157. *
  41158. * @type {number}
  41159. * @default NoToneMapping
  41160. */
  41161. this.toneMapping = NoToneMapping;
  41162. /**
  41163. * Defines the tone mapping exposure.
  41164. *
  41165. * @type {number}
  41166. * @default 1
  41167. */
  41168. this.toneMappingExposure = 1.0;
  41169. /**
  41170. * Whether the renderer should sort its render lists or not.
  41171. *
  41172. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  41173. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  41174. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  41175. * e.g. manually determining each object's rendering order.
  41176. *
  41177. * @type {boolean}
  41178. * @default true
  41179. */
  41180. this.sortObjects = true;
  41181. /**
  41182. * Whether the default framebuffer should have a depth buffer or not.
  41183. *
  41184. * @type {boolean}
  41185. * @default true
  41186. */
  41187. this.depth = depth;
  41188. /**
  41189. * Whether the default framebuffer should have a stencil buffer or not.
  41190. *
  41191. * @type {boolean}
  41192. * @default false
  41193. */
  41194. this.stencil = stencil;
  41195. /**
  41196. * Holds a series of statistical information about the GPU memory
  41197. * and the rendering process. Useful for debugging and monitoring.
  41198. *
  41199. * @type {Info}
  41200. */
  41201. this.info = new Info();
  41202. /**
  41203. * A global context node that stores override nodes for specific transformations or calculations.
  41204. * These nodes can be used to replace default behavior in the rendering pipeline.
  41205. *
  41206. * @type {ContextNode}
  41207. * @property {Object} value - The context value object.
  41208. */
  41209. this.contextNode = context();
  41210. /**
  41211. * The node library defines how certain library objects like materials, lights
  41212. * or tone mapping functions are mapped to node types. This is required since
  41213. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  41214. * be part of the scene graph, they are internally represented as nodes for
  41215. * further processing.
  41216. *
  41217. * @type {NodeLibrary}
  41218. */
  41219. this.library = new NodeLibrary();
  41220. /**
  41221. * A map-like data structure for managing lights.
  41222. *
  41223. * @type {Lighting}
  41224. */
  41225. this.lighting = new Lighting();
  41226. // internals
  41227. /**
  41228. * The number of MSAA samples.
  41229. *
  41230. * @private
  41231. * @type {number}
  41232. * @default 0
  41233. */
  41234. this._samples = samples || ( antialias === true ) ? 4 : 0;
  41235. /**
  41236. * OnCanvasTargetResize callback function.
  41237. *
  41238. * @private
  41239. * @type {Function}
  41240. */
  41241. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  41242. /**
  41243. * The canvas target for rendering.
  41244. *
  41245. * @private
  41246. * @type {CanvasTarget}
  41247. */
  41248. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  41249. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  41250. this._canvasTarget.isDefaultCanvasTarget = true;
  41251. /**
  41252. * The inspector provides information about the internal renderer state.
  41253. *
  41254. * @private
  41255. * @type {InspectorBase}
  41256. */
  41257. this._inspector = new InspectorBase();
  41258. this._inspector.setRenderer( this );
  41259. /**
  41260. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  41261. *
  41262. * @private
  41263. * @type {?Function}
  41264. */
  41265. this._getFallback = getFallback;
  41266. /**
  41267. * A reference to a renderer module for managing shader attributes.
  41268. *
  41269. * @private
  41270. * @type {?Attributes}
  41271. * @default null
  41272. */
  41273. this._attributes = null;
  41274. /**
  41275. * A reference to a renderer module for managing geometries.
  41276. *
  41277. * @private
  41278. * @type {?Geometries}
  41279. * @default null
  41280. */
  41281. this._geometries = null;
  41282. /**
  41283. * A reference to a renderer module for managing node related logic.
  41284. *
  41285. * @private
  41286. * @type {?NodeManager}
  41287. * @default null
  41288. */
  41289. this._nodes = null;
  41290. /**
  41291. * A reference to a renderer module for managing the internal animation loop.
  41292. *
  41293. * @private
  41294. * @type {?Animation}
  41295. * @default null
  41296. */
  41297. this._animation = null;
  41298. /**
  41299. * A reference to a renderer module for managing shader program bindings.
  41300. *
  41301. * @private
  41302. * @type {?Bindings}
  41303. * @default null
  41304. */
  41305. this._bindings = null;
  41306. /**
  41307. * A reference to a renderer module for managing render objects.
  41308. *
  41309. * @private
  41310. * @type {?RenderObjects}
  41311. * @default null
  41312. */
  41313. this._objects = null;
  41314. /**
  41315. * A reference to a renderer module for managing render and compute pipelines.
  41316. *
  41317. * @private
  41318. * @type {?Pipelines}
  41319. * @default null
  41320. */
  41321. this._pipelines = null;
  41322. /**
  41323. * A reference to a renderer module for managing render bundles.
  41324. *
  41325. * @private
  41326. * @type {?RenderBundles}
  41327. * @default null
  41328. */
  41329. this._bundles = null;
  41330. /**
  41331. * A reference to a renderer module for managing render lists.
  41332. *
  41333. * @private
  41334. * @type {?RenderLists}
  41335. * @default null
  41336. */
  41337. this._renderLists = null;
  41338. /**
  41339. * A reference to a renderer module for managing render contexts.
  41340. *
  41341. * @private
  41342. * @type {?RenderContexts}
  41343. * @default null
  41344. */
  41345. this._renderContexts = null;
  41346. /**
  41347. * A reference to a renderer module for managing textures.
  41348. *
  41349. * @private
  41350. * @type {?Textures}
  41351. * @default null
  41352. */
  41353. this._textures = null;
  41354. /**
  41355. * A reference to a renderer module for backgrounds.
  41356. *
  41357. * @private
  41358. * @type {?Background}
  41359. * @default null
  41360. */
  41361. this._background = null;
  41362. /**
  41363. * This fullscreen quad is used for internal render passes
  41364. * like the tone mapping and color space output pass.
  41365. *
  41366. * @private
  41367. * @type {QuadMesh}
  41368. */
  41369. this._quad = new QuadMesh( new NodeMaterial() );
  41370. this._quad.name = 'Output Color Transform';
  41371. this._quad.material.name = 'outputColorTransform';
  41372. /**
  41373. * A reference to the current render context.
  41374. *
  41375. * @private
  41376. * @type {?RenderContext}
  41377. * @default null
  41378. */
  41379. this._currentRenderContext = null;
  41380. /**
  41381. * A custom sort function for the opaque render list.
  41382. *
  41383. * @private
  41384. * @type {?Function}
  41385. * @default null
  41386. */
  41387. this._opaqueSort = null;
  41388. /**
  41389. * A custom sort function for the transparent render list.
  41390. *
  41391. * @private
  41392. * @type {?Function}
  41393. * @default null
  41394. */
  41395. this._transparentSort = null;
  41396. /**
  41397. * The framebuffer target.
  41398. *
  41399. * @private
  41400. * @type {?RenderTarget}
  41401. * @default null
  41402. */
  41403. this._frameBufferTarget = null;
  41404. const alphaClear = this.alpha === true ? 0 : 1;
  41405. /**
  41406. * The clear color value.
  41407. *
  41408. * @private
  41409. * @type {Color4}
  41410. */
  41411. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  41412. /**
  41413. * The clear depth value.
  41414. *
  41415. * @private
  41416. * @type {number}
  41417. * @default 1
  41418. */
  41419. this._clearDepth = 1;
  41420. /**
  41421. * The clear stencil value.
  41422. *
  41423. * @private
  41424. * @type {number}
  41425. * @default 0
  41426. */
  41427. this._clearStencil = 0;
  41428. /**
  41429. * The current render target.
  41430. *
  41431. * @private
  41432. * @type {?RenderTarget}
  41433. * @default null
  41434. */
  41435. this._renderTarget = null;
  41436. /**
  41437. * The active cube face.
  41438. *
  41439. * @private
  41440. * @type {number}
  41441. * @default 0
  41442. */
  41443. this._activeCubeFace = 0;
  41444. /**
  41445. * The active mipmap level.
  41446. *
  41447. * @private
  41448. * @type {number}
  41449. * @default 0
  41450. */
  41451. this._activeMipmapLevel = 0;
  41452. /**
  41453. * The current output render target.
  41454. *
  41455. * @private
  41456. * @type {?RenderTarget}
  41457. * @default null
  41458. */
  41459. this._outputRenderTarget = null;
  41460. /**
  41461. * The MRT setting.
  41462. *
  41463. * @private
  41464. * @type {?MRTNode}
  41465. * @default null
  41466. */
  41467. this._mrt = null;
  41468. /**
  41469. * This function defines how a render object is going
  41470. * to be rendered.
  41471. *
  41472. * @private
  41473. * @type {?Function}
  41474. * @default null
  41475. */
  41476. this._renderObjectFunction = null;
  41477. /**
  41478. * Used to keep track of the current render object function.
  41479. *
  41480. * @private
  41481. * @type {?Function}
  41482. * @default null
  41483. */
  41484. this._currentRenderObjectFunction = null;
  41485. /**
  41486. * Used to keep track of the current render bundle.
  41487. *
  41488. * @private
  41489. * @type {?RenderBundle}
  41490. * @default null
  41491. */
  41492. this._currentRenderBundle = null;
  41493. /**
  41494. * Next to `_renderObjectFunction()`, this function provides another hook
  41495. * for influencing the render process of a render object. It is meant for internal
  41496. * use and only relevant for `compileAsync()` right now. Instead of using
  41497. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  41498. * a different function might be used which performs no draw but just the node
  41499. * and pipeline updates.
  41500. *
  41501. * @private
  41502. * @type {Function}
  41503. */
  41504. this._handleObjectFunction = this._renderObjectDirect;
  41505. /**
  41506. * Indicates whether the device has been lost or not. In WebGL terms, the device
  41507. * lost is considered as a context lost. When this is set to `true`, rendering
  41508. * isn't possible anymore.
  41509. *
  41510. * @private
  41511. * @type {boolean}
  41512. * @default false
  41513. */
  41514. this._isDeviceLost = false;
  41515. /**
  41516. * A callback function that defines what should happen when a device/context lost occurs.
  41517. *
  41518. * @type {Function}
  41519. */
  41520. this.onDeviceLost = this._onDeviceLost;
  41521. /**
  41522. * Defines the type of output buffers. The default `HalfFloatType` is recommend for
  41523. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  41524. * This will reduce rendering quality though.
  41525. *
  41526. * @private
  41527. * @type {number}
  41528. * @default HalfFloatType
  41529. */
  41530. this._outputBufferType = outputBufferType;
  41531. /**
  41532. * A cache for shadow nodes per material
  41533. *
  41534. * @private
  41535. * @type {WeakMap<Material, Object>}
  41536. */
  41537. this._cacheShadowNodes = new WeakMap();
  41538. /**
  41539. * Whether the renderer has been initialized or not.
  41540. *
  41541. * @private
  41542. * @type {boolean}
  41543. * @default false
  41544. */
  41545. this._initialized = false;
  41546. /**
  41547. * The call depth of the renderer. Counts the number of
  41548. * nested render calls.
  41549. *
  41550. * @private
  41551. * @type {number}
  41552. * @default - 1
  41553. */
  41554. this._callDepth = -1;
  41555. /**
  41556. * A reference to the promise which initializes the renderer.
  41557. *
  41558. * @private
  41559. * @type {?Promise<this>}
  41560. * @default null
  41561. */
  41562. this._initPromise = null;
  41563. /**
  41564. * An array of compilation promises which are used in `compileAsync()`.
  41565. *
  41566. * @private
  41567. * @type {?Array<Promise>}
  41568. * @default null
  41569. */
  41570. this._compilationPromises = null;
  41571. /**
  41572. * Whether the renderer should render transparent render objects or not.
  41573. *
  41574. * @type {boolean}
  41575. * @default true
  41576. */
  41577. this.transparent = true;
  41578. /**
  41579. * Whether the renderer should render opaque render objects or not.
  41580. *
  41581. * @type {boolean}
  41582. * @default true
  41583. */
  41584. this.opaque = true;
  41585. /**
  41586. * Shadow map configuration
  41587. * @typedef {Object} ShadowMapConfig
  41588. * @property {boolean} enabled - Whether to globally enable shadows or not.
  41589. * @property {boolean} transmitted - Whether to enable light transmission through non-opaque materials.
  41590. * @property {number} type - The shadow map type.
  41591. */
  41592. /**
  41593. * The renderer's shadow configuration.
  41594. *
  41595. * @type {ShadowMapConfig}
  41596. */
  41597. this.shadowMap = {
  41598. enabled: false,
  41599. transmitted: false,
  41600. type: PCFShadowMap
  41601. };
  41602. /**
  41603. * XR configuration.
  41604. * @typedef {Object} XRConfig
  41605. * @property {boolean} enabled - Whether to globally enable XR or not.
  41606. */
  41607. /**
  41608. * The renderer's XR manager.
  41609. *
  41610. * @type {XRManager}
  41611. */
  41612. this.xr = new XRManager( this, multiview );
  41613. /**
  41614. * Debug configuration.
  41615. * @typedef {Object} DebugConfig
  41616. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  41617. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  41618. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  41619. */
  41620. /**
  41621. * The renderer's debug configuration.
  41622. *
  41623. * @type {DebugConfig}
  41624. */
  41625. this.debug = {
  41626. checkShaderErrors: true,
  41627. onShaderError: null,
  41628. getShaderAsync: async ( scene, camera, object ) => {
  41629. await this.compileAsync( scene, camera );
  41630. const renderList = this._renderLists.get( scene, camera );
  41631. const renderContext = this._renderContexts.get( this._renderTarget, this._mrt );
  41632. const material = scene.overrideMaterial || object.material;
  41633. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  41634. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  41635. return { fragmentShader, vertexShader };
  41636. }
  41637. };
  41638. }
  41639. /**
  41640. * Initializes the renderer so it is ready for usage.
  41641. *
  41642. * @async
  41643. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  41644. */
  41645. async init() {
  41646. if ( this._initPromise !== null ) {
  41647. return this._initPromise;
  41648. }
  41649. this._initPromise = new Promise( async ( resolve, reject ) => {
  41650. let backend = this.backend;
  41651. try {
  41652. await backend.init( this );
  41653. } catch ( error ) {
  41654. if ( this._getFallback !== null ) {
  41655. // try the fallback
  41656. try {
  41657. this.backend = backend = this._getFallback( error );
  41658. await backend.init( this );
  41659. } catch ( error ) {
  41660. reject( error );
  41661. return;
  41662. }
  41663. } else {
  41664. reject( error );
  41665. return;
  41666. }
  41667. }
  41668. this._nodes = new NodeManager( this, backend );
  41669. this._animation = new Animation( this, this._nodes, this.info );
  41670. this._attributes = new Attributes( backend );
  41671. this._background = new Background( this, this._nodes );
  41672. this._geometries = new Geometries( this._attributes, this.info );
  41673. this._textures = new Textures( this, backend, this.info );
  41674. this._pipelines = new Pipelines( backend, this._nodes );
  41675. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  41676. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  41677. this._renderLists = new RenderLists( this.lighting );
  41678. this._bundles = new RenderBundles();
  41679. this._renderContexts = new RenderContexts();
  41680. //
  41681. this._animation.start();
  41682. this._initialized = true;
  41683. //
  41684. this._inspector.init();
  41685. //
  41686. resolve( this );
  41687. } );
  41688. return this._initPromise;
  41689. }
  41690. /**
  41691. * A reference to the canvas element the renderer is drawing to.
  41692. * This value of this property will automatically be created by
  41693. * the renderer.
  41694. *
  41695. * @type {HTMLCanvasElement|OffscreenCanvas}
  41696. */
  41697. get domElement() {
  41698. return this._canvasTarget.domElement;
  41699. }
  41700. /**
  41701. * The coordinate system of the renderer. The value of this property
  41702. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  41703. * `THREE.WebGPUCoordinateSystem`.
  41704. *
  41705. * @readonly
  41706. * @type {number}
  41707. */
  41708. get coordinateSystem() {
  41709. return this.backend.coordinateSystem;
  41710. }
  41711. /**
  41712. * Compiles all materials in the given scene. This can be useful to avoid a
  41713. * phenomenon which is called "shader compilation stutter", which occurs when
  41714. * rendering an object with a new shader for the first time.
  41715. *
  41716. * If you want to add a 3D object to an existing scene, use the third optional
  41717. * parameter for applying the target scene. Note that the (target) scene's lighting
  41718. * and environment must be configured before calling this method.
  41719. *
  41720. * @async
  41721. * @param {Object3D} scene - The scene or 3D object to precompile.
  41722. * @param {Camera} camera - The camera that is used to render the scene.
  41723. * @param {?Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  41724. * @return {Promise} A Promise that resolves when the compile has been finished.
  41725. */
  41726. async compileAsync( scene, camera, targetScene = null ) {
  41727. if ( this._isDeviceLost === true ) return;
  41728. if ( this._initialized === false ) await this.init();
  41729. // preserve render tree
  41730. const nodeFrame = this._nodes.nodeFrame;
  41731. const previousRenderId = nodeFrame.renderId;
  41732. const previousRenderContext = this._currentRenderContext;
  41733. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  41734. const previousHandleObjectFunction = this._handleObjectFunction;
  41735. const previousCompilationPromises = this._compilationPromises;
  41736. //
  41737. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  41738. if ( targetScene === null ) targetScene = scene;
  41739. const renderTarget = this._renderTarget;
  41740. const renderContext = this._renderContexts.get( renderTarget, this._mrt );
  41741. const activeMipmapLevel = this._activeMipmapLevel;
  41742. const compilationPromises = [];
  41743. this._currentRenderContext = renderContext;
  41744. this._currentRenderObjectFunction = this.renderObject;
  41745. this._handleObjectFunction = this._createObjectPipeline;
  41746. this._compilationPromises = compilationPromises;
  41747. nodeFrame.renderId ++;
  41748. //
  41749. nodeFrame.update();
  41750. //
  41751. renderContext.depth = this.depth;
  41752. renderContext.stencil = this.stencil;
  41753. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  41754. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  41755. //
  41756. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  41757. //
  41758. const renderList = this._renderLists.get( scene, camera );
  41759. renderList.begin();
  41760. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  41761. // include lights from target scene
  41762. if ( targetScene !== scene ) {
  41763. targetScene.traverseVisible( function ( object ) {
  41764. if ( object.isLight && object.layers.test( camera.layers ) ) {
  41765. renderList.pushLight( object );
  41766. }
  41767. } );
  41768. }
  41769. renderList.finish();
  41770. //
  41771. if ( renderTarget !== null ) {
  41772. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  41773. const renderTargetData = this._textures.get( renderTarget );
  41774. renderContext.textures = renderTargetData.textures;
  41775. renderContext.depthTexture = renderTargetData.depthTexture;
  41776. } else {
  41777. renderContext.textures = null;
  41778. renderContext.depthTexture = null;
  41779. }
  41780. //
  41781. if ( targetScene !== scene ) {
  41782. this._background.update( targetScene, renderList, renderContext );
  41783. } else {
  41784. this._background.update( sceneRef, renderList, renderContext );
  41785. }
  41786. // process render lists
  41787. const opaqueObjects = renderList.opaque;
  41788. const transparentObjects = renderList.transparent;
  41789. const transparentDoublePassObjects = renderList.transparentDoublePass;
  41790. const lightsNode = renderList.lightsNode;
  41791. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41792. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41793. // restore render tree
  41794. nodeFrame.renderId = previousRenderId;
  41795. this._currentRenderContext = previousRenderContext;
  41796. this._currentRenderObjectFunction = previousRenderObjectFunction;
  41797. this._handleObjectFunction = previousHandleObjectFunction;
  41798. this._compilationPromises = previousCompilationPromises;
  41799. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  41800. await Promise.all( compilationPromises );
  41801. }
  41802. /**
  41803. * Renders the scene in an async fashion.
  41804. *
  41805. * @async
  41806. * @deprecated
  41807. * @param {Object3D} scene - The scene or 3D object to render.
  41808. * @param {Camera} camera - The camera.
  41809. * @return {Promise} A Promise that resolves when the render has been finished.
  41810. */
  41811. async renderAsync( scene, camera ) {
  41812. warnOnce( 'Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  41813. await this.init();
  41814. this.render( scene, camera );
  41815. }
  41816. /**
  41817. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41818. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41819. *
  41820. * @async
  41821. * @deprecated
  41822. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41823. */
  41824. async waitForGPU() {
  41825. error( 'Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.' );
  41826. }
  41827. //
  41828. set inspector( value ) {
  41829. if ( this._inspector !== null ) {
  41830. this._inspector.setRenderer( null );
  41831. }
  41832. this._inspector = value;
  41833. this._inspector.setRenderer( this );
  41834. }
  41835. /**
  41836. * The inspector instance. The inspector can be any class that extends from `InspectorBase`.
  41837. *
  41838. * @type {InspectorBase}
  41839. */
  41840. get inspector() {
  41841. return this._inspector;
  41842. }
  41843. /**
  41844. * Enables or disables high precision for model-view and normal-view matrices.
  41845. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  41846. *
  41847. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  41848. *
  41849. * @param {boolean} value - Whether to enable or disable high precision.
  41850. * @type {boolean}
  41851. */
  41852. set highPrecision( value ) {
  41853. const contextNodeData = this.contextNode.value;
  41854. if ( value === true ) {
  41855. contextNodeData.modelViewMatrix = highpModelViewMatrix;
  41856. contextNodeData.modelNormalViewMatrix = highpModelNormalViewMatrix;
  41857. } else if ( this.highPrecision ) {
  41858. delete contextNodeData.modelViewMatrix;
  41859. delete contextNodeData.modelNormalViewMatrix;
  41860. }
  41861. }
  41862. /**
  41863. * Returns whether high precision is enabled or not.
  41864. *
  41865. * @return {boolean} Whether high precision is enabled or not.
  41866. * @type {boolean}
  41867. */
  41868. get highPrecision() {
  41869. const contextNodeData = this.contextNode.value;
  41870. return contextNodeData.modelViewMatrix === highpModelViewMatrix && contextNodeData.modelNormalViewMatrix === highpModelNormalViewMatrix;
  41871. }
  41872. /**
  41873. * Sets the given MRT configuration.
  41874. *
  41875. * @param {MRTNode} mrt - The MRT node to set.
  41876. * @return {Renderer} A reference to this renderer.
  41877. */
  41878. setMRT( mrt ) {
  41879. this._mrt = mrt;
  41880. return this;
  41881. }
  41882. /**
  41883. * Returns the MRT configuration.
  41884. *
  41885. * @return {MRTNode} The MRT configuration.
  41886. */
  41887. getMRT() {
  41888. return this._mrt;
  41889. }
  41890. /**
  41891. * Returns the output buffer type.
  41892. *
  41893. * @return {number} The output buffer type.
  41894. */
  41895. getOutputBufferType() {
  41896. return this._outputBufferType;
  41897. }
  41898. /**
  41899. * Returns the output buffer type.
  41900. *
  41901. * @deprecated since r182. Use `.getOutputBufferType()` instead.
  41902. * @return {number} The output buffer type.
  41903. */
  41904. getColorBufferType() { // @deprecated, r182
  41905. warnOnce( 'Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".' );
  41906. return this.getOutputBufferType();
  41907. }
  41908. /**
  41909. * Default implementation of the device lost callback.
  41910. *
  41911. * @private
  41912. * @param {Object} info - Information about the context lost.
  41913. */
  41914. _onDeviceLost( info ) {
  41915. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  41916. if ( info.reason ) {
  41917. errorMessage += `\nReason: ${info.reason}`;
  41918. }
  41919. error( errorMessage );
  41920. this._isDeviceLost = true;
  41921. }
  41922. /**
  41923. * Renders the given render bundle.
  41924. *
  41925. * @private
  41926. * @param {Object} bundle - Render bundle data.
  41927. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  41928. * @param {LightsNode} lightsNode - The lights node.
  41929. */
  41930. _renderBundle( bundle, sceneRef, lightsNode ) {
  41931. const { bundleGroup, camera, renderList } = bundle;
  41932. const renderContext = this._currentRenderContext;
  41933. //
  41934. const renderBundle = this._bundles.get( bundleGroup, camera );
  41935. const renderBundleData = this.backend.get( renderBundle );
  41936. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  41937. //
  41938. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  41939. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  41940. renderBundleData.renderContexts.add( renderContext );
  41941. if ( renderBundleNeedsUpdate ) {
  41942. this.backend.beginBundle( renderContext );
  41943. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  41944. renderBundleData.renderObjects = [];
  41945. }
  41946. this._currentRenderBundle = renderBundle;
  41947. const {
  41948. transparentDoublePass: transparentDoublePassObjects,
  41949. transparent: transparentObjects,
  41950. opaque: opaqueObjects
  41951. } = renderList;
  41952. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  41953. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  41954. this._currentRenderBundle = null;
  41955. //
  41956. this.backend.finishBundle( renderContext, renderBundle );
  41957. renderBundleData.version = bundleGroup.version;
  41958. } else {
  41959. const { renderObjects } = renderBundleData;
  41960. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  41961. const renderObject = renderObjects[ i ];
  41962. if ( this._nodes.needsRefresh( renderObject ) ) {
  41963. this._nodes.updateBefore( renderObject );
  41964. this._nodes.updateForRender( renderObject );
  41965. this._bindings.updateForRender( renderObject );
  41966. this._nodes.updateAfter( renderObject );
  41967. }
  41968. }
  41969. }
  41970. this.backend.addBundle( renderContext, renderBundle );
  41971. }
  41972. /**
  41973. * Renders the scene or 3D object with the given camera. This method can only be called
  41974. * if the renderer has been initialized. When using `render()` inside an animation loop,
  41975. * it's guaranteed the renderer will be initialized. The animation loop must be defined
  41976. * with {@link Renderer#setAnimationLoop} though.
  41977. *
  41978. * For all other use cases (like when using on-demand rendering), you must call
  41979. * {@link Renderer#init} before rendering.
  41980. *
  41981. * The target of the method is the default framebuffer (meaning the canvas)
  41982. * or alternatively a render target when specified via `setRenderTarget()`.
  41983. *
  41984. * @param {Object3D} scene - The scene or 3D object to render.
  41985. * @param {Camera} camera - The camera to render the scene with.
  41986. */
  41987. render( scene, camera ) {
  41988. if ( this._initialized === false ) {
  41989. throw new Error( 'Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.' );
  41990. }
  41991. this._renderScene( scene, camera );
  41992. }
  41993. /**
  41994. * Returns whether the renderer has been initialized or not.
  41995. *
  41996. * @readonly
  41997. * @return {boolean} Whether the renderer has been initialized or not.
  41998. */
  41999. get initialized() {
  42000. return this._initialized;
  42001. }
  42002. /**
  42003. * Returns an internal render target which is used when computing the output tone mapping
  42004. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  42005. * pass and not inline to achieve more correct results.
  42006. *
  42007. * @private
  42008. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  42009. */
  42010. _getFrameBufferTarget() {
  42011. const { currentToneMapping, currentColorSpace } = this;
  42012. const useToneMapping = currentToneMapping !== NoToneMapping;
  42013. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  42014. if ( useToneMapping === false && useColorSpace === false ) return null;
  42015. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  42016. const { depth, stencil } = this;
  42017. let frameBufferTarget = this._frameBufferTarget;
  42018. if ( frameBufferTarget === null ) {
  42019. frameBufferTarget = new RenderTarget( width, height, {
  42020. depthBuffer: depth,
  42021. stencilBuffer: stencil,
  42022. type: this._outputBufferType,
  42023. format: RGBAFormat,
  42024. colorSpace: ColorManagement.workingColorSpace,
  42025. generateMipmaps: false,
  42026. minFilter: LinearFilter,
  42027. magFilter: LinearFilter,
  42028. samples: this.samples
  42029. } );
  42030. frameBufferTarget.isPostProcessingRenderTarget = true;
  42031. this._frameBufferTarget = frameBufferTarget;
  42032. }
  42033. const outputRenderTarget = this.getOutputRenderTarget();
  42034. frameBufferTarget.depthBuffer = depth;
  42035. frameBufferTarget.stencilBuffer = stencil;
  42036. if ( outputRenderTarget !== null ) {
  42037. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  42038. } else {
  42039. frameBufferTarget.setSize( width, height, 1 );
  42040. }
  42041. const canvasTarget = this._canvasTarget;
  42042. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  42043. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  42044. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  42045. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  42046. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  42047. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  42048. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  42049. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  42050. return frameBufferTarget;
  42051. }
  42052. /**
  42053. * Renders the scene or 3D object with the given camera.
  42054. *
  42055. * @private
  42056. * @param {Object3D} scene - The scene or 3D object to render.
  42057. * @param {Camera} camera - The camera to render the scene with.
  42058. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  42059. * @return {RenderContext} The current render context.
  42060. */
  42061. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  42062. if ( this._isDeviceLost === true ) return;
  42063. //
  42064. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  42065. // preserve render tree
  42066. const nodeFrame = this._nodes.nodeFrame;
  42067. const previousRenderId = nodeFrame.renderId;
  42068. const previousRenderContext = this._currentRenderContext;
  42069. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  42070. const previousHandleObjectFunction = this._handleObjectFunction;
  42071. //
  42072. this._callDepth ++;
  42073. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  42074. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  42075. const activeCubeFace = this._activeCubeFace;
  42076. const activeMipmapLevel = this._activeMipmapLevel;
  42077. //
  42078. let renderTarget;
  42079. if ( frameBufferTarget !== null ) {
  42080. renderTarget = frameBufferTarget;
  42081. this.setRenderTarget( renderTarget );
  42082. } else {
  42083. renderTarget = outputRenderTarget;
  42084. }
  42085. //
  42086. const renderContext = this._renderContexts.get( renderTarget, this._mrt, this._callDepth );
  42087. this._currentRenderContext = renderContext;
  42088. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  42089. this._handleObjectFunction = this._renderObjectDirect;
  42090. //
  42091. this.info.calls ++;
  42092. this.info.render.calls ++;
  42093. this.info.render.frameCalls ++;
  42094. nodeFrame.renderId = this.info.calls;
  42095. //
  42096. this.backend.updateTimeStampUID( renderContext );
  42097. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  42098. //
  42099. const coordinateSystem = this.coordinateSystem;
  42100. const xr = this.xr;
  42101. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  42102. camera.coordinateSystem = coordinateSystem;
  42103. camera.updateProjectionMatrix();
  42104. if ( camera.isArrayCamera ) {
  42105. for ( const subCamera of camera.cameras ) {
  42106. subCamera.coordinateSystem = coordinateSystem;
  42107. subCamera.updateProjectionMatrix();
  42108. }
  42109. }
  42110. }
  42111. //
  42112. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  42113. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  42114. if ( xr.enabled === true && xr.isPresenting === true ) {
  42115. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  42116. camera = xr.getCamera(); // use XR camera for rendering
  42117. }
  42118. //
  42119. const canvasTarget = this._canvasTarget;
  42120. let viewport = canvasTarget._viewport;
  42121. let scissor = canvasTarget._scissor;
  42122. let pixelRatio = canvasTarget._pixelRatio;
  42123. if ( renderTarget !== null ) {
  42124. viewport = renderTarget.viewport;
  42125. scissor = renderTarget.scissor;
  42126. pixelRatio = 1;
  42127. }
  42128. this.getDrawingBufferSize( _drawingBufferSize );
  42129. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  42130. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  42131. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  42132. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  42133. renderContext.viewportValue.width >>= activeMipmapLevel;
  42134. renderContext.viewportValue.height >>= activeMipmapLevel;
  42135. renderContext.viewportValue.minDepth = minDepth;
  42136. renderContext.viewportValue.maxDepth = maxDepth;
  42137. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  42138. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  42139. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  42140. renderContext.scissorValue.width >>= activeMipmapLevel;
  42141. renderContext.scissorValue.height >>= activeMipmapLevel;
  42142. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  42143. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  42144. //
  42145. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  42146. //
  42147. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  42148. if ( ! camera.isArrayCamera ) {
  42149. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  42150. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  42151. }
  42152. const renderList = this._renderLists.get( scene, camera );
  42153. renderList.begin();
  42154. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  42155. renderList.finish();
  42156. if ( this.sortObjects === true ) {
  42157. renderList.sort( this._opaqueSort, this._transparentSort );
  42158. }
  42159. //
  42160. if ( renderTarget !== null ) {
  42161. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  42162. const renderTargetData = this._textures.get( renderTarget );
  42163. renderContext.textures = renderTargetData.textures;
  42164. renderContext.depthTexture = renderTargetData.depthTexture;
  42165. renderContext.width = renderTargetData.width;
  42166. renderContext.height = renderTargetData.height;
  42167. renderContext.renderTarget = renderTarget;
  42168. renderContext.depth = renderTarget.depthBuffer;
  42169. renderContext.stencil = renderTarget.stencilBuffer;
  42170. } else {
  42171. renderContext.textures = null;
  42172. renderContext.depthTexture = null;
  42173. renderContext.width = _drawingBufferSize.width;
  42174. renderContext.height = _drawingBufferSize.height;
  42175. renderContext.depth = this.depth;
  42176. renderContext.stencil = this.stencil;
  42177. }
  42178. renderContext.width >>= activeMipmapLevel;
  42179. renderContext.height >>= activeMipmapLevel;
  42180. renderContext.activeCubeFace = activeCubeFace;
  42181. renderContext.activeMipmapLevel = activeMipmapLevel;
  42182. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  42183. //
  42184. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  42185. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  42186. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  42187. }
  42188. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  42189. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  42190. }
  42191. //
  42192. this._background.update( sceneRef, renderList, renderContext );
  42193. //
  42194. renderContext.camera = camera;
  42195. this.backend.beginRender( renderContext );
  42196. // process render lists
  42197. const {
  42198. bundles,
  42199. lightsNode,
  42200. transparentDoublePass: transparentDoublePassObjects,
  42201. transparent: transparentObjects,
  42202. opaque: opaqueObjects
  42203. } = renderList;
  42204. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  42205. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  42206. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  42207. // finish render pass
  42208. this.backend.finishRender( renderContext );
  42209. // restore render tree
  42210. nodeFrame.renderId = previousRenderId;
  42211. this._currentRenderContext = previousRenderContext;
  42212. this._currentRenderObjectFunction = previousRenderObjectFunction;
  42213. this._handleObjectFunction = previousHandleObjectFunction;
  42214. //
  42215. this._callDepth --;
  42216. if ( frameBufferTarget !== null ) {
  42217. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  42218. this._renderOutput( renderTarget );
  42219. }
  42220. //
  42221. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  42222. //
  42223. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  42224. //
  42225. return renderContext;
  42226. }
  42227. _setXRLayerSize( width, height ) {
  42228. // TODO: Find a better solution to resize the canvas when in XR.
  42229. this._canvasTarget._width = width;
  42230. this._canvasTarget._height = height;
  42231. this.setViewport( 0, 0, width, height );
  42232. }
  42233. /**
  42234. * The output pass performs tone mapping and color space conversion.
  42235. *
  42236. * @private
  42237. * @param {RenderTarget} renderTarget - The current render target.
  42238. */
  42239. _renderOutput( renderTarget ) {
  42240. const quad = this._quad;
  42241. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  42242. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  42243. quad.material.needsUpdate = true;
  42244. }
  42245. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  42246. const currentAutoClear = this.autoClear;
  42247. const currentXR = this.xr.enabled;
  42248. this.autoClear = false;
  42249. this.xr.enabled = false;
  42250. this._renderScene( quad, quad.camera, false );
  42251. this.autoClear = currentAutoClear;
  42252. this.xr.enabled = currentXR;
  42253. }
  42254. /**
  42255. * Returns the maximum available anisotropy for texture filtering.
  42256. *
  42257. * @return {number} The maximum available anisotropy.
  42258. */
  42259. getMaxAnisotropy() {
  42260. return this.backend.getMaxAnisotropy();
  42261. }
  42262. /**
  42263. * Returns the active cube face.
  42264. *
  42265. * @return {number} The active cube face.
  42266. */
  42267. getActiveCubeFace() {
  42268. return this._activeCubeFace;
  42269. }
  42270. /**
  42271. * Returns the active mipmap level.
  42272. *
  42273. * @return {number} The active mipmap level.
  42274. */
  42275. getActiveMipmapLevel() {
  42276. return this._activeMipmapLevel;
  42277. }
  42278. /**
  42279. * Applications are advised to always define the animation loop
  42280. * with this method and not manually with `requestAnimationFrame()`
  42281. * for best compatibility.
  42282. *
  42283. * @async
  42284. * @param {?onAnimationCallback} callback - The application's animation loop.
  42285. * @return {Promise} A Promise that resolves when the set has been executed.
  42286. */
  42287. async setAnimationLoop( callback ) {
  42288. if ( this._initialized === false ) await this.init();
  42289. this._animation.setAnimationLoop( callback );
  42290. }
  42291. /**
  42292. * Returns the current animation loop callback.
  42293. *
  42294. * @return {?Function} The current animation loop callback.
  42295. */
  42296. getAnimationLoop() {
  42297. return this._animation.getAnimationLoop();
  42298. }
  42299. /**
  42300. * Can be used to transfer buffer data from a storage buffer attribute
  42301. * from the GPU to the CPU in context of compute shaders.
  42302. *
  42303. * @async
  42304. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42305. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42306. */
  42307. async getArrayBufferAsync( attribute ) {
  42308. return await this.backend.getArrayBufferAsync( attribute );
  42309. }
  42310. /**
  42311. * Returns the rendering context.
  42312. *
  42313. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  42314. */
  42315. getContext() {
  42316. return this.backend.getContext();
  42317. }
  42318. /**
  42319. * Returns the pixel ratio.
  42320. *
  42321. * @return {number} The pixel ratio.
  42322. */
  42323. getPixelRatio() {
  42324. return this._canvasTarget.getPixelRatio();
  42325. }
  42326. /**
  42327. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  42328. *
  42329. * @param {Vector2} target - The method writes the result in this target object.
  42330. * @return {Vector2} The drawing buffer size.
  42331. */
  42332. getDrawingBufferSize( target ) {
  42333. return this._canvasTarget.getDrawingBufferSize( target );
  42334. }
  42335. /**
  42336. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  42337. *
  42338. * @param {Vector2} target - The method writes the result in this target object.
  42339. * @return {Vector2} The renderer's size in logical pixels.
  42340. */
  42341. getSize( target ) {
  42342. return this._canvasTarget.getSize( target );
  42343. }
  42344. /**
  42345. * Sets the given pixel ratio and resizes the canvas if necessary.
  42346. *
  42347. * @param {number} [value=1] - The pixel ratio.
  42348. */
  42349. setPixelRatio( value = 1 ) {
  42350. this._canvasTarget.setPixelRatio( value );
  42351. }
  42352. /**
  42353. * This method allows to define the drawing buffer size by specifying
  42354. * width, height and pixel ratio all at once. The size of the drawing
  42355. * buffer is computed with this formula:
  42356. * ```js
  42357. * size.x = width * pixelRatio;
  42358. * size.y = height * pixelRatio;
  42359. * ```
  42360. *
  42361. * @param {number} width - The width in logical pixels.
  42362. * @param {number} height - The height in logical pixels.
  42363. * @param {number} pixelRatio - The pixel ratio.
  42364. */
  42365. setDrawingBufferSize( width, height, pixelRatio ) {
  42366. // Renderer can't be resized while presenting in XR.
  42367. if ( this.xr && this.xr.isPresenting ) return;
  42368. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  42369. }
  42370. /**
  42371. * Sets the size of the renderer.
  42372. *
  42373. * @param {number} width - The width in logical pixels.
  42374. * @param {number} height - The height in logical pixels.
  42375. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  42376. */
  42377. setSize( width, height, updateStyle = true ) {
  42378. // Renderer can't be resized while presenting in XR.
  42379. if ( this.xr && this.xr.isPresenting ) return;
  42380. this._canvasTarget.setSize( width, height, updateStyle );
  42381. }
  42382. /**
  42383. * Defines a manual sort function for the opaque render list.
  42384. * Pass `null` to use the default sort.
  42385. *
  42386. * @param {Function} method - The sort function.
  42387. */
  42388. setOpaqueSort( method ) {
  42389. this._opaqueSort = method;
  42390. }
  42391. /**
  42392. * Defines a manual sort function for the transparent render list.
  42393. * Pass `null` to use the default sort.
  42394. *
  42395. * @param {Function} method - The sort function.
  42396. */
  42397. setTransparentSort( method ) {
  42398. this._transparentSort = method;
  42399. }
  42400. /**
  42401. * Returns the scissor rectangle.
  42402. *
  42403. * @param {Vector4} target - The method writes the result in this target object.
  42404. * @return {Vector4} The scissor rectangle.
  42405. */
  42406. getScissor( target ) {
  42407. return this._canvasTarget.getScissor( target );
  42408. }
  42409. /**
  42410. * Defines the scissor rectangle.
  42411. *
  42412. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the box in logical pixel unit.
  42413. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  42414. * @param {number} y - The vertical coordinate for the upper left corner of the box in logical pixel unit.
  42415. * @param {number} width - The width of the scissor box in logical pixel unit.
  42416. * @param {number} height - The height of the scissor box in logical pixel unit.
  42417. */
  42418. setScissor( x, y, width, height ) {
  42419. this._canvasTarget.setScissor( x, y, width, height );
  42420. }
  42421. /**
  42422. * Returns the scissor test value.
  42423. *
  42424. * @return {boolean} Whether the scissor test should be enabled or not.
  42425. */
  42426. getScissorTest() {
  42427. return this._canvasTarget.getScissorTest();
  42428. }
  42429. /**
  42430. * Defines the scissor test.
  42431. *
  42432. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42433. */
  42434. setScissorTest( boolean ) {
  42435. this._canvasTarget.setScissorTest( boolean );
  42436. // TODO: Move it to CanvasTarget event listener.
  42437. this.backend.setScissorTest( boolean );
  42438. }
  42439. /**
  42440. * Returns the viewport definition.
  42441. *
  42442. * @param {Vector4} target - The method writes the result in this target object.
  42443. * @return {Vector4} The viewport definition.
  42444. */
  42445. getViewport( target ) {
  42446. return this._canvasTarget.getViewport( target );
  42447. }
  42448. /**
  42449. * Defines the viewport.
  42450. *
  42451. * @param {number | Vector4} x - The horizontal coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42452. * @param {number} y - The vertical coordinate for the upper left corner of the viewport origin in logical pixel unit.
  42453. * @param {number} width - The width of the viewport in logical pixel unit.
  42454. * @param {number} height - The height of the viewport in logical pixel unit.
  42455. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  42456. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  42457. */
  42458. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  42459. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  42460. }
  42461. /**
  42462. * Returns the clear color.
  42463. *
  42464. * @param {Color} target - The method writes the result in this target object.
  42465. * @return {Color} The clear color.
  42466. */
  42467. getClearColor( target ) {
  42468. return target.copy( this._clearColor );
  42469. }
  42470. /**
  42471. * Defines the clear color and optionally the clear alpha.
  42472. *
  42473. * @param {Color} color - The clear color.
  42474. * @param {number} [alpha=1] - The clear alpha.
  42475. */
  42476. setClearColor( color, alpha = 1 ) {
  42477. this._clearColor.set( color );
  42478. this._clearColor.a = alpha;
  42479. }
  42480. /**
  42481. * Returns the clear alpha.
  42482. *
  42483. * @return {number} The clear alpha.
  42484. */
  42485. getClearAlpha() {
  42486. return this._clearColor.a;
  42487. }
  42488. /**
  42489. * Defines the clear alpha.
  42490. *
  42491. * @param {number} alpha - The clear alpha.
  42492. */
  42493. setClearAlpha( alpha ) {
  42494. this._clearColor.a = alpha;
  42495. }
  42496. /**
  42497. * Returns the clear depth.
  42498. *
  42499. * @return {number} The clear depth.
  42500. */
  42501. getClearDepth() {
  42502. return this._clearDepth;
  42503. }
  42504. /**
  42505. * Defines the clear depth.
  42506. *
  42507. * @param {number} depth - The clear depth.
  42508. */
  42509. setClearDepth( depth ) {
  42510. this._clearDepth = depth;
  42511. }
  42512. /**
  42513. * Returns the clear stencil.
  42514. *
  42515. * @return {number} The clear stencil.
  42516. */
  42517. getClearStencil() {
  42518. return this._clearStencil;
  42519. }
  42520. /**
  42521. * Defines the clear stencil.
  42522. *
  42523. * @param {number} stencil - The clear stencil.
  42524. */
  42525. setClearStencil( stencil ) {
  42526. this._clearStencil = stencil;
  42527. }
  42528. /**
  42529. * This method performs an occlusion query for the given 3D object.
  42530. * It returns `true` if the given 3D object is fully occluded by other
  42531. * 3D objects in the scene.
  42532. *
  42533. * @param {Object3D} object - The 3D object to test.
  42534. * @return {boolean} Whether the 3D object is fully occluded or not.
  42535. */
  42536. isOccluded( object ) {
  42537. const renderContext = this._currentRenderContext;
  42538. return renderContext && this.backend.isOccluded( renderContext, object );
  42539. }
  42540. /**
  42541. * Performs a manual clear operation. This method ignores `autoClear` properties.
  42542. *
  42543. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42544. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42545. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42546. */
  42547. clear( color = true, depth = true, stencil = true ) {
  42548. if ( this._initialized === false ) {
  42549. throw new Error( 'Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42550. }
  42551. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  42552. let renderContext = null;
  42553. if ( renderTarget !== null ) {
  42554. this._textures.updateRenderTarget( renderTarget );
  42555. const renderTargetData = this._textures.get( renderTarget );
  42556. renderContext = this._renderContexts.get( renderTarget );
  42557. renderContext.textures = renderTargetData.textures;
  42558. renderContext.depthTexture = renderTargetData.depthTexture;
  42559. renderContext.width = renderTargetData.width;
  42560. renderContext.height = renderTargetData.height;
  42561. renderContext.renderTarget = renderTarget;
  42562. renderContext.depth = renderTarget.depthBuffer;
  42563. renderContext.stencil = renderTarget.stencilBuffer;
  42564. // #30329
  42565. const color = this.backend.getClearColor();
  42566. renderContext.clearColorValue.r = color.r;
  42567. renderContext.clearColorValue.g = color.g;
  42568. renderContext.clearColorValue.b = color.b;
  42569. renderContext.clearColorValue.a = color.a;
  42570. renderContext.activeCubeFace = this.getActiveCubeFace();
  42571. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  42572. }
  42573. this.backend.clear( color, depth, stencil, renderContext );
  42574. if ( renderTarget !== null && this._renderTarget === null ) {
  42575. this._renderOutput( renderTarget );
  42576. }
  42577. }
  42578. /**
  42579. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  42580. */
  42581. clearColor() {
  42582. this.clear( true, false, false );
  42583. }
  42584. /**
  42585. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  42586. */
  42587. clearDepth() {
  42588. this.clear( false, true, false );
  42589. }
  42590. /**
  42591. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  42592. */
  42593. clearStencil() {
  42594. this.clear( false, false, true );
  42595. }
  42596. /**
  42597. * Async version of {@link Renderer#clear}.
  42598. *
  42599. * @async
  42600. * @deprecated
  42601. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  42602. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  42603. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  42604. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42605. */
  42606. async clearAsync( color = true, depth = true, stencil = true ) {
  42607. warnOnce( 'Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42608. await this.init();
  42609. this.clear( color, depth, stencil );
  42610. }
  42611. /**
  42612. * Async version of {@link Renderer#clearColor}.
  42613. *
  42614. * @async
  42615. * @deprecated
  42616. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42617. */
  42618. async clearColorAsync() {
  42619. warnOnce( 'Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42620. this.clear( true, false, false );
  42621. }
  42622. /**
  42623. * Async version of {@link Renderer#clearDepth}.
  42624. *
  42625. * @async
  42626. * @deprecated
  42627. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42628. */
  42629. async clearDepthAsync() {
  42630. warnOnce( 'Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42631. this.clear( false, true, false );
  42632. }
  42633. /**
  42634. * Async version of {@link Renderer#clearStencil}.
  42635. *
  42636. * @async
  42637. * @deprecated
  42638. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  42639. */
  42640. async clearStencilAsync() {
  42641. warnOnce( 'Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42642. this.clear( false, false, true );
  42643. }
  42644. /**
  42645. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  42646. * If this is the case, the renderer allocates an internal render target for that purpose.
  42647. *
  42648. */
  42649. get needsFrameBufferTarget() {
  42650. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  42651. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  42652. return useToneMapping || useColorSpace;
  42653. }
  42654. /**
  42655. * The number of samples used for multi-sample anti-aliasing (MSAA).
  42656. *
  42657. * @type {number}
  42658. * @default 0
  42659. */
  42660. get samples() {
  42661. return this._samples;
  42662. }
  42663. /**
  42664. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  42665. *
  42666. * When rendering to a custom render target, the number of samples of that render target is used.
  42667. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  42668. * the number of samples is set to 0.
  42669. *
  42670. * @type {number}
  42671. */
  42672. get currentSamples() {
  42673. let samples = this._samples;
  42674. if ( this._renderTarget !== null ) {
  42675. samples = this._renderTarget.samples;
  42676. } else if ( this.needsFrameBufferTarget ) {
  42677. samples = 0;
  42678. }
  42679. return samples;
  42680. }
  42681. /**
  42682. * The current tone mapping of the renderer. When not producing screen output,
  42683. * the tone mapping is always `NoToneMapping`.
  42684. *
  42685. * @type {number}
  42686. */
  42687. get currentToneMapping() {
  42688. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  42689. }
  42690. /**
  42691. * The current color space of the renderer. When not producing screen output,
  42692. * the color space is always the working color space.
  42693. *
  42694. * @type {string}
  42695. */
  42696. get currentColorSpace() {
  42697. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  42698. }
  42699. /**
  42700. * Returns `true` if the rendering settings are set to screen output.
  42701. *
  42702. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  42703. */
  42704. get isOutputTarget() {
  42705. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  42706. }
  42707. /**
  42708. * Frees all internal resources of the renderer. Call this method if the renderer
  42709. * is no longer in use by your app.
  42710. */
  42711. dispose() {
  42712. if ( this._initialized === true ) {
  42713. this.info.dispose();
  42714. this.backend.dispose();
  42715. this._animation.dispose();
  42716. this._objects.dispose();
  42717. this._geometries.dispose();
  42718. this._pipelines.dispose();
  42719. this._nodes.dispose();
  42720. this._bindings.dispose();
  42721. this._renderLists.dispose();
  42722. this._renderContexts.dispose();
  42723. this._textures.dispose();
  42724. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  42725. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  42726. if ( queryPool !== null ) queryPool.dispose();
  42727. } );
  42728. }
  42729. this.setRenderTarget( null );
  42730. this.setAnimationLoop( null );
  42731. }
  42732. /**
  42733. * Sets the given render target. Calling this method means the renderer does not
  42734. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  42735. * Use `null` as the first argument to reset the state.
  42736. *
  42737. * @param {?RenderTarget} renderTarget - The render target to set.
  42738. * @param {number} [activeCubeFace=0] - The active cube face.
  42739. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  42740. */
  42741. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  42742. this._renderTarget = renderTarget;
  42743. this._activeCubeFace = activeCubeFace;
  42744. this._activeMipmapLevel = activeMipmapLevel;
  42745. }
  42746. /**
  42747. * Returns the current render target.
  42748. *
  42749. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  42750. */
  42751. getRenderTarget() {
  42752. return this._renderTarget;
  42753. }
  42754. /**
  42755. * Sets the output render target for the renderer.
  42756. *
  42757. * @param {Object} renderTarget - The render target to set as the output target.
  42758. */
  42759. setOutputRenderTarget( renderTarget ) {
  42760. this._outputRenderTarget = renderTarget;
  42761. }
  42762. /**
  42763. * Returns the current output target.
  42764. *
  42765. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  42766. */
  42767. getOutputRenderTarget() {
  42768. return this._outputRenderTarget;
  42769. }
  42770. /**
  42771. * Sets the canvas target. The canvas target manages the HTML canvas
  42772. * or the offscreen canvas the renderer draws into.
  42773. *
  42774. * @param {CanvasTarget} canvasTarget - The canvas target.
  42775. */
  42776. setCanvasTarget( canvasTarget ) {
  42777. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  42778. this._canvasTarget = canvasTarget;
  42779. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  42780. }
  42781. /**
  42782. * Returns the current canvas target.
  42783. *
  42784. * @return {CanvasTarget} The current canvas target.
  42785. */
  42786. getCanvasTarget() {
  42787. return this._canvasTarget;
  42788. }
  42789. /**
  42790. * Resets the renderer to the initial state before WebXR started.
  42791. *
  42792. * @private
  42793. */
  42794. _resetXRState() {
  42795. this.backend.setXRTarget( null );
  42796. this.setOutputRenderTarget( null );
  42797. this.setRenderTarget( null );
  42798. this._frameBufferTarget.dispose();
  42799. this._frameBufferTarget = null;
  42800. }
  42801. /**
  42802. * Callback for {@link Renderer#setRenderObjectFunction}.
  42803. *
  42804. * @callback renderObjectFunction
  42805. * @param {Object3D} object - The 3D object.
  42806. * @param {Scene} scene - The scene the 3D object belongs to.
  42807. * @param {Camera} camera - The camera the object should be rendered with.
  42808. * @param {BufferGeometry} geometry - The object's geometry.
  42809. * @param {Material} material - The object's material.
  42810. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  42811. * @param {LightsNode} lightsNode - The current lights node.
  42812. * @param {ClippingContext} clippingContext - The clipping context.
  42813. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  42814. */
  42815. /**
  42816. * Sets the given render object function. Calling this method overwrites the default implementation
  42817. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  42818. * if you want to modify the way objects are rendered. For example you can define things like "every
  42819. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  42820. * The custom function must always call `renderObject()` in its implementation.
  42821. *
  42822. * Use `null` as the first argument to reset the state.
  42823. *
  42824. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  42825. */
  42826. setRenderObjectFunction( renderObjectFunction ) {
  42827. this._renderObjectFunction = renderObjectFunction;
  42828. }
  42829. /**
  42830. * Returns the current render object function.
  42831. *
  42832. * @return {?Function} The current render object function. Returns `null` if no function is set.
  42833. */
  42834. getRenderObjectFunction() {
  42835. return this._renderObjectFunction;
  42836. }
  42837. /**
  42838. * Execute a single or an array of compute nodes. This method can only be called
  42839. * if the renderer has been initialized.
  42840. *
  42841. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42842. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42843. * - A single number representing count, or
  42844. * - An array [x, y, z] representing dispatch size, or
  42845. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42846. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  42847. */
  42848. compute( computeNodes, dispatchSize = null ) {
  42849. if ( this._isDeviceLost === true ) return;
  42850. if ( this._initialized === false ) {
  42851. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  42852. return this.computeAsync( computeNodes, dispatchSize );
  42853. }
  42854. //
  42855. const nodeFrame = this._nodes.nodeFrame;
  42856. const previousRenderId = nodeFrame.renderId;
  42857. //
  42858. this.info.calls ++;
  42859. this.info.compute.calls ++;
  42860. this.info.compute.frameCalls ++;
  42861. nodeFrame.renderId = this.info.calls;
  42862. //
  42863. this.backend.updateTimeStampUID( computeNodes );
  42864. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  42865. //
  42866. const backend = this.backend;
  42867. const pipelines = this._pipelines;
  42868. const bindings = this._bindings;
  42869. const nodes = this._nodes;
  42870. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  42871. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  42872. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  42873. }
  42874. backend.beginCompute( computeNodes );
  42875. for ( const computeNode of computeList ) {
  42876. // onInit
  42877. if ( pipelines.has( computeNode ) === false ) {
  42878. const dispose = () => {
  42879. computeNode.removeEventListener( 'dispose', dispose );
  42880. pipelines.delete( computeNode );
  42881. bindings.deleteForCompute( computeNode );
  42882. nodes.delete( computeNode );
  42883. };
  42884. computeNode.addEventListener( 'dispose', dispose );
  42885. //
  42886. const onInitFn = computeNode.onInitFunction;
  42887. if ( onInitFn !== null ) {
  42888. onInitFn.call( computeNode, { renderer: this } );
  42889. }
  42890. }
  42891. nodes.updateForCompute( computeNode );
  42892. bindings.updateForCompute( computeNode );
  42893. const computeBindings = bindings.getForCompute( computeNode );
  42894. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  42895. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSize );
  42896. }
  42897. backend.finishCompute( computeNodes );
  42898. //
  42899. nodeFrame.renderId = previousRenderId;
  42900. //
  42901. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  42902. }
  42903. /**
  42904. * Execute a single or an array of compute nodes.
  42905. *
  42906. * @async
  42907. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  42908. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  42909. * - A single number representing count, or
  42910. * - An array [x, y, z] representing dispatch size, or
  42911. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  42912. * @return {Promise} A Promise that resolve when the compute has finished.
  42913. */
  42914. async computeAsync( computeNodes, dispatchSize = null ) {
  42915. if ( this._initialized === false ) await this.init();
  42916. this.compute( computeNodes, dispatchSize );
  42917. }
  42918. /**
  42919. * Checks if the given feature is supported by the selected backend.
  42920. *
  42921. * @async
  42922. * @deprecated
  42923. * @param {string} name - The feature's name.
  42924. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42925. */
  42926. async hasFeatureAsync( name ) {
  42927. warnOnce( 'Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42928. await this.init();
  42929. return this.hasFeature( name );
  42930. }
  42931. async resolveTimestampsAsync( type = 'render' ) {
  42932. if ( this._initialized === false ) await this.init();
  42933. return this.backend.resolveTimestampsAsync( type );
  42934. }
  42935. /**
  42936. * Checks if the given feature is supported by the selected backend. If the
  42937. * renderer has not been initialized, this method always returns `false`.
  42938. *
  42939. * @param {string} name - The feature's name.
  42940. * @return {boolean} Whether the feature is supported or not.
  42941. */
  42942. hasFeature( name ) {
  42943. if ( this._initialized === false ) {
  42944. throw new Error( 'Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42945. }
  42946. return this.backend.hasFeature( name );
  42947. }
  42948. /**
  42949. * Returns `true` when the renderer has been initialized.
  42950. *
  42951. * @return {boolean} Whether the renderer has been initialized or not.
  42952. */
  42953. hasInitialized() {
  42954. return this._initialized;
  42955. }
  42956. /**
  42957. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  42958. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42959. *
  42960. * @async
  42961. * @deprecated
  42962. * @param {Texture} texture - The texture.
  42963. * @return {Promise} A Promise that resolves when the texture has been initialized.
  42964. */
  42965. async initTextureAsync( texture ) {
  42966. warnOnce( 'Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  42967. await this.init();
  42968. this.initTexture( texture );
  42969. }
  42970. /**
  42971. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  42972. * (which can cause noticeable lags due to decode and GPU upload overhead).
  42973. *
  42974. * This method can only be used if the renderer has been initialized.
  42975. *
  42976. * @param {Texture} texture - The texture.
  42977. */
  42978. initTexture( texture ) {
  42979. if ( this._initialized === false ) {
  42980. throw new Error( 'Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.' );
  42981. }
  42982. this._textures.updateTexture( texture );
  42983. }
  42984. /**
  42985. * Copies the current bound framebuffer into the given texture.
  42986. *
  42987. * @param {FramebufferTexture} framebufferTexture - The texture.
  42988. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  42989. */
  42990. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  42991. if ( rectangle !== null ) {
  42992. if ( rectangle.isVector2 ) {
  42993. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  42994. } else if ( rectangle.isVector4 ) {
  42995. rectangle = _vector4.copy( rectangle ).floor();
  42996. } else {
  42997. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  42998. return;
  42999. }
  43000. } else {
  43001. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  43002. }
  43003. //
  43004. let renderContext = this._currentRenderContext;
  43005. let renderTarget;
  43006. if ( renderContext !== null ) {
  43007. renderTarget = renderContext.renderTarget;
  43008. } else {
  43009. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  43010. if ( renderTarget !== null ) {
  43011. this._textures.updateRenderTarget( renderTarget );
  43012. renderContext = this._textures.get( renderTarget );
  43013. }
  43014. }
  43015. //
  43016. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  43017. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  43018. this._inspector.copyFramebufferToTexture( framebufferTexture );
  43019. }
  43020. /**
  43021. * Copies data of the given source texture into a destination texture.
  43022. *
  43023. * @param {Texture} srcTexture - The source texture.
  43024. * @param {Texture} dstTexture - The destination texture.
  43025. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  43026. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  43027. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43028. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43029. */
  43030. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43031. this._textures.updateTexture( srcTexture );
  43032. this._textures.updateTexture( dstTexture );
  43033. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  43034. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  43035. }
  43036. /**
  43037. * Reads pixel data from the given render target.
  43038. *
  43039. * @async
  43040. * @param {RenderTarget} renderTarget - The render target to read from.
  43041. * @param {number} x - The `x` coordinate of the copy region's origin.
  43042. * @param {number} y - The `y` coordinate of the copy region's origin.
  43043. * @param {number} width - The width of the copy region.
  43044. * @param {number} height - The height of the copy region.
  43045. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  43046. * @param {number} [faceIndex=0] - The active cube face index.
  43047. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  43048. */
  43049. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  43050. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  43051. }
  43052. /**
  43053. * Analyzes the given 3D object's hierarchy and builds render lists from the
  43054. * processed hierarchy.
  43055. *
  43056. * @private
  43057. * @param {Object3D} object - The 3D object to process (usually a scene).
  43058. * @param {Camera} camera - The camera the object is rendered with.
  43059. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  43060. * @param {RenderList} renderList - The current render list.
  43061. * @param {ClippingContext} clippingContext - The current clipping context.
  43062. */
  43063. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  43064. if ( object.visible === false ) return;
  43065. const visible = object.layers.test( camera.layers );
  43066. if ( visible ) {
  43067. if ( object.isGroup ) {
  43068. groupOrder = object.renderOrder;
  43069. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  43070. } else if ( object.isLOD ) {
  43071. if ( object.autoUpdate === true ) object.update( camera );
  43072. } else if ( object.isLight ) {
  43073. renderList.pushLight( object );
  43074. } else if ( object.isSprite ) {
  43075. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43076. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  43077. if ( this.sortObjects === true ) {
  43078. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  43079. }
  43080. const { geometry, material } = object;
  43081. if ( material.visible ) {
  43082. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43083. }
  43084. }
  43085. } else if ( object.isLineLoop ) {
  43086. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  43087. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  43088. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  43089. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  43090. const { geometry, material } = object;
  43091. if ( this.sortObjects === true ) {
  43092. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  43093. _vector4
  43094. .copy( geometry.boundingSphere.center )
  43095. .applyMatrix4( object.matrixWorld )
  43096. .applyMatrix4( _projScreenMatrix );
  43097. }
  43098. if ( Array.isArray( material ) ) {
  43099. const groups = geometry.groups;
  43100. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  43101. const group = groups[ i ];
  43102. const groupMaterial = material[ group.materialIndex ];
  43103. if ( groupMaterial && groupMaterial.visible ) {
  43104. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  43105. }
  43106. }
  43107. } else if ( material.visible ) {
  43108. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  43109. }
  43110. }
  43111. }
  43112. }
  43113. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  43114. const baseRenderList = renderList;
  43115. // replace render list
  43116. renderList = this._renderLists.get( object, camera );
  43117. renderList.begin();
  43118. baseRenderList.pushBundle( {
  43119. bundleGroup: object,
  43120. camera,
  43121. renderList,
  43122. } );
  43123. renderList.finish();
  43124. }
  43125. const children = object.children;
  43126. for ( let i = 0, l = children.length; i < l; i ++ ) {
  43127. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  43128. }
  43129. }
  43130. /**
  43131. * Renders the given render bundles.
  43132. *
  43133. * @private
  43134. * @param {Array<Object>} bundles - Array with render bundle data.
  43135. * @param {Scene} sceneRef - The scene the render bundles belong to.
  43136. * @param {LightsNode} lightsNode - The current lights node.
  43137. */
  43138. _renderBundles( bundles, sceneRef, lightsNode ) {
  43139. for ( const bundle of bundles ) {
  43140. this._renderBundle( bundle, sceneRef, lightsNode );
  43141. }
  43142. }
  43143. /**
  43144. * Renders the transparent objects from the given render lists.
  43145. *
  43146. * @private
  43147. * @param {Array<Object>} renderList - The transparent render list.
  43148. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  43149. * @param {Camera} camera - The camera the render list should be rendered with.
  43150. * @param {Scene} scene - The scene the render list belongs to.
  43151. * @param {LightsNode} lightsNode - The current lights node.
  43152. */
  43153. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  43154. if ( doublePassList.length > 0 ) {
  43155. // render back side
  43156. for ( const { material } of doublePassList ) {
  43157. material.side = BackSide;
  43158. }
  43159. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  43160. // render front side
  43161. for ( const { material } of doublePassList ) {
  43162. material.side = FrontSide;
  43163. }
  43164. this._renderObjects( renderList, camera, scene, lightsNode );
  43165. // restore
  43166. for ( const { material } of doublePassList ) {
  43167. material.side = DoubleSide;
  43168. }
  43169. } else {
  43170. this._renderObjects( renderList, camera, scene, lightsNode );
  43171. }
  43172. }
  43173. /**
  43174. * Renders the objects from the given render list.
  43175. *
  43176. * @private
  43177. * @param {Array<Object>} renderList - The render list.
  43178. * @param {Camera} camera - The camera the render list should be rendered with.
  43179. * @param {Scene} scene - The scene the render list belongs to.
  43180. * @param {LightsNode} lightsNode - The current lights node.
  43181. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43182. */
  43183. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  43184. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  43185. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  43186. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  43187. }
  43188. }
  43189. /**
  43190. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  43191. * The result is cached per material and updated when the material's version changes.
  43192. *
  43193. * @private
  43194. * @param {Material} material
  43195. * @returns {Object} - The shadow nodes for the material.
  43196. */
  43197. _getShadowNodes( material ) {
  43198. const version = material.version;
  43199. let cache = this._cacheShadowNodes.get( material );
  43200. if ( cache === undefined || cache.version !== version ) {
  43201. const hasMap = material.map !== null;
  43202. const hasColorNode = material.colorNode && material.colorNode.isNode;
  43203. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  43204. const hasMaskNode = ( material.maskShadowNode && material.maskShadowNode.isNode ) || ( material.maskNode && material.maskNode.isNode );
  43205. let positionNode = null;
  43206. let colorNode = null;
  43207. let depthNode = null;
  43208. if ( hasMap || hasColorNode || hasCastShadowNode || hasMaskNode ) {
  43209. let shadowRGB;
  43210. let shadowAlpha;
  43211. if ( hasCastShadowNode ) {
  43212. shadowRGB = material.castShadowNode.rgb;
  43213. shadowAlpha = material.castShadowNode.a;
  43214. if ( this.shadowMap.transmitted !== true ) {
  43215. warnOnce( 'Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.' );
  43216. }
  43217. } else {
  43218. shadowRGB = vec3( 0 );
  43219. shadowAlpha = float( 1 );
  43220. }
  43221. if ( hasMap ) {
  43222. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  43223. }
  43224. if ( hasColorNode ) {
  43225. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  43226. }
  43227. colorNode = vec4( shadowRGB, shadowAlpha );
  43228. if ( hasMaskNode ) {
  43229. const maskNode = material.maskShadowNode || material.maskNode;
  43230. colorNode = Fn( ( [ color ] ) => {
  43231. maskNode.not().discard();
  43232. return color;
  43233. } )( colorNode );
  43234. }
  43235. }
  43236. if ( material.depthNode && material.depthNode.isNode ) {
  43237. depthNode = material.depthNode;
  43238. }
  43239. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  43240. positionNode = material.castShadowPositionNode;
  43241. } else if ( material.positionNode && material.positionNode.isNode ) {
  43242. positionNode = material.positionNode;
  43243. }
  43244. cache = {
  43245. version,
  43246. colorNode,
  43247. depthNode,
  43248. positionNode
  43249. };
  43250. this._cacheShadowNodes.set( material, cache );
  43251. }
  43252. return cache;
  43253. }
  43254. /**
  43255. * This method represents the default render object function that manages the render lifecycle
  43256. * of the object.
  43257. *
  43258. * @param {Object3D} object - The 3D object.
  43259. * @param {Scene} scene - The scene the 3D object belongs to.
  43260. * @param {Camera} camera - The camera the object should be rendered with.
  43261. * @param {BufferGeometry} geometry - The object's geometry.
  43262. * @param {Material} material - The object's material.
  43263. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43264. * @param {LightsNode} lightsNode - The current lights node.
  43265. * @param {?ClippingContext} clippingContext - The clipping context.
  43266. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  43267. */
  43268. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  43269. let materialOverride = false;
  43270. let materialColorNode;
  43271. let materialDepthNode;
  43272. let materialPositionNode;
  43273. let materialSide;
  43274. //
  43275. object.onBeforeRender( this, scene, camera, geometry, material, group );
  43276. //
  43277. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  43278. const overrideMaterial = scene.overrideMaterial;
  43279. materialOverride = true;
  43280. // store original nodes
  43281. materialColorNode = scene.overrideMaterial.colorNode;
  43282. materialDepthNode = scene.overrideMaterial.depthNode;
  43283. materialPositionNode = scene.overrideMaterial.positionNode;
  43284. materialSide = scene.overrideMaterial.side;
  43285. if ( material.positionNode && material.positionNode.isNode ) {
  43286. overrideMaterial.positionNode = material.positionNode;
  43287. }
  43288. overrideMaterial.alphaTest = material.alphaTest;
  43289. overrideMaterial.alphaMap = material.alphaMap;
  43290. overrideMaterial.transparent = material.transparent || material.transmission > 0 ||
  43291. ( material.transmissionNode && material.transmissionNode.isNode ) ||
  43292. ( material.backdropNode && material.backdropNode.isNode );
  43293. if ( overrideMaterial.isShadowPassMaterial ) {
  43294. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  43295. if ( this.shadowMap.type === VSMShadowMap ) {
  43296. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  43297. } else {
  43298. overrideMaterial.side = ( material.shadowSide !== null ) ? material.shadowSide : _shadowSide[ material.side ];
  43299. }
  43300. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  43301. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  43302. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  43303. }
  43304. material = overrideMaterial;
  43305. }
  43306. //
  43307. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  43308. material.side = BackSide;
  43309. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  43310. material.side = FrontSide;
  43311. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  43312. material.side = DoubleSide;
  43313. } else {
  43314. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  43315. }
  43316. //
  43317. if ( materialOverride ) {
  43318. scene.overrideMaterial.colorNode = materialColorNode;
  43319. scene.overrideMaterial.depthNode = materialDepthNode;
  43320. scene.overrideMaterial.positionNode = materialPositionNode;
  43321. scene.overrideMaterial.side = materialSide;
  43322. }
  43323. //
  43324. object.onAfterRender( this, scene, camera, geometry, material, group );
  43325. }
  43326. /**
  43327. * Checks if the given compatibility is supported by the selected backend. If the
  43328. * renderer has not been initialized, this method always returns `false`.
  43329. *
  43330. * @param {string} name - The compatibility's name.
  43331. * @return {boolean} Whether the compatibility is supported or not.
  43332. */
  43333. hasCompatibility( name ) {
  43334. return this.backend.hasCompatibility( name );
  43335. }
  43336. /**
  43337. * This method represents the default `_handleObjectFunction` implementation which creates
  43338. * a render object from the given data and performs the draw command with the selected backend.
  43339. *
  43340. * @private
  43341. * @param {Object3D} object - The 3D object.
  43342. * @param {Material} material - The object's material.
  43343. * @param {Scene} scene - The scene the 3D object belongs to.
  43344. * @param {Camera} camera - The camera the object should be rendered with.
  43345. * @param {LightsNode} lightsNode - The current lights node.
  43346. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43347. * @param {ClippingContext} clippingContext - The clipping context.
  43348. * @param {string} [passId] - An optional ID for identifying the pass.
  43349. */
  43350. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43351. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43352. renderObject.drawRange = object.geometry.drawRange;
  43353. renderObject.group = group;
  43354. //
  43355. const needsRefresh = this._nodes.needsRefresh( renderObject );
  43356. if ( needsRefresh ) {
  43357. this._nodes.updateBefore( renderObject );
  43358. this._geometries.updateForRender( renderObject );
  43359. this._nodes.updateForRender( renderObject );
  43360. this._bindings.updateForRender( renderObject );
  43361. }
  43362. this._pipelines.updateForRender( renderObject );
  43363. //
  43364. if ( this._currentRenderBundle !== null ) {
  43365. const renderBundleData = this.backend.get( this._currentRenderBundle );
  43366. renderBundleData.renderObjects.push( renderObject );
  43367. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  43368. }
  43369. this.backend.draw( renderObject, this.info );
  43370. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  43371. }
  43372. /**
  43373. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  43374. * Used in `compileAsync()`.
  43375. *
  43376. * @private
  43377. * @param {Object3D} object - The 3D object.
  43378. * @param {Material} material - The object's material.
  43379. * @param {Scene} scene - The scene the 3D object belongs to.
  43380. * @param {Camera} camera - The camera the object should be rendered with.
  43381. * @param {LightsNode} lightsNode - The current lights node.
  43382. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  43383. * @param {ClippingContext} clippingContext - The clipping context.
  43384. * @param {string} [passId] - An optional ID for identifying the pass.
  43385. */
  43386. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  43387. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  43388. renderObject.drawRange = object.geometry.drawRange;
  43389. renderObject.group = group;
  43390. //
  43391. this._nodes.updateBefore( renderObject );
  43392. this._geometries.updateForRender( renderObject );
  43393. this._nodes.updateForRender( renderObject );
  43394. this._bindings.updateForRender( renderObject );
  43395. this._pipelines.getForRender( renderObject, this._compilationPromises );
  43396. this._nodes.updateAfter( renderObject );
  43397. }
  43398. /**
  43399. * Callback when the canvas has been resized.
  43400. *
  43401. * @private
  43402. */
  43403. _onCanvasTargetResize() {
  43404. if ( this._initialized ) this.backend.updateSize();
  43405. }
  43406. /**
  43407. * Alias for `compileAsync()`.
  43408. *
  43409. * @method
  43410. * @param {Object3D} scene - The scene or 3D object to precompile.
  43411. * @param {Camera} camera - The camera that is used to render the scene.
  43412. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  43413. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  43414. */
  43415. get compile() {
  43416. return this.compileAsync;
  43417. }
  43418. }
  43419. /**
  43420. * A binding represents the connection between a resource (like a texture, sampler
  43421. * or uniform buffer) and the resource definition in a shader stage.
  43422. *
  43423. * This module is an abstract base class for all concrete bindings types.
  43424. *
  43425. * @abstract
  43426. * @private
  43427. */
  43428. class Binding {
  43429. /**
  43430. * Constructs a new binding.
  43431. *
  43432. * @param {string} [name=''] - The binding's name.
  43433. */
  43434. constructor( name = '' ) {
  43435. /**
  43436. * The binding's name.
  43437. *
  43438. * @type {string}
  43439. */
  43440. this.name = name;
  43441. /**
  43442. * A bitmask that defines in what shader stages the
  43443. * binding's resource is accessible.
  43444. *
  43445. * @type {number}
  43446. */
  43447. this.visibility = 0;
  43448. }
  43449. /**
  43450. * Makes sure binding's resource is visible for the given shader stage.
  43451. *
  43452. * @param {number} visibility - The shader stage.
  43453. */
  43454. setVisibility( visibility ) {
  43455. this.visibility |= visibility;
  43456. }
  43457. /**
  43458. * The shader stages in which the binding's resource is visible.
  43459. *
  43460. * @return {number} The visibility bitmask.
  43461. */
  43462. getVisibility() {
  43463. return this.visibility;
  43464. }
  43465. /**
  43466. * Clones the binding.
  43467. *
  43468. * @return {Binding} The cloned binding.
  43469. */
  43470. clone() {
  43471. return Object.assign( new this.constructor(), this );
  43472. }
  43473. }
  43474. /**
  43475. * This function is usually called with the length in bytes of an array buffer.
  43476. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  43477. *
  43478. * @function
  43479. * @param {number} floatLength - The buffer length.
  43480. * @return {number} The padded length.
  43481. */
  43482. function getFloatLength( floatLength ) {
  43483. // ensure chunk size alignment (STD140 layout)
  43484. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  43485. }
  43486. /**
  43487. * Represents a buffer binding type.
  43488. *
  43489. * @private
  43490. * @abstract
  43491. * @augments Binding
  43492. */
  43493. class Buffer extends Binding {
  43494. /**
  43495. * Constructs a new buffer.
  43496. *
  43497. * @param {string} name - The buffer's name.
  43498. * @param {TypedArray} [buffer=null] - The buffer.
  43499. */
  43500. constructor( name, buffer = null ) {
  43501. super( name );
  43502. /**
  43503. * This flag can be used for type testing.
  43504. *
  43505. * @type {boolean}
  43506. * @readonly
  43507. * @default true
  43508. */
  43509. this.isBuffer = true;
  43510. /**
  43511. * The bytes per element.
  43512. *
  43513. * @type {number}
  43514. */
  43515. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  43516. /**
  43517. * A reference to the internal buffer.
  43518. *
  43519. * @private
  43520. * @type {TypedArray}
  43521. */
  43522. this._buffer = buffer;
  43523. /**
  43524. * An array of update ranges.
  43525. *
  43526. * @private
  43527. * @type {Array<{start: number, count: number}>}
  43528. */
  43529. this._updateRanges = [];
  43530. }
  43531. /**
  43532. * The array of update ranges.
  43533. *
  43534. * @type {Array<{start: number, count: number}>}
  43535. */
  43536. get updateRanges() {
  43537. return this._updateRanges;
  43538. }
  43539. /**
  43540. * Adds an update range.
  43541. *
  43542. * @param {number} start - The start index.
  43543. * @param {number} count - The number of elements.
  43544. */
  43545. addUpdateRange( start, count ) {
  43546. this.updateRanges.push( { start, count } );
  43547. }
  43548. /**
  43549. * Clears all update ranges.
  43550. */
  43551. clearUpdateRanges() {
  43552. this.updateRanges.length = 0;
  43553. }
  43554. /**
  43555. * The buffer's byte length.
  43556. *
  43557. * @type {number}
  43558. * @readonly
  43559. */
  43560. get byteLength() {
  43561. return getFloatLength( this._buffer.byteLength );
  43562. }
  43563. /**
  43564. * A reference to the internal buffer.
  43565. *
  43566. * @type {Float32Array}
  43567. * @readonly
  43568. */
  43569. get buffer() {
  43570. return this._buffer;
  43571. }
  43572. /**
  43573. * Updates the binding.
  43574. *
  43575. * @return {boolean} Whether the buffer has been updated and must be
  43576. * uploaded to the GPU.
  43577. */
  43578. update() {
  43579. return true;
  43580. }
  43581. }
  43582. /**
  43583. * Represents a uniform buffer binding type.
  43584. *
  43585. * @private
  43586. * @augments Buffer
  43587. */
  43588. class UniformBuffer extends Buffer {
  43589. /**
  43590. * Constructs a new uniform buffer.
  43591. *
  43592. * @param {string} name - The buffer's name.
  43593. * @param {TypedArray} [buffer=null] - The buffer.
  43594. */
  43595. constructor( name, buffer = null ) {
  43596. super( name, buffer );
  43597. /**
  43598. * This flag can be used for type testing.
  43599. *
  43600. * @type {boolean}
  43601. * @readonly
  43602. * @default true
  43603. */
  43604. this.isUniformBuffer = true;
  43605. }
  43606. }
  43607. let _id$4 = 0;
  43608. /**
  43609. * A special form of uniform buffer binding type.
  43610. * It's buffer value is managed by a node object.
  43611. *
  43612. * @private
  43613. * @augments UniformBuffer
  43614. */
  43615. class NodeUniformBuffer extends UniformBuffer {
  43616. /**
  43617. * Constructs a new node-based uniform buffer.
  43618. *
  43619. * @param {BufferNode} nodeUniform - The uniform buffer node.
  43620. * @param {UniformGroupNode} groupNode - The uniform group node.
  43621. */
  43622. constructor( nodeUniform, groupNode ) {
  43623. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  43624. /**
  43625. * The uniform buffer node.
  43626. *
  43627. * @type {BufferNode}
  43628. */
  43629. this.nodeUniform = nodeUniform;
  43630. /**
  43631. * The uniform group node.
  43632. *
  43633. * @type {UniformGroupNode}
  43634. */
  43635. this.groupNode = groupNode;
  43636. /**
  43637. * This flag can be used for type testing.
  43638. *
  43639. * @type {boolean}
  43640. * @readonly
  43641. * @default true
  43642. */
  43643. this.isNodeUniformBuffer = true;
  43644. }
  43645. /**
  43646. * The array of update ranges.
  43647. *
  43648. * @param {Array<{start: number, count: number}>} value - The update ranges.
  43649. */
  43650. set updateRanges( value ) {
  43651. this.nodeUniform.updateRanges = value;
  43652. }
  43653. /**
  43654. * The array of update ranges.
  43655. *
  43656. * @type {Array<{start: number, count: number}>}
  43657. */
  43658. get updateRanges() {
  43659. return this.nodeUniform.updateRanges;
  43660. }
  43661. /**
  43662. * Adds a range of data in the data array to be updated on the GPU.
  43663. *
  43664. * @param {number} start - Position at which to start update.
  43665. * @param {number} count - The number of components to update.
  43666. */
  43667. addUpdateRange( start, count ) {
  43668. this.nodeUniform.addUpdateRange( start, count );
  43669. }
  43670. /**
  43671. * Clears all update ranges.
  43672. */
  43673. clearUpdateRanges() {
  43674. this.nodeUniform.clearUpdateRanges();
  43675. }
  43676. /**
  43677. * The uniform buffer.
  43678. *
  43679. * @type {Float32Array}
  43680. */
  43681. get buffer() {
  43682. return this.nodeUniform.value;
  43683. }
  43684. }
  43685. /**
  43686. * This class represents a uniform buffer binding but with
  43687. * an API that allows to maintain individual uniform objects.
  43688. *
  43689. * @private
  43690. * @augments UniformBuffer
  43691. */
  43692. class UniformsGroup extends UniformBuffer {
  43693. /**
  43694. * Constructs a new uniforms group.
  43695. *
  43696. * @param {string} name - The group's name.
  43697. */
  43698. constructor( name ) {
  43699. super( name );
  43700. /**
  43701. * This flag can be used for type testing.
  43702. *
  43703. * @type {boolean}
  43704. * @readonly
  43705. * @default true
  43706. */
  43707. this.isUniformsGroup = true;
  43708. /**
  43709. * An array with the raw uniform values.
  43710. *
  43711. * @private
  43712. * @type {?Array<number>}
  43713. * @default null
  43714. */
  43715. this._values = null;
  43716. /**
  43717. * An array of uniform objects.
  43718. *
  43719. * The order of uniforms in this array must match the order of uniforms in the shader.
  43720. *
  43721. * @type {Array<Uniform>}
  43722. */
  43723. this.uniforms = [];
  43724. /**
  43725. * A cache for the uniform update ranges.
  43726. *
  43727. * @private
  43728. * @type {Map<number, {start: number, count: number}>}
  43729. */
  43730. this._updateRangeCache = new Map();
  43731. }
  43732. /**
  43733. * Adds a uniform's update range to this buffer.
  43734. *
  43735. * @param {Uniform} uniform - The uniform.
  43736. */
  43737. addUniformUpdateRange( uniform ) {
  43738. const index = uniform.index;
  43739. if ( this._updateRangeCache.has( index ) !== true ) {
  43740. const updateRanges = this.updateRanges;
  43741. const start = uniform.offset;
  43742. const count = uniform.itemSize;
  43743. const range = { start, count };
  43744. updateRanges.push( range );
  43745. this._updateRangeCache.set( index, range );
  43746. }
  43747. }
  43748. /**
  43749. * Clears all update ranges of this buffer.
  43750. */
  43751. clearUpdateRanges() {
  43752. this._updateRangeCache.clear();
  43753. super.clearUpdateRanges();
  43754. }
  43755. /**
  43756. * Adds a uniform to this group.
  43757. *
  43758. * @param {Uniform} uniform - The uniform to add.
  43759. * @return {UniformsGroup} A reference to this group.
  43760. */
  43761. addUniform( uniform ) {
  43762. this.uniforms.push( uniform );
  43763. return this;
  43764. }
  43765. /**
  43766. * Removes a uniform from this group.
  43767. *
  43768. * @param {Uniform} uniform - The uniform to remove.
  43769. * @return {UniformsGroup} A reference to this group.
  43770. */
  43771. removeUniform( uniform ) {
  43772. const index = this.uniforms.indexOf( uniform );
  43773. if ( index !== -1 ) {
  43774. this.uniforms.splice( index, 1 );
  43775. }
  43776. return this;
  43777. }
  43778. /**
  43779. * An array with the raw uniform values.
  43780. *
  43781. * @type {Array<number>}
  43782. */
  43783. get values() {
  43784. if ( this._values === null ) {
  43785. this._values = Array.from( this.buffer );
  43786. }
  43787. return this._values;
  43788. }
  43789. /**
  43790. * A Float32 array buffer with the uniform values.
  43791. *
  43792. * @type {Float32Array}
  43793. */
  43794. get buffer() {
  43795. let buffer = this._buffer;
  43796. if ( buffer === null ) {
  43797. const byteLength = this.byteLength;
  43798. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  43799. this._buffer = buffer;
  43800. }
  43801. return buffer;
  43802. }
  43803. /**
  43804. * The byte length of the buffer with correct buffer alignment.
  43805. *
  43806. * @type {number}
  43807. */
  43808. get byteLength() {
  43809. const bytesPerElement = this.bytesPerElement;
  43810. let offset = 0; // global buffer offset in bytes
  43811. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  43812. const uniform = this.uniforms[ i ];
  43813. const boundary = uniform.boundary;
  43814. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  43815. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  43816. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  43817. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  43818. offset += chunkPadding;
  43819. // Check for chunk overflow
  43820. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  43821. // Add padding to the end of the chunk
  43822. offset += ( GPU_CHUNK_BYTES - chunkStart );
  43823. }
  43824. uniform.offset = offset / bytesPerElement;
  43825. uniform.index = i;
  43826. offset += itemSize;
  43827. }
  43828. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  43829. }
  43830. /**
  43831. * Updates this group by updating each uniform object of
  43832. * the internal uniform list. The uniform objects check if their
  43833. * values has actually changed so this method only returns
  43834. * `true` if there is a real value change.
  43835. *
  43836. * @return {boolean} Whether the uniforms have been updated and
  43837. * must be uploaded to the GPU.
  43838. */
  43839. update() {
  43840. let updated = false;
  43841. for ( const uniform of this.uniforms ) {
  43842. if ( this.updateByType( uniform ) === true ) {
  43843. updated = true;
  43844. }
  43845. }
  43846. return updated;
  43847. }
  43848. /**
  43849. * Updates a given uniform by calling an update method matching
  43850. * the uniforms type.
  43851. *
  43852. * @param {Uniform} uniform - The uniform to update.
  43853. * @return {boolean} Whether the uniform has been updated or not.
  43854. */
  43855. updateByType( uniform ) {
  43856. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  43857. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  43858. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  43859. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  43860. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  43861. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  43862. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  43863. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  43864. }
  43865. /**
  43866. * Updates a given Number uniform.
  43867. *
  43868. * @param {NumberUniform} uniform - The Number uniform.
  43869. * @return {boolean} Whether the uniform has been updated or not.
  43870. */
  43871. updateNumber( uniform ) {
  43872. let updated = false;
  43873. const a = this.values;
  43874. const v = uniform.getValue();
  43875. const offset = uniform.offset;
  43876. const type = uniform.getType();
  43877. if ( a[ offset ] !== v ) {
  43878. const b = this._getBufferForType( type );
  43879. b[ offset ] = a[ offset ] = v;
  43880. updated = true;
  43881. this.addUniformUpdateRange( uniform );
  43882. }
  43883. return updated;
  43884. }
  43885. /**
  43886. * Updates a given Vector2 uniform.
  43887. *
  43888. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  43889. * @return {boolean} Whether the uniform has been updated or not.
  43890. */
  43891. updateVector2( uniform ) {
  43892. let updated = false;
  43893. const a = this.values;
  43894. const v = uniform.getValue();
  43895. const offset = uniform.offset;
  43896. const type = uniform.getType();
  43897. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  43898. const b = this._getBufferForType( type );
  43899. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43900. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43901. updated = true;
  43902. this.addUniformUpdateRange( uniform );
  43903. }
  43904. return updated;
  43905. }
  43906. /**
  43907. * Updates a given Vector3 uniform.
  43908. *
  43909. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  43910. * @return {boolean} Whether the uniform has been updated or not.
  43911. */
  43912. updateVector3( uniform ) {
  43913. let updated = false;
  43914. const a = this.values;
  43915. const v = uniform.getValue();
  43916. const offset = uniform.offset;
  43917. const type = uniform.getType();
  43918. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  43919. const b = this._getBufferForType( type );
  43920. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43921. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43922. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43923. updated = true;
  43924. this.addUniformUpdateRange( uniform );
  43925. }
  43926. return updated;
  43927. }
  43928. /**
  43929. * Updates a given Vector4 uniform.
  43930. *
  43931. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  43932. * @return {boolean} Whether the uniform has been updated or not.
  43933. */
  43934. updateVector4( uniform ) {
  43935. let updated = false;
  43936. const a = this.values;
  43937. const v = uniform.getValue();
  43938. const offset = uniform.offset;
  43939. const type = uniform.getType();
  43940. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  43941. const b = this._getBufferForType( type );
  43942. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  43943. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  43944. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  43945. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  43946. updated = true;
  43947. this.addUniformUpdateRange( uniform );
  43948. }
  43949. return updated;
  43950. }
  43951. /**
  43952. * Updates a given Color uniform.
  43953. *
  43954. * @param {ColorUniform} uniform - The Color uniform.
  43955. * @return {boolean} Whether the uniform has been updated or not.
  43956. */
  43957. updateColor( uniform ) {
  43958. let updated = false;
  43959. const a = this.values;
  43960. const c = uniform.getValue();
  43961. const offset = uniform.offset;
  43962. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  43963. const b = this.buffer;
  43964. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  43965. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  43966. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  43967. updated = true;
  43968. this.addUniformUpdateRange( uniform );
  43969. }
  43970. return updated;
  43971. }
  43972. /**
  43973. * Updates a given Matrix3 uniform.
  43974. *
  43975. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  43976. * @return {boolean} Whether the uniform has been updated or not.
  43977. */
  43978. updateMatrix3( uniform ) {
  43979. let updated = false;
  43980. const a = this.values;
  43981. const e = uniform.getValue().elements;
  43982. const offset = uniform.offset;
  43983. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  43984. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  43985. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  43986. const b = this.buffer;
  43987. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  43988. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  43989. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  43990. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  43991. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  43992. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  43993. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  43994. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  43995. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  43996. updated = true;
  43997. this.addUniformUpdateRange( uniform );
  43998. }
  43999. return updated;
  44000. }
  44001. /**
  44002. * Updates a given Matrix4 uniform.
  44003. *
  44004. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  44005. * @return {boolean} Whether the uniform has been updated or not.
  44006. */
  44007. updateMatrix4( uniform ) {
  44008. let updated = false;
  44009. const a = this.values;
  44010. const e = uniform.getValue().elements;
  44011. const offset = uniform.offset;
  44012. if ( arraysEqual( a, e, offset ) === false ) {
  44013. const b = this.buffer;
  44014. b.set( e, offset );
  44015. setArray( a, e, offset );
  44016. updated = true;
  44017. this.addUniformUpdateRange( uniform );
  44018. }
  44019. return updated;
  44020. }
  44021. /**
  44022. * Returns a typed array that matches the given data type.
  44023. *
  44024. * @private
  44025. * @param {string} type - The data type.
  44026. * @return {TypedArray} The typed array.
  44027. */
  44028. _getBufferForType( type ) {
  44029. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  44030. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  44031. return this.buffer;
  44032. }
  44033. }
  44034. /**
  44035. * Sets the values of the second array to the first array.
  44036. *
  44037. * @private
  44038. * @param {TypedArray} a - The first array.
  44039. * @param {TypedArray} b - The second array.
  44040. * @param {number} offset - An index offset for the first array.
  44041. */
  44042. function setArray( a, b, offset ) {
  44043. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44044. a[ offset + i ] = b[ i ];
  44045. }
  44046. }
  44047. /**
  44048. * Returns `true` if the given arrays are equal.
  44049. *
  44050. * @private
  44051. * @param {TypedArray} a - The first array.
  44052. * @param {TypedArray} b - The second array.
  44053. * @param {number} offset - An index offset for the first array.
  44054. * @return {boolean} Whether the given arrays are equal or not.
  44055. */
  44056. function arraysEqual( a, b, offset ) {
  44057. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44058. if ( a[ offset + i ] !== b[ i ] ) return false;
  44059. }
  44060. return true;
  44061. }
  44062. let _id$3 = 0;
  44063. /**
  44064. * A special form of uniforms group that represents
  44065. * the individual uniforms as node-based uniforms.
  44066. *
  44067. * @private
  44068. * @augments UniformsGroup
  44069. */
  44070. class NodeUniformsGroup extends UniformsGroup {
  44071. /**
  44072. * Constructs a new node-based uniforms group.
  44073. *
  44074. * @param {string} name - The group's name.
  44075. * @param {UniformGroupNode} groupNode - The uniform group node.
  44076. */
  44077. constructor( name, groupNode ) {
  44078. super( name );
  44079. /**
  44080. * The group's ID.
  44081. *
  44082. * @type {number}
  44083. */
  44084. this.id = _id$3 ++;
  44085. /**
  44086. * The uniform group node.
  44087. *
  44088. * @type {UniformGroupNode}
  44089. */
  44090. this.groupNode = groupNode;
  44091. /**
  44092. * This flag can be used for type testing.
  44093. *
  44094. * @type {boolean}
  44095. * @readonly
  44096. * @default true
  44097. */
  44098. this.isNodeUniformsGroup = true;
  44099. }
  44100. }
  44101. /**
  44102. * Represents a sampler binding type.
  44103. *
  44104. * @private
  44105. * @augments Binding
  44106. */
  44107. class Sampler extends Binding {
  44108. /**
  44109. * Constructs a new sampler.
  44110. *
  44111. * @param {string} name - The samplers's name.
  44112. * @param {?Texture} texture - The texture this binding is referring to.
  44113. */
  44114. constructor( name, texture ) {
  44115. super( name );
  44116. /**
  44117. * The texture the sampler is referring to.
  44118. *
  44119. * @private
  44120. * @type {?Texture}
  44121. */
  44122. this._texture = null;
  44123. /**
  44124. * An event listener which is added to {@link texture}'s dispose event.
  44125. *
  44126. * @private
  44127. * @type {Function}
  44128. */
  44129. this._onTextureDispose = () => {
  44130. this.generation = null;
  44131. this.version = 0;
  44132. };
  44133. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  44134. this.texture = texture;
  44135. /**
  44136. * The binding's version.
  44137. *
  44138. * @type {number}
  44139. */
  44140. this.version = texture ? texture.version : 0;
  44141. /**
  44142. * The binding's generation which is an additional version
  44143. * qualifier.
  44144. *
  44145. * @type {?number}
  44146. * @default null
  44147. */
  44148. this.generation = null;
  44149. /**
  44150. * The binding's sampler key.
  44151. *
  44152. * @type {string}
  44153. * @default ''
  44154. */
  44155. this.samplerKey = '';
  44156. /**
  44157. * This flag can be used for type testing.
  44158. *
  44159. * @type {boolean}
  44160. * @readonly
  44161. * @default true
  44162. */
  44163. this.isSampler = true;
  44164. }
  44165. /**
  44166. * Sets the texture of this sampler.
  44167. *
  44168. * @param {Texture} value - The texture to set.
  44169. */
  44170. set texture( value ) {
  44171. if ( this._texture === value ) return;
  44172. if ( this._texture ) {
  44173. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  44174. }
  44175. this._texture = value;
  44176. this.generation = null;
  44177. this.version = 0;
  44178. if ( this._texture ) {
  44179. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  44180. }
  44181. }
  44182. /**
  44183. * Gets the texture of this sampler.
  44184. * @return {?Texture} The texture.
  44185. */
  44186. get texture() {
  44187. return this._texture;
  44188. }
  44189. /**
  44190. * Updates the binding.
  44191. *
  44192. * @return {boolean} Whether the texture has been updated and must be
  44193. * uploaded to the GPU.
  44194. */
  44195. update() {
  44196. const { texture, version } = this;
  44197. if ( version !== texture.version ) {
  44198. this.version = texture.version;
  44199. return true;
  44200. }
  44201. return false;
  44202. }
  44203. clone() {
  44204. const clonedSampler = super.clone();
  44205. // fix dispose handler for cloned instances
  44206. // TODO: Find better solution, see #31747
  44207. clonedSampler._texture = null;
  44208. clonedSampler._onTextureDispose = () => {
  44209. clonedSampler.generation = null;
  44210. clonedSampler.version = 0;
  44211. };
  44212. clonedSampler.texture = this.texture;
  44213. return clonedSampler;
  44214. }
  44215. }
  44216. let _id$2 = 0;
  44217. /**
  44218. * Represents a sampled texture binding type.
  44219. *
  44220. * @private
  44221. * @augments Sampler
  44222. */
  44223. class SampledTexture extends Sampler {
  44224. /**
  44225. * Constructs a new sampled texture.
  44226. *
  44227. * @param {string} name - The sampled texture's name.
  44228. * @param {?Texture} texture - The texture this binding is referring to.
  44229. */
  44230. constructor( name, texture ) {
  44231. super( name, texture );
  44232. /**
  44233. * This identifier.
  44234. *
  44235. * @type {number}
  44236. */
  44237. this.id = _id$2 ++;
  44238. /**
  44239. * Whether the texture is a storage texture or not.
  44240. *
  44241. * @type {boolean}
  44242. * @default false
  44243. */
  44244. this.store = false;
  44245. /**
  44246. * The mip level to bind for storage textures.
  44247. *
  44248. * @type {number}
  44249. * @default 0
  44250. */
  44251. this.mipLevel = 0;
  44252. /**
  44253. * This flag can be used for type testing.
  44254. *
  44255. * @type {boolean}
  44256. * @readonly
  44257. * @default true
  44258. */
  44259. this.isSampledTexture = true;
  44260. }
  44261. }
  44262. /**
  44263. * A special form of sampled texture binding type.
  44264. * It's texture value is managed by a node object.
  44265. *
  44266. * @private
  44267. * @augments SampledTexture
  44268. */
  44269. class NodeSampledTexture extends SampledTexture {
  44270. /**
  44271. * Constructs a new node-based sampled texture.
  44272. *
  44273. * @param {string} name - The textures's name.
  44274. * @param {TextureNode} textureNode - The texture node.
  44275. * @param {UniformGroupNode} groupNode - The uniform group node.
  44276. * @param {?string} [access=null] - The access type.
  44277. */
  44278. constructor( name, textureNode, groupNode, access = null ) {
  44279. super( name, textureNode ? textureNode.value : null );
  44280. /**
  44281. * The texture node.
  44282. *
  44283. * @type {TextureNode}
  44284. */
  44285. this.textureNode = textureNode;
  44286. /**
  44287. * The uniform group node.
  44288. *
  44289. * @type {UniformGroupNode}
  44290. */
  44291. this.groupNode = groupNode;
  44292. /**
  44293. * The access type.
  44294. *
  44295. * @type {?string}
  44296. * @default null
  44297. */
  44298. this.access = access;
  44299. }
  44300. /**
  44301. * Updates the binding.
  44302. *
  44303. * @return {boolean} Whether the texture has been updated and must be
  44304. * uploaded to the GPU.
  44305. */
  44306. update() {
  44307. const { textureNode } = this;
  44308. if ( this.texture !== textureNode.value ) {
  44309. this.texture = textureNode.value;
  44310. return true;
  44311. }
  44312. return super.update();
  44313. }
  44314. }
  44315. /**
  44316. * A special form of sampled cube texture binding type.
  44317. * It's texture value is managed by a node object.
  44318. *
  44319. * @private
  44320. * @augments NodeSampledTexture
  44321. */
  44322. class NodeSampledCubeTexture extends NodeSampledTexture {
  44323. /**
  44324. * Constructs a new node-based sampled cube texture.
  44325. *
  44326. * @param {string} name - The textures's name.
  44327. * @param {TextureNode} textureNode - The texture node.
  44328. * @param {UniformGroupNode} groupNode - The uniform group node.
  44329. * @param {?string} [access=null] - The access type.
  44330. */
  44331. constructor( name, textureNode, groupNode, access = null ) {
  44332. super( name, textureNode, groupNode, access );
  44333. /**
  44334. * This flag can be used for type testing.
  44335. *
  44336. * @type {boolean}
  44337. * @readonly
  44338. * @default true
  44339. */
  44340. this.isSampledCubeTexture = true;
  44341. }
  44342. }
  44343. /**
  44344. * A special form of sampled 3D texture binding type.
  44345. * It's texture value is managed by a node object.
  44346. *
  44347. * @private
  44348. * @augments NodeSampledTexture
  44349. */
  44350. class NodeSampledTexture3D extends NodeSampledTexture {
  44351. /**
  44352. * Constructs a new node-based sampled 3D texture.
  44353. *
  44354. * @param {string} name - The textures's name.
  44355. * @param {TextureNode} textureNode - The texture node.
  44356. * @param {UniformGroupNode} groupNode - The uniform group node.
  44357. * @param {?string} [access=null] - The access type.
  44358. */
  44359. constructor( name, textureNode, groupNode, access = null ) {
  44360. super( name, textureNode, groupNode, access );
  44361. /**
  44362. * This flag can be used for type testing.
  44363. *
  44364. * @type {boolean}
  44365. * @readonly
  44366. * @default true
  44367. */
  44368. this.isSampledTexture3D = true;
  44369. }
  44370. }
  44371. const glslPolyfills = {
  44372. bitcast_int_uint: new CodeNode( /* glsl */'uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }' ),
  44373. bitcast_uint_int: new CodeNode( /* glsl */'uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }' )
  44374. };
  44375. const glslMethods = {
  44376. textureDimensions: 'textureSize',
  44377. equals: 'equal',
  44378. bitcast_float_int: 'floatBitsToInt',
  44379. bitcast_int_float: 'intBitsToFloat',
  44380. bitcast_uint_float: 'uintBitsToFloat',
  44381. bitcast_float_uint: 'floatBitsToUint',
  44382. bitcast_uint_int: 'tsl_bitcast_uint_to_int',
  44383. bitcast_int_uint: 'tsl_bitcast_int_to_uint',
  44384. floatpack_snorm_2x16: 'packSnorm2x16',
  44385. floatpack_unorm_2x16: 'packUnorm2x16',
  44386. floatpack_float16_2x16: 'packHalf2x16',
  44387. floatunpack_snorm_2x16: 'unpackSnorm2x16',
  44388. floatunpack_unorm_2x16: 'unpackUnorm2x16',
  44389. floatunpack_float16_2x16: 'unpackHalf2x16'
  44390. };
  44391. const precisionLib = {
  44392. low: 'lowp',
  44393. medium: 'mediump',
  44394. high: 'highp'
  44395. };
  44396. const supports$1 = {
  44397. swizzleAssign: true,
  44398. storageBuffer: false
  44399. };
  44400. const interpolationTypeMap = {
  44401. perspective: 'smooth',
  44402. linear: 'noperspective'
  44403. };
  44404. const interpolationModeMap = {
  44405. 'centroid': 'centroid'
  44406. };
  44407. const defaultPrecisions = `
  44408. precision highp float;
  44409. precision highp int;
  44410. precision highp sampler2D;
  44411. precision highp sampler3D;
  44412. precision highp samplerCube;
  44413. precision highp sampler2DArray;
  44414. precision highp usampler2D;
  44415. precision highp usampler3D;
  44416. precision highp usamplerCube;
  44417. precision highp usampler2DArray;
  44418. precision highp isampler2D;
  44419. precision highp isampler3D;
  44420. precision highp isamplerCube;
  44421. precision highp isampler2DArray;
  44422. precision highp sampler2DShadow;
  44423. precision highp sampler2DArrayShadow;
  44424. precision highp samplerCubeShadow;
  44425. `;
  44426. /**
  44427. * A node builder targeting GLSL.
  44428. *
  44429. * This module generates GLSL shader code from node materials and also
  44430. * generates the respective bindings and vertex buffer definitions. These
  44431. * data are later used by the renderer to create render and compute pipelines
  44432. * for render objects.
  44433. *
  44434. * @augments NodeBuilder
  44435. */
  44436. class GLSLNodeBuilder extends NodeBuilder {
  44437. /**
  44438. * Constructs a new GLSL node builder renderer.
  44439. *
  44440. * @param {Object3D} object - The 3D object.
  44441. * @param {Renderer} renderer - The renderer.
  44442. */
  44443. constructor( object, renderer ) {
  44444. super( object, renderer, new GLSLNodeParser() );
  44445. /**
  44446. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  44447. * another dictionary which manages UBOs per group ('render','frame','object').
  44448. *
  44449. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  44450. */
  44451. this.uniformGroups = {};
  44452. /**
  44453. * An array that holds objects defining the varying and attribute data in
  44454. * context of Transform Feedback.
  44455. *
  44456. * @type {Array<Object<string,AttributeNode|string>>}
  44457. */
  44458. this.transforms = [];
  44459. /**
  44460. * A dictionary that holds for each shader stage a Map of used extensions.
  44461. *
  44462. * @type {Object<string,Map<string,Object>>}
  44463. */
  44464. this.extensions = {};
  44465. /**
  44466. * A dictionary that holds for each shader stage an Array of used builtins.
  44467. *
  44468. * @type {Object<string,Array<string>>}
  44469. */
  44470. this.builtins = { vertex: [], fragment: [], compute: [] };
  44471. }
  44472. /**
  44473. * Checks if the given texture requires a manual conversion to the working color space.
  44474. *
  44475. * @param {Texture} texture - The texture to check.
  44476. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  44477. */
  44478. needsToWorkingColorSpace( texture ) {
  44479. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44480. }
  44481. /**
  44482. * Includes the given method name into the current
  44483. * function node.
  44484. *
  44485. * @private
  44486. * @param {string} name - The method name to include.
  44487. * @return {CodeNode} The respective code node.
  44488. */
  44489. _include( name ) {
  44490. const codeNode = glslPolyfills[ name ];
  44491. codeNode.build( this );
  44492. this.addInclude( codeNode );
  44493. return codeNode;
  44494. }
  44495. /**
  44496. * Returns the native shader method name for a given generic name.
  44497. *
  44498. * @param {string} method - The method name to resolve.
  44499. * @return {string} The resolved GLSL method name.
  44500. */
  44501. getMethod( method ) {
  44502. if ( glslPolyfills[ method ] !== undefined ) {
  44503. this._include( method );
  44504. }
  44505. return glslMethods[ method ] || method;
  44506. }
  44507. /**
  44508. * Returns the bitcast method name for a given input and outputType.
  44509. *
  44510. * @param {string} type - The output type to bitcast to.
  44511. * @param {string} inputType - The input type of the.
  44512. * @return {string} The resolved WGSL bitcast invocation.
  44513. */
  44514. getBitcastMethod( type, inputType ) {
  44515. return this.getMethod( `bitcast_${ inputType }_${ type }` );
  44516. }
  44517. /**
  44518. * Returns the float packing method name for a given numeric encoding.
  44519. *
  44520. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  44521. * @returns {string} The resolved GLSL float packing method name.
  44522. */
  44523. getFloatPackingMethod( encoding ) {
  44524. return this.getMethod( `floatpack_${ encoding }_2x16` );
  44525. }
  44526. /**
  44527. * Returns the float unpacking method name for a given numeric encoding.
  44528. *
  44529. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  44530. * @returns {string} The resolved GLSL float unpacking method name.
  44531. */
  44532. getFloatUnpackingMethod( encoding ) {
  44533. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  44534. }
  44535. /**
  44536. * Returns the native snippet for a ternary operation.
  44537. *
  44538. * @param {string} condSnippet - The condition determining which expression gets resolved.
  44539. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  44540. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  44541. * @return {string} The resolved method name.
  44542. */
  44543. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  44544. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  44545. }
  44546. /**
  44547. * Returns the output struct name. Not relevant for GLSL.
  44548. *
  44549. * @return {string}
  44550. */
  44551. getOutputStructName() {
  44552. return '';
  44553. }
  44554. /**
  44555. * Builds the given shader node.
  44556. *
  44557. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44558. * @return {string} The GLSL function code.
  44559. */
  44560. buildFunctionCode( shaderNode ) {
  44561. const layout = shaderNode.layout;
  44562. const flowData = this.flowShaderNode( shaderNode );
  44563. const parameters = [];
  44564. for ( const input of layout.inputs ) {
  44565. parameters.push( this.getType( input.type ) + ' ' + input.name );
  44566. }
  44567. //
  44568. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  44569. ${ flowData.vars }
  44570. ${ flowData.code }
  44571. return ${ flowData.result };
  44572. }`;
  44573. //
  44574. return code;
  44575. }
  44576. /**
  44577. * Setups the Pixel Buffer Object (PBO) for the given storage
  44578. * buffer node.
  44579. *
  44580. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  44581. */
  44582. setupPBO( storageBufferNode ) {
  44583. const attribute = storageBufferNode.value;
  44584. if ( attribute.pbo === undefined ) {
  44585. const originalArray = attribute.array;
  44586. const numElements = attribute.count * attribute.itemSize;
  44587. const { itemSize } = attribute;
  44588. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  44589. let format = isInteger ? RedIntegerFormat : RedFormat;
  44590. if ( itemSize === 2 ) {
  44591. format = isInteger ? RGIntegerFormat : RGFormat;
  44592. } else if ( itemSize === 3 ) {
  44593. format = isInteger ? RGBIntegerFormat : RGBFormat;
  44594. } else if ( itemSize === 4 ) {
  44595. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  44596. }
  44597. const typeMap = {
  44598. Float32Array: FloatType,
  44599. Uint8Array: UnsignedByteType,
  44600. Uint16Array: UnsignedShortType,
  44601. Uint32Array: UnsignedIntType,
  44602. Int8Array: ByteType,
  44603. Int16Array: ShortType,
  44604. Int32Array: IntType,
  44605. Uint8ClampedArray: UnsignedByteType,
  44606. };
  44607. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  44608. let height = Math.ceil( ( numElements / itemSize ) / width );
  44609. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  44610. const newSize = width * height * itemSize;
  44611. const newArray = new originalArray.constructor( newSize );
  44612. newArray.set( originalArray, 0 );
  44613. attribute.array = newArray;
  44614. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  44615. pboTexture.needsUpdate = true;
  44616. pboTexture.isPBOTexture = true;
  44617. const pbo = new TextureNode( pboTexture, null, null );
  44618. pbo.setPrecision( 'high' );
  44619. attribute.pboNode = pbo;
  44620. attribute.pbo = pbo.value;
  44621. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44622. }
  44623. }
  44624. /**
  44625. * Returns a GLSL snippet that represents the property name of the given node.
  44626. *
  44627. * @param {Node} node - The node.
  44628. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44629. * @return {string} The property name.
  44630. */
  44631. getPropertyName( node, shaderStage = this.shaderStage ) {
  44632. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  44633. return node.name;
  44634. }
  44635. return super.getPropertyName( node, shaderStage );
  44636. }
  44637. /**
  44638. * Setups the Pixel Buffer Object (PBO) for the given storage
  44639. * buffer node.
  44640. *
  44641. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  44642. * @return {string} The property name.
  44643. */
  44644. generatePBO( storageArrayElementNode ) {
  44645. const { node, indexNode } = storageArrayElementNode;
  44646. const attribute = node.value;
  44647. if ( this.renderer.backend.has( attribute ) ) {
  44648. const attributeData = this.renderer.backend.get( attribute );
  44649. attributeData.pbo = attribute.pbo;
  44650. }
  44651. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  44652. const textureName = this.getPropertyName( nodeUniform );
  44653. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  44654. const indexSnippet = indexNode.build( this, 'uint' );
  44655. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  44656. let propertyName = elementNodeData.propertyName;
  44657. if ( propertyName === undefined ) {
  44658. // property element
  44659. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  44660. propertyName = this.getPropertyName( nodeVar );
  44661. // property size
  44662. const bufferNodeData = this.getDataFromNode( node );
  44663. let propertySizeName = bufferNodeData.propertySizeName;
  44664. if ( propertySizeName === undefined ) {
  44665. propertySizeName = propertyName + 'Size';
  44666. this.getVarFromNode( node, propertySizeName, 'uint' );
  44667. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  44668. bufferNodeData.propertySizeName = propertySizeName;
  44669. }
  44670. //
  44671. const { itemSize } = attribute;
  44672. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  44673. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  44674. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  44675. //
  44676. let prefix = 'vec4';
  44677. if ( attribute.pbo.type === UnsignedIntType ) {
  44678. prefix = 'uvec4';
  44679. } else if ( attribute.pbo.type === IntType ) {
  44680. prefix = 'ivec4';
  44681. }
  44682. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  44683. elementNodeData.propertyName = propertyName;
  44684. }
  44685. return propertyName;
  44686. }
  44687. /**
  44688. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  44689. *
  44690. * @param {?Texture} texture - The texture.
  44691. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44692. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44693. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44694. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44695. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44696. * @return {string} The GLSL snippet.
  44697. */
  44698. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  44699. if ( levelSnippet === null ) levelSnippet = '0';
  44700. let snippet;
  44701. if ( depthSnippet ) {
  44702. if ( offsetSnippet ) {
  44703. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  44704. } else {
  44705. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  44706. }
  44707. } else {
  44708. if ( offsetSnippet ) {
  44709. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44710. } else {
  44711. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  44712. }
  44713. }
  44714. if ( texture !== null && texture.isDepthTexture ) {
  44715. snippet += '.x';
  44716. }
  44717. return snippet;
  44718. }
  44719. /**
  44720. * Generates the GLSL snippet for sampling/loading the given texture.
  44721. *
  44722. * @param {Texture} texture - The texture.
  44723. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44724. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44725. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  44726. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44727. * @return {string} The GLSL snippet.
  44728. */
  44729. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  44730. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  44731. if ( texture.isDepthTexture ) {
  44732. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  44733. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  44734. }
  44735. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  44736. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  44737. }
  44738. /**
  44739. * Generates the GLSL snippet when sampling textures with explicit mip level.
  44740. *
  44741. * @param {Texture} texture - The texture.
  44742. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44743. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44744. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44745. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44746. * @return {string} The GLSL snippet.
  44747. */
  44748. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  44749. if ( offsetSnippet ) {
  44750. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  44751. }
  44752. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  44753. }
  44754. /**
  44755. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  44756. *
  44757. * @param {Texture} texture - The texture.
  44758. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44759. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44760. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  44761. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44762. * @return {string} The GLSL snippet.
  44763. */
  44764. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  44765. if ( offsetSnippet ) {
  44766. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  44767. }
  44768. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  44769. }
  44770. /**
  44771. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  44772. *
  44773. * @param {Texture} texture - The texture.
  44774. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44775. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44776. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  44777. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44778. * @return {string} The GLSL snippet.
  44779. */
  44780. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  44781. if ( offsetSnippet ) {
  44782. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  44783. }
  44784. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44785. }
  44786. /**
  44787. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  44788. * against a reference value.
  44789. *
  44790. * @param {Texture} texture - The texture.
  44791. * @param {string} textureProperty - The name of the texture uniform in the shader.
  44792. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  44793. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  44794. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  44795. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  44796. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44797. * @return {string} The GLSL snippet.
  44798. */
  44799. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  44800. if ( shaderStage === 'fragment' ) {
  44801. // Cube shadow maps use vec4(direction, compareValue)
  44802. if ( texture.isCubeTexture ) {
  44803. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44804. }
  44805. if ( depthSnippet ) {
  44806. if ( offsetSnippet ) {
  44807. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44808. }
  44809. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  44810. }
  44811. if ( offsetSnippet ) {
  44812. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  44813. }
  44814. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  44815. } else {
  44816. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44817. }
  44818. }
  44819. /**
  44820. * Returns the variables of the given shader stage as a GLSL string.
  44821. *
  44822. * @param {string} shaderStage - The shader stage.
  44823. * @return {string} The GLSL snippet that defines the variables.
  44824. */
  44825. getVars( shaderStage ) {
  44826. const snippets = [];
  44827. const vars = this.vars[ shaderStage ];
  44828. if ( vars !== undefined ) {
  44829. for ( const variable of vars ) {
  44830. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  44831. }
  44832. }
  44833. return snippets.join( '\n\t' );
  44834. }
  44835. /**
  44836. * Returns the uniforms of the given shader stage as a GLSL string.
  44837. *
  44838. * @param {string} shaderStage - The shader stage.
  44839. * @return {string} The GLSL snippet that defines the uniforms.
  44840. */
  44841. getUniforms( shaderStage ) {
  44842. const uniforms = this.uniforms[ shaderStage ];
  44843. const bindingSnippets = [];
  44844. const uniformGroups = {};
  44845. for ( const uniform of uniforms ) {
  44846. let snippet = null;
  44847. let group = false;
  44848. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  44849. const texture = uniform.node.value;
  44850. let typePrefix = '';
  44851. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  44852. if ( texture.type === UnsignedIntType ) {
  44853. typePrefix = 'u';
  44854. } else if ( texture.type === IntType ) {
  44855. typePrefix = 'i';
  44856. }
  44857. }
  44858. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  44859. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  44860. } else if ( texture.compareFunction ) {
  44861. if ( texture.isArrayTexture === true ) {
  44862. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  44863. } else {
  44864. snippet = `sampler2DShadow ${ uniform.name };`;
  44865. }
  44866. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44867. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  44868. } else {
  44869. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  44870. }
  44871. } else if ( uniform.type === 'cubeTexture' ) {
  44872. snippet = `samplerCube ${ uniform.name };`;
  44873. } else if ( uniform.type === 'cubeDepthTexture' ) {
  44874. snippet = `samplerCubeShadow ${ uniform.name };`;
  44875. } else if ( uniform.type === 'buffer' ) {
  44876. const bufferNode = uniform.node;
  44877. const bufferType = this.getType( bufferNode.bufferType );
  44878. const bufferCount = bufferNode.bufferCount;
  44879. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  44880. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  44881. } else {
  44882. const groupName = uniform.groupNode.name;
  44883. // Check if this group has already been processed
  44884. if ( uniformGroups[ groupName ] === undefined ) {
  44885. // Get the shared uniform group that contains uniforms from all stages
  44886. const sharedUniformGroup = this.uniformGroups[ groupName ];
  44887. if ( sharedUniformGroup !== undefined ) {
  44888. // Generate snippets for ALL uniforms in this shared group
  44889. const snippets = [];
  44890. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  44891. const type = sharedUniform.getType();
  44892. const vectorType = this.getVectorType( type );
  44893. const precision = sharedUniform.nodeUniform.node.precision;
  44894. let uniformSnippet = `${ vectorType } ${ sharedUniform.name };`;
  44895. if ( precision !== null ) {
  44896. uniformSnippet = precisionLib[ precision ] + ' ' + uniformSnippet;
  44897. }
  44898. snippets.push( '\t' + uniformSnippet );
  44899. }
  44900. uniformGroups[ groupName ] = snippets;
  44901. }
  44902. }
  44903. group = true;
  44904. }
  44905. if ( ! group ) {
  44906. const precision = uniform.node.precision;
  44907. if ( precision !== null ) {
  44908. snippet = precisionLib[ precision ] + ' ' + snippet;
  44909. }
  44910. snippet = 'uniform ' + snippet;
  44911. bindingSnippets.push( snippet );
  44912. }
  44913. }
  44914. let output = '';
  44915. for ( const name in uniformGroups ) {
  44916. const groupSnippets = uniformGroups[ name ];
  44917. output += this._getGLSLUniformStruct( name, groupSnippets.join( '\n' ) ) + '\n';
  44918. }
  44919. output += bindingSnippets.join( '\n' );
  44920. return output;
  44921. }
  44922. /**
  44923. * Returns the type for a given buffer attribute.
  44924. *
  44925. * @param {BufferAttribute} attribute - The buffer attribute.
  44926. * @return {string} The type.
  44927. */
  44928. getTypeFromAttribute( attribute ) {
  44929. let nodeType = super.getTypeFromAttribute( attribute );
  44930. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  44931. let dataAttribute = attribute;
  44932. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  44933. const array = dataAttribute.array;
  44934. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  44935. nodeType = nodeType.slice( 1 );
  44936. }
  44937. }
  44938. return nodeType;
  44939. }
  44940. /**
  44941. * Returns the shader attributes of the given shader stage as a GLSL string.
  44942. *
  44943. * @param {string} shaderStage - The shader stage.
  44944. * @return {string} The GLSL snippet that defines the shader attributes.
  44945. */
  44946. getAttributes( shaderStage ) {
  44947. let snippet = '';
  44948. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44949. const attributes = this.getAttributesArray();
  44950. let location = 0;
  44951. for ( const attribute of attributes ) {
  44952. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  44953. }
  44954. }
  44955. return snippet;
  44956. }
  44957. /**
  44958. * Returns the members of the given struct type node as a GLSL string.
  44959. *
  44960. * @param {StructTypeNode} struct - The struct type node.
  44961. * @return {string} The GLSL snippet that defines the struct members.
  44962. */
  44963. getStructMembers( struct ) {
  44964. const snippets = [];
  44965. for ( const member of struct.members ) {
  44966. snippets.push( `\t${ member.type } ${ member.name };` );
  44967. }
  44968. return snippets.join( '\n' );
  44969. }
  44970. /**
  44971. * Returns the structs of the given shader stage as a GLSL string.
  44972. *
  44973. * @param {string} shaderStage - The shader stage.
  44974. * @return {string} The GLSL snippet that defines the structs.
  44975. */
  44976. getStructs( shaderStage ) {
  44977. const snippets = [];
  44978. const structs = this.structs[ shaderStage ];
  44979. const outputSnippet = [];
  44980. for ( const struct of structs ) {
  44981. if ( struct.output ) {
  44982. for ( const member of struct.members ) {
  44983. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  44984. }
  44985. } else {
  44986. let snippet = 'struct ' + struct.name + ' {\n';
  44987. snippet += this.getStructMembers( struct );
  44988. snippet += '\n};\n';
  44989. snippets.push( snippet );
  44990. }
  44991. }
  44992. if ( outputSnippet.length === 0 ) {
  44993. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  44994. }
  44995. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  44996. }
  44997. /**
  44998. * Returns the varyings of the given shader stage as a GLSL string.
  44999. *
  45000. * @param {string} shaderStage - The shader stage.
  45001. * @return {string} The GLSL snippet that defines the varyings.
  45002. */
  45003. getVaryings( shaderStage ) {
  45004. let snippet = '';
  45005. const varyings = this.varyings;
  45006. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45007. for ( const varying of varyings ) {
  45008. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  45009. const type = this.getType( varying.type );
  45010. if ( varying.needsInterpolation ) {
  45011. if ( varying.interpolationType ) {
  45012. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45013. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45014. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  45015. } else {
  45016. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  45017. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  45018. }
  45019. } else {
  45020. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  45021. }
  45022. }
  45023. } else if ( shaderStage === 'fragment' ) {
  45024. for ( const varying of varyings ) {
  45025. if ( varying.needsInterpolation ) {
  45026. const type = this.getType( varying.type );
  45027. if ( varying.interpolationType ) {
  45028. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  45029. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  45030. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  45031. } else {
  45032. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  45033. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  45034. }
  45035. }
  45036. }
  45037. }
  45038. for ( const builtin of this.builtins[ shaderStage ] ) {
  45039. snippet += `${builtin};\n`;
  45040. }
  45041. return snippet;
  45042. }
  45043. /**
  45044. * Returns the vertex index builtin.
  45045. *
  45046. * @return {string} The vertex index.
  45047. */
  45048. getVertexIndex() {
  45049. return 'uint( gl_VertexID )';
  45050. }
  45051. /**
  45052. * Contextually returns either the vertex stage instance index builtin
  45053. * or the linearized index of an compute invocation within a grid of workgroups.
  45054. *
  45055. * @return {string} The instance index.
  45056. */
  45057. getInstanceIndex() {
  45058. return 'uint( gl_InstanceID )';
  45059. }
  45060. /**
  45061. * Returns a builtin representing the index of an invocation within its workgroup.
  45062. *
  45063. * @return {string} The invocation local index.
  45064. */
  45065. getInvocationLocalIndex() {
  45066. const workgroupSize = this.object.workgroupSize;
  45067. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  45068. return `uint( gl_InstanceID ) % ${size}u`;
  45069. }
  45070. /**
  45071. * Returns a builtin representing the size of a subgroup within the current shader.
  45072. */
  45073. getSubgroupSize() {
  45074. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  45075. }
  45076. /**
  45077. * Returns a builtin representing the index of an invocation within its subgroup.
  45078. */
  45079. getInvocationSubgroupIndex() {
  45080. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  45081. }
  45082. /**
  45083. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  45084. */
  45085. getSubgroupIndex() {
  45086. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  45087. }
  45088. /**
  45089. * Returns the draw index builtin.
  45090. *
  45091. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  45092. */
  45093. getDrawIndex() {
  45094. const extensions = this.renderer.backend.extensions;
  45095. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  45096. return 'uint( gl_DrawID )';
  45097. }
  45098. return null;
  45099. }
  45100. /**
  45101. * Returns the front facing builtin.
  45102. *
  45103. * @return {string} The front facing builtin.
  45104. */
  45105. getFrontFacing() {
  45106. return 'gl_FrontFacing';
  45107. }
  45108. /**
  45109. * Returns the frag coord builtin.
  45110. *
  45111. * @return {string} The frag coord builtin.
  45112. */
  45113. getFragCoord() {
  45114. return 'gl_FragCoord.xy';
  45115. }
  45116. /**
  45117. * Returns the frag depth builtin.
  45118. *
  45119. * @return {string} The frag depth builtin.
  45120. */
  45121. getFragDepth() {
  45122. return 'gl_FragDepth';
  45123. }
  45124. /**
  45125. * Enables the given extension.
  45126. *
  45127. * @param {string} name - The extension name.
  45128. * @param {string} behavior - The extension behavior.
  45129. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  45130. */
  45131. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  45132. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  45133. if ( map.has( name ) === false ) {
  45134. map.set( name, {
  45135. name,
  45136. behavior
  45137. } );
  45138. }
  45139. }
  45140. /**
  45141. * Returns the enabled extensions of the given shader stage as a GLSL string.
  45142. *
  45143. * @param {string} shaderStage - The shader stage.
  45144. * @return {string} The GLSL snippet that defines the enabled extensions.
  45145. */
  45146. getExtensions( shaderStage ) {
  45147. const snippets = [];
  45148. if ( shaderStage === 'vertex' ) {
  45149. const ext = this.renderer.backend.extensions;
  45150. const isBatchedMesh = this.object.isBatchedMesh;
  45151. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  45152. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  45153. }
  45154. }
  45155. const extensions = this.extensions[ shaderStage ];
  45156. if ( extensions !== undefined ) {
  45157. for ( const { name, behavior } of extensions.values() ) {
  45158. snippets.push( `#extension ${name} : ${behavior}` );
  45159. }
  45160. }
  45161. return snippets.join( '\n' );
  45162. }
  45163. /**
  45164. * Returns the clip distances builtin.
  45165. *
  45166. * @return {string} The clip distances builtin.
  45167. */
  45168. getClipDistance() {
  45169. return 'gl_ClipDistance';
  45170. }
  45171. /**
  45172. * Whether the requested feature is available or not.
  45173. *
  45174. * @param {string} name - The requested feature.
  45175. * @return {boolean} Whether the requested feature is supported or not.
  45176. */
  45177. isAvailable( name ) {
  45178. let result = supports$1[ name ];
  45179. if ( result === undefined ) {
  45180. let extensionName;
  45181. result = false;
  45182. switch ( name ) {
  45183. case 'float32Filterable':
  45184. extensionName = 'OES_texture_float_linear';
  45185. break;
  45186. case 'clipDistance':
  45187. extensionName = 'WEBGL_clip_cull_distance';
  45188. break;
  45189. }
  45190. if ( extensionName !== undefined ) {
  45191. const extensions = this.renderer.backend.extensions;
  45192. if ( extensions.has( extensionName ) ) {
  45193. extensions.get( extensionName );
  45194. result = true;
  45195. }
  45196. }
  45197. supports$1[ name ] = result;
  45198. }
  45199. return result;
  45200. }
  45201. /**
  45202. * Whether to flip texture data along its vertical axis or not.
  45203. *
  45204. * @return {boolean} Returns always `true` in context of GLSL.
  45205. */
  45206. isFlipY() {
  45207. return true;
  45208. }
  45209. /**
  45210. * Enables hardware clipping.
  45211. *
  45212. * @param {string} planeCount - The clipping plane count.
  45213. */
  45214. enableHardwareClipping( planeCount ) {
  45215. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  45216. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  45217. }
  45218. /**
  45219. * Enables multiview.
  45220. */
  45221. enableMultiview() {
  45222. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  45223. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  45224. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  45225. }
  45226. /**
  45227. * Registers a transform in context of Transform Feedback.
  45228. *
  45229. * @param {string} varyingName - The varying name.
  45230. * @param {AttributeNode} attributeNode - The attribute node.
  45231. */
  45232. registerTransform( varyingName, attributeNode ) {
  45233. this.transforms.push( { varyingName, attributeNode } );
  45234. }
  45235. /**
  45236. * Returns the transforms of the given shader stage as a GLSL string.
  45237. *
  45238. * @param {string} shaderStage - The shader stage.
  45239. * @return {string} The GLSL snippet that defines the transforms.
  45240. */
  45241. getTransforms( /* shaderStage */ ) {
  45242. const transforms = this.transforms;
  45243. let snippet = '';
  45244. for ( let i = 0; i < transforms.length; i ++ ) {
  45245. const transform = transforms[ i ];
  45246. const attributeName = this.getPropertyName( transform.attributeNode );
  45247. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  45248. }
  45249. return snippet;
  45250. }
  45251. /**
  45252. * Returns a GLSL struct based on the given name and variables.
  45253. *
  45254. * @private
  45255. * @param {string} name - The struct name.
  45256. * @param {string} vars - The struct variables.
  45257. * @return {string} The GLSL snippet representing a struct.
  45258. */
  45259. _getGLSLUniformStruct( name, vars ) {
  45260. return `
  45261. layout( std140 ) uniform ${name} {
  45262. ${vars}
  45263. };`;
  45264. }
  45265. /**
  45266. * Returns a GLSL vertex shader based on the given shader data.
  45267. *
  45268. * @private
  45269. * @param {Object} shaderData - The shader data.
  45270. * @return {string} The vertex shader.
  45271. */
  45272. _getGLSLVertexCode( shaderData ) {
  45273. return `#version 300 es
  45274. ${ this.getSignature() }
  45275. // extensions
  45276. ${shaderData.extensions}
  45277. // precision
  45278. ${ defaultPrecisions }
  45279. // uniforms
  45280. ${shaderData.uniforms}
  45281. // varyings
  45282. ${shaderData.varyings}
  45283. // attributes
  45284. ${shaderData.attributes}
  45285. // codes
  45286. ${shaderData.codes}
  45287. void main() {
  45288. // vars
  45289. ${shaderData.vars}
  45290. // transforms
  45291. ${shaderData.transforms}
  45292. // flow
  45293. ${shaderData.flow}
  45294. gl_PointSize = 1.0;
  45295. }
  45296. `;
  45297. }
  45298. /**
  45299. * Returns a GLSL fragment shader based on the given shader data.
  45300. *
  45301. * @private
  45302. * @param {Object} shaderData - The shader data.
  45303. * @return {string} The vertex shader.
  45304. */
  45305. _getGLSLFragmentCode( shaderData ) {
  45306. return `#version 300 es
  45307. ${ this.getSignature() }
  45308. // extensions
  45309. ${shaderData.extensions}
  45310. // precision
  45311. ${ defaultPrecisions }
  45312. // structs
  45313. ${shaderData.structs}
  45314. // uniforms
  45315. ${shaderData.uniforms}
  45316. // varyings
  45317. ${shaderData.varyings}
  45318. // codes
  45319. ${shaderData.codes}
  45320. void main() {
  45321. // vars
  45322. ${shaderData.vars}
  45323. // flow
  45324. ${shaderData.flow}
  45325. }
  45326. `;
  45327. }
  45328. /**
  45329. * Controls the code build of the shader stages.
  45330. */
  45331. buildCode() {
  45332. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45333. this.sortBindingGroups();
  45334. for ( const shaderStage in shadersData ) {
  45335. let flow = '// code\n\n';
  45336. flow += this.flowCode[ shaderStage ];
  45337. const flowNodes = this.flowNodes[ shaderStage ];
  45338. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45339. for ( const node of flowNodes ) {
  45340. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45341. const slotName = node.name;
  45342. if ( slotName ) {
  45343. if ( flow.length > 0 ) flow += '\n';
  45344. flow += `\t// flow -> ${ slotName }\n\t`;
  45345. }
  45346. flow += `${ flowSlotData.code }\n\t`;
  45347. if ( node === mainNode && shaderStage !== 'compute' ) {
  45348. flow += '// result\n\t';
  45349. if ( shaderStage === 'vertex' ) {
  45350. flow += 'gl_Position = ';
  45351. flow += `${ flowSlotData.result };`;
  45352. } else if ( shaderStage === 'fragment' ) {
  45353. if ( ! node.outputNode.isOutputStructNode ) {
  45354. flow += 'fragColor = ';
  45355. flow += `${ flowSlotData.result };`;
  45356. }
  45357. }
  45358. }
  45359. }
  45360. const stageData = shadersData[ shaderStage ];
  45361. stageData.extensions = this.getExtensions( shaderStage );
  45362. stageData.uniforms = this.getUniforms( shaderStage );
  45363. stageData.attributes = this.getAttributes( shaderStage );
  45364. stageData.varyings = this.getVaryings( shaderStage );
  45365. stageData.vars = this.getVars( shaderStage );
  45366. stageData.structs = this.getStructs( shaderStage );
  45367. stageData.codes = this.getCodes( shaderStage );
  45368. stageData.transforms = this.getTransforms( shaderStage );
  45369. stageData.flow = flow;
  45370. }
  45371. if ( this.material !== null ) {
  45372. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  45373. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  45374. } else {
  45375. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  45376. }
  45377. }
  45378. /**
  45379. * This method is one of the more important ones since it's responsible
  45380. * for generating a matching binding instance for the given uniform node.
  45381. *
  45382. * These bindings are later used in the renderer to create bind groups
  45383. * and layouts.
  45384. *
  45385. * @param {UniformNode} node - The uniform node.
  45386. * @param {string} type - The node data type.
  45387. * @param {string} shaderStage - The shader stage.
  45388. * @param {?string} [name=null] - An optional uniform name.
  45389. * @return {NodeUniform} The node uniform object.
  45390. */
  45391. getUniformFromNode( node, type, shaderStage, name = null ) {
  45392. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45393. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45394. let uniformGPU = nodeData.uniformGPU;
  45395. if ( uniformGPU === undefined ) {
  45396. const group = node.groupNode;
  45397. const groupName = group.name;
  45398. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45399. if ( type === 'texture' ) {
  45400. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  45401. bindings.push( uniformGPU );
  45402. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  45403. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  45404. bindings.push( uniformGPU );
  45405. } else if ( type === 'texture3D' ) {
  45406. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  45407. bindings.push( uniformGPU );
  45408. } else if ( type === 'buffer' ) {
  45409. uniformNode.name = `buffer${ node.id }`;
  45410. const sharedData = this.getSharedDataFromNode( node );
  45411. let buffer = sharedData.buffer;
  45412. if ( buffer === undefined ) {
  45413. node.name = `NodeBuffer_${ node.id }`;
  45414. buffer = new NodeUniformBuffer( node, group );
  45415. buffer.name = node.name;
  45416. sharedData.buffer = buffer;
  45417. }
  45418. bindings.push( buffer );
  45419. uniformGPU = buffer;
  45420. } else {
  45421. let uniformsGroup = this.uniformGroups[ groupName ];
  45422. if ( uniformsGroup === undefined ) {
  45423. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45424. this.uniformGroups[ groupName ] = uniformsGroup;
  45425. bindings.push( uniformsGroup );
  45426. } else {
  45427. // Add to bindings for this stage if not already present
  45428. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  45429. bindings.push( uniformsGroup );
  45430. }
  45431. }
  45432. uniformGPU = this.getNodeUniform( uniformNode, type );
  45433. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  45434. const uniformName = uniformGPU.name;
  45435. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  45436. if ( ! alreadyExists ) {
  45437. uniformsGroup.addUniform( uniformGPU );
  45438. }
  45439. }
  45440. nodeData.uniformGPU = uniformGPU;
  45441. }
  45442. return uniformNode;
  45443. }
  45444. }
  45445. let _vector2 = null;
  45446. let _color4 = null;
  45447. /**
  45448. * Most of the rendering related logic is implemented in the
  45449. * {@link Renderer} module and related management components.
  45450. * Sometimes it is required though to execute commands which are
  45451. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  45452. * This abstract base class defines an interface that encapsulates
  45453. * all backend-related logic. Derived classes for each backend must
  45454. * implement the interface.
  45455. *
  45456. * @abstract
  45457. * @private
  45458. */
  45459. class Backend {
  45460. /**
  45461. * Constructs a new backend.
  45462. *
  45463. * @param {Object} parameters - An object holding parameters for the backend.
  45464. */
  45465. constructor( parameters = {} ) {
  45466. /**
  45467. * The parameters of the backend.
  45468. *
  45469. * @type {Object}
  45470. */
  45471. this.parameters = Object.assign( {}, parameters );
  45472. /**
  45473. * This weak map holds backend-specific data of objects
  45474. * like textures, attributes or render targets.
  45475. *
  45476. * @type {WeakMap<Object, Object>}
  45477. */
  45478. this.data = new WeakMap();
  45479. /**
  45480. * A reference to the renderer.
  45481. *
  45482. * @type {?Renderer}
  45483. * @default null
  45484. */
  45485. this.renderer = null;
  45486. /**
  45487. * A reference to the canvas element the renderer is drawing to.
  45488. *
  45489. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  45490. * @default null
  45491. */
  45492. this.domElement = null;
  45493. /**
  45494. * A reference to the timestamp query pool.
  45495. *
  45496. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  45497. */
  45498. this.timestampQueryPool = {
  45499. [ TimestampQuery.RENDER ]: null,
  45500. [ TimestampQuery.COMPUTE ]: null
  45501. };
  45502. /**
  45503. * Whether to track timestamps with a Timestamp Query API or not.
  45504. *
  45505. * @type {boolean}
  45506. * @default false
  45507. */
  45508. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45509. }
  45510. /**
  45511. * Initializes the backend so it is ready for usage. Concrete backends
  45512. * are supposed to implement their rendering context creation and related
  45513. * operations in this method.
  45514. *
  45515. * @async
  45516. * @param {Renderer} renderer - The renderer.
  45517. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45518. */
  45519. async init( renderer ) {
  45520. this.renderer = renderer;
  45521. }
  45522. /**
  45523. * The coordinate system of the backend.
  45524. *
  45525. * @abstract
  45526. * @type {number}
  45527. * @readonly
  45528. */
  45529. get coordinateSystem() {}
  45530. // render context
  45531. /**
  45532. * This method is executed at the beginning of a render call and
  45533. * can be used by the backend to prepare the state for upcoming
  45534. * draw calls.
  45535. *
  45536. * @abstract
  45537. * @param {RenderContext} renderContext - The render context.
  45538. */
  45539. beginRender( /*renderContext*/ ) {}
  45540. /**
  45541. * This method is executed at the end of a render call and
  45542. * can be used by the backend to finalize work after draw
  45543. * calls.
  45544. *
  45545. * @abstract
  45546. * @param {RenderContext} renderContext - The render context.
  45547. */
  45548. finishRender( /*renderContext*/ ) {}
  45549. /**
  45550. * This method is executed at the beginning of a compute call and
  45551. * can be used by the backend to prepare the state for upcoming
  45552. * compute tasks.
  45553. *
  45554. * @abstract
  45555. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45556. */
  45557. beginCompute( /*computeGroup*/ ) {}
  45558. /**
  45559. * This method is executed at the end of a compute call and
  45560. * can be used by the backend to finalize work after compute
  45561. * tasks.
  45562. *
  45563. * @abstract
  45564. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45565. */
  45566. finishCompute( /*computeGroup*/ ) {}
  45567. // render object
  45568. /**
  45569. * Executes a draw command for the given render object.
  45570. *
  45571. * @abstract
  45572. * @param {RenderObject} renderObject - The render object to draw.
  45573. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45574. */
  45575. draw( /*renderObject, info*/ ) { }
  45576. // compute node
  45577. /**
  45578. * Executes a compute command for the given compute node.
  45579. *
  45580. * @abstract
  45581. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45582. * @param {Node} computeNode - The compute node.
  45583. * @param {Array<BindGroup>} bindings - The bindings.
  45584. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45585. */
  45586. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  45587. // program
  45588. /**
  45589. * Creates a shader program from the given programmable stage.
  45590. *
  45591. * @abstract
  45592. * @param {ProgrammableStage} program - The programmable stage.
  45593. */
  45594. createProgram( /*program*/ ) { }
  45595. /**
  45596. * Destroys the shader program of the given programmable stage.
  45597. *
  45598. * @abstract
  45599. * @param {ProgrammableStage} program - The programmable stage.
  45600. */
  45601. destroyProgram( /*program*/ ) { }
  45602. // bindings
  45603. /**
  45604. * Creates bindings from the given bind group definition.
  45605. *
  45606. * @abstract
  45607. * @param {BindGroup} bindGroup - The bind group.
  45608. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45609. * @param {number} cacheIndex - The cache index.
  45610. * @param {number} version - The version.
  45611. */
  45612. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45613. /**
  45614. * Updates the given bind group definition.
  45615. *
  45616. * @abstract
  45617. * @param {BindGroup} bindGroup - The bind group.
  45618. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45619. * @param {number} cacheIndex - The cache index.
  45620. * @param {number} version - The version.
  45621. */
  45622. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  45623. /**
  45624. * Updates a buffer binding.
  45625. *
  45626. * @abstract
  45627. * @param {Buffer} binding - The buffer binding to update.
  45628. */
  45629. updateBinding( /*binding*/ ) { }
  45630. // pipeline
  45631. /**
  45632. * Creates a render pipeline for the given render object.
  45633. *
  45634. * @abstract
  45635. * @param {RenderObject} renderObject - The render object.
  45636. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45637. */
  45638. createRenderPipeline( /*renderObject, promises*/ ) { }
  45639. /**
  45640. * Creates a compute pipeline for the given compute node.
  45641. *
  45642. * @abstract
  45643. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45644. * @param {Array<BindGroup>} bindings - The bindings.
  45645. */
  45646. createComputePipeline( /*computePipeline, bindings*/ ) { }
  45647. // cache key
  45648. /**
  45649. * Returns `true` if the render pipeline requires an update.
  45650. *
  45651. * @abstract
  45652. * @param {RenderObject} renderObject - The render object.
  45653. * @return {boolean} Whether the render pipeline requires an update or not.
  45654. */
  45655. needsRenderUpdate( /*renderObject*/ ) { }
  45656. /**
  45657. * Returns a cache key that is used to identify render pipelines.
  45658. *
  45659. * @abstract
  45660. * @param {RenderObject} renderObject - The render object.
  45661. * @return {string} The cache key.
  45662. */
  45663. getRenderCacheKey( /*renderObject*/ ) { }
  45664. // node builder
  45665. /**
  45666. * Returns a node builder for the given render object.
  45667. *
  45668. * @abstract
  45669. * @param {RenderObject} renderObject - The render object.
  45670. * @param {Renderer} renderer - The renderer.
  45671. * @return {NodeBuilder} The node builder.
  45672. */
  45673. createNodeBuilder( /*renderObject, renderer*/ ) { }
  45674. // textures
  45675. /**
  45676. * Updates a GPU sampler for the given texture.
  45677. *
  45678. * @abstract
  45679. * @param {Texture} texture - The texture to update the sampler for.
  45680. * @return {string} The current sampler key.
  45681. */
  45682. updateSampler( /*texture*/ ) { }
  45683. /**
  45684. * Creates a default texture for the given texture that can be used
  45685. * as a placeholder until the actual texture is ready for usage.
  45686. *
  45687. * @abstract
  45688. * @param {Texture} texture - The texture to create a default texture for.
  45689. */
  45690. createDefaultTexture( /*texture*/ ) { }
  45691. /**
  45692. * Defines a texture on the GPU for the given texture object.
  45693. *
  45694. * @abstract
  45695. * @param {Texture} texture - The texture.
  45696. * @param {Object} [options={}] - Optional configuration parameter.
  45697. */
  45698. createTexture( /*texture, options={}*/ ) { }
  45699. /**
  45700. * Uploads the updated texture data to the GPU.
  45701. *
  45702. * @abstract
  45703. * @param {Texture} texture - The texture.
  45704. * @param {Object} [options={}] - Optional configuration parameter.
  45705. */
  45706. updateTexture( /*texture, options = {}*/ ) { }
  45707. /**
  45708. * Generates mipmaps for the given texture.
  45709. *
  45710. * @abstract
  45711. * @param {Texture} texture - The texture.
  45712. */
  45713. generateMipmaps( /*texture*/ ) { }
  45714. /**
  45715. * Destroys the GPU data for the given texture object.
  45716. *
  45717. * @abstract
  45718. * @param {Texture} texture - The texture.
  45719. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45720. */
  45721. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  45722. /**
  45723. * Returns texture data as a typed array.
  45724. *
  45725. * @abstract
  45726. * @async
  45727. * @param {Texture} texture - The texture to copy.
  45728. * @param {number} x - The x coordinate of the copy origin.
  45729. * @param {number} y - The y coordinate of the copy origin.
  45730. * @param {number} width - The width of the copy.
  45731. * @param {number} height - The height of the copy.
  45732. * @param {number} faceIndex - The face index.
  45733. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45734. */
  45735. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  45736. /**
  45737. * Copies data of the given source texture to the given destination texture.
  45738. *
  45739. * @abstract
  45740. * @param {Texture} srcTexture - The source texture.
  45741. * @param {Texture} dstTexture - The destination texture.
  45742. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45743. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45744. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45745. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45746. */
  45747. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  45748. /**
  45749. * Copies the current bound framebuffer to the given texture.
  45750. *
  45751. * @abstract
  45752. * @param {Texture} texture - The destination texture.
  45753. * @param {RenderContext} renderContext - The render context.
  45754. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45755. */
  45756. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  45757. // attributes
  45758. /**
  45759. * Creates the GPU buffer of a shader attribute.
  45760. *
  45761. * @abstract
  45762. * @param {BufferAttribute} attribute - The buffer attribute.
  45763. */
  45764. createAttribute( /*attribute*/ ) { }
  45765. /**
  45766. * Creates the GPU buffer of an indexed shader attribute.
  45767. *
  45768. * @abstract
  45769. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45770. */
  45771. createIndexAttribute( /*attribute*/ ) { }
  45772. /**
  45773. * Creates the GPU buffer of a storage attribute.
  45774. *
  45775. * @abstract
  45776. * @param {BufferAttribute} attribute - The buffer attribute.
  45777. */
  45778. createStorageAttribute( /*attribute*/ ) { }
  45779. /**
  45780. * Updates the GPU buffer of a shader attribute.
  45781. *
  45782. * @abstract
  45783. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45784. */
  45785. updateAttribute( /*attribute*/ ) { }
  45786. /**
  45787. * Destroys the GPU buffer of a shader attribute.
  45788. *
  45789. * @abstract
  45790. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45791. */
  45792. destroyAttribute( /*attribute*/ ) { }
  45793. // canvas
  45794. /**
  45795. * Returns the backend's rendering context.
  45796. *
  45797. * @abstract
  45798. * @return {Object} The rendering context.
  45799. */
  45800. getContext() { }
  45801. /**
  45802. * Backends can use this method if they have to run
  45803. * logic when the renderer gets resized.
  45804. *
  45805. * @abstract
  45806. */
  45807. updateSize() { }
  45808. /**
  45809. * Updates the viewport with the values from the given render context.
  45810. *
  45811. * @abstract
  45812. * @param {RenderContext} renderContext - The render context.
  45813. */
  45814. updateViewport( /*renderContext*/ ) {}
  45815. // utils
  45816. /**
  45817. * Updates a unique identifier for the given render context that can be used
  45818. * to allocate resources like occlusion queries or timestamp queries.
  45819. *
  45820. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45821. */
  45822. updateTimeStampUID( abstractRenderContext ) {
  45823. const contextData = this.get( abstractRenderContext );
  45824. const frame = this.renderer.info.frame;
  45825. let prefix;
  45826. if ( abstractRenderContext.isComputeNode === true ) {
  45827. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  45828. } else {
  45829. prefix = 'r:' + this.renderer.info.render.frameCalls;
  45830. }
  45831. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  45832. }
  45833. /**
  45834. * Returns a unique identifier for the given render context that can be used
  45835. * to allocate resources like occlusion queries or timestamp queries.
  45836. *
  45837. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  45838. * @return {string} The unique identifier.
  45839. */
  45840. getTimestampUID( abstractRenderContext ) {
  45841. return this.get( abstractRenderContext ).timestampUID;
  45842. }
  45843. /**
  45844. * Returns all timestamp frames for the given type.
  45845. *
  45846. * @param {string} type - The type of the time stamp.
  45847. * @return {Array<number>} The timestamp frames.
  45848. */
  45849. getTimestampFrames( type ) {
  45850. const queryPool = this.timestampQueryPool[ type ];
  45851. return queryPool ? queryPool.getTimestampFrames() : [];
  45852. }
  45853. /**
  45854. * Returns the query pool for the given uid.
  45855. *
  45856. * @param {string} uid - The unique identifier.
  45857. * @return {TimestampQueryPool} The query pool.
  45858. */
  45859. _getQueryPool( uid ) {
  45860. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  45861. const queryPool = this.timestampQueryPool[ type ];
  45862. return queryPool;
  45863. }
  45864. /**
  45865. * Returns the timestamp for the given uid.
  45866. *
  45867. * @param {string} uid - The unique identifier.
  45868. * @return {number} The timestamp.
  45869. */
  45870. getTimestamp( uid ) {
  45871. const queryPool = this._getQueryPool( uid );
  45872. return queryPool.getTimestamp( uid );
  45873. }
  45874. /**
  45875. * Returns `true` if a timestamp for the given uid is available.
  45876. *
  45877. * @param {string} uid - The unique identifier.
  45878. * @return {boolean} Whether the timestamp is available or not.
  45879. */
  45880. hasTimestamp( uid ) {
  45881. const queryPool = this._getQueryPool( uid );
  45882. return queryPool.hasTimestamp( uid );
  45883. }
  45884. /**
  45885. * Returns `true` if the given 3D object is fully occluded by other
  45886. * 3D objects in the scene. Backends must implement this method by using
  45887. * a Occlusion Query API.
  45888. *
  45889. * @abstract
  45890. * @param {RenderContext} renderContext - The render context.
  45891. * @param {Object3D} object - The 3D object to test.
  45892. * @return {boolean} Whether the 3D object is fully occluded or not.
  45893. */
  45894. isOccluded( /*renderContext, object*/ ) {}
  45895. /**
  45896. * Resolves the time stamp for the given render context and type.
  45897. *
  45898. * @async
  45899. * @abstract
  45900. * @param {string} [type='render'] - The type of the time stamp.
  45901. * @return {Promise<number>} A Promise that resolves with the time stamp.
  45902. */
  45903. async resolveTimestampsAsync( type = 'render' ) {
  45904. if ( ! this.trackTimestamp ) {
  45905. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  45906. return;
  45907. }
  45908. const queryPool = this.timestampQueryPool[ type ];
  45909. if ( ! queryPool ) {
  45910. return;
  45911. }
  45912. const duration = await queryPool.resolveQueriesAsync();
  45913. this.renderer.info[ type ].timestamp = duration;
  45914. return duration;
  45915. }
  45916. /**
  45917. * This method performs a readback operation by moving buffer data from
  45918. * a storage buffer attribute from the GPU to the CPU.
  45919. *
  45920. * @async
  45921. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45922. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45923. */
  45924. async getArrayBufferAsync( /* attribute */ ) {}
  45925. /**
  45926. * Checks if the given feature is supported by the backend.
  45927. *
  45928. * @async
  45929. * @abstract
  45930. * @param {string} name - The feature's name.
  45931. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  45932. */
  45933. async hasFeatureAsync( /*name*/ ) { }
  45934. /**
  45935. * Checks if the given feature is supported by the backend.
  45936. *
  45937. * @abstract
  45938. * @param {string} name - The feature's name.
  45939. * @return {boolean} Whether the feature is supported or not.
  45940. */
  45941. hasFeature( /*name*/ ) {}
  45942. /**
  45943. * Returns the maximum anisotropy texture filtering value.
  45944. *
  45945. * @abstract
  45946. * @return {number} The maximum anisotropy texture filtering value.
  45947. */
  45948. getMaxAnisotropy() {}
  45949. /**
  45950. * Returns the drawing buffer size.
  45951. *
  45952. * @return {Vector2} The drawing buffer size.
  45953. */
  45954. getDrawingBufferSize() {
  45955. _vector2 = _vector2 || new Vector2();
  45956. return this.renderer.getDrawingBufferSize( _vector2 );
  45957. }
  45958. /**
  45959. * Defines the scissor test.
  45960. *
  45961. * @abstract
  45962. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45963. */
  45964. setScissorTest( /*boolean*/ ) { }
  45965. /**
  45966. * Returns the clear color and alpha into a single
  45967. * color object.
  45968. *
  45969. * @return {Color4} The clear color.
  45970. */
  45971. getClearColor() {
  45972. const renderer = this.renderer;
  45973. _color4 = _color4 || new Color4();
  45974. renderer.getClearColor( _color4 );
  45975. _color4.getRGB( _color4 );
  45976. return _color4;
  45977. }
  45978. /**
  45979. * Returns the DOM element. If no DOM element exists, the backend
  45980. * creates a new one.
  45981. *
  45982. * @return {HTMLCanvasElement} The DOM element.
  45983. */
  45984. getDomElement() {
  45985. let domElement = this.domElement;
  45986. if ( domElement === null ) {
  45987. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  45988. // OffscreenCanvas does not have setAttribute, see #22811
  45989. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  45990. this.domElement = domElement;
  45991. }
  45992. return domElement;
  45993. }
  45994. /**
  45995. * Checks if the backend has the given compatibility.
  45996. *
  45997. * @abstract
  45998. * @param {string} name - The compatibility.
  45999. * @return {boolean} Whether the backend has the given compatibility or not.
  46000. */
  46001. hasCompatibility( /*name*/ ) {
  46002. return false;
  46003. }
  46004. /**
  46005. * Sets a dictionary for the given object into the
  46006. * internal data structure.
  46007. *
  46008. * @param {Object} object - The object.
  46009. * @param {Object} value - The dictionary to set.
  46010. */
  46011. set( object, value ) {
  46012. this.data.set( object, value );
  46013. }
  46014. /**
  46015. * Returns the dictionary for the given object.
  46016. *
  46017. * @param {Object} object - The object.
  46018. * @return {Object} The object's dictionary.
  46019. */
  46020. get( object ) {
  46021. let map = this.data.get( object );
  46022. if ( map === undefined ) {
  46023. map = {};
  46024. this.data.set( object, map );
  46025. }
  46026. return map;
  46027. }
  46028. /**
  46029. * Checks if the given object has a dictionary
  46030. * with data defined.
  46031. *
  46032. * @param {Object} object - The object.
  46033. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  46034. */
  46035. has( object ) {
  46036. return this.data.has( object );
  46037. }
  46038. /**
  46039. * Deletes an object from the internal data structure.
  46040. *
  46041. * @param {Object} object - The object to delete.
  46042. */
  46043. delete( object ) {
  46044. this.data.delete( object );
  46045. }
  46046. /**
  46047. * Delete GPU data associated with a bind group.
  46048. *
  46049. * @abstract
  46050. * @param {BindGroup} bindGroup - The bind group.
  46051. */
  46052. deleteBindGroupData( /*bindGroup*/ ) { }
  46053. /**
  46054. * Frees internal resources.
  46055. *
  46056. * @abstract
  46057. */
  46058. dispose() { }
  46059. }
  46060. let _id$1 = 0;
  46061. /**
  46062. * This module is internally used in context of compute shaders.
  46063. * This type of shader is not natively supported in WebGL 2 and
  46064. * thus implemented via Transform Feedback. `DualAttributeData`
  46065. * manages the related data.
  46066. *
  46067. * @private
  46068. */
  46069. class DualAttributeData {
  46070. constructor( attributeData, dualBuffer ) {
  46071. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  46072. this.type = attributeData.type;
  46073. this.bufferType = attributeData.bufferType;
  46074. this.pbo = attributeData.pbo;
  46075. this.byteLength = attributeData.byteLength;
  46076. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  46077. this.version = attributeData.version;
  46078. this.isInteger = attributeData.isInteger;
  46079. this.activeBufferIndex = 0;
  46080. this.baseId = attributeData.id;
  46081. }
  46082. get id() {
  46083. return `${ this.baseId }|${ this.activeBufferIndex }`;
  46084. }
  46085. get bufferGPU() {
  46086. return this.buffers[ this.activeBufferIndex ];
  46087. }
  46088. get transformBuffer() {
  46089. return this.buffers[ this.activeBufferIndex ^ 1 ];
  46090. }
  46091. switchBuffers() {
  46092. this.activeBufferIndex ^= 1;
  46093. }
  46094. }
  46095. /**
  46096. * A WebGL 2 backend utility module for managing shader attributes.
  46097. *
  46098. * @private
  46099. */
  46100. class WebGLAttributeUtils {
  46101. /**
  46102. * Constructs a new utility object.
  46103. *
  46104. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46105. */
  46106. constructor( backend ) {
  46107. /**
  46108. * A reference to the WebGL 2 backend.
  46109. *
  46110. * @type {WebGLBackend}
  46111. */
  46112. this.backend = backend;
  46113. }
  46114. /**
  46115. * Creates the GPU buffer for the given buffer attribute.
  46116. *
  46117. * @param {BufferAttribute} attribute - The buffer attribute.
  46118. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46119. */
  46120. createAttribute( attribute, bufferType ) {
  46121. const backend = this.backend;
  46122. const { gl } = backend;
  46123. const array = attribute.array;
  46124. const usage = attribute.usage || gl.STATIC_DRAW;
  46125. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46126. const bufferData = backend.get( bufferAttribute );
  46127. let bufferGPU = bufferData.bufferGPU;
  46128. if ( bufferGPU === undefined ) {
  46129. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  46130. bufferData.bufferGPU = bufferGPU;
  46131. bufferData.bufferType = bufferType;
  46132. bufferData.version = bufferAttribute.version;
  46133. }
  46134. //attribute.onUploadCallback();
  46135. let type;
  46136. if ( array instanceof Float32Array ) {
  46137. type = gl.FLOAT;
  46138. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  46139. type = gl.HALF_FLOAT;
  46140. } else if ( array instanceof Uint16Array ) {
  46141. if ( attribute.isFloat16BufferAttribute ) {
  46142. type = gl.HALF_FLOAT;
  46143. } else {
  46144. type = gl.UNSIGNED_SHORT;
  46145. }
  46146. } else if ( array instanceof Int16Array ) {
  46147. type = gl.SHORT;
  46148. } else if ( array instanceof Uint32Array ) {
  46149. type = gl.UNSIGNED_INT;
  46150. } else if ( array instanceof Int32Array ) {
  46151. type = gl.INT;
  46152. } else if ( array instanceof Int8Array ) {
  46153. type = gl.BYTE;
  46154. } else if ( array instanceof Uint8Array ) {
  46155. type = gl.UNSIGNED_BYTE;
  46156. } else if ( array instanceof Uint8ClampedArray ) {
  46157. type = gl.UNSIGNED_BYTE;
  46158. } else {
  46159. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  46160. }
  46161. let attributeData = {
  46162. bufferGPU,
  46163. bufferType,
  46164. type,
  46165. byteLength: array.byteLength,
  46166. bytesPerElement: array.BYTES_PER_ELEMENT,
  46167. version: attribute.version,
  46168. pbo: attribute.pbo,
  46169. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  46170. id: _id$1 ++
  46171. };
  46172. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  46173. // create buffer for transform feedback use
  46174. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  46175. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  46176. }
  46177. backend.set( attribute, attributeData );
  46178. }
  46179. /**
  46180. * Updates the GPU buffer of the given buffer attribute.
  46181. *
  46182. * @param {BufferAttribute} attribute - The buffer attribute.
  46183. */
  46184. updateAttribute( attribute ) {
  46185. const backend = this.backend;
  46186. const { gl } = backend;
  46187. const array = attribute.array;
  46188. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46189. const bufferData = backend.get( bufferAttribute );
  46190. const bufferType = bufferData.bufferType;
  46191. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  46192. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  46193. if ( updateRanges.length === 0 ) {
  46194. // Not using update ranges
  46195. gl.bufferSubData( bufferType, 0, array );
  46196. } else {
  46197. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46198. const range = updateRanges[ i ];
  46199. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  46200. array, range.start, range.count );
  46201. }
  46202. bufferAttribute.clearUpdateRanges();
  46203. }
  46204. gl.bindBuffer( bufferType, null );
  46205. bufferData.version = bufferAttribute.version;
  46206. }
  46207. /**
  46208. * Destroys the GPU buffer of the given buffer attribute.
  46209. *
  46210. * @param {BufferAttribute} attribute - The buffer attribute.
  46211. */
  46212. destroyAttribute( attribute ) {
  46213. const backend = this.backend;
  46214. const { gl } = backend;
  46215. if ( attribute.isInterleavedBufferAttribute ) {
  46216. backend.delete( attribute.data );
  46217. }
  46218. const attributeData = backend.get( attribute );
  46219. gl.deleteBuffer( attributeData.bufferGPU );
  46220. backend.delete( attribute );
  46221. }
  46222. /**
  46223. * This method performs a readback operation by moving buffer data from
  46224. * a storage buffer attribute from the GPU to the CPU.
  46225. *
  46226. * @async
  46227. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46228. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46229. */
  46230. async getArrayBufferAsync( attribute ) {
  46231. const backend = this.backend;
  46232. const { gl } = backend;
  46233. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  46234. const { bufferGPU } = backend.get( bufferAttribute );
  46235. const array = attribute.array;
  46236. const byteLength = array.byteLength;
  46237. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  46238. const writeBuffer = gl.createBuffer();
  46239. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46240. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  46241. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  46242. await backend.utils._clientWaitAsync();
  46243. const dstBuffer = new attribute.array.constructor( array.length );
  46244. // Ensure the buffer is bound before reading
  46245. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  46246. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  46247. gl.deleteBuffer( writeBuffer );
  46248. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  46249. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  46250. return dstBuffer.buffer;
  46251. }
  46252. /**
  46253. * Creates a WebGL buffer with the given data.
  46254. *
  46255. * @private
  46256. * @param {WebGL2RenderingContext} gl - The rendering context.
  46257. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  46258. * @param {TypedArray} array - The array of the buffer attribute.
  46259. * @param {GLenum} usage - The usage.
  46260. * @return {WebGLBuffer} The WebGL buffer.
  46261. */
  46262. _createBuffer( gl, bufferType, array, usage ) {
  46263. const bufferGPU = gl.createBuffer();
  46264. gl.bindBuffer( bufferType, bufferGPU );
  46265. gl.bufferData( bufferType, array, usage );
  46266. gl.bindBuffer( bufferType, null );
  46267. return bufferGPU;
  46268. }
  46269. }
  46270. let equationToGL, factorToGL;
  46271. /**
  46272. * A WebGL 2 backend utility module for managing the WebGL state.
  46273. *
  46274. * The major goal of this module is to reduce the number of state changes
  46275. * by caching the WEbGL state with a series of variables. In this way, the
  46276. * renderer only executes state change commands when necessary which
  46277. * improves the overall performance.
  46278. *
  46279. * @private
  46280. */
  46281. class WebGLState {
  46282. /**
  46283. * Constructs a new utility object.
  46284. *
  46285. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46286. */
  46287. constructor( backend ) {
  46288. /**
  46289. * A reference to the WebGL 2 backend.
  46290. *
  46291. * @type {WebGLBackend}
  46292. */
  46293. this.backend = backend;
  46294. /**
  46295. * A reference to the rendering context.
  46296. *
  46297. * @type {WebGL2RenderingContext}
  46298. */
  46299. this.gl = this.backend.gl;
  46300. // Below properties are intended to cache
  46301. // the WebGL state and are not explicitly
  46302. // documented for convenience reasons.
  46303. this.enabled = {};
  46304. this.currentFlipSided = null;
  46305. this.currentCullFace = null;
  46306. this.currentProgram = null;
  46307. this.currentBlendingEnabled = false;
  46308. this.currentBlending = null;
  46309. this.currentBlendSrc = null;
  46310. this.currentBlendDst = null;
  46311. this.currentBlendSrcAlpha = null;
  46312. this.currentBlendDstAlpha = null;
  46313. this.currentPremultipledAlpha = null;
  46314. this.currentPolygonOffsetFactor = null;
  46315. this.currentPolygonOffsetUnits = null;
  46316. this.currentColorMask = null;
  46317. this.currentDepthFunc = null;
  46318. this.currentDepthMask = null;
  46319. this.currentStencilFunc = null;
  46320. this.currentStencilRef = null;
  46321. this.currentStencilFuncMask = null;
  46322. this.currentStencilFail = null;
  46323. this.currentStencilZFail = null;
  46324. this.currentStencilZPass = null;
  46325. this.currentStencilMask = null;
  46326. this.currentLineWidth = null;
  46327. this.currentClippingPlanes = 0;
  46328. this.currentVAO = null;
  46329. this.currentIndex = null;
  46330. this.currentBoundFramebuffers = {};
  46331. this.currentDrawbuffers = new WeakMap();
  46332. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  46333. this.currentTextureSlot = null;
  46334. this.currentBoundTextures = {};
  46335. this.currentBoundBufferBases = {};
  46336. this._init();
  46337. }
  46338. /**
  46339. * Inits the state of the utility.
  46340. *
  46341. * @private
  46342. */
  46343. _init() {
  46344. const gl = this.gl;
  46345. // Store only WebGL constants here.
  46346. equationToGL = {
  46347. [ AddEquation ]: gl.FUNC_ADD,
  46348. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  46349. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  46350. };
  46351. factorToGL = {
  46352. [ ZeroFactor ]: gl.ZERO,
  46353. [ OneFactor ]: gl.ONE,
  46354. [ SrcColorFactor ]: gl.SRC_COLOR,
  46355. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  46356. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  46357. [ DstColorFactor ]: gl.DST_COLOR,
  46358. [ DstAlphaFactor ]: gl.DST_ALPHA,
  46359. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  46360. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  46361. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  46362. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  46363. };
  46364. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  46365. const viewportParam = gl.getParameter( gl.VIEWPORT );
  46366. this.currentScissor = new Vector4().fromArray( scissorParam );
  46367. this.currentViewport = new Vector4().fromArray( viewportParam );
  46368. this._tempVec4 = new Vector4();
  46369. }
  46370. /**
  46371. * Enables the given WebGL capability.
  46372. *
  46373. * This method caches the capability state so
  46374. * `gl.enable()` is only called when necessary.
  46375. *
  46376. * @param {GLenum} id - The capability to enable.
  46377. */
  46378. enable( id ) {
  46379. const { enabled } = this;
  46380. if ( enabled[ id ] !== true ) {
  46381. this.gl.enable( id );
  46382. enabled[ id ] = true;
  46383. }
  46384. }
  46385. /**
  46386. * Disables the given WebGL capability.
  46387. *
  46388. * This method caches the capability state so
  46389. * `gl.disable()` is only called when necessary.
  46390. *
  46391. * @param {GLenum} id - The capability to enable.
  46392. */
  46393. disable( id ) {
  46394. const { enabled } = this;
  46395. if ( enabled[ id ] !== false ) {
  46396. this.gl.disable( id );
  46397. enabled[ id ] = false;
  46398. }
  46399. }
  46400. /**
  46401. * Specifies whether polygons are front- or back-facing
  46402. * by setting the winding orientation.
  46403. *
  46404. * This method caches the state so `gl.frontFace()` is only
  46405. * called when necessary.
  46406. *
  46407. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  46408. */
  46409. setFlipSided( flipSided ) {
  46410. if ( this.currentFlipSided !== flipSided ) {
  46411. const { gl } = this;
  46412. if ( flipSided ) {
  46413. gl.frontFace( gl.CW );
  46414. } else {
  46415. gl.frontFace( gl.CCW );
  46416. }
  46417. this.currentFlipSided = flipSided;
  46418. }
  46419. }
  46420. /**
  46421. * Specifies whether or not front- and/or back-facing
  46422. * polygons can be culled.
  46423. *
  46424. * This method caches the state so `gl.cullFace()` is only
  46425. * called when necessary.
  46426. *
  46427. * @param {number} cullFace - Defines which polygons are candidates for culling.
  46428. */
  46429. setCullFace( cullFace ) {
  46430. const { gl } = this;
  46431. if ( cullFace !== CullFaceNone ) {
  46432. this.enable( gl.CULL_FACE );
  46433. if ( cullFace !== this.currentCullFace ) {
  46434. if ( cullFace === CullFaceBack ) {
  46435. gl.cullFace( gl.BACK );
  46436. } else if ( cullFace === CullFaceFront ) {
  46437. gl.cullFace( gl.FRONT );
  46438. } else {
  46439. gl.cullFace( gl.FRONT_AND_BACK );
  46440. }
  46441. }
  46442. } else {
  46443. this.disable( gl.CULL_FACE );
  46444. }
  46445. this.currentCullFace = cullFace;
  46446. }
  46447. /**
  46448. * Specifies the width of line primitives.
  46449. *
  46450. * This method caches the state so `gl.lineWidth()` is only
  46451. * called when necessary.
  46452. *
  46453. * @param {number} width - The line width.
  46454. */
  46455. setLineWidth( width ) {
  46456. const { currentLineWidth, gl } = this;
  46457. if ( width !== currentLineWidth ) {
  46458. gl.lineWidth( width );
  46459. this.currentLineWidth = width;
  46460. }
  46461. }
  46462. setMRTBlending( textures, mrt, material ) {
  46463. const gl = this.gl;
  46464. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46465. if ( ! drawBuffersIndexedExt ) return;
  46466. for ( let i = 0; i < textures.length; i ++ ) {
  46467. const texture = textures[ i ];
  46468. let blending = null;
  46469. if ( mrt !== null ) {
  46470. const blendMode = mrt.getBlendMode( texture.name );
  46471. if ( blendMode.blending === MaterialBlending ) {
  46472. // use material blending
  46473. blending = material;
  46474. } else if ( blendMode.blending !== NoBlending ) {
  46475. blending = blendMode;
  46476. }
  46477. } else {
  46478. // use material blending
  46479. blending = material;
  46480. }
  46481. if ( blending !== null ) {
  46482. this._setMRTBlendingIndex( i, blending );
  46483. } else {
  46484. // use opaque blending (no blending)
  46485. drawBuffersIndexedExt.blendFuncSeparateiOES( i, gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  46486. }
  46487. }
  46488. }
  46489. /**
  46490. * Applies blending configuration for a specific draw buffer index.
  46491. *
  46492. * @private
  46493. * @param {number} index - The draw buffer index.
  46494. * @param {Object} blending - The blending configuration (material or BlendMode).
  46495. */
  46496. _setMRTBlendingIndex( index, blending ) {
  46497. const { gl } = this;
  46498. const drawBuffersIndexedExt = this.backend.drawBuffersIndexedExt;
  46499. const blendingType = blending.blending;
  46500. const blendSrc = blending.blendSrc;
  46501. const blendDst = blending.blendDst;
  46502. const blendEquation = blending.blendEquation;
  46503. const premultipliedAlpha = blending.premultipliedAlpha;
  46504. if ( blendingType === CustomBlending ) {
  46505. const blendSrcAlpha = blending.blendSrcAlpha !== null ? blending.blendSrcAlpha : blendSrc;
  46506. const blendDstAlpha = blending.blendDstAlpha !== null ? blending.blendDstAlpha : blendDst;
  46507. const blendEquationAlpha = blending.blendEquationAlpha !== null ? blending.blendEquationAlpha : blendEquation;
  46508. drawBuffersIndexedExt.blendEquationSeparateiOES( index, equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46509. drawBuffersIndexedExt.blendFuncSeparateiOES( index, factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46510. } else {
  46511. drawBuffersIndexedExt.blendEquationSeparateiOES( index, gl.FUNC_ADD, gl.FUNC_ADD );
  46512. if ( premultipliedAlpha ) {
  46513. switch ( blendingType ) {
  46514. case NormalBlending:
  46515. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46516. break;
  46517. case AdditiveBlending:
  46518. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  46519. break;
  46520. case SubtractiveBlending:
  46521. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46522. break;
  46523. case MultiplyBlending:
  46524. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46525. break;
  46526. default:
  46527. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46528. break;
  46529. }
  46530. } else {
  46531. switch ( blendingType ) {
  46532. case NormalBlending:
  46533. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46534. break;
  46535. case AdditiveBlending:
  46536. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46537. break;
  46538. case SubtractiveBlending:
  46539. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46540. break;
  46541. case MultiplyBlending:
  46542. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46543. break;
  46544. default:
  46545. drawBuffersIndexedExt.blendFuncSeparateiOES( index, gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46546. break;
  46547. }
  46548. }
  46549. }
  46550. }
  46551. /**
  46552. * Defines the blending.
  46553. *
  46554. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  46555. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  46556. *
  46557. * @param {number} blending - The blending type.
  46558. * @param {number} blendEquation - The blending equation.
  46559. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  46560. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  46561. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  46562. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  46563. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  46564. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  46565. */
  46566. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  46567. const { gl } = this;
  46568. if ( blending === NoBlending ) {
  46569. if ( this.currentBlendingEnabled === true ) {
  46570. this.disable( gl.BLEND );
  46571. this.currentBlendingEnabled = false;
  46572. }
  46573. return;
  46574. }
  46575. if ( this.currentBlendingEnabled === false ) {
  46576. this.enable( gl.BLEND );
  46577. this.currentBlendingEnabled = true;
  46578. }
  46579. if ( blending !== CustomBlending ) {
  46580. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  46581. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  46582. gl.blendEquation( gl.FUNC_ADD );
  46583. this.currentBlendEquation = AddEquation;
  46584. this.currentBlendEquationAlpha = AddEquation;
  46585. }
  46586. if ( premultipliedAlpha ) {
  46587. switch ( blending ) {
  46588. case NormalBlending:
  46589. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46590. break;
  46591. case AdditiveBlending:
  46592. gl.blendFunc( gl.ONE, gl.ONE );
  46593. break;
  46594. case SubtractiveBlending:
  46595. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  46596. break;
  46597. case MultiplyBlending:
  46598. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  46599. break;
  46600. default:
  46601. error( 'WebGLState: Invalid blending: ', blending );
  46602. break;
  46603. }
  46604. } else {
  46605. switch ( blending ) {
  46606. case NormalBlending:
  46607. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  46608. break;
  46609. case AdditiveBlending:
  46610. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  46611. break;
  46612. case SubtractiveBlending:
  46613. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  46614. break;
  46615. case MultiplyBlending:
  46616. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  46617. break;
  46618. default:
  46619. error( 'WebGLState: Invalid blending: ', blending );
  46620. break;
  46621. }
  46622. }
  46623. this.currentBlendSrc = null;
  46624. this.currentBlendDst = null;
  46625. this.currentBlendSrcAlpha = null;
  46626. this.currentBlendDstAlpha = null;
  46627. this.currentBlending = blending;
  46628. this.currentPremultipledAlpha = premultipliedAlpha;
  46629. }
  46630. return;
  46631. }
  46632. // custom blending
  46633. blendEquationAlpha = blendEquationAlpha || blendEquation;
  46634. blendSrcAlpha = blendSrcAlpha || blendSrc;
  46635. blendDstAlpha = blendDstAlpha || blendDst;
  46636. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  46637. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  46638. this.currentBlendEquation = blendEquation;
  46639. this.currentBlendEquationAlpha = blendEquationAlpha;
  46640. }
  46641. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  46642. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  46643. this.currentBlendSrc = blendSrc;
  46644. this.currentBlendDst = blendDst;
  46645. this.currentBlendSrcAlpha = blendSrcAlpha;
  46646. this.currentBlendDstAlpha = blendDstAlpha;
  46647. }
  46648. this.currentBlending = blending;
  46649. this.currentPremultipledAlpha = false;
  46650. }
  46651. /**
  46652. * Specifies whether colors can be written when rendering
  46653. * into a framebuffer or not.
  46654. *
  46655. * This method caches the state so `gl.colorMask()` is only
  46656. * called when necessary.
  46657. *
  46658. * @param {boolean} colorMask - The color mask.
  46659. */
  46660. setColorMask( colorMask ) {
  46661. if ( this.currentColorMask !== colorMask ) {
  46662. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  46663. this.currentColorMask = colorMask;
  46664. }
  46665. }
  46666. /**
  46667. * Specifies whether the depth test is enabled or not.
  46668. *
  46669. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  46670. */
  46671. setDepthTest( depthTest ) {
  46672. const { gl } = this;
  46673. if ( depthTest ) {
  46674. this.enable( gl.DEPTH_TEST );
  46675. } else {
  46676. this.disable( gl.DEPTH_TEST );
  46677. }
  46678. }
  46679. /**
  46680. * Specifies whether depth values can be written when rendering
  46681. * into a framebuffer or not.
  46682. *
  46683. * This method caches the state so `gl.depthMask()` is only
  46684. * called when necessary.
  46685. *
  46686. * @param {boolean} depthMask - The depth mask.
  46687. */
  46688. setDepthMask( depthMask ) {
  46689. if ( this.currentDepthMask !== depthMask ) {
  46690. this.gl.depthMask( depthMask );
  46691. this.currentDepthMask = depthMask;
  46692. }
  46693. }
  46694. /**
  46695. * Specifies the depth compare function.
  46696. *
  46697. * This method caches the state so `gl.depthFunc()` is only
  46698. * called when necessary.
  46699. *
  46700. * @param {number} depthFunc - The depth compare function.
  46701. */
  46702. setDepthFunc( depthFunc ) {
  46703. if ( this.currentDepthFunc !== depthFunc ) {
  46704. const { gl } = this;
  46705. switch ( depthFunc ) {
  46706. case NeverDepth:
  46707. gl.depthFunc( gl.NEVER );
  46708. break;
  46709. case AlwaysDepth:
  46710. gl.depthFunc( gl.ALWAYS );
  46711. break;
  46712. case LessDepth:
  46713. gl.depthFunc( gl.LESS );
  46714. break;
  46715. case LessEqualDepth:
  46716. gl.depthFunc( gl.LEQUAL );
  46717. break;
  46718. case EqualDepth:
  46719. gl.depthFunc( gl.EQUAL );
  46720. break;
  46721. case GreaterEqualDepth:
  46722. gl.depthFunc( gl.GEQUAL );
  46723. break;
  46724. case GreaterDepth:
  46725. gl.depthFunc( gl.GREATER );
  46726. break;
  46727. case NotEqualDepth:
  46728. gl.depthFunc( gl.NOTEQUAL );
  46729. break;
  46730. default:
  46731. gl.depthFunc( gl.LEQUAL );
  46732. }
  46733. this.currentDepthFunc = depthFunc;
  46734. }
  46735. }
  46736. /**
  46737. * Specifies the scissor box.
  46738. *
  46739. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46740. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46741. * @param {number} width - The width of the viewport.
  46742. * @param {number} height - The height of the viewport.
  46743. *
  46744. */
  46745. scissor( x, y, width, height ) {
  46746. const scissor = this._tempVec4.set( x, y, width, height );
  46747. if ( this.currentScissor.equals( scissor ) === false ) {
  46748. const { gl } = this;
  46749. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  46750. this.currentScissor.copy( scissor );
  46751. }
  46752. }
  46753. /**
  46754. * Specifies the viewport.
  46755. *
  46756. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  46757. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  46758. * @param {number} width - The width of the viewport.
  46759. * @param {number} height - The height of the viewport.
  46760. *
  46761. */
  46762. viewport( x, y, width, height ) {
  46763. const viewport = this._tempVec4.set( x, y, width, height );
  46764. if ( this.currentViewport.equals( viewport ) === false ) {
  46765. const { gl } = this;
  46766. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  46767. this.currentViewport.copy( viewport );
  46768. }
  46769. }
  46770. /**
  46771. * Defines the scissor test.
  46772. *
  46773. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46774. */
  46775. setScissorTest( boolean ) {
  46776. const gl = this.gl;
  46777. if ( boolean ) {
  46778. this.enable( gl.SCISSOR_TEST );
  46779. } else {
  46780. this.disable( gl.SCISSOR_TEST );
  46781. }
  46782. }
  46783. /**
  46784. * Specifies whether the stencil test is enabled or not.
  46785. *
  46786. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  46787. */
  46788. setStencilTest( stencilTest ) {
  46789. const { gl } = this;
  46790. if ( stencilTest ) {
  46791. this.enable( gl.STENCIL_TEST );
  46792. } else {
  46793. this.disable( gl.STENCIL_TEST );
  46794. }
  46795. }
  46796. /**
  46797. * Specifies whether stencil values can be written when rendering
  46798. * into a framebuffer or not.
  46799. *
  46800. * This method caches the state so `gl.stencilMask()` is only
  46801. * called when necessary.
  46802. *
  46803. * @param {boolean} stencilMask - The stencil mask.
  46804. */
  46805. setStencilMask( stencilMask ) {
  46806. if ( this.currentStencilMask !== stencilMask ) {
  46807. this.gl.stencilMask( stencilMask );
  46808. this.currentStencilMask = stencilMask;
  46809. }
  46810. }
  46811. /**
  46812. * Specifies whether the stencil test functions.
  46813. *
  46814. * This method caches the state so `gl.stencilFunc()` is only
  46815. * called when necessary.
  46816. *
  46817. * @param {number} stencilFunc - The stencil compare function.
  46818. * @param {number} stencilRef - The reference value for the stencil test.
  46819. * @param {number} stencilMask - A bit-wise mask that is used to AND the reference value and the stored stencil value when the test is done.
  46820. */
  46821. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  46822. if ( this.currentStencilFunc !== stencilFunc ||
  46823. this.currentStencilRef !== stencilRef ||
  46824. this.currentStencilFuncMask !== stencilMask ) {
  46825. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  46826. this.currentStencilFunc = stencilFunc;
  46827. this.currentStencilRef = stencilRef;
  46828. this.currentStencilFuncMask = stencilMask;
  46829. }
  46830. }
  46831. /**
  46832. * Specifies whether the stencil test operation.
  46833. *
  46834. * This method caches the state so `gl.stencilOp()` is only
  46835. * called when necessary.
  46836. *
  46837. * @param {number} stencilFail - The function to use when the stencil test fails.
  46838. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  46839. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  46840. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  46841. */
  46842. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  46843. if ( this.currentStencilFail !== stencilFail ||
  46844. this.currentStencilZFail !== stencilZFail ||
  46845. this.currentStencilZPass !== stencilZPass ) {
  46846. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  46847. this.currentStencilFail = stencilFail;
  46848. this.currentStencilZFail = stencilZFail;
  46849. this.currentStencilZPass = stencilZPass;
  46850. }
  46851. }
  46852. /**
  46853. * Configures the WebGL state for the given material.
  46854. *
  46855. * @param {Material} material - The material to configure the state for.
  46856. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  46857. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  46858. */
  46859. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  46860. const { gl } = this;
  46861. material.side === DoubleSide
  46862. ? this.disable( gl.CULL_FACE )
  46863. : this.enable( gl.CULL_FACE );
  46864. let flipSided = ( material.side === BackSide );
  46865. if ( frontFaceCW ) flipSided = ! flipSided;
  46866. this.setFlipSided( flipSided );
  46867. ( material.blending === NormalBlending && material.transparent === false )
  46868. ? this.setBlending( NoBlending )
  46869. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  46870. this.setDepthFunc( material.depthFunc );
  46871. this.setDepthTest( material.depthTest );
  46872. this.setDepthMask( material.depthWrite );
  46873. this.setColorMask( material.colorWrite );
  46874. const stencilWrite = material.stencilWrite;
  46875. this.setStencilTest( stencilWrite );
  46876. if ( stencilWrite ) {
  46877. this.setStencilMask( material.stencilWriteMask );
  46878. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  46879. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  46880. }
  46881. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  46882. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  46883. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  46884. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  46885. if ( hardwareClippingPlanes > 0 ) {
  46886. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  46887. const CLIP_DISTANCE0_WEBGL = 0x3000;
  46888. for ( let i = 0; i < 8; i ++ ) {
  46889. if ( i < hardwareClippingPlanes ) {
  46890. this.enable( CLIP_DISTANCE0_WEBGL + i );
  46891. } else {
  46892. this.disable( CLIP_DISTANCE0_WEBGL + i );
  46893. }
  46894. }
  46895. }
  46896. }
  46897. }
  46898. /**
  46899. * Specifies the polygon offset.
  46900. *
  46901. * This method caches the state so `gl.polygonOffset()` is only
  46902. * called when necessary.
  46903. *
  46904. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  46905. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  46906. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  46907. */
  46908. setPolygonOffset( polygonOffset, factor, units ) {
  46909. const { gl } = this;
  46910. if ( polygonOffset ) {
  46911. this.enable( gl.POLYGON_OFFSET_FILL );
  46912. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  46913. gl.polygonOffset( factor, units );
  46914. this.currentPolygonOffsetFactor = factor;
  46915. this.currentPolygonOffsetUnits = units;
  46916. }
  46917. } else {
  46918. this.disable( gl.POLYGON_OFFSET_FILL );
  46919. }
  46920. }
  46921. /**
  46922. * Defines the usage of the given WebGL program.
  46923. *
  46924. * This method caches the state so `gl.useProgram()` is only
  46925. * called when necessary.
  46926. *
  46927. * @param {WebGLProgram} program - The WebGL program to use.
  46928. * @return {boolean} Whether a program change has been executed or not.
  46929. */
  46930. useProgram( program ) {
  46931. if ( this.currentProgram !== program ) {
  46932. this.gl.useProgram( program );
  46933. this.currentProgram = program;
  46934. return true;
  46935. }
  46936. return false;
  46937. }
  46938. /**
  46939. * Sets the vertex state by binding the given VAO and element buffer.
  46940. *
  46941. * @param {WebGLVertexArrayObject} vao - The VAO.
  46942. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  46943. * @return {boolean} Whether a vertex state has been changed or not.
  46944. */
  46945. setVertexState( vao, indexBuffer = null ) {
  46946. const gl = this.gl;
  46947. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  46948. gl.bindVertexArray( vao );
  46949. if ( indexBuffer !== null ) {
  46950. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  46951. }
  46952. this.currentVAO = vao;
  46953. this.currentIndex = indexBuffer;
  46954. return true;
  46955. }
  46956. return false;
  46957. }
  46958. /**
  46959. * Resets the vertex array state by resetting the VAO and element buffer.
  46960. */
  46961. resetVertexState() {
  46962. const gl = this.gl;
  46963. gl.bindVertexArray( null );
  46964. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  46965. this.currentVAO = null;
  46966. this.currentIndex = null;
  46967. }
  46968. // framebuffer
  46969. /**
  46970. * Binds the given framebuffer.
  46971. *
  46972. * This method caches the state so `gl.bindFramebuffer()` is only
  46973. * called when necessary.
  46974. *
  46975. * @param {number} target - The binding point (target).
  46976. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  46977. * @return {boolean} Whether a bind has been executed or not.
  46978. */
  46979. bindFramebuffer( target, framebuffer ) {
  46980. const { gl, currentBoundFramebuffers } = this;
  46981. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  46982. gl.bindFramebuffer( target, framebuffer );
  46983. currentBoundFramebuffers[ target ] = framebuffer;
  46984. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  46985. if ( target === gl.DRAW_FRAMEBUFFER ) {
  46986. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  46987. }
  46988. if ( target === gl.FRAMEBUFFER ) {
  46989. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  46990. }
  46991. return true;
  46992. }
  46993. return false;
  46994. }
  46995. /**
  46996. * Defines draw buffers to which fragment colors are written into.
  46997. * Configures the MRT setup of custom framebuffers.
  46998. *
  46999. * This method caches the state so `gl.drawBuffers()` is only
  47000. * called when necessary.
  47001. *
  47002. * @param {RenderContext} renderContext - The render context.
  47003. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  47004. */
  47005. drawBuffers( renderContext, framebuffer ) {
  47006. const { gl } = this;
  47007. let drawBuffers = [];
  47008. let needsUpdate = false;
  47009. if ( renderContext.textures !== null ) {
  47010. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  47011. if ( drawBuffers === undefined ) {
  47012. drawBuffers = [];
  47013. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  47014. }
  47015. const textures = renderContext.textures;
  47016. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  47017. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  47018. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  47019. }
  47020. drawBuffers.length = textures.length;
  47021. needsUpdate = true;
  47022. }
  47023. } else {
  47024. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  47025. drawBuffers[ 0 ] = gl.BACK;
  47026. needsUpdate = true;
  47027. }
  47028. }
  47029. if ( needsUpdate ) {
  47030. gl.drawBuffers( drawBuffers );
  47031. }
  47032. }
  47033. // texture
  47034. /**
  47035. * Makes the given texture unit active.
  47036. *
  47037. * This method caches the state so `gl.activeTexture()` is only
  47038. * called when necessary.
  47039. *
  47040. * @param {number} webglSlot - The texture unit to make active.
  47041. */
  47042. activeTexture( webglSlot ) {
  47043. const { gl, currentTextureSlot, maxTextures } = this;
  47044. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47045. if ( currentTextureSlot !== webglSlot ) {
  47046. gl.activeTexture( webglSlot );
  47047. this.currentTextureSlot = webglSlot;
  47048. }
  47049. }
  47050. /**
  47051. * Binds the given WebGL texture to a target.
  47052. *
  47053. * This method caches the state so `gl.bindTexture()` is only
  47054. * called when necessary.
  47055. *
  47056. * @param {number} webglType - The binding point (target).
  47057. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  47058. * @param {number} webglSlot - The texture.
  47059. */
  47060. bindTexture( webglType, webglTexture, webglSlot ) {
  47061. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  47062. if ( webglSlot === undefined ) {
  47063. if ( currentTextureSlot === null ) {
  47064. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47065. } else {
  47066. webglSlot = currentTextureSlot;
  47067. }
  47068. }
  47069. let boundTexture = currentBoundTextures[ webglSlot ];
  47070. if ( boundTexture === undefined ) {
  47071. boundTexture = { type: undefined, texture: undefined };
  47072. currentBoundTextures[ webglSlot ] = boundTexture;
  47073. }
  47074. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  47075. if ( currentTextureSlot !== webglSlot ) {
  47076. gl.activeTexture( webglSlot );
  47077. this.currentTextureSlot = webglSlot;
  47078. }
  47079. gl.bindTexture( webglType, webglTexture );
  47080. boundTexture.type = webglType;
  47081. boundTexture.texture = webglTexture;
  47082. }
  47083. }
  47084. /**
  47085. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  47086. *
  47087. * This method caches the state so `gl.bindBufferBase()` is only
  47088. * called when necessary.
  47089. *
  47090. * @param {number} target - The target for the bind operation.
  47091. * @param {number} index - The index of the target.
  47092. * @param {WebGLBuffer} buffer - The WebGL buffer.
  47093. * @return {boolean} Whether a bind has been executed or not.
  47094. */
  47095. bindBufferBase( target, index, buffer ) {
  47096. const { gl } = this;
  47097. const key = `${target}-${index}`;
  47098. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  47099. gl.bindBufferBase( target, index, buffer );
  47100. this.currentBoundBufferBases[ key ] = buffer;
  47101. return true;
  47102. }
  47103. return false;
  47104. }
  47105. /**
  47106. * Unbinds the current bound texture.
  47107. *
  47108. * This method caches the state so `gl.bindTexture()` is only
  47109. * called when necessary.
  47110. */
  47111. unbindTexture() {
  47112. const { gl, currentTextureSlot, currentBoundTextures } = this;
  47113. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  47114. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  47115. gl.bindTexture( boundTexture.type, null );
  47116. boundTexture.type = undefined;
  47117. boundTexture.texture = undefined;
  47118. }
  47119. }
  47120. }
  47121. /**
  47122. * A WebGL 2 backend utility module with common helpers.
  47123. *
  47124. * @private
  47125. */
  47126. class WebGLUtils {
  47127. /**
  47128. * Constructs a new utility object.
  47129. *
  47130. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47131. */
  47132. constructor( backend ) {
  47133. /**
  47134. * A reference to the WebGL 2 backend.
  47135. *
  47136. * @type {WebGLBackend}
  47137. */
  47138. this.backend = backend;
  47139. /**
  47140. * A reference to the rendering context.
  47141. *
  47142. * @type {WebGL2RenderingContext}
  47143. */
  47144. this.gl = this.backend.gl;
  47145. /**
  47146. * A reference to a backend module holding extension-related
  47147. * utility functions.
  47148. *
  47149. * @type {WebGLExtensions}
  47150. */
  47151. this.extensions = backend.extensions;
  47152. }
  47153. /**
  47154. * Converts the given three.js constant into a WebGL constant.
  47155. * The method currently supports the conversion of texture formats
  47156. * and types.
  47157. *
  47158. * @param {number} p - The three.js constant.
  47159. * @param {string} [colorSpace=NoColorSpace] - The color space.
  47160. * @return {?number} The corresponding WebGL constant.
  47161. */
  47162. convert( p, colorSpace = NoColorSpace ) {
  47163. const { gl, extensions } = this;
  47164. let extension;
  47165. const transfer = ColorManagement.getTransfer( colorSpace );
  47166. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  47167. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  47168. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  47169. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  47170. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  47171. if ( p === ByteType ) return gl.BYTE;
  47172. if ( p === ShortType ) return gl.SHORT;
  47173. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  47174. if ( p === IntType ) return gl.INT;
  47175. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  47176. if ( p === FloatType ) return gl.FLOAT;
  47177. if ( p === HalfFloatType ) {
  47178. return gl.HALF_FLOAT;
  47179. }
  47180. if ( p === AlphaFormat ) return gl.ALPHA;
  47181. if ( p === RGBFormat ) return gl.RGB;
  47182. if ( p === RGBAFormat ) return gl.RGBA;
  47183. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  47184. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  47185. // WebGL2 formats.
  47186. if ( p === RedFormat ) return gl.RED;
  47187. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  47188. if ( p === RGFormat ) return gl.RG;
  47189. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  47190. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  47191. // S3TC
  47192. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  47193. if ( transfer === SRGBTransfer ) {
  47194. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  47195. if ( extension !== null ) {
  47196. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  47197. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  47198. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  47199. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  47200. } else {
  47201. return null;
  47202. }
  47203. } else {
  47204. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  47205. if ( extension !== null ) {
  47206. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  47207. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47208. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47209. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47210. } else {
  47211. return null;
  47212. }
  47213. }
  47214. }
  47215. // PVRTC
  47216. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  47217. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  47218. if ( extension !== null ) {
  47219. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  47220. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  47221. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  47222. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  47223. } else {
  47224. return null;
  47225. }
  47226. }
  47227. // ETC
  47228. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  47229. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  47230. if ( extension !== null ) {
  47231. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  47232. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  47233. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  47234. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  47235. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  47236. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  47237. } else {
  47238. return null;
  47239. }
  47240. }
  47241. // ASTC
  47242. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  47243. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  47244. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  47245. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  47246. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  47247. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  47248. if ( extension !== null ) {
  47249. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  47250. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  47251. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  47252. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  47253. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  47254. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  47255. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  47256. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  47257. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  47258. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  47259. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  47260. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  47261. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  47262. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  47263. } else {
  47264. return null;
  47265. }
  47266. }
  47267. // BPTC
  47268. if ( p === RGBA_BPTC_Format ) {
  47269. extension = extensions.get( 'EXT_texture_compression_bptc' );
  47270. if ( extension !== null ) {
  47271. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  47272. } else {
  47273. return null;
  47274. }
  47275. }
  47276. // RGTC
  47277. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  47278. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  47279. if ( extension !== null ) {
  47280. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  47281. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  47282. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  47283. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  47284. } else {
  47285. return null;
  47286. }
  47287. }
  47288. //
  47289. if ( p === UnsignedInt248Type ) {
  47290. return gl.UNSIGNED_INT_24_8;
  47291. }
  47292. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  47293. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  47294. }
  47295. /**
  47296. * This method can be used to synchronize the CPU with the GPU by waiting until
  47297. * ongoing GPU commands have been completed.
  47298. *
  47299. * @private
  47300. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  47301. */
  47302. _clientWaitAsync() {
  47303. const { gl } = this;
  47304. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  47305. gl.flush();
  47306. return new Promise( ( resolve, reject ) => {
  47307. function test() {
  47308. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  47309. if ( res === gl.WAIT_FAILED ) {
  47310. gl.deleteSync( sync );
  47311. reject();
  47312. return;
  47313. }
  47314. if ( res === gl.TIMEOUT_EXPIRED ) {
  47315. requestAnimationFrame( test );
  47316. return;
  47317. }
  47318. gl.deleteSync( sync );
  47319. resolve();
  47320. }
  47321. test();
  47322. } );
  47323. }
  47324. }
  47325. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  47326. /**
  47327. * A WebGL 2 backend utility module for managing textures.
  47328. *
  47329. * @private
  47330. */
  47331. class WebGLTextureUtils {
  47332. /**
  47333. * Constructs a new utility object.
  47334. *
  47335. * @param {WebGLBackend} backend - The WebGL 2 backend.
  47336. */
  47337. constructor( backend ) {
  47338. /**
  47339. * A reference to the WebGL 2 backend.
  47340. *
  47341. * @type {WebGLBackend}
  47342. */
  47343. this.backend = backend;
  47344. /**
  47345. * A reference to the rendering context.
  47346. *
  47347. * @type {WebGL2RenderingContext}
  47348. */
  47349. this.gl = backend.gl;
  47350. /**
  47351. * A reference to a backend module holding extension-related
  47352. * utility functions.
  47353. *
  47354. * @type {WebGLExtensions}
  47355. */
  47356. this.extensions = backend.extensions;
  47357. /**
  47358. * A dictionary for managing default textures. The key
  47359. * is the binding point (target), the value the WEbGL texture object.
  47360. *
  47361. * @type {Object<GLenum,WebGLTexture>}
  47362. */
  47363. this.defaultTextures = {};
  47364. /**
  47365. * A scratch framebuffer used for attaching the source texture in
  47366. * {@link copyTextureToTexture}.
  47367. *
  47368. * @private
  47369. * @type {?WebGLFramebuffer}
  47370. */
  47371. this._srcFramebuffer = null;
  47372. /**
  47373. * A scratch framebuffer used for attaching the destination texture in
  47374. * {@link copyTextureToTexture}.
  47375. *
  47376. * @private
  47377. * @type {?WebGLFramebuffer}
  47378. */
  47379. this._dstFramebuffer = null;
  47380. if ( initialized === false ) {
  47381. this._init();
  47382. initialized = true;
  47383. }
  47384. }
  47385. /**
  47386. * Inits the state of the utility.
  47387. *
  47388. * @private
  47389. */
  47390. _init() {
  47391. const gl = this.gl;
  47392. // Store only WebGL constants here.
  47393. wrappingToGL = {
  47394. [ RepeatWrapping ]: gl.REPEAT,
  47395. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  47396. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  47397. };
  47398. filterToGL = {
  47399. [ NearestFilter ]: gl.NEAREST,
  47400. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  47401. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  47402. [ LinearFilter ]: gl.LINEAR,
  47403. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  47404. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  47405. };
  47406. compareToGL = {
  47407. [ NeverCompare ]: gl.NEVER,
  47408. [ AlwaysCompare ]: gl.ALWAYS,
  47409. [ LessCompare ]: gl.LESS,
  47410. [ LessEqualCompare ]: gl.LEQUAL,
  47411. [ EqualCompare ]: gl.EQUAL,
  47412. [ GreaterEqualCompare ]: gl.GEQUAL,
  47413. [ GreaterCompare ]: gl.GREATER,
  47414. [ NotEqualCompare ]: gl.NOTEQUAL
  47415. };
  47416. }
  47417. /**
  47418. * Returns the native texture type for the given texture.
  47419. *
  47420. * @param {Texture} texture - The texture.
  47421. * @return {GLenum} The native texture type.
  47422. */
  47423. getGLTextureType( texture ) {
  47424. const { gl } = this;
  47425. let glTextureType;
  47426. if ( texture.isCubeTexture === true ) {
  47427. glTextureType = gl.TEXTURE_CUBE_MAP;
  47428. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  47429. glTextureType = gl.TEXTURE_2D_ARRAY;
  47430. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  47431. glTextureType = gl.TEXTURE_3D;
  47432. } else {
  47433. glTextureType = gl.TEXTURE_2D;
  47434. }
  47435. return glTextureType;
  47436. }
  47437. /**
  47438. * Returns the native texture type for the given texture.
  47439. *
  47440. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  47441. * @param {GLenum} glFormat - The WebGL format.
  47442. * @param {GLenum} glType - The WebGL type.
  47443. * @param {string} colorSpace - The texture's color space.
  47444. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  47445. * @return {GLenum} The internal format.
  47446. */
  47447. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47448. const { gl, extensions } = this;
  47449. if ( internalFormatName !== null ) {
  47450. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  47451. warn( 'WebGLBackend: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47452. }
  47453. let internalFormat = glFormat;
  47454. if ( glFormat === gl.RED ) {
  47455. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  47456. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  47457. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  47458. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  47459. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47460. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47461. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47462. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47463. }
  47464. if ( glFormat === gl.RED_INTEGER ) {
  47465. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  47466. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  47467. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  47468. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  47469. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  47470. if ( glType === gl.INT ) internalFormat = gl.R32I;
  47471. }
  47472. if ( glFormat === gl.RG ) {
  47473. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  47474. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  47475. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  47476. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  47477. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47478. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47479. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47480. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47481. }
  47482. if ( glFormat === gl.RG_INTEGER ) {
  47483. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  47484. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  47485. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  47486. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  47487. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  47488. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  47489. }
  47490. if ( glFormat === gl.RGB ) {
  47491. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47492. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  47493. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  47494. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  47495. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  47496. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47497. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47498. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47499. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47500. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  47501. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  47502. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47503. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  47504. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  47505. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  47506. }
  47507. if ( glFormat === gl.RGB_INTEGER ) {
  47508. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  47509. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  47510. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  47511. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  47512. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  47513. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  47514. }
  47515. if ( glFormat === gl.RGBA ) {
  47516. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47517. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  47518. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  47519. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  47520. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  47521. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47522. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47523. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47524. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47525. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  47526. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  47527. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  47528. }
  47529. if ( glFormat === gl.RGBA_INTEGER ) {
  47530. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  47531. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  47532. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  47533. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  47534. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  47535. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  47536. }
  47537. if ( glFormat === gl.DEPTH_COMPONENT ) {
  47538. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  47539. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  47540. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  47541. }
  47542. if ( glFormat === gl.DEPTH_STENCIL ) {
  47543. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  47544. }
  47545. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  47546. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  47547. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  47548. extensions.get( 'EXT_color_buffer_float' );
  47549. }
  47550. return internalFormat;
  47551. }
  47552. /**
  47553. * Sets the texture parameters for the given texture.
  47554. *
  47555. * @param {GLenum} textureType - The texture type.
  47556. * @param {Texture} texture - The texture.
  47557. */
  47558. setTextureParameters( textureType, texture ) {
  47559. const { gl, extensions, backend } = this;
  47560. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  47561. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  47562. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  47563. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  47564. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  47565. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  47566. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  47567. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  47568. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  47569. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  47570. // WebGL 2 does not support wrapping for depth 2D array textures
  47571. if ( ! texture.isArrayTexture ) {
  47572. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  47573. }
  47574. }
  47575. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  47576. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  47577. // follow WebGPU backend mapping for texture filtering
  47578. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  47579. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  47580. if ( texture.compareFunction ) {
  47581. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  47582. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  47583. }
  47584. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  47585. if ( texture.magFilter === NearestFilter ) return;
  47586. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  47587. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  47588. if ( texture.anisotropy > 1 ) {
  47589. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  47590. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  47591. }
  47592. }
  47593. }
  47594. /**
  47595. * Creates a default texture for the given texture that can be used
  47596. * as a placeholder until the actual texture is ready for usage.
  47597. *
  47598. * @param {Texture} texture - The texture to create a default texture for.
  47599. */
  47600. createDefaultTexture( texture ) {
  47601. const { gl, backend, defaultTextures } = this;
  47602. const glTextureType = this.getGLTextureType( texture );
  47603. let textureGPU = defaultTextures[ glTextureType ];
  47604. if ( textureGPU === undefined ) {
  47605. textureGPU = gl.createTexture();
  47606. backend.state.bindTexture( glTextureType, textureGPU );
  47607. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47608. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47609. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47610. defaultTextures[ glTextureType ] = textureGPU;
  47611. }
  47612. backend.set( texture, {
  47613. textureGPU,
  47614. glTextureType
  47615. } );
  47616. }
  47617. /**
  47618. * Defines a texture on the GPU for the given texture object.
  47619. *
  47620. * @param {Texture} texture - The texture.
  47621. * @param {Object} [options={}] - Optional configuration parameter.
  47622. * @return {undefined}
  47623. */
  47624. createTexture( texture, options ) {
  47625. const { gl, backend } = this;
  47626. const { levels, width, height, depth } = options;
  47627. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  47628. const glType = backend.utils.convert( texture.type );
  47629. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  47630. const textureGPU = gl.createTexture();
  47631. const glTextureType = this.getGLTextureType( texture );
  47632. backend.state.bindTexture( glTextureType, textureGPU );
  47633. this.setTextureParameters( glTextureType, texture );
  47634. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  47635. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  47636. } else if ( texture.isData3DTexture ) {
  47637. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  47638. } else if ( ! texture.isVideoTexture ) {
  47639. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  47640. }
  47641. backend.set( texture, {
  47642. textureGPU,
  47643. glTextureType,
  47644. glFormat,
  47645. glType,
  47646. glInternalFormat
  47647. } );
  47648. }
  47649. /**
  47650. * Uploads texture buffer data to the GPU memory.
  47651. *
  47652. * @param {WebGLBuffer} buffer - The buffer data.
  47653. * @param {Texture} texture - The texture,
  47654. */
  47655. copyBufferToTexture( buffer, texture ) {
  47656. const { gl, backend } = this;
  47657. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  47658. const { width, height } = texture.source.data;
  47659. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  47660. backend.state.bindTexture( glTextureType, textureGPU );
  47661. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  47662. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  47663. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  47664. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  47665. backend.state.unbindTexture();
  47666. // debug
  47667. // const framebuffer = gl.createFramebuffer();
  47668. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  47669. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  47670. // const readout = new Float32Array( width * height * 4 );
  47671. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  47672. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  47673. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  47674. // backend.state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47675. // log( readout );
  47676. }
  47677. /**
  47678. * Uploads the updated texture data to the GPU.
  47679. *
  47680. * @param {Texture} texture - The texture.
  47681. * @param {Object} [options={}] - Optional configuration parameter.
  47682. */
  47683. updateTexture( texture, options ) {
  47684. const { gl } = this;
  47685. const { width, height } = options;
  47686. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  47687. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  47688. return;
  47689. this.backend.state.bindTexture( glTextureType, textureGPU );
  47690. this.setTextureParameters( glTextureType, texture );
  47691. if ( texture.isCompressedTexture ) {
  47692. const mipmaps = texture.mipmaps;
  47693. const image = options.image;
  47694. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47695. const mipmap = mipmaps[ i ];
  47696. if ( texture.isCompressedArrayTexture ) {
  47697. if ( texture.format !== gl.RGBA ) {
  47698. if ( glFormat !== null ) {
  47699. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  47700. } else {
  47701. warn( 'WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  47702. }
  47703. } else {
  47704. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  47705. }
  47706. } else {
  47707. if ( glFormat !== null ) {
  47708. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  47709. } else {
  47710. warn( 'WebGLBackend: Unsupported compressed texture format' );
  47711. }
  47712. }
  47713. }
  47714. } else if ( texture.isCubeTexture ) {
  47715. const images = options.images;
  47716. const mipmaps = texture.mipmaps;
  47717. for ( let i = 0; i < 6; i ++ ) {
  47718. const image = getImage( images[ i ] );
  47719. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  47720. for ( let j = 0; j < mipmaps.length; j ++ ) {
  47721. const mipmap = mipmaps[ j ];
  47722. const image = getImage( mipmap.images[ i ] );
  47723. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  47724. }
  47725. }
  47726. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  47727. const image = options.image;
  47728. if ( texture.layerUpdates.size > 0 ) {
  47729. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  47730. for ( const layerIndex of texture.layerUpdates ) {
  47731. const layerData = image.data.subarray(
  47732. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  47733. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  47734. );
  47735. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  47736. }
  47737. texture.clearLayerUpdates();
  47738. } else {
  47739. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47740. }
  47741. } else if ( texture.isData3DTexture ) {
  47742. const image = options.image;
  47743. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  47744. } else if ( texture.isVideoTexture ) {
  47745. texture.update();
  47746. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  47747. } else {
  47748. const mipmaps = texture.mipmaps;
  47749. if ( mipmaps.length > 0 ) {
  47750. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  47751. const mipmap = mipmaps[ i ];
  47752. const image = getImage( mipmap );
  47753. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  47754. }
  47755. } else {
  47756. const image = getImage( options.image );
  47757. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  47758. }
  47759. }
  47760. }
  47761. /**
  47762. * Generates mipmaps for the given texture.
  47763. *
  47764. * @param {Texture} texture - The texture.
  47765. */
  47766. generateMipmaps( texture ) {
  47767. const { gl, backend } = this;
  47768. const { textureGPU, glTextureType } = backend.get( texture );
  47769. backend.state.bindTexture( glTextureType, textureGPU );
  47770. gl.generateMipmap( glTextureType );
  47771. }
  47772. /**
  47773. * Deallocates the render buffers of the given render target.
  47774. *
  47775. * @param {RenderTarget} renderTarget - The render target.
  47776. */
  47777. deallocateRenderBuffers( renderTarget ) {
  47778. const { gl, backend } = this;
  47779. // remove framebuffer reference
  47780. if ( renderTarget ) {
  47781. const renderContextData = backend.get( renderTarget );
  47782. renderContextData.renderBufferStorageSetup = undefined;
  47783. if ( renderContextData.framebuffers ) {
  47784. for ( const cacheKey in renderContextData.framebuffers ) {
  47785. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  47786. }
  47787. delete renderContextData.framebuffers;
  47788. }
  47789. if ( renderContextData.depthRenderbuffer ) {
  47790. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  47791. delete renderContextData.depthRenderbuffer;
  47792. }
  47793. if ( renderContextData.stencilRenderbuffer ) {
  47794. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  47795. delete renderContextData.stencilRenderbuffer;
  47796. }
  47797. if ( renderContextData.msaaFrameBuffer ) {
  47798. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  47799. delete renderContextData.msaaFrameBuffer;
  47800. }
  47801. if ( renderContextData.msaaRenderbuffers ) {
  47802. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  47803. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  47804. }
  47805. delete renderContextData.msaaRenderbuffers;
  47806. }
  47807. }
  47808. }
  47809. /**
  47810. * Destroys the GPU data for the given texture object.
  47811. *
  47812. * @param {Texture} texture - The texture.
  47813. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47814. */
  47815. destroyTexture( texture, isDefaultTexture = false ) {
  47816. const { gl, backend } = this;
  47817. const { textureGPU, renderTarget } = backend.get( texture );
  47818. this.deallocateRenderBuffers( renderTarget );
  47819. if ( isDefaultTexture === false ) {
  47820. gl.deleteTexture( textureGPU );
  47821. }
  47822. backend.delete( texture );
  47823. }
  47824. /**
  47825. * Copies data of the given source texture to the given destination texture.
  47826. *
  47827. * @param {Texture} srcTexture - The source texture.
  47828. * @param {Texture} dstTexture - The destination texture.
  47829. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47830. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47831. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47832. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47833. */
  47834. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47835. const { gl, backend } = this;
  47836. const { state } = this.backend;
  47837. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  47838. state.bindTexture( glTextureType, dstTextureGPU );
  47839. // gather the necessary dimensions to copy
  47840. let width, height, depth, minX, minY, minZ;
  47841. let dstX, dstY, dstZ;
  47842. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  47843. if ( srcRegion !== null ) {
  47844. width = srcRegion.max.x - srcRegion.min.x;
  47845. height = srcRegion.max.y - srcRegion.min.y;
  47846. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  47847. minX = srcRegion.min.x;
  47848. minY = srcRegion.min.y;
  47849. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  47850. } else {
  47851. const levelScale = Math.pow( 2, - srcLevel );
  47852. width = Math.floor( image.width * levelScale );
  47853. height = Math.floor( image.height * levelScale );
  47854. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  47855. depth = image.depth;
  47856. } else if ( srcTexture.isData3DTexture ) {
  47857. depth = Math.floor( image.depth * levelScale );
  47858. } else {
  47859. depth = 1;
  47860. }
  47861. minX = 0;
  47862. minY = 0;
  47863. minZ = 0;
  47864. }
  47865. if ( dstPosition !== null ) {
  47866. dstX = dstPosition.x;
  47867. dstY = dstPosition.y;
  47868. dstZ = dstPosition.z;
  47869. } else {
  47870. dstX = 0;
  47871. dstY = 0;
  47872. dstZ = 0;
  47873. }
  47874. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  47875. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  47876. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  47877. // used for copying data from cpu
  47878. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  47879. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  47880. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  47881. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  47882. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  47883. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  47884. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  47885. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  47886. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  47887. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  47888. // set up the src texture
  47889. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  47890. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  47891. if ( srcTexture.isDepthTexture ) {
  47892. const srcTextureData = backend.get( srcTexture );
  47893. const dstTextureData = backend.get( dstTexture );
  47894. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  47895. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  47896. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  47897. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  47898. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  47899. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  47900. for ( let i = 0; i < depth; i ++ ) {
  47901. // if the source or destination are a 3d target then a layer needs to be bound
  47902. if ( isSrc3D ) {
  47903. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47904. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47905. }
  47906. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  47907. }
  47908. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47909. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47910. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  47911. // get the appropriate frame buffers
  47912. const srcTextureData = backend.get( srcTexture );
  47913. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  47914. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  47915. // bind the frame buffer targets
  47916. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  47917. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  47918. for ( let i = 0; i < depth; i ++ ) {
  47919. // assign the correct layers and mip maps to the frame buffers
  47920. if ( isSrc3D ) {
  47921. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  47922. } else {
  47923. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  47924. }
  47925. if ( isDst3D ) {
  47926. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  47927. } else {
  47928. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  47929. }
  47930. // copy the data using the fastest function that can achieve the copy
  47931. if ( srcLevel !== 0 ) {
  47932. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  47933. } else if ( isDst3D ) {
  47934. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  47935. } else {
  47936. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  47937. }
  47938. }
  47939. // unbind read, draw buffers
  47940. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47941. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47942. } else {
  47943. if ( isDst3D ) {
  47944. // copy data into the 3d texture
  47945. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  47946. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  47947. } else if ( dstTexture.isCompressedArrayTexture ) {
  47948. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  47949. } else {
  47950. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  47951. }
  47952. } else {
  47953. // copy data into the 2d texture
  47954. if ( srcTexture.isDataTexture ) {
  47955. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  47956. } else if ( srcTexture.isCompressedTexture ) {
  47957. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  47958. } else {
  47959. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  47960. }
  47961. }
  47962. }
  47963. // reset values
  47964. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  47965. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  47966. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  47967. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  47968. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  47969. // Generate mipmaps only when copying level 0
  47970. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  47971. gl.generateMipmap( glTextureType );
  47972. }
  47973. state.unbindTexture();
  47974. }
  47975. /**
  47976. * Copies the current bound framebuffer to the given texture.
  47977. *
  47978. * @param {Texture} texture - The destination texture.
  47979. * @param {RenderContext} renderContext - The render context.
  47980. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47981. */
  47982. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47983. const { gl } = this;
  47984. const { state } = this.backend;
  47985. const { textureGPU } = this.backend.get( texture );
  47986. const { x, y, z: width, w: height } = rectangle;
  47987. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  47988. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  47989. if ( requireDrawFrameBuffer ) {
  47990. const partial = ( x !== 0 || y !== 0 );
  47991. let mask;
  47992. let attachment;
  47993. if ( texture.isDepthTexture === true ) {
  47994. mask = gl.DEPTH_BUFFER_BIT;
  47995. attachment = gl.DEPTH_ATTACHMENT;
  47996. if ( renderContext.stencil ) {
  47997. mask |= gl.STENCIL_BUFFER_BIT;
  47998. }
  47999. } else {
  48000. mask = gl.COLOR_BUFFER_BIT;
  48001. attachment = gl.COLOR_ATTACHMENT0;
  48002. }
  48003. if ( partial ) {
  48004. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  48005. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48006. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48007. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48008. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48009. const flippedY = srcHeight - y - height;
  48010. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  48011. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  48012. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  48013. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  48014. state.unbindTexture();
  48015. } else {
  48016. const fb = gl.createFramebuffer();
  48017. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48018. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  48019. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  48020. gl.deleteFramebuffer( fb );
  48021. }
  48022. } else {
  48023. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  48024. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  48025. state.unbindTexture();
  48026. }
  48027. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  48028. this.backend._setFramebuffer( renderContext );
  48029. }
  48030. /**
  48031. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  48032. *
  48033. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  48034. * @param {RenderContext} renderContext - The render context.
  48035. * @param {number} samples - The MSAA sample count.
  48036. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  48037. */
  48038. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  48039. const { gl } = this;
  48040. const renderTarget = renderContext.renderTarget;
  48041. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  48042. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  48043. if ( depthBuffer && ! stencilBuffer ) {
  48044. let glInternalFormat = gl.DEPTH_COMPONENT24;
  48045. if ( useMultisampledRTT === true ) {
  48046. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48047. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  48048. } else if ( samples > 0 ) {
  48049. if ( depthTexture && depthTexture.isDepthTexture ) {
  48050. if ( depthTexture.type === gl.FLOAT ) {
  48051. glInternalFormat = gl.DEPTH_COMPONENT32F;
  48052. }
  48053. }
  48054. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  48055. } else {
  48056. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  48057. }
  48058. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  48059. } else if ( depthBuffer && stencilBuffer ) {
  48060. if ( samples > 0 ) {
  48061. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  48062. } else {
  48063. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  48064. }
  48065. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  48066. }
  48067. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  48068. }
  48069. /**
  48070. * Returns texture data as a typed array.
  48071. *
  48072. * @async
  48073. * @param {Texture} texture - The texture to copy.
  48074. * @param {number} x - The x coordinate of the copy origin.
  48075. * @param {number} y - The y coordinate of the copy origin.
  48076. * @param {number} width - The width of the copy.
  48077. * @param {number} height - The height of the copy.
  48078. * @param {number} faceIndex - The face index.
  48079. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48080. */
  48081. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48082. const { backend, gl } = this;
  48083. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  48084. const fb = gl.createFramebuffer();
  48085. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  48086. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  48087. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  48088. const typedArrayType = this._getTypedArrayType( glType );
  48089. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  48090. const elementCount = width * height;
  48091. const byteLength = elementCount * bytesPerTexel;
  48092. const buffer = gl.createBuffer();
  48093. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  48094. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  48095. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  48096. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  48097. await backend.utils._clientWaitAsync();
  48098. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  48099. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  48100. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  48101. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  48102. backend.state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48103. gl.deleteFramebuffer( fb );
  48104. return dstBuffer;
  48105. }
  48106. /**
  48107. * Returns the corresponding typed array type for the given WebGL data type.
  48108. *
  48109. * @private
  48110. * @param {GLenum} glType - The WebGL data type.
  48111. * @return {TypedArray.constructor} The typed array type.
  48112. */
  48113. _getTypedArrayType( glType ) {
  48114. const { gl } = this;
  48115. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  48116. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  48117. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  48118. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  48119. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  48120. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  48121. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  48122. if ( glType === gl.FLOAT ) return Float32Array;
  48123. throw new Error( `Unsupported WebGL type: ${glType}` );
  48124. }
  48125. /**
  48126. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  48127. *
  48128. * @private
  48129. * @param {GLenum} glType - The WebGL data type.
  48130. * @param {GLenum} glFormat - The WebGL texture format.
  48131. * @return {number} The bytes-per-texel.
  48132. */
  48133. _getBytesPerTexel( glType, glFormat ) {
  48134. const { gl } = this;
  48135. let bytesPerComponent = 0;
  48136. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  48137. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  48138. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  48139. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  48140. glType === gl.UNSIGNED_SHORT ||
  48141. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  48142. if ( glType === gl.UNSIGNED_INT ||
  48143. glType === gl.FLOAT ) bytesPerComponent = 4;
  48144. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  48145. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  48146. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  48147. }
  48148. /**
  48149. * Frees the internal resources.
  48150. */
  48151. dispose() {
  48152. const { gl } = this;
  48153. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  48154. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  48155. }
  48156. }
  48157. function getImage( source ) {
  48158. if ( source.isDataTexture ) {
  48159. return source.image.data;
  48160. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  48161. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  48162. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  48163. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  48164. return source;
  48165. }
  48166. return source.data;
  48167. }
  48168. /**
  48169. * A WebGL 2 backend utility module for managing extensions.
  48170. *
  48171. * @private
  48172. */
  48173. class WebGLExtensions {
  48174. /**
  48175. * Constructs a new utility object.
  48176. *
  48177. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48178. */
  48179. constructor( backend ) {
  48180. /**
  48181. * A reference to the WebGL 2 backend.
  48182. *
  48183. * @type {WebGLBackend}
  48184. */
  48185. this.backend = backend;
  48186. /**
  48187. * A reference to the rendering context.
  48188. *
  48189. * @type {WebGL2RenderingContext}
  48190. */
  48191. this.gl = this.backend.gl;
  48192. /**
  48193. * A list with all the supported WebGL extensions.
  48194. *
  48195. * @type {Array<string>}
  48196. */
  48197. this.availableExtensions = this.gl.getSupportedExtensions();
  48198. /**
  48199. * A dictionary with requested WebGL extensions.
  48200. * The key is the name of the extension, the value
  48201. * the requested extension object.
  48202. *
  48203. * @type {Object<string,Object>}
  48204. */
  48205. this.extensions = {};
  48206. }
  48207. /**
  48208. * Returns the extension object for the given extension name.
  48209. *
  48210. * @param {string} name - The extension name.
  48211. * @return {Object} The extension object.
  48212. */
  48213. get( name ) {
  48214. let extension = this.extensions[ name ];
  48215. if ( extension === undefined ) {
  48216. extension = this.gl.getExtension( name );
  48217. this.extensions[ name ] = extension;
  48218. }
  48219. return extension;
  48220. }
  48221. /**
  48222. * Returns `true` if the requested extension is available.
  48223. *
  48224. * @param {string} name - The extension name.
  48225. * @return {boolean} Whether the given extension is available or not.
  48226. */
  48227. has( name ) {
  48228. return this.availableExtensions.includes( name );
  48229. }
  48230. }
  48231. /**
  48232. * A WebGL 2 backend utility module for managing the device's capabilities.
  48233. *
  48234. * @private
  48235. */
  48236. class WebGLCapabilities {
  48237. /**
  48238. * Constructs a new utility object.
  48239. *
  48240. * @param {WebGLBackend} backend - The WebGL 2 backend.
  48241. */
  48242. constructor( backend ) {
  48243. /**
  48244. * A reference to the WebGL 2 backend.
  48245. *
  48246. * @type {WebGLBackend}
  48247. */
  48248. this.backend = backend;
  48249. /**
  48250. * This value holds the cached max anisotropy value.
  48251. *
  48252. * @type {?number}
  48253. * @default null
  48254. */
  48255. this.maxAnisotropy = null;
  48256. }
  48257. /**
  48258. * Returns the maximum anisotropy texture filtering value. This value
  48259. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  48260. * WebGL extension.
  48261. *
  48262. * @return {number} The maximum anisotropy texture filtering value.
  48263. */
  48264. getMaxAnisotropy() {
  48265. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  48266. const gl = this.backend.gl;
  48267. const extensions = this.backend.extensions;
  48268. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48269. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48270. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  48271. } else {
  48272. this.maxAnisotropy = 0;
  48273. }
  48274. return this.maxAnisotropy;
  48275. }
  48276. }
  48277. const GLFeatureName = {
  48278. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  48279. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  48280. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  48281. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  48282. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  48283. 'WEBGL_compressed_texture_s3tc': 'texture-compression-s3tc',
  48284. 'EXT_texture_compression_bptc': 'texture-compression-bc',
  48285. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  48286. 'OVR_multiview2': 'OVR_multiview2'
  48287. };
  48288. class WebGLBufferRenderer {
  48289. constructor( backend ) {
  48290. this.gl = backend.gl;
  48291. this.extensions = backend.extensions;
  48292. this.info = backend.renderer.info;
  48293. this.mode = null;
  48294. this.index = 0;
  48295. this.type = null;
  48296. this.object = null;
  48297. }
  48298. render( start, count ) {
  48299. const { gl, mode, object, type, info, index } = this;
  48300. if ( index !== 0 ) {
  48301. gl.drawElements( mode, count, type, start );
  48302. } else {
  48303. gl.drawArrays( mode, start, count );
  48304. }
  48305. info.update( object, count, 1 );
  48306. }
  48307. renderInstances( start, count, primcount ) {
  48308. const { gl, mode, type, index, object, info } = this;
  48309. if ( primcount === 0 ) return;
  48310. if ( index !== 0 ) {
  48311. gl.drawElementsInstanced( mode, count, type, start, primcount );
  48312. } else {
  48313. gl.drawArraysInstanced( mode, start, count, primcount );
  48314. }
  48315. info.update( object, count, primcount );
  48316. }
  48317. renderMultiDraw( starts, counts, drawCount ) {
  48318. const { extensions, mode, object, info } = this;
  48319. if ( drawCount === 0 ) return;
  48320. const extension = extensions.get( 'WEBGL_multi_draw' );
  48321. if ( extension === null ) {
  48322. for ( let i = 0; i < drawCount; i ++ ) {
  48323. this.render( starts[ i ], counts[ i ] );
  48324. }
  48325. } else {
  48326. if ( this.index !== 0 ) {
  48327. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  48328. } else {
  48329. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  48330. }
  48331. let elementCount = 0;
  48332. for ( let i = 0; i < drawCount; i ++ ) {
  48333. elementCount += counts[ i ];
  48334. }
  48335. info.update( object, elementCount, 1 );
  48336. }
  48337. }
  48338. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  48339. const { extensions, mode, object, info } = this;
  48340. if ( drawCount === 0 ) return;
  48341. const extension = extensions.get( 'WEBGL_multi_draw' );
  48342. if ( extension === null ) {
  48343. for ( let i = 0; i < drawCount; i ++ ) {
  48344. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  48345. }
  48346. } else {
  48347. if ( this.index !== 0 ) {
  48348. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  48349. } else {
  48350. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  48351. }
  48352. let elementCount = 0;
  48353. for ( let i = 0; i < drawCount; i ++ ) {
  48354. elementCount += counts[ i ] * primcount[ i ];
  48355. }
  48356. info.update( object, elementCount, 1 );
  48357. }
  48358. }
  48359. //
  48360. }
  48361. /**
  48362. * Abstract base class of a timestamp query pool.
  48363. *
  48364. * @abstract
  48365. */
  48366. class TimestampQueryPool {
  48367. /**
  48368. * Creates a new timestamp query pool.
  48369. *
  48370. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  48371. */
  48372. constructor( maxQueries = 256 ) {
  48373. /**
  48374. * Whether to track timestamps or not.
  48375. *
  48376. * @type {boolean}
  48377. * @default true
  48378. */
  48379. this.trackTimestamp = true;
  48380. /**
  48381. * Maximum number of queries this pool can hold.
  48382. *
  48383. * @type {number}
  48384. * @default 256
  48385. */
  48386. this.maxQueries = maxQueries;
  48387. /**
  48388. * How many queries allocated so far.
  48389. *
  48390. * @type {number}
  48391. * @default 0
  48392. */
  48393. this.currentQueryIndex = 0;
  48394. /**
  48395. * Tracks offsets for different contexts.
  48396. *
  48397. * @type {Map<string, number>}
  48398. */
  48399. this.queryOffsets = new Map();
  48400. /**
  48401. * Whether the pool has been disposed or not.
  48402. *
  48403. * @type {boolean}
  48404. * @default false
  48405. */
  48406. this.isDisposed = false;
  48407. /**
  48408. * TODO
  48409. *
  48410. * @type {number}
  48411. * @default 0
  48412. */
  48413. this.lastValue = 0;
  48414. /**
  48415. * Stores all timestamp frames.
  48416. *
  48417. * @type {Array<number>}
  48418. */
  48419. this.frames = [];
  48420. /**
  48421. * TODO
  48422. *
  48423. * @type {boolean}
  48424. * @default false
  48425. */
  48426. this.pendingResolve = false;
  48427. /**
  48428. * Stores the latest timestamp for each render context.
  48429. *
  48430. * @type {Map<string, number>}
  48431. */
  48432. this.timestamps = new Map();
  48433. }
  48434. /**
  48435. * Returns all timestamp frames.
  48436. *
  48437. * @return {Array<number>} The timestamp frames.
  48438. */
  48439. getTimestampFrames() {
  48440. return this.frames;
  48441. }
  48442. /**
  48443. * Returns the timestamp for a given render context.
  48444. *
  48445. * @param {string} uid - A unique identifier for the render context.
  48446. * @return {?number} The timestamp, or undefined if not available.
  48447. */
  48448. getTimestamp( uid ) {
  48449. let timestamp = this.timestamps.get( uid );
  48450. if ( timestamp === undefined ) {
  48451. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  48452. timestamp = 0;
  48453. }
  48454. return timestamp;
  48455. }
  48456. /**
  48457. * Returns whether a timestamp is available for a given render context.
  48458. *
  48459. * @param {string} uid - A unique identifier for the render context.
  48460. * @return {boolean} True if a timestamp is available, false otherwise.
  48461. */
  48462. hasTimestamp( uid ) {
  48463. return this.timestamps.has( uid );
  48464. }
  48465. /**
  48466. * Allocate queries for a specific uid.
  48467. *
  48468. * @abstract
  48469. * @param {string} uid - A unique identifier for the render context.
  48470. * @param {number} frameId - The current frame identifier.
  48471. * @returns {?number}
  48472. */
  48473. allocateQueriesForContext( /* uid, frameId */ ) {}
  48474. /**
  48475. * Resolve all timestamps and return data (or process them).
  48476. *
  48477. * @abstract
  48478. * @async
  48479. * @returns {Promise<number>|number} The resolved timestamp value.
  48480. */
  48481. async resolveQueriesAsync() {}
  48482. /**
  48483. * Dispose of the query pool.
  48484. *
  48485. * @abstract
  48486. */
  48487. dispose() {}
  48488. }
  48489. /**
  48490. * Manages a pool of WebGL timestamp queries for performance measurement.
  48491. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  48492. *
  48493. * @augments TimestampQueryPool
  48494. */
  48495. class WebGLTimestampQueryPool extends TimestampQueryPool {
  48496. /**
  48497. * Creates a new WebGL timestamp query pool.
  48498. *
  48499. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  48500. * @param {string} type - The type identifier for this query pool.
  48501. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48502. */
  48503. constructor( gl, type, maxQueries = 2048 ) {
  48504. super( maxQueries );
  48505. this.gl = gl;
  48506. this.type = type;
  48507. // Check for timer query extensions
  48508. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  48509. gl.getExtension( 'EXT_disjoint_timer_query' );
  48510. if ( ! this.ext ) {
  48511. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  48512. this.trackTimestamp = false;
  48513. return;
  48514. }
  48515. // Create query objects
  48516. this.queries = [];
  48517. for ( let i = 0; i < this.maxQueries; i ++ ) {
  48518. this.queries.push( gl.createQuery() );
  48519. }
  48520. this.activeQuery = null;
  48521. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  48522. }
  48523. /**
  48524. * Allocates a pair of queries for a given render context.
  48525. *
  48526. * @param {string} uid - A unique identifier for the render context.
  48527. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48528. */
  48529. allocateQueriesForContext( uid ) {
  48530. if ( ! this.trackTimestamp ) return null;
  48531. // Check if we have enough space for a new query pair
  48532. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48533. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  48534. return null;
  48535. }
  48536. const baseOffset = this.currentQueryIndex;
  48537. this.currentQueryIndex += 2;
  48538. // Initialize query states
  48539. this.queryStates.set( baseOffset, 'inactive' );
  48540. this.queryOffsets.set( uid, baseOffset );
  48541. return baseOffset;
  48542. }
  48543. /**
  48544. * Begins a timestamp query for the specified render context.
  48545. *
  48546. * @param {string} uid - A unique identifier for the render context.
  48547. */
  48548. beginQuery( uid ) {
  48549. if ( ! this.trackTimestamp || this.isDisposed ) {
  48550. return;
  48551. }
  48552. const baseOffset = this.queryOffsets.get( uid );
  48553. if ( baseOffset == null ) {
  48554. return;
  48555. }
  48556. // Don't start a new query if there's an active one
  48557. if ( this.activeQuery !== null ) {
  48558. return;
  48559. }
  48560. const query = this.queries[ baseOffset ];
  48561. if ( ! query ) {
  48562. return;
  48563. }
  48564. try {
  48565. // Only begin if query is inactive
  48566. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  48567. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  48568. this.activeQuery = baseOffset;
  48569. this.queryStates.set( baseOffset, 'started' );
  48570. }
  48571. } catch ( e ) {
  48572. error( 'Error in beginQuery:', e );
  48573. this.activeQuery = null;
  48574. this.queryStates.set( baseOffset, 'inactive' );
  48575. }
  48576. }
  48577. /**
  48578. * Ends the active timestamp query for the specified render context.
  48579. *
  48580. * @param {string} uid - A unique identifier for the render context.
  48581. */
  48582. endQuery( uid ) {
  48583. if ( ! this.trackTimestamp || this.isDisposed ) {
  48584. return;
  48585. }
  48586. const baseOffset = this.queryOffsets.get( uid );
  48587. if ( baseOffset == null ) {
  48588. return;
  48589. }
  48590. // Only end if this is the active query
  48591. if ( this.activeQuery !== baseOffset ) {
  48592. return;
  48593. }
  48594. try {
  48595. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  48596. this.queryStates.set( baseOffset, 'ended' );
  48597. this.activeQuery = null;
  48598. } catch ( e ) {
  48599. error( 'Error in endQuery:', e );
  48600. // Reset state on error
  48601. this.queryStates.set( baseOffset, 'inactive' );
  48602. this.activeQuery = null;
  48603. }
  48604. }
  48605. /**
  48606. * Asynchronously resolves all completed queries and returns the total duration.
  48607. *
  48608. * @async
  48609. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48610. */
  48611. async resolveQueriesAsync() {
  48612. if ( ! this.trackTimestamp || this.pendingResolve ) {
  48613. return this.lastValue;
  48614. }
  48615. this.pendingResolve = true;
  48616. try {
  48617. // Wait for all ended queries to complete
  48618. const resolvePromises = new Map();
  48619. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  48620. const state = this.queryStates.get( baseOffset );
  48621. if ( state === 'ended' ) {
  48622. const query = this.queries[ baseOffset ];
  48623. resolvePromises.set( uid, this.resolveQuery( query ) );
  48624. }
  48625. }
  48626. if ( resolvePromises.size === 0 ) {
  48627. return this.lastValue;
  48628. }
  48629. //
  48630. const framesDuration = {};
  48631. const frames = [];
  48632. for ( const [ uid, promise ] of resolvePromises ) {
  48633. const match = uid.match( /^(.*):f(\d+)$/ );
  48634. const frame = parseInt( match[ 2 ] );
  48635. if ( frames.includes( frame ) === false ) {
  48636. frames.push( frame );
  48637. }
  48638. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  48639. const duration = await promise;
  48640. this.timestamps.set( uid, duration );
  48641. framesDuration[ frame ] += duration;
  48642. }
  48643. // Return the total duration of the last frame
  48644. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  48645. // Store the last valid result
  48646. this.lastValue = totalDuration;
  48647. this.frames = frames;
  48648. // Reset states
  48649. this.currentQueryIndex = 0;
  48650. this.queryOffsets.clear();
  48651. this.queryStates.clear();
  48652. this.activeQuery = null;
  48653. return totalDuration;
  48654. } catch ( e ) {
  48655. error( 'Error resolving queries:', e );
  48656. return this.lastValue;
  48657. } finally {
  48658. this.pendingResolve = false;
  48659. }
  48660. }
  48661. /**
  48662. * Resolves a single query, checking for completion and disjoint operation.
  48663. *
  48664. * @async
  48665. * @param {WebGLQuery} query - The query object to resolve.
  48666. * @returns {Promise<number>} The elapsed time in milliseconds.
  48667. */
  48668. async resolveQuery( query ) {
  48669. return new Promise( ( resolve ) => {
  48670. if ( this.isDisposed ) {
  48671. resolve( this.lastValue );
  48672. return;
  48673. }
  48674. let timeoutId;
  48675. let isResolved = false;
  48676. const cleanup = () => {
  48677. if ( timeoutId ) {
  48678. clearTimeout( timeoutId );
  48679. timeoutId = null;
  48680. }
  48681. };
  48682. const finalizeResolution = ( value ) => {
  48683. if ( ! isResolved ) {
  48684. isResolved = true;
  48685. cleanup();
  48686. resolve( value );
  48687. }
  48688. };
  48689. const checkQuery = () => {
  48690. if ( this.isDisposed ) {
  48691. finalizeResolution( this.lastValue );
  48692. return;
  48693. }
  48694. try {
  48695. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  48696. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  48697. if ( disjoint ) {
  48698. finalizeResolution( this.lastValue );
  48699. return;
  48700. }
  48701. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  48702. if ( ! available ) {
  48703. timeoutId = setTimeout( checkQuery, 1 );
  48704. return;
  48705. }
  48706. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  48707. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  48708. } catch ( e ) {
  48709. error( 'Error checking query:', e );
  48710. resolve( this.lastValue );
  48711. }
  48712. };
  48713. checkQuery();
  48714. } );
  48715. }
  48716. /**
  48717. * Releases all resources held by this query pool.
  48718. * This includes deleting all query objects and clearing internal state.
  48719. */
  48720. dispose() {
  48721. if ( this.isDisposed ) {
  48722. return;
  48723. }
  48724. this.isDisposed = true;
  48725. if ( ! this.trackTimestamp ) return;
  48726. for ( const query of this.queries ) {
  48727. this.gl.deleteQuery( query );
  48728. }
  48729. this.queries = [];
  48730. this.queryStates.clear();
  48731. this.queryOffsets.clear();
  48732. this.lastValue = 0;
  48733. this.activeQuery = null;
  48734. }
  48735. }
  48736. /**
  48737. * A backend implementation targeting WebGL 2.
  48738. *
  48739. * @private
  48740. * @augments Backend
  48741. */
  48742. class WebGLBackend extends Backend {
  48743. /**
  48744. * WebGLBackend options.
  48745. *
  48746. * @typedef {Object} WebGLBackend~Options
  48747. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48748. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48749. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48750. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48751. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48752. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  48753. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48754. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  48755. */
  48756. /**
  48757. * Constructs a new WebGPU backend.
  48758. *
  48759. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  48760. */
  48761. constructor( parameters = {} ) {
  48762. super( parameters );
  48763. /**
  48764. * This flag can be used for type testing.
  48765. *
  48766. * @type {boolean}
  48767. * @readonly
  48768. * @default true
  48769. */
  48770. this.isWebGLBackend = true;
  48771. /**
  48772. * A reference to a backend module holding shader attribute-related
  48773. * utility functions.
  48774. *
  48775. * @type {?WebGLAttributeUtils}
  48776. * @default null
  48777. */
  48778. this.attributeUtils = null;
  48779. /**
  48780. * A reference to a backend module holding extension-related
  48781. * utility functions.
  48782. *
  48783. * @type {?WebGLExtensions}
  48784. * @default null
  48785. */
  48786. this.extensions = null;
  48787. /**
  48788. * A reference to a backend module holding capability-related
  48789. * utility functions.
  48790. *
  48791. * @type {?WebGLCapabilities}
  48792. * @default null
  48793. */
  48794. this.capabilities = null;
  48795. /**
  48796. * A reference to a backend module holding texture-related
  48797. * utility functions.
  48798. *
  48799. * @type {?WebGLTextureUtils}
  48800. * @default null
  48801. */
  48802. this.textureUtils = null;
  48803. /**
  48804. * A reference to a backend module holding renderer-related
  48805. * utility functions.
  48806. *
  48807. * @type {?WebGLBufferRenderer}
  48808. * @default null
  48809. */
  48810. this.bufferRenderer = null;
  48811. /**
  48812. * A reference to the rendering context.
  48813. *
  48814. * @type {?WebGL2RenderingContext}
  48815. * @default null
  48816. */
  48817. this.gl = null;
  48818. /**
  48819. * A reference to a backend module holding state-related
  48820. * utility functions.
  48821. *
  48822. * @type {?WebGLState}
  48823. * @default null
  48824. */
  48825. this.state = null;
  48826. /**
  48827. * A reference to a backend module holding common
  48828. * utility functions.
  48829. *
  48830. * @type {?WebGLUtils}
  48831. * @default null
  48832. */
  48833. this.utils = null;
  48834. /**
  48835. * Dictionary for caching VAOs.
  48836. *
  48837. * @type {Object<string,WebGLVertexArrayObject>}
  48838. */
  48839. this.vaoCache = {};
  48840. /**
  48841. * Dictionary for caching transform feedback objects.
  48842. *
  48843. * @type {Object<string,WebGLTransformFeedback>}
  48844. */
  48845. this.transformFeedbackCache = {};
  48846. /**
  48847. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  48848. * Only relevant when using compute shaders.
  48849. *
  48850. * @type {boolean}
  48851. * @default false
  48852. */
  48853. this.discard = false;
  48854. /**
  48855. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  48856. * device does not support the extension.
  48857. *
  48858. * @type {?EXTDisjointTimerQueryWebGL2}
  48859. * @default null
  48860. */
  48861. this.disjoint = null;
  48862. /**
  48863. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  48864. * device does not support the extension.
  48865. *
  48866. * @type {?KHRParallelShaderCompile}
  48867. * @default null
  48868. */
  48869. this.parallel = null;
  48870. /**
  48871. * A reference to the current render context.
  48872. *
  48873. * @private
  48874. * @type {RenderContext}
  48875. * @default null
  48876. */
  48877. this._currentContext = null;
  48878. /**
  48879. * A unique collection of bindings.
  48880. *
  48881. * @private
  48882. * @type {WeakSet<Array<BindGroup>>}
  48883. */
  48884. this._knownBindings = new WeakSet();
  48885. /**
  48886. * Whether the device supports framebuffers invalidation or not.
  48887. *
  48888. * @private
  48889. * @type {boolean}
  48890. */
  48891. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48892. /**
  48893. * The target framebuffer when rendering with
  48894. * the WebXR device API.
  48895. *
  48896. * @private
  48897. * @type {?WebGLFramebuffer}
  48898. * @default null
  48899. */
  48900. this._xrFramebuffer = null;
  48901. }
  48902. /**
  48903. * Initializes the backend so it is ready for usage.
  48904. *
  48905. * @param {Renderer} renderer - The renderer.
  48906. */
  48907. init( renderer ) {
  48908. super.init( renderer );
  48909. //
  48910. const parameters = this.parameters;
  48911. const contextAttributes = {
  48912. antialias: renderer.currentSamples > 0,
  48913. alpha: true, // always true for performance reasons
  48914. depth: renderer.depth,
  48915. stencil: renderer.stencil
  48916. };
  48917. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  48918. function onContextLost( event ) {
  48919. event.preventDefault();
  48920. const contextLossInfo = {
  48921. api: 'WebGL',
  48922. message: event.statusMessage || 'Unknown reason',
  48923. reason: null,
  48924. originalEvent: event
  48925. };
  48926. renderer.onDeviceLost( contextLossInfo );
  48927. }
  48928. this._onContextLost = onContextLost;
  48929. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  48930. this.gl = glContext;
  48931. this.extensions = new WebGLExtensions( this );
  48932. this.capabilities = new WebGLCapabilities( this );
  48933. this.attributeUtils = new WebGLAttributeUtils( this );
  48934. this.textureUtils = new WebGLTextureUtils( this );
  48935. this.bufferRenderer = new WebGLBufferRenderer( this );
  48936. this.state = new WebGLState( this );
  48937. this.utils = new WebGLUtils( this );
  48938. this.extensions.get( 'EXT_color_buffer_float' );
  48939. this.extensions.get( 'WEBGL_clip_cull_distance' );
  48940. this.extensions.get( 'OES_texture_float_linear' );
  48941. this.extensions.get( 'EXT_color_buffer_half_float' );
  48942. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  48943. this.extensions.get( 'WEBGL_render_shared_exponent' );
  48944. this.extensions.get( 'WEBGL_multi_draw' );
  48945. this.extensions.get( 'OVR_multiview2' );
  48946. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  48947. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  48948. this.drawBuffersIndexedExt = this.extensions.get( 'OES_draw_buffers_indexed' );
  48949. }
  48950. /**
  48951. * The coordinate system of the backend.
  48952. *
  48953. * @type {number}
  48954. * @readonly
  48955. */
  48956. get coordinateSystem() {
  48957. return WebGLCoordinateSystem;
  48958. }
  48959. /**
  48960. * This method performs a readback operation by moving buffer data from
  48961. * a storage buffer attribute from the GPU to the CPU.
  48962. *
  48963. * @async
  48964. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48965. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48966. */
  48967. async getArrayBufferAsync( attribute ) {
  48968. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48969. }
  48970. /**
  48971. * Ensures the backend is XR compatible.
  48972. *
  48973. * @async
  48974. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  48975. */
  48976. async makeXRCompatible() {
  48977. const attributes = this.gl.getContextAttributes();
  48978. if ( attributes.xrCompatible !== true ) {
  48979. await this.gl.makeXRCompatible();
  48980. }
  48981. }
  48982. /**
  48983. * Sets the XR rendering destination.
  48984. *
  48985. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  48986. */
  48987. setXRTarget( xrFramebuffer ) {
  48988. this._xrFramebuffer = xrFramebuffer;
  48989. }
  48990. /**
  48991. * Configures the given XR render target with external textures.
  48992. *
  48993. * This method is only relevant when using the WebXR Layers API.
  48994. *
  48995. * @param {XRRenderTarget} renderTarget - The XR render target.
  48996. * @param {WebGLTexture} colorTexture - A native color texture.
  48997. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  48998. */
  48999. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  49000. const gl = this.gl;
  49001. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  49002. if ( depthTexture !== null ) {
  49003. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  49004. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  49005. // The multisample_render_to_texture extension doesn't work properly if there
  49006. // are midframe flushes and an external depth texture.
  49007. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  49008. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  49009. }
  49010. renderTarget._autoAllocateDepthBuffer = false;
  49011. }
  49012. }
  49013. /**
  49014. * Inits a time stamp query for the given render context.
  49015. *
  49016. * @param {string} type - The type of the timestamp query.
  49017. * @param {string} uid - A unique identifier for the timestamp query.
  49018. */
  49019. initTimestampQuery( type, uid ) {
  49020. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  49021. if ( ! this.timestampQueryPool[ type ] ) {
  49022. // TODO: Variable maxQueries?
  49023. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  49024. }
  49025. const timestampQueryPool = this.timestampQueryPool[ type ];
  49026. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  49027. if ( baseOffset !== null ) {
  49028. timestampQueryPool.beginQuery( uid );
  49029. }
  49030. }
  49031. // timestamp utils
  49032. /**
  49033. * Prepares the timestamp buffer.
  49034. *
  49035. * @param {string} type - The type of the timestamp query.
  49036. * @param {string} uid - A unique identifier for the timestamp query.
  49037. */
  49038. prepareTimestampBuffer( type, uid ) {
  49039. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  49040. const timestampQueryPool = this.timestampQueryPool[ type ];
  49041. timestampQueryPool.endQuery( uid );
  49042. }
  49043. /**
  49044. * Returns the backend's rendering context.
  49045. *
  49046. * @return {WebGL2RenderingContext} The rendering context.
  49047. */
  49048. getContext() {
  49049. return this.gl;
  49050. }
  49051. /**
  49052. * This method is executed at the beginning of a render call and prepares
  49053. * the WebGL state for upcoming render calls
  49054. *
  49055. * @param {RenderContext} renderContext - The render context.
  49056. */
  49057. beginRender( renderContext ) {
  49058. const { state } = this;
  49059. const renderContextData = this.get( renderContext );
  49060. //
  49061. if ( renderContext.viewport ) {
  49062. this.updateViewport( renderContext );
  49063. } else {
  49064. const { width, height } = this.getDrawingBufferSize();
  49065. state.viewport( 0, 0, width, height );
  49066. }
  49067. if ( renderContext.scissor ) {
  49068. const { x, y, width, height } = renderContext.scissorValue;
  49069. state.scissor( x, renderContext.height - height - y, width, height );
  49070. }
  49071. //
  49072. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  49073. renderContextData.previousContext = this._currentContext;
  49074. this._currentContext = renderContext;
  49075. this._setFramebuffer( renderContext );
  49076. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  49077. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49078. if ( occlusionQueryCount > 0 ) {
  49079. // Get a reference to the array of objects with queries. The renderContextData property
  49080. // can be changed by another render pass before the async reading of all previous queries complete
  49081. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  49082. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  49083. renderContextData.lastOcclusionObject = null;
  49084. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  49085. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  49086. renderContextData.occlusionQueryIndex = 0;
  49087. }
  49088. }
  49089. /**
  49090. * This method is executed at the end of a render call and finalizes work
  49091. * after draw calls.
  49092. *
  49093. * @param {RenderContext} renderContext - The render context.
  49094. */
  49095. finishRender( renderContext ) {
  49096. const { gl, state } = this;
  49097. const renderContextData = this.get( renderContext );
  49098. const previousContext = renderContextData.previousContext;
  49099. state.resetVertexState();
  49100. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49101. if ( occlusionQueryCount > 0 ) {
  49102. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  49103. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49104. }
  49105. this.resolveOccludedAsync( renderContext );
  49106. }
  49107. const textures = renderContext.textures;
  49108. if ( textures !== null ) {
  49109. for ( let i = 0; i < textures.length; i ++ ) {
  49110. const texture = textures[ i ];
  49111. if ( texture.generateMipmaps ) {
  49112. this.generateMipmaps( texture );
  49113. }
  49114. }
  49115. }
  49116. this._currentContext = previousContext;
  49117. this._resolveRenderTarget( renderContext );
  49118. if ( previousContext !== null ) {
  49119. this._setFramebuffer( previousContext );
  49120. if ( previousContext.viewport ) {
  49121. this.updateViewport( previousContext );
  49122. } else {
  49123. const { width, height } = this.getDrawingBufferSize();
  49124. state.viewport( 0, 0, width, height );
  49125. }
  49126. }
  49127. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  49128. }
  49129. /**
  49130. * This method processes the result of occlusion queries and writes it
  49131. * into render context data.
  49132. *
  49133. * @async
  49134. * @param {RenderContext} renderContext - The render context.
  49135. */
  49136. resolveOccludedAsync( renderContext ) {
  49137. const renderContextData = this.get( renderContext );
  49138. // handle occlusion query results
  49139. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  49140. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  49141. const occluded = new WeakSet();
  49142. const { gl } = this;
  49143. renderContextData.currentOcclusionQueryObjects = null;
  49144. renderContextData.currentOcclusionQueries = null;
  49145. const check = () => {
  49146. let completed = 0;
  49147. // check all queries and requeue as appropriate
  49148. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  49149. const query = currentOcclusionQueries[ i ];
  49150. if ( query === null ) continue;
  49151. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  49152. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  49153. currentOcclusionQueries[ i ] = null;
  49154. gl.deleteQuery( query );
  49155. completed ++;
  49156. }
  49157. }
  49158. if ( completed < currentOcclusionQueries.length ) {
  49159. requestAnimationFrame( check );
  49160. } else {
  49161. renderContextData.occluded = occluded;
  49162. }
  49163. };
  49164. check();
  49165. }
  49166. }
  49167. /**
  49168. * Returns `true` if the given 3D object is fully occluded by other
  49169. * 3D objects in the scene.
  49170. *
  49171. * @param {RenderContext} renderContext - The render context.
  49172. * @param {Object3D} object - The 3D object to test.
  49173. * @return {boolean} Whether the 3D object is fully occluded or not.
  49174. */
  49175. isOccluded( renderContext, object ) {
  49176. const renderContextData = this.get( renderContext );
  49177. return renderContextData.occluded && renderContextData.occluded.has( object );
  49178. }
  49179. /**
  49180. * Updates the viewport with the values from the given render context.
  49181. *
  49182. * @param {RenderContext} renderContext - The render context.
  49183. */
  49184. updateViewport( renderContext ) {
  49185. const { state } = this;
  49186. const { x, y, width, height } = renderContext.viewportValue;
  49187. state.viewport( x, renderContext.height - height - y, width, height );
  49188. }
  49189. /**
  49190. * Defines the scissor test.
  49191. *
  49192. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  49193. */
  49194. setScissorTest( boolean ) {
  49195. const state = this.state;
  49196. state.setScissorTest( boolean );
  49197. }
  49198. /**
  49199. * Returns the clear color and alpha into a single
  49200. * color object.
  49201. *
  49202. * @return {Color4} The clear color.
  49203. */
  49204. getClearColor() {
  49205. const clearColor = super.getClearColor();
  49206. // Since the canvas is always created with alpha: true,
  49207. // WebGL must always premultiply the clear color.
  49208. clearColor.r *= clearColor.a;
  49209. clearColor.g *= clearColor.a;
  49210. clearColor.b *= clearColor.a;
  49211. return clearColor;
  49212. }
  49213. /**
  49214. * Performs a clear operation.
  49215. *
  49216. * @param {boolean} color - Whether the color buffer should be cleared or not.
  49217. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  49218. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  49219. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  49220. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  49221. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  49222. * or not. Only relevant for explicit clears.
  49223. */
  49224. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  49225. const { gl, renderer } = this;
  49226. if ( descriptor === null ) {
  49227. const clearColor = this.getClearColor();
  49228. descriptor = {
  49229. textures: null,
  49230. clearColorValue: clearColor
  49231. };
  49232. }
  49233. //
  49234. let clear = 0;
  49235. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  49236. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  49237. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  49238. if ( clear !== 0 ) {
  49239. let clearColor;
  49240. if ( descriptor.clearColorValue ) {
  49241. clearColor = descriptor.clearColorValue;
  49242. } else {
  49243. clearColor = this.getClearColor();
  49244. }
  49245. const clearDepth = renderer.getClearDepth();
  49246. const clearStencil = renderer.getClearStencil();
  49247. if ( depth ) this.state.setDepthMask( true );
  49248. if ( descriptor.textures === null ) {
  49249. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  49250. gl.clear( clear );
  49251. } else {
  49252. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  49253. if ( color ) {
  49254. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  49255. if ( i === 0 ) {
  49256. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  49257. } else {
  49258. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  49259. }
  49260. }
  49261. }
  49262. if ( depth && stencil ) {
  49263. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  49264. } else if ( depth ) {
  49265. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  49266. } else if ( stencil ) {
  49267. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  49268. }
  49269. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  49270. }
  49271. }
  49272. }
  49273. /**
  49274. * This method is executed at the beginning of a compute call and
  49275. * prepares the state for upcoming compute tasks.
  49276. *
  49277. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49278. */
  49279. beginCompute( computeGroup ) {
  49280. const { state, gl } = this;
  49281. //
  49282. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  49283. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49284. }
  49285. /**
  49286. * Executes a compute command for the given compute node.
  49287. *
  49288. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  49289. * @param {Node} computeNode - The compute node.
  49290. * @param {Array<BindGroup>} bindings - The bindings.
  49291. * @param {ComputePipeline} pipeline - The compute pipeline.
  49292. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  49293. */
  49294. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  49295. const { state, gl } = this;
  49296. if ( this.discard === false ) {
  49297. // required here to handle async behaviour of render.compute()
  49298. state.enable( gl.RASTERIZER_DISCARD );
  49299. this.discard = true;
  49300. }
  49301. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  49302. const vaoKey = this._getVaoKey( attributes );
  49303. const vaoGPU = this.vaoCache[ vaoKey ];
  49304. if ( vaoGPU === undefined ) {
  49305. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  49306. } else {
  49307. state.setVertexState( vaoGPU );
  49308. }
  49309. state.useProgram( programGPU );
  49310. this._bindUniforms( bindings );
  49311. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  49312. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  49313. gl.beginTransformFeedback( gl.POINTS );
  49314. count = ( count !== null ) ? count : computeNode.count;
  49315. if ( Array.isArray( count ) ) {
  49316. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  49317. count = count[ 0 ];
  49318. } else if ( count && typeof count === 'object' && count.isIndirectStorageBufferAttribute ) {
  49319. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute' );
  49320. count = computeNode.count;
  49321. }
  49322. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  49323. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  49324. } else {
  49325. gl.drawArrays( gl.POINTS, 0, count );
  49326. }
  49327. gl.endTransformFeedback();
  49328. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  49329. // switch active buffers
  49330. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  49331. const dualAttributeData = transformBuffers[ i ];
  49332. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  49333. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  49334. }
  49335. dualAttributeData.switchBuffers();
  49336. }
  49337. }
  49338. /**
  49339. * This method is executed at the end of a compute call and
  49340. * finalizes work after compute tasks.
  49341. *
  49342. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49343. */
  49344. finishCompute( computeGroup ) {
  49345. const { state, gl } = this;
  49346. this.discard = false;
  49347. state.disable( gl.RASTERIZER_DISCARD );
  49348. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  49349. if ( this._currentContext ) {
  49350. this._setFramebuffer( this._currentContext );
  49351. }
  49352. }
  49353. /**
  49354. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49355. *
  49356. * @param {RenderContext} renderContext - The render context.
  49357. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49358. *
  49359. * @private
  49360. */
  49361. _isRenderCameraDepthArray( renderContext ) {
  49362. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  49363. }
  49364. /**
  49365. * Executes a draw command for the given render object.
  49366. *
  49367. * @param {RenderObject} renderObject - The render object to draw.
  49368. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49369. */
  49370. draw( renderObject/*, info*/ ) {
  49371. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  49372. const { programGPU } = this.get( pipeline );
  49373. const { gl, state } = this;
  49374. const contextData = this.get( context );
  49375. const drawParams = renderObject.getDrawParameters();
  49376. if ( drawParams === null ) return;
  49377. //
  49378. this._bindUniforms( renderObject.getBindings() );
  49379. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  49380. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  49381. if ( context.mrt !== null && context.textures !== null ) {
  49382. state.setMRTBlending( context.textures, context.mrt, material );
  49383. }
  49384. state.useProgram( programGPU );
  49385. // vertex state
  49386. const attributes = renderObject.getAttributes();
  49387. const attributesData = this.get( attributes );
  49388. let vaoGPU = attributesData.vaoGPU;
  49389. if ( vaoGPU === undefined ) {
  49390. const vaoKey = this._getVaoKey( attributes );
  49391. vaoGPU = this.vaoCache[ vaoKey ];
  49392. if ( vaoGPU === undefined ) {
  49393. vaoGPU = this._createVao( attributes );
  49394. this.vaoCache[ vaoKey ] = vaoGPU;
  49395. attributesData.vaoGPU = vaoGPU;
  49396. }
  49397. }
  49398. const index = renderObject.getIndex();
  49399. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  49400. state.setVertexState( vaoGPU, indexGPU );
  49401. //
  49402. const lastObject = contextData.lastOcclusionObject;
  49403. if ( lastObject !== object && lastObject !== undefined ) {
  49404. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49405. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  49406. contextData.occlusionQueryIndex ++;
  49407. }
  49408. if ( object.occlusionTest === true ) {
  49409. const query = gl.createQuery();
  49410. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  49411. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  49412. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  49413. }
  49414. contextData.lastOcclusionObject = object;
  49415. }
  49416. //
  49417. const renderer = this.bufferRenderer;
  49418. if ( object.isPoints ) renderer.mode = gl.POINTS;
  49419. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  49420. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  49421. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  49422. else {
  49423. if ( material.wireframe === true ) {
  49424. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  49425. renderer.mode = gl.LINES;
  49426. } else {
  49427. renderer.mode = gl.TRIANGLES;
  49428. }
  49429. }
  49430. //
  49431. const { vertexCount, instanceCount } = drawParams;
  49432. let { firstVertex } = drawParams;
  49433. renderer.object = object;
  49434. if ( index !== null ) {
  49435. firstVertex *= index.array.BYTES_PER_ELEMENT;
  49436. const indexData = this.get( index );
  49437. renderer.index = index.count;
  49438. renderer.type = indexData.type;
  49439. } else {
  49440. renderer.index = 0;
  49441. }
  49442. const draw = () => {
  49443. if ( object.isBatchedMesh ) {
  49444. if ( object._multiDrawInstances !== null ) {
  49445. // @deprecated, r174
  49446. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49447. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  49448. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  49449. warnOnce( 'WebGLBackend: WEBGL_multi_draw not supported.' );
  49450. } else {
  49451. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  49452. }
  49453. } else if ( instanceCount > 1 ) {
  49454. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  49455. } else {
  49456. renderer.render( firstVertex, vertexCount );
  49457. }
  49458. };
  49459. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  49460. const cameraData = this.get( renderObject.camera );
  49461. const cameras = renderObject.camera.cameras;
  49462. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  49463. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49464. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49465. const indexesGPU = [];
  49466. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49467. const bufferGPU = gl.createBuffer();
  49468. data[ 0 ] = i;
  49469. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49470. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  49471. indexesGPU.push( bufferGPU );
  49472. }
  49473. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49474. }
  49475. const cameraIndexData = this.get( cameraIndex );
  49476. const pixelRatio = this.renderer.getPixelRatio();
  49477. const renderTarget = this._currentContext.renderTarget;
  49478. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  49479. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  49480. if ( isRenderCameraDepthArray ) {
  49481. // Clear the depth texture
  49482. const textureData = this.get( renderTarget.depthTexture );
  49483. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  49484. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  49485. const { stencilBuffer } = renderTarget;
  49486. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49487. this.renderer._activeCubeFace = i;
  49488. this._currentContext.activeCubeFace = i;
  49489. this._setFramebuffer( this._currentContext );
  49490. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  49491. }
  49492. this.renderer._activeCubeFace = prevActiveCubeFace;
  49493. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49494. }
  49495. }
  49496. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49497. const subCamera = cameras[ i ];
  49498. if ( object.layers.test( subCamera.layers ) ) {
  49499. if ( isRenderCameraDepthArray ) {
  49500. // Update the active layer
  49501. this.renderer._activeCubeFace = i;
  49502. this._currentContext.activeCubeFace = i;
  49503. this._setFramebuffer( this._currentContext );
  49504. }
  49505. const vp = subCamera.viewport;
  49506. if ( vp !== undefined ) {
  49507. const x = vp.x * pixelRatio;
  49508. const y = vp.y * pixelRatio;
  49509. const width = vp.width * pixelRatio;
  49510. const height = vp.height * pixelRatio;
  49511. state.viewport(
  49512. Math.floor( x ),
  49513. Math.floor( renderObject.context.height - height - y ),
  49514. Math.floor( width ),
  49515. Math.floor( height )
  49516. );
  49517. }
  49518. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  49519. draw();
  49520. }
  49521. this._currentContext.activeCubeFace = prevActiveCubeFace;
  49522. this.renderer._activeCubeFace = prevActiveCubeFace;
  49523. }
  49524. } else {
  49525. draw();
  49526. }
  49527. }
  49528. /**
  49529. * Explain why always null is returned.
  49530. *
  49531. * @param {RenderObject} renderObject - The render object.
  49532. * @return {boolean} Whether the render pipeline requires an update or not.
  49533. */
  49534. needsRenderUpdate( /*renderObject*/ ) {
  49535. return false;
  49536. }
  49537. /**
  49538. * Explain why no cache key is computed.
  49539. *
  49540. * @param {RenderObject} renderObject - The render object.
  49541. * @return {string} The cache key.
  49542. */
  49543. getRenderCacheKey( /*renderObject*/ ) {
  49544. return '';
  49545. }
  49546. // textures
  49547. /**
  49548. * Creates a default texture for the given texture that can be used
  49549. * as a placeholder until the actual texture is ready for usage.
  49550. *
  49551. * @param {Texture} texture - The texture to create a default texture for.
  49552. */
  49553. createDefaultTexture( texture ) {
  49554. this.textureUtils.createDefaultTexture( texture );
  49555. }
  49556. /**
  49557. * Defines a texture on the GPU for the given texture object.
  49558. *
  49559. * @param {Texture} texture - The texture.
  49560. * @param {Object} [options={}] - Optional configuration parameter.
  49561. */
  49562. createTexture( texture, options ) {
  49563. this.textureUtils.createTexture( texture, options );
  49564. }
  49565. /**
  49566. * Uploads the updated texture data to the GPU.
  49567. *
  49568. * @param {Texture} texture - The texture.
  49569. * @param {Object} [options={}] - Optional configuration parameter.
  49570. */
  49571. updateTexture( texture, options ) {
  49572. this.textureUtils.updateTexture( texture, options );
  49573. }
  49574. /**
  49575. * Generates mipmaps for the given texture.
  49576. *
  49577. * @param {Texture} texture - The texture.
  49578. */
  49579. generateMipmaps( texture ) {
  49580. this.textureUtils.generateMipmaps( texture );
  49581. }
  49582. /**
  49583. * Destroys the GPU data for the given texture object.
  49584. *
  49585. * @param {Texture} texture - The texture.
  49586. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49587. */
  49588. destroyTexture( texture, isDefaultTexture = false ) {
  49589. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  49590. }
  49591. /**
  49592. * Returns texture data as a typed array.
  49593. *
  49594. * @async
  49595. * @param {Texture} texture - The texture to copy.
  49596. * @param {number} x - The x coordinate of the copy origin.
  49597. * @param {number} y - The y coordinate of the copy origin.
  49598. * @param {number} width - The width of the copy.
  49599. * @param {number} height - The height of the copy.
  49600. * @param {number} faceIndex - The face index.
  49601. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49602. */
  49603. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49604. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49605. }
  49606. /**
  49607. * This method does nothing since WebGL 2 has no concept of samplers.
  49608. *
  49609. * @param {Texture} texture - The texture to update the sampler for.
  49610. * @return {string} The current sampler key.
  49611. */
  49612. updateSampler( /*texture*/ ) {
  49613. return '';
  49614. }
  49615. // node builder
  49616. /**
  49617. * Returns a node builder for the given render object.
  49618. *
  49619. * @param {RenderObject} object - The render object.
  49620. * @param {Renderer} renderer - The renderer.
  49621. * @return {GLSLNodeBuilder} The node builder.
  49622. */
  49623. createNodeBuilder( object, renderer ) {
  49624. return new GLSLNodeBuilder( object, renderer );
  49625. }
  49626. // program
  49627. /**
  49628. * Creates a shader program from the given programmable stage.
  49629. *
  49630. * @param {ProgrammableStage} program - The programmable stage.
  49631. */
  49632. createProgram( program ) {
  49633. const gl = this.gl;
  49634. const { stage, code } = program;
  49635. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  49636. gl.shaderSource( shader, code );
  49637. gl.compileShader( shader );
  49638. this.set( program, {
  49639. shaderGPU: shader
  49640. } );
  49641. }
  49642. /**
  49643. * Destroys the shader program of the given programmable stage.
  49644. *
  49645. * @param {ProgrammableStage} program - The programmable stage.
  49646. */
  49647. destroyProgram( program ) {
  49648. this.delete( program );
  49649. }
  49650. /**
  49651. * Creates a render pipeline for the given render object.
  49652. *
  49653. * @param {RenderObject} renderObject - The render object.
  49654. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49655. */
  49656. createRenderPipeline( renderObject, promises ) {
  49657. const gl = this.gl;
  49658. const pipeline = renderObject.pipeline;
  49659. // Program
  49660. const { fragmentProgram, vertexProgram } = pipeline;
  49661. const programGPU = gl.createProgram();
  49662. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49663. const vertexShader = this.get( vertexProgram ).shaderGPU;
  49664. gl.attachShader( programGPU, fragmentShader );
  49665. gl.attachShader( programGPU, vertexShader );
  49666. gl.linkProgram( programGPU );
  49667. this.set( pipeline, {
  49668. programGPU,
  49669. fragmentShader,
  49670. vertexShader
  49671. } );
  49672. if ( promises !== null && this.parallel ) {
  49673. const p = new Promise( ( resolve /*, reject*/ ) => {
  49674. const parallel = this.parallel;
  49675. const checkStatus = () => {
  49676. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  49677. this._completeCompile( renderObject, pipeline );
  49678. resolve();
  49679. } else {
  49680. requestAnimationFrame( checkStatus );
  49681. }
  49682. };
  49683. checkStatus();
  49684. } );
  49685. promises.push( p );
  49686. return;
  49687. }
  49688. this._completeCompile( renderObject, pipeline );
  49689. }
  49690. /**
  49691. * Formats the source code of error messages.
  49692. *
  49693. * @private
  49694. * @param {string} string - The code.
  49695. * @param {number} errorLine - The error line.
  49696. * @return {string} The formatted code.
  49697. */
  49698. _handleSource( string, errorLine ) {
  49699. const lines = string.split( '\n' );
  49700. const lines2 = [];
  49701. const from = Math.max( errorLine - 6, 0 );
  49702. const to = Math.min( errorLine + 6, lines.length );
  49703. for ( let i = from; i < to; i ++ ) {
  49704. const line = i + 1;
  49705. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  49706. }
  49707. return lines2.join( '\n' );
  49708. }
  49709. /**
  49710. * Gets the shader compilation errors from the info log.
  49711. *
  49712. * @private
  49713. * @param {WebGL2RenderingContext} gl - The rendering context.
  49714. * @param {WebGLShader} shader - The WebGL shader object.
  49715. * @param {string} type - The shader type.
  49716. * @return {string} The shader errors.
  49717. */
  49718. _getShaderErrors( gl, shader, type ) {
  49719. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  49720. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  49721. const errors = shaderInfoLog.trim();
  49722. if ( status && errors === '' ) return '';
  49723. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  49724. if ( errorMatches ) {
  49725. const errorLine = parseInt( errorMatches[ 1 ] );
  49726. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  49727. } else {
  49728. return errors;
  49729. }
  49730. }
  49731. /**
  49732. * Logs shader compilation errors.
  49733. *
  49734. * @private
  49735. * @param {WebGLProgram} programGPU - The WebGL program.
  49736. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  49737. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  49738. */
  49739. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  49740. if ( this.renderer.debug.checkShaderErrors ) {
  49741. const gl = this.gl;
  49742. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  49743. const programLog = programInfoLog.trim();
  49744. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49745. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  49746. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  49747. } else {
  49748. // default error reporting
  49749. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  49750. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  49751. error(
  49752. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  49753. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  49754. 'Program Info Log: ' + programLog + '\n' +
  49755. vertexErrors + '\n' +
  49756. fragmentErrors
  49757. );
  49758. }
  49759. } else if ( programLog !== '' ) {
  49760. warn( 'WebGLProgram: Program Info Log:', programLog );
  49761. }
  49762. }
  49763. }
  49764. /**
  49765. * Completes the shader program setup for the given render object.
  49766. *
  49767. * @private
  49768. * @param {RenderObject} renderObject - The render object.
  49769. * @param {RenderPipeline} pipeline - The render pipeline.
  49770. */
  49771. _completeCompile( renderObject, pipeline ) {
  49772. const { state, gl } = this;
  49773. const pipelineData = this.get( pipeline );
  49774. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  49775. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49776. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49777. }
  49778. state.useProgram( programGPU );
  49779. // Bindings
  49780. const bindings = renderObject.getBindings();
  49781. this._setupBindings( bindings, programGPU );
  49782. //
  49783. this.set( pipeline, {
  49784. programGPU
  49785. } );
  49786. }
  49787. /**
  49788. * Creates a compute pipeline for the given compute node.
  49789. *
  49790. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49791. * @param {Array<BindGroup>} bindings - The bindings.
  49792. */
  49793. createComputePipeline( computePipeline, bindings ) {
  49794. const { state, gl } = this;
  49795. // Program
  49796. const fragmentProgram = {
  49797. stage: 'fragment',
  49798. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  49799. };
  49800. this.createProgram( fragmentProgram );
  49801. const { computeProgram } = computePipeline;
  49802. const programGPU = gl.createProgram();
  49803. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  49804. const vertexShader = this.get( computeProgram ).shaderGPU;
  49805. const transforms = computeProgram.transforms;
  49806. const transformVaryingNames = [];
  49807. const transformAttributeNodes = [];
  49808. for ( let i = 0; i < transforms.length; i ++ ) {
  49809. const transform = transforms[ i ];
  49810. transformVaryingNames.push( transform.varyingName );
  49811. transformAttributeNodes.push( transform.attributeNode );
  49812. }
  49813. gl.attachShader( programGPU, fragmentShader );
  49814. gl.attachShader( programGPU, vertexShader );
  49815. gl.transformFeedbackVaryings(
  49816. programGPU,
  49817. transformVaryingNames,
  49818. gl.SEPARATE_ATTRIBS
  49819. );
  49820. gl.linkProgram( programGPU );
  49821. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  49822. this._logProgramError( programGPU, fragmentShader, vertexShader );
  49823. }
  49824. state.useProgram( programGPU );
  49825. // Bindings
  49826. this._setupBindings( bindings, programGPU );
  49827. const attributeNodes = computeProgram.attributes;
  49828. const attributes = [];
  49829. const transformBuffers = [];
  49830. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  49831. const attribute = attributeNodes[ i ].node.attribute;
  49832. attributes.push( attribute );
  49833. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49834. }
  49835. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  49836. const attribute = transformAttributeNodes[ i ].attribute;
  49837. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49838. const attributeData = this.get( attribute );
  49839. transformBuffers.push( attributeData );
  49840. }
  49841. //
  49842. this.set( computePipeline, {
  49843. programGPU,
  49844. transformBuffers,
  49845. attributes
  49846. } );
  49847. }
  49848. /**
  49849. * Creates bindings from the given bind group definition.
  49850. *
  49851. * @param {BindGroup} bindGroup - The bind group.
  49852. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49853. * @param {number} cacheIndex - The cache index.
  49854. * @param {number} version - The version.
  49855. */
  49856. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  49857. if ( this._knownBindings.has( bindings ) === false ) {
  49858. this._knownBindings.add( bindings );
  49859. let uniformBuffers = 0;
  49860. let textures = 0;
  49861. for ( const bindGroup of bindings ) {
  49862. this.set( bindGroup, {
  49863. textures: textures,
  49864. uniformBuffers: uniformBuffers
  49865. } );
  49866. for ( const binding of bindGroup.bindings ) {
  49867. if ( binding.isUniformBuffer ) uniformBuffers ++;
  49868. if ( binding.isSampledTexture ) textures ++;
  49869. }
  49870. }
  49871. }
  49872. this.updateBindings( bindGroup, bindings );
  49873. }
  49874. /**
  49875. * Updates the given bind group definition.
  49876. *
  49877. * @param {BindGroup} bindGroup - The bind group.
  49878. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49879. * @param {number} cacheIndex - The cache index.
  49880. * @param {number} version - The version.
  49881. */
  49882. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  49883. const { gl } = this;
  49884. const bindGroupData = this.get( bindGroup );
  49885. let i = bindGroupData.uniformBuffers;
  49886. let t = bindGroupData.textures;
  49887. for ( const binding of bindGroup.bindings ) {
  49888. const map = this.get( binding );
  49889. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49890. const array = binding.buffer;
  49891. let { bufferGPU } = this.get( array );
  49892. if ( bufferGPU === undefined ) {
  49893. // create
  49894. bufferGPU = gl.createBuffer();
  49895. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49896. gl.bufferData( gl.UNIFORM_BUFFER, array.byteLength, gl.DYNAMIC_DRAW );
  49897. this.set( array, { bufferGPU } );
  49898. } else {
  49899. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49900. }
  49901. // update
  49902. const updateRanges = binding.updateRanges;
  49903. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49904. if ( updateRanges.length === 0 ) {
  49905. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49906. } else {
  49907. const isTyped = isTypedArray( array );
  49908. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49909. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49910. const range = updateRanges[ i ];
  49911. const dataOffset = range.start * byteOffsetFactor;
  49912. const size = range.count * byteOffsetFactor;
  49913. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49914. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49915. }
  49916. }
  49917. map.index = i ++;
  49918. map.bufferGPU = bufferGPU;
  49919. this.set( binding, map );
  49920. } else if ( binding.isSampledTexture ) {
  49921. const { textureGPU, glTextureType } = this.get( binding.texture );
  49922. map.index = t ++;
  49923. map.textureGPU = textureGPU;
  49924. map.glTextureType = glTextureType;
  49925. this.set( binding, map );
  49926. }
  49927. }
  49928. }
  49929. /**
  49930. * Updates a buffer binding.
  49931. *
  49932. * @param {Buffer} binding - The buffer binding to update.
  49933. */
  49934. updateBinding( binding ) {
  49935. const gl = this.gl;
  49936. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  49937. const bindingData = this.get( binding );
  49938. const bufferGPU = bindingData.bufferGPU;
  49939. const array = binding.buffer;
  49940. const updateRanges = binding.updateRanges;
  49941. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  49942. if ( updateRanges.length === 0 ) {
  49943. gl.bufferData( gl.UNIFORM_BUFFER, array, gl.DYNAMIC_DRAW );
  49944. } else {
  49945. const isTyped = isTypedArray( array );
  49946. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  49947. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49948. const range = updateRanges[ i ];
  49949. const dataOffset = range.start * byteOffsetFactor;
  49950. const size = range.count * byteOffsetFactor;
  49951. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49952. gl.bufferSubData( gl.UNIFORM_BUFFER, bufferOffset, array, dataOffset, size );
  49953. }
  49954. }
  49955. }
  49956. }
  49957. // attributes
  49958. /**
  49959. * Creates the GPU buffer of an indexed shader attribute.
  49960. *
  49961. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49962. */
  49963. createIndexAttribute( attribute ) {
  49964. const gl = this.gl;
  49965. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  49966. }
  49967. /**
  49968. * Creates the GPU buffer of a shader attribute.
  49969. *
  49970. * @param {BufferAttribute} attribute - The buffer attribute.
  49971. */
  49972. createAttribute( attribute ) {
  49973. if ( this.has( attribute ) ) return;
  49974. const gl = this.gl;
  49975. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49976. }
  49977. /**
  49978. * Creates the GPU buffer of a storage attribute.
  49979. *
  49980. * @param {BufferAttribute} attribute - The buffer attribute.
  49981. */
  49982. createStorageAttribute( attribute ) {
  49983. if ( this.has( attribute ) ) return;
  49984. const gl = this.gl;
  49985. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  49986. }
  49987. /**
  49988. * Updates the GPU buffer of a shader attribute.
  49989. *
  49990. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49991. */
  49992. updateAttribute( attribute ) {
  49993. this.attributeUtils.updateAttribute( attribute );
  49994. }
  49995. /**
  49996. * Destroys the GPU buffer of a shader attribute.
  49997. *
  49998. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49999. */
  50000. destroyAttribute( attribute ) {
  50001. this.attributeUtils.destroyAttribute( attribute );
  50002. }
  50003. /**
  50004. * Checks if the given feature is supported by the backend.
  50005. *
  50006. * @param {string} name - The feature's name.
  50007. * @return {boolean} Whether the feature is supported or not.
  50008. */
  50009. hasFeature( name ) {
  50010. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  50011. const extensions = this.extensions;
  50012. for ( let i = 0; i < keysMatching.length; i ++ ) {
  50013. if ( extensions.has( keysMatching[ i ] ) ) return true;
  50014. }
  50015. return false;
  50016. }
  50017. /**
  50018. * Returns the maximum anisotropy texture filtering value.
  50019. *
  50020. * @return {number} The maximum anisotropy texture filtering value.
  50021. */
  50022. getMaxAnisotropy() {
  50023. return this.capabilities.getMaxAnisotropy();
  50024. }
  50025. /**
  50026. * Copies data of the given source texture to the given destination texture.
  50027. *
  50028. * @param {Texture} srcTexture - The source texture.
  50029. * @param {Texture} dstTexture - The destination texture.
  50030. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  50031. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  50032. * @param {number} [srcLevel=0] - The source mip level to copy from.
  50033. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  50034. */
  50035. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  50036. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  50037. }
  50038. /**
  50039. * Copies the current bound framebuffer to the given texture.
  50040. *
  50041. * @param {Texture} texture - The destination texture.
  50042. * @param {RenderContext} renderContext - The render context.
  50043. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  50044. */
  50045. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  50046. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  50047. }
  50048. /**
  50049. * Checks if the given compatibility is supported by the backend.
  50050. *
  50051. * @param {string} name - The compatibility name.
  50052. * @return {boolean} Whether the compatibility is supported or not.
  50053. */
  50054. hasCompatibility( name ) {
  50055. if ( name === Compatibility.TEXTURE_COMPARE ) return true;
  50056. return super.hasCompatibility( name );
  50057. }
  50058. /**
  50059. * Configures the active framebuffer from the given render context.
  50060. *
  50061. * @private
  50062. * @param {RenderContext} descriptor - The render context.
  50063. */
  50064. _setFramebuffer( descriptor ) {
  50065. const { gl, state } = this;
  50066. let currentFrameBuffer = null;
  50067. if ( descriptor.textures !== null ) {
  50068. const renderTarget = descriptor.renderTarget;
  50069. const renderTargetContextData = this.get( renderTarget );
  50070. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  50071. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  50072. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  50073. const isRenderTargetArray = renderTarget.depth > 1;
  50074. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  50075. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  50076. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  50077. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  50078. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  50079. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  50080. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  50081. const cacheKey = getCacheKey( descriptor );
  50082. let fb;
  50083. if ( isCube ) {
  50084. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  50085. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  50086. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  50087. fb = this._xrFramebuffer;
  50088. } else {
  50089. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  50090. fb = renderTargetContextData.framebuffers[ cacheKey ];
  50091. }
  50092. if ( fb === undefined ) {
  50093. fb = gl.createFramebuffer();
  50094. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50095. const textures = descriptor.textures;
  50096. const depthInvalidationArray = [];
  50097. if ( isCube ) {
  50098. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  50099. const { textureGPU } = this.get( textures[ 0 ] );
  50100. const cubeFace = this.renderer._activeCubeFace;
  50101. const mipLevel = this.renderer._activeMipmapLevel;
  50102. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  50103. } else {
  50104. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  50105. for ( let i = 0; i < textures.length; i ++ ) {
  50106. const texture = textures[ i ];
  50107. const textureData = this.get( texture );
  50108. textureData.renderTarget = descriptor.renderTarget;
  50109. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  50110. const attachment = gl.COLOR_ATTACHMENT0 + i;
  50111. if ( renderTarget.multiview ) {
  50112. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  50113. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  50114. const layer = this.renderer._activeCubeFace;
  50115. const mipLevel = this.renderer._activeMipmapLevel;
  50116. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  50117. } else {
  50118. if ( useMultisampledRTT ) {
  50119. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50120. } else {
  50121. const mipLevel = this.renderer._activeMipmapLevel;
  50122. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  50123. }
  50124. }
  50125. }
  50126. }
  50127. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50128. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  50129. const renderbuffer = gl.createRenderbuffer();
  50130. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  50131. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  50132. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  50133. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  50134. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  50135. } else {
  50136. if ( descriptor.depthTexture !== null ) {
  50137. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  50138. const textureData = this.get( descriptor.depthTexture );
  50139. textureData.renderTarget = descriptor.renderTarget;
  50140. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  50141. if ( renderTarget.multiview ) {
  50142. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  50143. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  50144. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50145. } else {
  50146. if ( descriptor.depthTexture.isArrayTexture ) {
  50147. const layer = this.renderer._activeCubeFace;
  50148. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  50149. } else if ( descriptor.depthTexture.isCubeTexture ) {
  50150. const cubeFace = this.renderer._activeCubeFace;
  50151. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureData.textureGPU, 0 );
  50152. } else {
  50153. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50154. }
  50155. }
  50156. }
  50157. }
  50158. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  50159. } else {
  50160. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  50161. if ( isRenderCameraDepthArray ) {
  50162. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50163. const layer = this.renderer._activeCubeFace;
  50164. const depthData = this.get( descriptor.depthTexture );
  50165. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50166. gl.framebufferTextureLayer(
  50167. gl.FRAMEBUFFER,
  50168. depthStyle,
  50169. depthData.textureGPU,
  50170. 0,
  50171. layer
  50172. );
  50173. }
  50174. // rebind external XR textures
  50175. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  50176. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  50177. // rebind color
  50178. const textureData = this.get( descriptor.textures[ 0 ] );
  50179. if ( renderTarget.multiview ) {
  50180. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  50181. } else if ( useMultisampledRTT ) {
  50182. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50183. } else {
  50184. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50185. }
  50186. // rebind depth
  50187. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50188. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  50189. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  50190. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  50191. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  50192. } else {
  50193. const textureData = this.get( descriptor.depthTexture );
  50194. if ( renderTarget.multiview ) {
  50195. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  50196. } else if ( useMultisampledRTT ) {
  50197. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  50198. } else {
  50199. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  50200. }
  50201. }
  50202. }
  50203. }
  50204. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  50205. if ( msaaFb === undefined ) {
  50206. const invalidationArray = [];
  50207. msaaFb = gl.createFramebuffer();
  50208. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  50209. const msaaRenderbuffers = [];
  50210. const textures = descriptor.textures;
  50211. for ( let i = 0; i < textures.length; i ++ ) {
  50212. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  50213. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50214. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  50215. const texture = descriptor.textures[ i ];
  50216. const textureData = this.get( texture );
  50217. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  50218. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50219. }
  50220. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  50221. renderTargetContextData.msaaFrameBuffer = msaaFb;
  50222. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  50223. if ( depthBuffer && depthRenderbuffer === undefined ) {
  50224. depthRenderbuffer = gl.createRenderbuffer();
  50225. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  50226. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  50227. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  50228. invalidationArray.push( depthStyle );
  50229. }
  50230. renderTargetContextData.invalidationArray = invalidationArray;
  50231. }
  50232. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50233. } else {
  50234. currentFrameBuffer = fb;
  50235. }
  50236. state.drawBuffers( descriptor, fb );
  50237. }
  50238. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  50239. }
  50240. /**
  50241. * Computes the VAO key for the given index and attributes.
  50242. *
  50243. * @private
  50244. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50245. * @return {string} The VAO key.
  50246. */
  50247. _getVaoKey( attributes ) {
  50248. let key = '';
  50249. for ( let i = 0; i < attributes.length; i ++ ) {
  50250. const attributeData = this.get( attributes[ i ] );
  50251. key += ':' + attributeData.id;
  50252. }
  50253. return key;
  50254. }
  50255. /**
  50256. * Creates a VAO from the index and attributes.
  50257. *
  50258. * @private
  50259. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  50260. * @return {Object} The VAO data.
  50261. */
  50262. _createVao( attributes ) {
  50263. const { gl } = this;
  50264. const vaoGPU = gl.createVertexArray();
  50265. gl.bindVertexArray( vaoGPU );
  50266. for ( let i = 0; i < attributes.length; i ++ ) {
  50267. const attribute = attributes[ i ];
  50268. const attributeData = this.get( attribute );
  50269. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  50270. gl.enableVertexAttribArray( i );
  50271. let stride, offset;
  50272. if ( attribute.isInterleavedBufferAttribute === true ) {
  50273. stride = attribute.data.stride * attributeData.bytesPerElement;
  50274. offset = attribute.offset * attributeData.bytesPerElement;
  50275. } else {
  50276. stride = 0;
  50277. offset = 0;
  50278. }
  50279. if ( attributeData.isInteger ) {
  50280. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  50281. } else {
  50282. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  50283. }
  50284. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  50285. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  50286. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  50287. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  50288. }
  50289. }
  50290. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  50291. return vaoGPU;
  50292. }
  50293. /**
  50294. * Creates a transform feedback from the given transform buffers.
  50295. *
  50296. * @private
  50297. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  50298. * @return {WebGLTransformFeedback} The transform feedback.
  50299. */
  50300. _getTransformFeedback( transformBuffers ) {
  50301. let key = '';
  50302. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50303. key += ':' + transformBuffers[ i ].id;
  50304. }
  50305. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  50306. if ( transformFeedbackGPU !== undefined ) {
  50307. return transformFeedbackGPU;
  50308. }
  50309. const { gl } = this;
  50310. transformFeedbackGPU = gl.createTransformFeedback();
  50311. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  50312. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  50313. const attributeData = transformBuffers[ i ];
  50314. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  50315. }
  50316. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  50317. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  50318. return transformFeedbackGPU;
  50319. }
  50320. /**
  50321. * Setups the given bindings.
  50322. *
  50323. * @private
  50324. * @param {Array<BindGroup>} bindings - The bindings.
  50325. * @param {WebGLProgram} programGPU - The WebGL program.
  50326. */
  50327. _setupBindings( bindings, programGPU ) {
  50328. const gl = this.gl;
  50329. for ( const bindGroup of bindings ) {
  50330. for ( const binding of bindGroup.bindings ) {
  50331. const bindingData = this.get( binding );
  50332. const index = bindingData.index;
  50333. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50334. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  50335. gl.uniformBlockBinding( programGPU, location, index );
  50336. } else if ( binding.isSampledTexture ) {
  50337. const location = gl.getUniformLocation( programGPU, binding.name );
  50338. gl.uniform1i( location, index );
  50339. }
  50340. }
  50341. }
  50342. }
  50343. /**
  50344. * Binds the given uniforms.
  50345. *
  50346. * @private
  50347. * @param {Array<BindGroup>} bindings - The bindings.
  50348. */
  50349. _bindUniforms( bindings ) {
  50350. const { gl, state } = this;
  50351. for ( const bindGroup of bindings ) {
  50352. for ( const binding of bindGroup.bindings ) {
  50353. const bindingData = this.get( binding );
  50354. const index = bindingData.index;
  50355. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  50356. // TODO USE bindBufferRange to group multiple uniform buffers
  50357. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  50358. } else if ( binding.isSampledTexture ) {
  50359. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  50360. }
  50361. }
  50362. }
  50363. }
  50364. /**
  50365. * The method ensures multisampled render targets are resolved.
  50366. *
  50367. * @private
  50368. * @param {RenderContext} renderContext - The render context.
  50369. */
  50370. _resolveRenderTarget( renderContext ) {
  50371. const { gl, state } = this;
  50372. const renderTarget = renderContext.renderTarget;
  50373. if ( renderContext.textures !== null && renderTarget ) {
  50374. const renderTargetContextData = this.get( renderTarget );
  50375. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  50376. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50377. let mask = gl.COLOR_BUFFER_BIT;
  50378. if ( renderTarget.resolveDepthBuffer ) {
  50379. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  50380. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  50381. }
  50382. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  50383. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  50384. const textures = renderContext.textures;
  50385. const isMRT = textures.length > 1;
  50386. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  50387. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50388. if ( isMRT ) {
  50389. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  50390. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  50391. for ( let i = 0; i < textures.length; i ++ ) {
  50392. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  50393. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  50394. }
  50395. }
  50396. for ( let i = 0; i < textures.length; i ++ ) {
  50397. if ( isMRT ) {
  50398. // configure attachment for resolve
  50399. const { textureGPU } = this.get( textures[ i ] );
  50400. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50401. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  50402. }
  50403. if ( renderContext.scissor ) {
  50404. const { x, y, width, height } = renderContext.scissorValue;
  50405. const viewY = renderContext.height - height - y;
  50406. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  50407. } else {
  50408. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  50409. }
  50410. }
  50411. if ( isMRT ) {
  50412. // restore attachments
  50413. for ( let i = 0; i < textures.length; i ++ ) {
  50414. const { textureGPU } = this.get( textures[ i ] );
  50415. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  50416. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  50417. }
  50418. }
  50419. if ( this._supportsInvalidateFramebuffer === true ) {
  50420. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  50421. }
  50422. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  50423. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  50424. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  50425. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  50426. }
  50427. }
  50428. }
  50429. /**
  50430. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  50431. * should be used when MSAA is enabled.
  50432. *
  50433. * @private
  50434. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  50435. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  50436. */
  50437. _useMultisampledExtension( renderTarget ) {
  50438. if ( renderTarget.multiview === true ) {
  50439. return true;
  50440. }
  50441. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  50442. }
  50443. /**
  50444. * Frees internal resources.
  50445. */
  50446. dispose() {
  50447. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  50448. const extension = this.extensions.get( 'WEBGL_lose_context' );
  50449. if ( extension ) extension.loseContext();
  50450. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  50451. }
  50452. }
  50453. const GPUPrimitiveTopology = {
  50454. PointList: 'point-list',
  50455. LineList: 'line-list',
  50456. LineStrip: 'line-strip',
  50457. TriangleList: 'triangle-list',
  50458. TriangleStrip: 'triangle-strip',
  50459. };
  50460. const GPUShaderStage = ( typeof self !== 'undefined' && self.GPUShaderStage ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50461. const GPUCompareFunction = {
  50462. Never: 'never',
  50463. Less: 'less',
  50464. Equal: 'equal',
  50465. LessEqual: 'less-equal',
  50466. Greater: 'greater',
  50467. NotEqual: 'not-equal',
  50468. GreaterEqual: 'greater-equal',
  50469. Always: 'always'
  50470. };
  50471. const GPUStoreOp = {
  50472. Store: 'store'};
  50473. const GPULoadOp = {
  50474. Load: 'load',
  50475. Clear: 'clear'
  50476. };
  50477. const GPUFrontFace = {
  50478. CCW: 'ccw',
  50479. CW: 'cw'
  50480. };
  50481. const GPUCullMode = {
  50482. None: 'none',
  50483. Back: 'back'
  50484. };
  50485. const GPUIndexFormat = {
  50486. Uint16: 'uint16',
  50487. Uint32: 'uint32'
  50488. };
  50489. const GPUTextureFormat = {
  50490. // 8-bit formats
  50491. R8Unorm: 'r8unorm',
  50492. R8Snorm: 'r8snorm',
  50493. R8Uint: 'r8uint',
  50494. R8Sint: 'r8sint',
  50495. // 16-bit formats
  50496. R16Uint: 'r16uint',
  50497. R16Sint: 'r16sint',
  50498. R16Float: 'r16float',
  50499. RG8Unorm: 'rg8unorm',
  50500. RG8Snorm: 'rg8snorm',
  50501. RG8Uint: 'rg8uint',
  50502. RG8Sint: 'rg8sint',
  50503. // 32-bit formats
  50504. R32Uint: 'r32uint',
  50505. R32Sint: 'r32sint',
  50506. R32Float: 'r32float',
  50507. RG16Uint: 'rg16uint',
  50508. RG16Sint: 'rg16sint',
  50509. RG16Float: 'rg16float',
  50510. RGBA8Unorm: 'rgba8unorm',
  50511. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  50512. RGBA8Snorm: 'rgba8snorm',
  50513. RGBA8Uint: 'rgba8uint',
  50514. RGBA8Sint: 'rgba8sint',
  50515. BGRA8Unorm: 'bgra8unorm',
  50516. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  50517. // Packed 32-bit formats
  50518. RGB9E5UFloat: 'rgb9e5ufloat',
  50519. RGB10A2Unorm: 'rgb10a2unorm',
  50520. RG11B10UFloat: 'rg11b10ufloat',
  50521. // 64-bit formats
  50522. RG32Uint: 'rg32uint',
  50523. RG32Sint: 'rg32sint',
  50524. RG32Float: 'rg32float',
  50525. RGBA16Uint: 'rgba16uint',
  50526. RGBA16Sint: 'rgba16sint',
  50527. RGBA16Float: 'rgba16float',
  50528. // 128-bit formats
  50529. RGBA32Uint: 'rgba32uint',
  50530. RGBA32Sint: 'rgba32sint',
  50531. RGBA32Float: 'rgba32float',
  50532. Depth16Unorm: 'depth16unorm',
  50533. Depth24Plus: 'depth24plus',
  50534. Depth24PlusStencil8: 'depth24plus-stencil8',
  50535. Depth32Float: 'depth32float',
  50536. // 'depth32float-stencil8' extension
  50537. Depth32FloatStencil8: 'depth32float-stencil8',
  50538. // BC compressed formats usable if 'texture-compression-bc' is both
  50539. // supported by the device/user agent and enabled in requestDevice.
  50540. BC1RGBAUnorm: 'bc1-rgba-unorm',
  50541. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  50542. BC2RGBAUnorm: 'bc2-rgba-unorm',
  50543. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  50544. BC3RGBAUnorm: 'bc3-rgba-unorm',
  50545. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  50546. BC4RUnorm: 'bc4-r-unorm',
  50547. BC4RSnorm: 'bc4-r-snorm',
  50548. BC5RGUnorm: 'bc5-rg-unorm',
  50549. BC5RGSnorm: 'bc5-rg-snorm',
  50550. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  50551. BC6HRGBFloat: 'bc6h-rgb-float',
  50552. BC7RGBAUnorm: 'bc7-rgba-unorm',
  50553. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  50554. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  50555. // supported by the device/user agent and enabled in requestDevice.
  50556. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  50557. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  50558. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  50559. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  50560. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  50561. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  50562. EACR11Unorm: 'eac-r11unorm',
  50563. EACR11Snorm: 'eac-r11snorm',
  50564. EACRG11Unorm: 'eac-rg11unorm',
  50565. EACRG11Snorm: 'eac-rg11snorm',
  50566. // ASTC compressed formats usable if 'texture-compression-astc' is both
  50567. // supported by the device/user agent and enabled in requestDevice.
  50568. ASTC4x4Unorm: 'astc-4x4-unorm',
  50569. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  50570. ASTC5x4Unorm: 'astc-5x4-unorm',
  50571. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  50572. ASTC5x5Unorm: 'astc-5x5-unorm',
  50573. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  50574. ASTC6x5Unorm: 'astc-6x5-unorm',
  50575. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  50576. ASTC6x6Unorm: 'astc-6x6-unorm',
  50577. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  50578. ASTC8x5Unorm: 'astc-8x5-unorm',
  50579. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  50580. ASTC8x6Unorm: 'astc-8x6-unorm',
  50581. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  50582. ASTC8x8Unorm: 'astc-8x8-unorm',
  50583. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  50584. ASTC10x5Unorm: 'astc-10x5-unorm',
  50585. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  50586. ASTC10x6Unorm: 'astc-10x6-unorm',
  50587. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  50588. ASTC10x8Unorm: 'astc-10x8-unorm',
  50589. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  50590. ASTC10x10Unorm: 'astc-10x10-unorm',
  50591. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  50592. ASTC12x10Unorm: 'astc-12x10-unorm',
  50593. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  50594. ASTC12x12Unorm: 'astc-12x12-unorm',
  50595. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  50596. };
  50597. const GPUAddressMode = {
  50598. ClampToEdge: 'clamp-to-edge',
  50599. Repeat: 'repeat',
  50600. MirrorRepeat: 'mirror-repeat'
  50601. };
  50602. const GPUFilterMode = {
  50603. Linear: 'linear',
  50604. Nearest: 'nearest'
  50605. };
  50606. const GPUBlendFactor = {
  50607. Zero: 'zero',
  50608. One: 'one',
  50609. Src: 'src',
  50610. OneMinusSrc: 'one-minus-src',
  50611. SrcAlpha: 'src-alpha',
  50612. OneMinusSrcAlpha: 'one-minus-src-alpha',
  50613. Dst: 'dst',
  50614. OneMinusDst: 'one-minus-dst',
  50615. DstAlpha: 'dst-alpha',
  50616. OneMinusDstAlpha: 'one-minus-dst-alpha',
  50617. SrcAlphaSaturated: 'src-alpha-saturated',
  50618. Constant: 'constant',
  50619. OneMinusConstant: 'one-minus-constant'
  50620. };
  50621. const GPUBlendOperation = {
  50622. Add: 'add',
  50623. Subtract: 'subtract',
  50624. ReverseSubtract: 'reverse-subtract',
  50625. Min: 'min',
  50626. Max: 'max'
  50627. };
  50628. const GPUColorWriteFlags = {
  50629. None: 0,
  50630. All: 0xF
  50631. };
  50632. const GPUStencilOperation = {
  50633. Keep: 'keep',
  50634. Zero: 'zero',
  50635. Replace: 'replace',
  50636. Invert: 'invert',
  50637. IncrementClamp: 'increment-clamp',
  50638. DecrementClamp: 'decrement-clamp',
  50639. IncrementWrap: 'increment-wrap',
  50640. DecrementWrap: 'decrement-wrap'
  50641. };
  50642. const GPUBufferBindingType = {
  50643. Storage: 'storage',
  50644. ReadOnlyStorage: 'read-only-storage'
  50645. };
  50646. const GPUStorageTextureAccess = {
  50647. WriteOnly: 'write-only',
  50648. ReadOnly: 'read-only',
  50649. ReadWrite: 'read-write',
  50650. };
  50651. const GPUSamplerBindingType = {
  50652. NonFiltering: 'non-filtering',
  50653. Comparison: 'comparison'
  50654. };
  50655. const GPUTextureSampleType = {
  50656. Float: 'float',
  50657. UnfilterableFloat: 'unfilterable-float',
  50658. Depth: 'depth',
  50659. SInt: 'sint',
  50660. UInt: 'uint'
  50661. };
  50662. const GPUTextureDimension = {
  50663. TwoD: '2d',
  50664. ThreeD: '3d'
  50665. };
  50666. const GPUTextureViewDimension = {
  50667. TwoD: '2d',
  50668. TwoDArray: '2d-array',
  50669. Cube: 'cube',
  50670. ThreeD: '3d'
  50671. };
  50672. const GPUTextureAspect = {
  50673. All: 'all'};
  50674. const GPUInputStepMode = {
  50675. Vertex: 'vertex',
  50676. Instance: 'instance'
  50677. };
  50678. const GPUFeatureName = {
  50679. CoreFeaturesAndLimits: 'core-features-and-limits',
  50680. DepthClipControl: 'depth-clip-control',
  50681. Depth32FloatStencil8: 'depth32float-stencil8',
  50682. TextureCompressionBC: 'texture-compression-bc',
  50683. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  50684. TextureCompressionETC2: 'texture-compression-etc2',
  50685. TextureCompressionASTC: 'texture-compression-astc',
  50686. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  50687. TimestampQuery: 'timestamp-query',
  50688. IndirectFirstInstance: 'indirect-first-instance',
  50689. ShaderF16: 'shader-f16',
  50690. RG11B10UFloat: 'rg11b10ufloat-renderable',
  50691. BGRA8UNormStorage: 'bgra8unorm-storage',
  50692. Float32Filterable: 'float32-filterable',
  50693. Float32Blendable: 'float32-blendable',
  50694. ClipDistances: 'clip-distances',
  50695. DualSourceBlending: 'dual-source-blending',
  50696. Subgroups: 'subgroups',
  50697. TextureFormatsTier1: 'texture-formats-tier1',
  50698. TextureFormatsTier2: 'texture-formats-tier2'
  50699. };
  50700. const GPUFeatureMap = {
  50701. 'texture-compression-s3tc': 'texture-compression-bc',
  50702. 'texture-compression-etc1': 'texture-compression-etc2'
  50703. };
  50704. /**
  50705. * A special form of sampler binding type.
  50706. * It's texture value is managed by a node object.
  50707. *
  50708. * @private
  50709. * @augments Sampler
  50710. */
  50711. class NodeSampler extends Sampler {
  50712. /**
  50713. * Constructs a new node-based sampler.
  50714. *
  50715. * @param {string} name - The samplers's name.
  50716. * @param {TextureNode} textureNode - The texture node.
  50717. * @param {UniformGroupNode} groupNode - The uniform group node.
  50718. */
  50719. constructor( name, textureNode, groupNode ) {
  50720. super( name, textureNode ? textureNode.value : null );
  50721. /**
  50722. * The texture node.
  50723. *
  50724. * @type {TextureNode}
  50725. */
  50726. this.textureNode = textureNode;
  50727. /**
  50728. * The uniform group node.
  50729. *
  50730. * @type {UniformGroupNode}
  50731. */
  50732. this.groupNode = groupNode;
  50733. }
  50734. /**
  50735. * Updates the texture value of this sampler.
  50736. *
  50737. * @return {boolean} Whether the sampler needs an update or not.
  50738. */
  50739. update() {
  50740. const { textureNode } = this;
  50741. if ( this.texture !== textureNode.value ) {
  50742. this.texture = textureNode.value;
  50743. return true;
  50744. }
  50745. return super.update();
  50746. }
  50747. }
  50748. /**
  50749. * Represents a storage buffer binding type.
  50750. *
  50751. * @private
  50752. * @augments Buffer
  50753. */
  50754. class StorageBuffer extends Buffer {
  50755. /**
  50756. * Constructs a new uniform buffer.
  50757. *
  50758. * @param {string} name - The buffer's name.
  50759. * @param {BufferAttribute} attribute - The buffer attribute.
  50760. */
  50761. constructor( name, attribute ) {
  50762. super( name, attribute ? attribute.array : null );
  50763. /**
  50764. * This flag can be used for type testing.
  50765. *
  50766. * @private
  50767. * @type {BufferAttribute}
  50768. */
  50769. this._attribute = attribute;
  50770. /**
  50771. * This flag can be used for type testing.
  50772. *
  50773. * @type {boolean}
  50774. * @readonly
  50775. * @default true
  50776. */
  50777. this.isStorageBuffer = true;
  50778. }
  50779. /**
  50780. * The storage buffer attribute.
  50781. *
  50782. * @type {BufferAttribute}
  50783. */
  50784. get attribute() {
  50785. return this._attribute;
  50786. }
  50787. }
  50788. let _id = 0;
  50789. /**
  50790. * A special form of storage buffer binding type.
  50791. * It's buffer value is managed by a node object.
  50792. *
  50793. * @private
  50794. * @augments StorageBuffer
  50795. */
  50796. class NodeStorageBuffer extends StorageBuffer {
  50797. /**
  50798. * Constructs a new node-based storage buffer.
  50799. *
  50800. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  50801. * @param {UniformGroupNode} groupNode - The uniform group node.
  50802. */
  50803. constructor( nodeUniform, groupNode ) {
  50804. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  50805. /**
  50806. * The node uniform.
  50807. *
  50808. * @type {StorageBufferNode}
  50809. */
  50810. this.nodeUniform = nodeUniform;
  50811. /**
  50812. * The access type.
  50813. *
  50814. * @type {string}
  50815. */
  50816. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  50817. /**
  50818. * The uniform group node.
  50819. *
  50820. * @type {UniformGroupNode}
  50821. */
  50822. this.groupNode = groupNode;
  50823. }
  50824. /**
  50825. * The storage buffer attribute node.
  50826. *
  50827. * @type {StorageBufferAttribute}
  50828. */
  50829. get attribute() {
  50830. return this.nodeUniform.value;
  50831. }
  50832. /**
  50833. * The storage buffer.
  50834. *
  50835. * @type {Float32Array}
  50836. */
  50837. get buffer() {
  50838. return this.nodeUniform.value.array;
  50839. }
  50840. }
  50841. /**
  50842. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  50843. *
  50844. * @private
  50845. */
  50846. class WebGPUTexturePassUtils extends DataMap {
  50847. /**
  50848. * Constructs a new utility object.
  50849. *
  50850. * @param {GPUDevice} device - The WebGPU device.
  50851. */
  50852. constructor( device ) {
  50853. super();
  50854. /**
  50855. * The WebGPU device.
  50856. *
  50857. * @type {GPUDevice}
  50858. */
  50859. this.device = device;
  50860. const mipmapVertexSource = `
  50861. struct VarysStruct {
  50862. @builtin( position ) Position: vec4<f32>,
  50863. @location( 0 ) vTex : vec2<f32>
  50864. };
  50865. @vertex
  50866. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  50867. var Varys : VarysStruct;
  50868. var pos = array< vec2<f32>, 4 >(
  50869. vec2<f32>( -1.0, 1.0 ),
  50870. vec2<f32>( 1.0, 1.0 ),
  50871. vec2<f32>( -1.0, -1.0 ),
  50872. vec2<f32>( 1.0, -1.0 )
  50873. );
  50874. var tex = array< vec2<f32>, 4 >(
  50875. vec2<f32>( 0.0, 0.0 ),
  50876. vec2<f32>( 1.0, 0.0 ),
  50877. vec2<f32>( 0.0, 1.0 ),
  50878. vec2<f32>( 1.0, 1.0 )
  50879. );
  50880. Varys.vTex = tex[ vertexIndex ];
  50881. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  50882. return Varys;
  50883. }
  50884. `;
  50885. const mipmapFragmentSource = `
  50886. @group( 0 ) @binding( 0 )
  50887. var imgSampler : sampler;
  50888. @group( 0 ) @binding( 1 )
  50889. var img : texture_2d<f32>;
  50890. @fragment
  50891. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50892. return textureSample( img, imgSampler, vTex );
  50893. }
  50894. `;
  50895. const flipYFragmentSource = `
  50896. @group( 0 ) @binding( 0 )
  50897. var imgSampler : sampler;
  50898. @group( 0 ) @binding( 1 )
  50899. var img : texture_2d<f32>;
  50900. @fragment
  50901. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  50902. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  50903. }
  50904. `;
  50905. /**
  50906. * The mipmap GPU sampler.
  50907. *
  50908. * @type {GPUSampler}
  50909. */
  50910. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  50911. /**
  50912. * The flipY GPU sampler.
  50913. *
  50914. * @type {GPUSampler}
  50915. */
  50916. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  50917. /**
  50918. * A cache for GPU render pipelines used for copy/transfer passes.
  50919. * Every texture format requires a unique pipeline.
  50920. *
  50921. * @type {Object<string,GPURenderPipeline>}
  50922. */
  50923. this.transferPipelines = {};
  50924. /**
  50925. * A cache for GPU render pipelines used for flipY passes.
  50926. * Every texture format requires a unique pipeline.
  50927. *
  50928. * @type {Object<string,GPURenderPipeline>}
  50929. */
  50930. this.flipYPipelines = {};
  50931. /**
  50932. * The mipmap vertex shader module.
  50933. *
  50934. * @type {GPUShaderModule}
  50935. */
  50936. this.mipmapVertexShaderModule = device.createShaderModule( {
  50937. label: 'mipmapVertex',
  50938. code: mipmapVertexSource
  50939. } );
  50940. /**
  50941. * The mipmap fragment shader module.
  50942. *
  50943. * @type {GPUShaderModule}
  50944. */
  50945. this.mipmapFragmentShaderModule = device.createShaderModule( {
  50946. label: 'mipmapFragment',
  50947. code: mipmapFragmentSource
  50948. } );
  50949. /**
  50950. * The flipY fragment shader module.
  50951. *
  50952. * @type {GPUShaderModule}
  50953. */
  50954. this.flipYFragmentShaderModule = device.createShaderModule( {
  50955. label: 'flipYFragment',
  50956. code: flipYFragmentSource
  50957. } );
  50958. }
  50959. /**
  50960. * Returns a render pipeline for the internal copy render pass. The pass
  50961. * requires a unique render pipeline for each texture format.
  50962. *
  50963. * @param {string} format - The GPU texture format
  50964. * @return {GPURenderPipeline} The GPU render pipeline.
  50965. */
  50966. getTransferPipeline( format ) {
  50967. let pipeline = this.transferPipelines[ format ];
  50968. if ( pipeline === undefined ) {
  50969. pipeline = this.device.createRenderPipeline( {
  50970. label: `mipmap-${ format }`,
  50971. vertex: {
  50972. module: this.mipmapVertexShaderModule,
  50973. entryPoint: 'main'
  50974. },
  50975. fragment: {
  50976. module: this.mipmapFragmentShaderModule,
  50977. entryPoint: 'main',
  50978. targets: [ { format } ]
  50979. },
  50980. primitive: {
  50981. topology: GPUPrimitiveTopology.TriangleStrip,
  50982. stripIndexFormat: GPUIndexFormat.Uint32
  50983. },
  50984. layout: 'auto'
  50985. } );
  50986. this.transferPipelines[ format ] = pipeline;
  50987. }
  50988. return pipeline;
  50989. }
  50990. /**
  50991. * Returns a render pipeline for the flipY render pass. The pass
  50992. * requires a unique render pipeline for each texture format.
  50993. *
  50994. * @param {string} format - The GPU texture format
  50995. * @return {GPURenderPipeline} The GPU render pipeline.
  50996. */
  50997. getFlipYPipeline( format ) {
  50998. let pipeline = this.flipYPipelines[ format ];
  50999. if ( pipeline === undefined ) {
  51000. pipeline = this.device.createRenderPipeline( {
  51001. label: `flipY-${ format }`,
  51002. vertex: {
  51003. module: this.mipmapVertexShaderModule,
  51004. entryPoint: 'main'
  51005. },
  51006. fragment: {
  51007. module: this.flipYFragmentShaderModule,
  51008. entryPoint: 'main',
  51009. targets: [ { format } ]
  51010. },
  51011. primitive: {
  51012. topology: GPUPrimitiveTopology.TriangleStrip,
  51013. stripIndexFormat: GPUIndexFormat.Uint32
  51014. },
  51015. layout: 'auto'
  51016. } );
  51017. this.flipYPipelines[ format ] = pipeline;
  51018. }
  51019. return pipeline;
  51020. }
  51021. /**
  51022. * Flip the contents of the given GPU texture along its vertical axis.
  51023. *
  51024. * @param {GPUTexture} textureGPU - The GPU texture object.
  51025. * @param {Object} textureGPUDescriptor - The texture descriptor.
  51026. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51027. */
  51028. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  51029. const format = textureGPUDescriptor.format;
  51030. const { width, height } = textureGPUDescriptor.size;
  51031. const transferPipeline = this.getTransferPipeline( format );
  51032. const flipYPipeline = this.getFlipYPipeline( format );
  51033. const tempTexture = this.device.createTexture( {
  51034. size: { width, height, depthOrArrayLayers: 1 },
  51035. format,
  51036. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  51037. } );
  51038. const srcView = textureGPU.createView( {
  51039. baseMipLevel: 0,
  51040. mipLevelCount: 1,
  51041. dimension: GPUTextureViewDimension.TwoD,
  51042. baseArrayLayer
  51043. } );
  51044. const dstView = tempTexture.createView( {
  51045. baseMipLevel: 0,
  51046. mipLevelCount: 1,
  51047. dimension: GPUTextureViewDimension.TwoD,
  51048. baseArrayLayer: 0
  51049. } );
  51050. const commandEncoder = this.device.createCommandEncoder( {} );
  51051. const pass = ( pipeline, sourceView, destinationView ) => {
  51052. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  51053. const bindGroup = this.device.createBindGroup( {
  51054. layout: bindGroupLayout,
  51055. entries: [ {
  51056. binding: 0,
  51057. resource: this.flipYSampler
  51058. }, {
  51059. binding: 1,
  51060. resource: sourceView
  51061. } ]
  51062. } );
  51063. const passEncoder = commandEncoder.beginRenderPass( {
  51064. colorAttachments: [ {
  51065. view: destinationView,
  51066. loadOp: GPULoadOp.Clear,
  51067. storeOp: GPUStoreOp.Store,
  51068. clearValue: [ 0, 0, 0, 0 ]
  51069. } ]
  51070. } );
  51071. passEncoder.setPipeline( pipeline );
  51072. passEncoder.setBindGroup( 0, bindGroup );
  51073. passEncoder.draw( 4, 1, 0, 0 );
  51074. passEncoder.end();
  51075. };
  51076. pass( transferPipeline, srcView, dstView );
  51077. pass( flipYPipeline, dstView, srcView );
  51078. this.device.queue.submit( [ commandEncoder.finish() ] );
  51079. tempTexture.destroy();
  51080. }
  51081. /**
  51082. * Generates mipmaps for the given GPU texture.
  51083. *
  51084. * @param {GPUTexture} textureGPU - The GPU texture object.
  51085. * @param {Object} textureGPUDescriptor - The texture descriptor.
  51086. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51087. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51088. */
  51089. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0, encoder = null ) {
  51090. const textureData = this.get( textureGPU );
  51091. if ( textureData.layers === undefined ) {
  51092. textureData.layers = [];
  51093. }
  51094. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  51095. const commandEncoder = encoder || this.device.createCommandEncoder( { label: 'mipmapEncoder' } );
  51096. this._mipmapRunBundles( commandEncoder, passes );
  51097. if ( encoder === null ) this.device.queue.submit( [ commandEncoder.finish() ] );
  51098. textureData.layers[ baseArrayLayer ] = passes;
  51099. }
  51100. /**
  51101. * Since multiple copy render passes are required to generate mipmaps, the passes
  51102. * are managed as render bundles to improve performance.
  51103. *
  51104. * @param {GPUTexture} textureGPU - The GPU texture object.
  51105. * @param {Object} textureGPUDescriptor - The texture descriptor.
  51106. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  51107. * @return {Array<Object>} An array of render bundles.
  51108. */
  51109. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  51110. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  51111. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  51112. let srcView = textureGPU.createView( {
  51113. baseMipLevel: 0,
  51114. mipLevelCount: 1,
  51115. dimension: GPUTextureViewDimension.TwoD,
  51116. baseArrayLayer
  51117. } );
  51118. const passes = [];
  51119. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  51120. const bindGroup = this.device.createBindGroup( {
  51121. layout: bindGroupLayout,
  51122. entries: [ {
  51123. binding: 0,
  51124. resource: this.mipmapSampler
  51125. }, {
  51126. binding: 1,
  51127. resource: srcView
  51128. } ]
  51129. } );
  51130. const dstView = textureGPU.createView( {
  51131. baseMipLevel: i,
  51132. mipLevelCount: 1,
  51133. dimension: GPUTextureViewDimension.TwoD,
  51134. baseArrayLayer
  51135. } );
  51136. const passDescriptor = {
  51137. colorAttachments: [ {
  51138. view: dstView,
  51139. loadOp: GPULoadOp.Clear,
  51140. storeOp: GPUStoreOp.Store,
  51141. clearValue: [ 0, 0, 0, 0 ]
  51142. } ]
  51143. };
  51144. const passEncoder = this.device.createRenderBundleEncoder( {
  51145. colorFormats: [ textureGPUDescriptor.format ]
  51146. } );
  51147. passEncoder.setPipeline( pipeline );
  51148. passEncoder.setBindGroup( 0, bindGroup );
  51149. passEncoder.draw( 4, 1, 0, 0 );
  51150. passes.push( {
  51151. renderBundles: [ passEncoder.finish() ],
  51152. passDescriptor
  51153. } );
  51154. srcView = dstView;
  51155. }
  51156. return passes;
  51157. }
  51158. /**
  51159. * Executes the render bundles.
  51160. *
  51161. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  51162. * @param {Array<Object>} passes - An array of render bundles.
  51163. */
  51164. _mipmapRunBundles( commandEncoder, passes ) {
  51165. const levels = passes.length;
  51166. for ( let i = 0; i < levels; i ++ ) {
  51167. const pass = passes[ i ];
  51168. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  51169. passEncoder.executeBundles( pass.renderBundles );
  51170. passEncoder.end();
  51171. }
  51172. }
  51173. }
  51174. const _compareToWebGPU = {
  51175. [ NeverCompare ]: 'never',
  51176. [ LessCompare ]: 'less',
  51177. [ EqualCompare ]: 'equal',
  51178. [ LessEqualCompare ]: 'less-equal',
  51179. [ GreaterCompare ]: 'greater',
  51180. [ GreaterEqualCompare ]: 'greater-equal',
  51181. [ AlwaysCompare ]: 'always',
  51182. [ NotEqualCompare ]: 'not-equal'
  51183. };
  51184. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  51185. /**
  51186. * A WebGPU backend utility module for managing textures.
  51187. *
  51188. * @private
  51189. */
  51190. class WebGPUTextureUtils {
  51191. /**
  51192. * Constructs a new utility object.
  51193. *
  51194. * @param {WebGPUBackend} backend - The WebGPU backend.
  51195. */
  51196. constructor( backend ) {
  51197. /**
  51198. * A reference to the WebGPU backend.
  51199. *
  51200. * @type {WebGPUBackend}
  51201. */
  51202. this.backend = backend;
  51203. /**
  51204. * A reference to the pass utils.
  51205. *
  51206. * @type {?WebGPUTexturePassUtils}
  51207. * @default null
  51208. */
  51209. this._passUtils = null;
  51210. /**
  51211. * A dictionary for managing default textures. The key
  51212. * is the texture format, the value the texture object.
  51213. *
  51214. * @type {Object<string,Texture>}
  51215. */
  51216. this.defaultTexture = {};
  51217. /**
  51218. * A dictionary for managing default cube textures. The key
  51219. * is the texture format, the value the texture object.
  51220. *
  51221. * @type {Object<string,CubeTexture>}
  51222. */
  51223. this.defaultCubeTexture = {};
  51224. /**
  51225. * A default video frame.
  51226. *
  51227. * @type {?VideoFrame}
  51228. * @default null
  51229. */
  51230. this.defaultVideoFrame = null;
  51231. /**
  51232. * A cache of shared texture samplers.
  51233. *
  51234. * @type {Map<string, Object>}
  51235. */
  51236. this._samplerCache = new Map();
  51237. }
  51238. /**
  51239. * Creates a GPU sampler for the given texture.
  51240. *
  51241. * @param {Texture} texture - The texture to create the sampler for.
  51242. * @return {string} The current sampler key.
  51243. */
  51244. updateSampler( texture ) {
  51245. const backend = this.backend;
  51246. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  51247. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  51248. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  51249. let samplerData = this._samplerCache.get( samplerKey );
  51250. if ( samplerData === undefined ) {
  51251. const samplerDescriptorGPU = {
  51252. addressModeU: this._convertAddressMode( texture.wrapS ),
  51253. addressModeV: this._convertAddressMode( texture.wrapT ),
  51254. addressModeW: this._convertAddressMode( texture.wrapR ),
  51255. magFilter: this._convertFilterMode( texture.magFilter ),
  51256. minFilter: this._convertFilterMode( texture.minFilter ),
  51257. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  51258. maxAnisotropy: 1
  51259. };
  51260. // Depth textures without compare function must use non-filtering (nearest) sampling
  51261. if ( texture.isDepthTexture && texture.compareFunction === null ) {
  51262. samplerDescriptorGPU.magFilter = GPUFilterMode.Nearest;
  51263. samplerDescriptorGPU.minFilter = GPUFilterMode.Nearest;
  51264. samplerDescriptorGPU.mipmapFilter = GPUFilterMode.Nearest;
  51265. }
  51266. // anisotropy can only be used when all filter modes are set to linear.
  51267. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  51268. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  51269. }
  51270. if ( texture.isDepthTexture && texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  51271. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  51272. }
  51273. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  51274. samplerData = { sampler, usedTimes: 0 };
  51275. this._samplerCache.set( samplerKey, samplerData );
  51276. }
  51277. const textureData = backend.get( texture );
  51278. if ( textureData.sampler !== samplerData.sampler ) {
  51279. // check if previous sampler is unused so it can be deleted
  51280. if ( textureData.sampler !== undefined ) {
  51281. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  51282. oldSamplerData.usedTimes --;
  51283. if ( oldSamplerData.usedTimes === 0 ) {
  51284. this._samplerCache.delete( textureData.samplerKey );
  51285. }
  51286. }
  51287. // update to new sampler data
  51288. textureData.samplerKey = samplerKey;
  51289. textureData.sampler = samplerData.sampler;
  51290. samplerData.usedTimes ++;
  51291. }
  51292. return samplerKey;
  51293. }
  51294. /**
  51295. * Creates a default texture for the given texture that can be used
  51296. * as a placeholder until the actual texture is ready for usage.
  51297. *
  51298. * @param {Texture} texture - The texture to create a default texture for.
  51299. */
  51300. createDefaultTexture( texture ) {
  51301. let textureGPU;
  51302. const format = getFormat( texture );
  51303. if ( texture.isCubeTexture ) {
  51304. textureGPU = this._getDefaultCubeTextureGPU( format );
  51305. } else {
  51306. textureGPU = this._getDefaultTextureGPU( format );
  51307. }
  51308. this.backend.get( texture ).texture = textureGPU;
  51309. }
  51310. /**
  51311. * Defines a texture on the GPU for the given texture object.
  51312. *
  51313. * @param {Texture} texture - The texture.
  51314. * @param {Object} [options={}] - Optional configuration parameter.
  51315. */
  51316. createTexture( texture, options = {} ) {
  51317. const backend = this.backend;
  51318. const textureData = backend.get( texture );
  51319. if ( textureData.initialized ) {
  51320. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  51321. }
  51322. if ( texture.isExternalTexture ) {
  51323. textureData.texture = texture.sourceTexture;
  51324. textureData.initialized = true;
  51325. return;
  51326. }
  51327. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  51328. if ( options.levels === undefined ) options.levels = 1;
  51329. if ( options.depth === undefined ) options.depth = 1;
  51330. const { width, height, depth, levels } = options;
  51331. if ( texture.isFramebufferTexture ) {
  51332. if ( options.renderTarget ) {
  51333. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  51334. } else {
  51335. options.format = this.backend.utils.getPreferredCanvasFormat();
  51336. }
  51337. }
  51338. const dimension = this._getDimension( texture );
  51339. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  51340. textureData.format = format;
  51341. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  51342. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  51343. if ( texture.isStorageTexture === true ) {
  51344. usage |= GPUTextureUsage.STORAGE_BINDING;
  51345. }
  51346. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  51347. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  51348. }
  51349. const textureDescriptorGPU = {
  51350. label: texture.name,
  51351. size: {
  51352. width: width,
  51353. height: height,
  51354. depthOrArrayLayers: depth,
  51355. },
  51356. mipLevelCount: levels,
  51357. sampleCount: primarySamples,
  51358. dimension: dimension,
  51359. format: format,
  51360. usage: usage
  51361. };
  51362. // texture creation
  51363. if ( format === undefined ) {
  51364. warn( 'WebGPURenderer: Texture format not supported.' );
  51365. this.createDefaultTexture( texture );
  51366. return;
  51367. }
  51368. if ( texture.isCubeTexture ) {
  51369. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  51370. }
  51371. try {
  51372. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  51373. } catch ( e ) {
  51374. warn( 'WebGPURenderer: Failed to create texture with descriptor:', textureDescriptorGPU );
  51375. this.createDefaultTexture( texture );
  51376. return;
  51377. }
  51378. if ( isMSAA ) {
  51379. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  51380. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  51381. msaaTextureDescriptorGPU.sampleCount = samples;
  51382. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  51383. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  51384. }
  51385. textureData.initialized = true;
  51386. textureData.textureDescriptorGPU = textureDescriptorGPU;
  51387. }
  51388. /**
  51389. * Destroys the GPU data for the given texture object.
  51390. *
  51391. * @param {Texture} texture - The texture.
  51392. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  51393. */
  51394. destroyTexture( texture, isDefaultTexture = false ) {
  51395. const backend = this.backend;
  51396. const textureData = backend.get( texture );
  51397. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  51398. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  51399. backend.delete( texture );
  51400. }
  51401. /**
  51402. * Generates mipmaps for the given texture.
  51403. *
  51404. * @param {Texture} texture - The texture.
  51405. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51406. */
  51407. generateMipmaps( texture, encoder = null ) {
  51408. const textureData = this.backend.get( texture );
  51409. if ( texture.isCubeTexture ) {
  51410. for ( let i = 0; i < 6; i ++ ) {
  51411. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51412. }
  51413. } else {
  51414. const depth = texture.image.depth || 1;
  51415. for ( let i = 0; i < depth; i ++ ) {
  51416. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i, encoder );
  51417. }
  51418. }
  51419. }
  51420. /**
  51421. * Returns the color buffer representing the color
  51422. * attachment of the default framebuffer.
  51423. *
  51424. * @return {GPUTexture} The color buffer.
  51425. */
  51426. getColorBuffer() {
  51427. const backend = this.backend;
  51428. const canvasTarget = backend.renderer.getCanvasTarget();
  51429. const { width, height } = backend.getDrawingBufferSize();
  51430. const samples = backend.renderer.currentSamples;
  51431. const colorTexture = canvasTarget.colorTexture;
  51432. const colorTextureData = backend.get( colorTexture );
  51433. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  51434. return colorTextureData.texture;
  51435. }
  51436. // recreate
  51437. let colorBuffer = colorTextureData.texture;
  51438. if ( colorBuffer ) colorBuffer.destroy();
  51439. colorBuffer = backend.device.createTexture( {
  51440. label: 'colorBuffer',
  51441. size: {
  51442. width: width,
  51443. height: height,
  51444. depthOrArrayLayers: 1
  51445. },
  51446. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  51447. format: backend.utils.getPreferredCanvasFormat(),
  51448. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  51449. } );
  51450. //
  51451. colorTexture.source.width = width;
  51452. colorTexture.source.height = height;
  51453. colorTexture.samples = samples;
  51454. colorTextureData.texture = colorBuffer;
  51455. return colorBuffer;
  51456. }
  51457. /**
  51458. * Returns the depth buffer representing the depth
  51459. * attachment of the default framebuffer.
  51460. *
  51461. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  51462. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  51463. * @return {GPUTexture} The depth buffer.
  51464. */
  51465. getDepthBuffer( depth = true, stencil = false ) {
  51466. const backend = this.backend;
  51467. const canvasTarget = backend.renderer.getCanvasTarget();
  51468. const { width, height } = backend.getDrawingBufferSize();
  51469. const samples = backend.renderer.currentSamples;
  51470. const depthTexture = canvasTarget.depthTexture;
  51471. if ( depthTexture.width === width &&
  51472. depthTexture.height === height &&
  51473. depthTexture.samples === samples &&
  51474. depthTexture.depth === depth &&
  51475. depthTexture.stencil === stencil ) {
  51476. return backend.get( depthTexture ).texture;
  51477. }
  51478. //
  51479. const depthTextureGPU = backend.get( depthTexture ).texture;
  51480. let format, type;
  51481. if ( stencil ) {
  51482. format = DepthStencilFormat;
  51483. type = UnsignedInt248Type;
  51484. } else if ( depth ) {
  51485. format = DepthFormat;
  51486. type = UnsignedIntType;
  51487. }
  51488. if ( depthTextureGPU !== undefined ) {
  51489. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  51490. return depthTextureGPU;
  51491. }
  51492. this.destroyTexture( depthTexture );
  51493. }
  51494. // recreate
  51495. depthTexture.name = 'depthBuffer';
  51496. depthTexture.format = format;
  51497. depthTexture.type = type;
  51498. depthTexture.image.width = width;
  51499. depthTexture.image.height = height;
  51500. depthTexture.samples = samples;
  51501. this.createTexture( depthTexture, { width, height } );
  51502. return backend.get( depthTexture ).texture;
  51503. }
  51504. /**
  51505. * Uploads the updated texture data to the GPU.
  51506. *
  51507. * @param {Texture} texture - The texture.
  51508. * @param {Object} [options={}] - Optional configuration parameter.
  51509. */
  51510. updateTexture( texture, options ) {
  51511. const textureData = this.backend.get( texture );
  51512. const mipmaps = texture.mipmaps;
  51513. const { textureDescriptorGPU } = textureData;
  51514. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  51515. return;
  51516. // transfer texture data
  51517. if ( texture.isDataTexture ) {
  51518. if ( mipmaps.length > 0 ) {
  51519. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51520. const mipmap = mipmaps[ i ];
  51521. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  51522. }
  51523. } else {
  51524. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  51525. }
  51526. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  51527. for ( let i = 0; i < options.image.depth; i ++ ) {
  51528. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  51529. }
  51530. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  51531. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  51532. } else if ( texture.isCubeTexture ) {
  51533. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  51534. } else {
  51535. if ( mipmaps.length > 0 ) {
  51536. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  51537. const mipmap = mipmaps[ i ];
  51538. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  51539. }
  51540. } else {
  51541. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  51542. }
  51543. }
  51544. //
  51545. textureData.version = texture.version;
  51546. }
  51547. /**
  51548. * Returns texture data as a typed array.
  51549. *
  51550. * @async
  51551. * @param {Texture} texture - The texture to copy.
  51552. * @param {number} x - The x coordinate of the copy origin.
  51553. * @param {number} y - The y coordinate of the copy origin.
  51554. * @param {number} width - The width of the copy.
  51555. * @param {number} height - The height of the copy.
  51556. * @param {number} faceIndex - The face index.
  51557. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51558. */
  51559. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51560. const device = this.backend.device;
  51561. const textureData = this.backend.get( texture );
  51562. const textureGPU = textureData.texture;
  51563. const format = textureData.textureDescriptorGPU.format;
  51564. const bytesPerTexel = this._getBytesPerTexel( format );
  51565. let bytesPerRow = width * bytesPerTexel;
  51566. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  51567. const readBuffer = device.createBuffer(
  51568. {
  51569. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  51570. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51571. }
  51572. );
  51573. const encoder = device.createCommandEncoder();
  51574. encoder.copyTextureToBuffer(
  51575. {
  51576. texture: textureGPU,
  51577. origin: { x, y, z: faceIndex },
  51578. },
  51579. {
  51580. buffer: readBuffer,
  51581. bytesPerRow: bytesPerRow
  51582. },
  51583. {
  51584. width: width,
  51585. height: height
  51586. }
  51587. );
  51588. const typedArrayType = this._getTypedArrayType( format );
  51589. device.queue.submit( [ encoder.finish() ] );
  51590. await readBuffer.mapAsync( GPUMapMode.READ );
  51591. const buffer = readBuffer.getMappedRange();
  51592. return new typedArrayType( buffer );
  51593. }
  51594. /**
  51595. * Frees all internal resources.
  51596. */
  51597. dispose() {
  51598. this._samplerCache.clear();
  51599. }
  51600. /**
  51601. * Returns the default GPU texture for the given format.
  51602. *
  51603. * @private
  51604. * @param {string} format - The GPU format.
  51605. * @return {GPUTexture} The GPU texture.
  51606. */
  51607. _getDefaultTextureGPU( format ) {
  51608. let defaultTexture = this.defaultTexture[ format ];
  51609. if ( defaultTexture === undefined ) {
  51610. const texture = new Texture();
  51611. texture.minFilter = NearestFilter;
  51612. texture.magFilter = NearestFilter;
  51613. this.createTexture( texture, { width: 1, height: 1, format } );
  51614. this.defaultTexture[ format ] = defaultTexture = texture;
  51615. }
  51616. return this.backend.get( defaultTexture ).texture;
  51617. }
  51618. /**
  51619. * Returns the default GPU cube texture for the given format.
  51620. *
  51621. * @private
  51622. * @param {string} format - The GPU format.
  51623. * @return {GPUTexture} The GPU texture.
  51624. */
  51625. _getDefaultCubeTextureGPU( format ) {
  51626. let defaultCubeTexture = this.defaultCubeTexture[ format ];
  51627. if ( defaultCubeTexture === undefined ) {
  51628. const texture = new CubeTexture();
  51629. texture.minFilter = NearestFilter;
  51630. texture.magFilter = NearestFilter;
  51631. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  51632. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  51633. }
  51634. return this.backend.get( defaultCubeTexture ).texture;
  51635. }
  51636. /**
  51637. * Uploads cube texture image data to the GPU memory.
  51638. *
  51639. * @private
  51640. * @param {CubeTexture} texture - The cube texture.
  51641. * @param {GPUTexture} textureGPU - The GPU texture.
  51642. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51643. */
  51644. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  51645. const images = texture.images;
  51646. const mipmaps = texture.mipmaps;
  51647. for ( let i = 0; i < 6; i ++ ) {
  51648. const image = images[ i ];
  51649. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  51650. if ( image.isDataTexture ) {
  51651. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  51652. } else {
  51653. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  51654. }
  51655. for ( let j = 0; j < mipmaps.length; j ++ ) {
  51656. const mipmap = mipmaps[ j ];
  51657. const image = mipmap.images[ i ];
  51658. if ( image.isDataTexture ) {
  51659. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  51660. } else {
  51661. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  51662. }
  51663. }
  51664. }
  51665. }
  51666. /**
  51667. * Uploads texture image data to the GPU memory.
  51668. *
  51669. * @private
  51670. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  51671. * @param {GPUTexture} textureGPU - The GPU texture.
  51672. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51673. * @param {number} originDepth - The origin depth.
  51674. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51675. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  51676. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51677. */
  51678. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  51679. const device = this.backend.device;
  51680. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  51681. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  51682. try {
  51683. device.queue.copyExternalImageToTexture(
  51684. {
  51685. source: image,
  51686. flipY: flipY
  51687. }, {
  51688. texture: textureGPU,
  51689. mipLevel: mipLevel,
  51690. origin: { x: 0, y: 0, z: originDepth },
  51691. premultipliedAlpha: premultiplyAlpha
  51692. }, {
  51693. width: width,
  51694. height: height,
  51695. depthOrArrayLayers: 1
  51696. }
  51697. );
  51698. // try/catch has been added to fix bad video frame data on certain devices, see #32391
  51699. } catch ( _ ) {}
  51700. }
  51701. /**
  51702. * Returns the pass utils singleton.
  51703. *
  51704. * @private
  51705. * @return {WebGPUTexturePassUtils} The utils instance.
  51706. */
  51707. _getPassUtils() {
  51708. let passUtils = this._passUtils;
  51709. if ( passUtils === null ) {
  51710. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  51711. }
  51712. return passUtils;
  51713. }
  51714. /**
  51715. * Generates mipmaps for the given GPU texture.
  51716. *
  51717. * @private
  51718. * @param {GPUTexture} textureGPU - The GPU texture object.
  51719. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51720. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  51721. * @param {?GPUCommandEncoder} [encoder=null] - An optional command encoder used to generate mipmaps.
  51722. */
  51723. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0, encoder = null ) {
  51724. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer, encoder );
  51725. }
  51726. /**
  51727. * Flip the contents of the given GPU texture along its vertical axis.
  51728. *
  51729. * @private
  51730. * @param {GPUTexture} textureGPU - The GPU texture object.
  51731. * @param {Object} textureDescriptorGPU - The texture descriptor.
  51732. * @param {number} [originDepth=0] - The origin depth.
  51733. */
  51734. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  51735. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  51736. }
  51737. /**
  51738. * Uploads texture buffer data to the GPU memory.
  51739. *
  51740. * @private
  51741. * @param {Object} image - An object defining the image buffer data.
  51742. * @param {GPUTexture} textureGPU - The GPU texture.
  51743. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51744. * @param {number} originDepth - The origin depth.
  51745. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  51746. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  51747. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  51748. */
  51749. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  51750. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51751. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  51752. const device = this.backend.device;
  51753. const data = image.data;
  51754. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  51755. const bytesPerRow = image.width * bytesPerTexel;
  51756. device.queue.writeTexture(
  51757. {
  51758. texture: textureGPU,
  51759. mipLevel: mipLevel,
  51760. origin: { x: 0, y: 0, z: originDepth }
  51761. },
  51762. data,
  51763. {
  51764. offset: image.width * image.height * bytesPerTexel * depth,
  51765. bytesPerRow
  51766. },
  51767. {
  51768. width: image.width,
  51769. height: image.height,
  51770. depthOrArrayLayers: 1
  51771. } );
  51772. if ( flipY === true ) {
  51773. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  51774. }
  51775. }
  51776. /**
  51777. * Uploads compressed texture data to the GPU memory.
  51778. *
  51779. * @private
  51780. * @param {Array<Object>} mipmaps - An array with mipmap data.
  51781. * @param {GPUTexture} textureGPU - The GPU texture.
  51782. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  51783. */
  51784. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  51785. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  51786. const device = this.backend.device;
  51787. const blockData = this._getBlockData( textureDescriptorGPU.format );
  51788. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  51789. for ( let i = 0; i < mipmaps.length; i ++ ) {
  51790. const mipmap = mipmaps[ i ];
  51791. const width = mipmap.width;
  51792. const height = mipmap.height;
  51793. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  51794. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  51795. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  51796. for ( let j = 0; j < depth; j ++ ) {
  51797. device.queue.writeTexture(
  51798. {
  51799. texture: textureGPU,
  51800. mipLevel: i,
  51801. origin: { x: 0, y: 0, z: j }
  51802. },
  51803. mipmap.data,
  51804. {
  51805. offset: j * bytesPerImage,
  51806. bytesPerRow,
  51807. rowsPerImage: Math.ceil( height / blockData.height )
  51808. },
  51809. {
  51810. width: Math.ceil( width / blockData.width ) * blockData.width,
  51811. height: Math.ceil( height / blockData.height ) * blockData.height,
  51812. depthOrArrayLayers: 1
  51813. }
  51814. );
  51815. }
  51816. }
  51817. }
  51818. /**
  51819. * This method is only relevant for compressed texture formats. It returns a block
  51820. * data descriptor for the given GPU compressed texture format.
  51821. *
  51822. * @private
  51823. * @param {string} format - The GPU compressed texture format.
  51824. * @return {Object} The block data descriptor.
  51825. */
  51826. _getBlockData( format ) {
  51827. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  51828. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  51829. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  51830. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  51831. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  51832. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  51833. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  51834. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51835. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  51836. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51837. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  51838. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  51839. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  51840. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  51841. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  51842. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  51843. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  51844. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  51845. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  51846. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  51847. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  51848. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  51849. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  51850. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  51851. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  51852. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  51853. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  51854. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  51855. }
  51856. /**
  51857. * Converts the three.js uv wrapping constants to GPU address mode constants.
  51858. *
  51859. * @private
  51860. * @param {number} value - The three.js constant defining a uv wrapping mode.
  51861. * @return {string} The GPU address mode.
  51862. */
  51863. _convertAddressMode( value ) {
  51864. let addressMode = GPUAddressMode.ClampToEdge;
  51865. if ( value === RepeatWrapping ) {
  51866. addressMode = GPUAddressMode.Repeat;
  51867. } else if ( value === MirroredRepeatWrapping ) {
  51868. addressMode = GPUAddressMode.MirrorRepeat;
  51869. }
  51870. return addressMode;
  51871. }
  51872. /**
  51873. * Converts the three.js filter constants to GPU filter constants.
  51874. *
  51875. * @private
  51876. * @param {number} value - The three.js constant defining a filter mode.
  51877. * @return {string} The GPU filter mode.
  51878. */
  51879. _convertFilterMode( value ) {
  51880. let filterMode = GPUFilterMode.Linear;
  51881. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  51882. filterMode = GPUFilterMode.Nearest;
  51883. }
  51884. return filterMode;
  51885. }
  51886. /**
  51887. * Returns the bytes-per-texel value for the given GPU texture format.
  51888. *
  51889. * @private
  51890. * @param {string} format - The GPU texture format.
  51891. * @return {number} The bytes-per-texel.
  51892. */
  51893. _getBytesPerTexel( format ) {
  51894. // 8-bit formats
  51895. if ( format === GPUTextureFormat.R8Unorm ||
  51896. format === GPUTextureFormat.R8Snorm ||
  51897. format === GPUTextureFormat.R8Uint ||
  51898. format === GPUTextureFormat.R8Sint ) return 1;
  51899. // 16-bit formats
  51900. if ( format === GPUTextureFormat.R16Uint ||
  51901. format === GPUTextureFormat.R16Sint ||
  51902. format === GPUTextureFormat.R16Float ||
  51903. format === GPUTextureFormat.RG8Unorm ||
  51904. format === GPUTextureFormat.RG8Snorm ||
  51905. format === GPUTextureFormat.RG8Uint ||
  51906. format === GPUTextureFormat.RG8Sint ) return 2;
  51907. // 32-bit formats
  51908. if ( format === GPUTextureFormat.R32Uint ||
  51909. format === GPUTextureFormat.R32Sint ||
  51910. format === GPUTextureFormat.R32Float ||
  51911. format === GPUTextureFormat.RG16Uint ||
  51912. format === GPUTextureFormat.RG16Sint ||
  51913. format === GPUTextureFormat.RG16Float ||
  51914. format === GPUTextureFormat.RGBA8Unorm ||
  51915. format === GPUTextureFormat.RGBA8UnormSRGB ||
  51916. format === GPUTextureFormat.RGBA8Snorm ||
  51917. format === GPUTextureFormat.RGBA8Uint ||
  51918. format === GPUTextureFormat.RGBA8Sint ||
  51919. format === GPUTextureFormat.BGRA8Unorm ||
  51920. format === GPUTextureFormat.BGRA8UnormSRGB ||
  51921. // Packed 32-bit formats
  51922. format === GPUTextureFormat.RGB9E5UFloat ||
  51923. format === GPUTextureFormat.RGB10A2Unorm ||
  51924. format === GPUTextureFormat.RG11B10UFloat ||
  51925. format === GPUTextureFormat.Depth32Float ||
  51926. format === GPUTextureFormat.Depth24Plus ||
  51927. format === GPUTextureFormat.Depth24PlusStencil8 ||
  51928. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  51929. // 64-bit formats
  51930. if ( format === GPUTextureFormat.RG32Uint ||
  51931. format === GPUTextureFormat.RG32Sint ||
  51932. format === GPUTextureFormat.RG32Float ||
  51933. format === GPUTextureFormat.RGBA16Uint ||
  51934. format === GPUTextureFormat.RGBA16Sint ||
  51935. format === GPUTextureFormat.RGBA16Float ) return 8;
  51936. // 128-bit formats
  51937. if ( format === GPUTextureFormat.RGBA32Uint ||
  51938. format === GPUTextureFormat.RGBA32Sint ||
  51939. format === GPUTextureFormat.RGBA32Float ) return 16;
  51940. }
  51941. /**
  51942. * Returns the corresponding typed array type for the given GPU texture format.
  51943. *
  51944. * @private
  51945. * @param {string} format - The GPU texture format.
  51946. * @return {TypedArray.constructor} The typed array type.
  51947. */
  51948. _getTypedArrayType( format ) {
  51949. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  51950. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  51951. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  51952. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  51953. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  51954. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  51955. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  51956. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  51957. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  51958. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  51959. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  51960. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  51961. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  51962. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  51963. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  51964. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  51965. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  51966. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  51967. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  51968. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  51969. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  51970. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  51971. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  51972. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  51973. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  51974. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  51975. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  51976. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  51977. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  51978. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  51979. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  51980. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  51981. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  51982. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  51983. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  51984. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  51985. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  51986. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  51987. }
  51988. /**
  51989. * Returns the GPU dimensions for the given texture.
  51990. *
  51991. * @private
  51992. * @param {Texture} texture - The texture.
  51993. * @return {string} The GPU dimension.
  51994. */
  51995. _getDimension( texture ) {
  51996. let dimension;
  51997. if ( texture.is3DTexture || texture.isData3DTexture ) {
  51998. dimension = GPUTextureDimension.ThreeD;
  51999. } else {
  52000. dimension = GPUTextureDimension.TwoD;
  52001. }
  52002. return dimension;
  52003. }
  52004. }
  52005. /**
  52006. * Returns the GPU format for the given texture.
  52007. *
  52008. * @param {Texture} texture - The texture.
  52009. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  52010. * It is not necessary to apply the device for most formats.
  52011. * @return {string} The GPU format.
  52012. */
  52013. function getFormat( texture, device = null ) {
  52014. const format = texture.format;
  52015. const type = texture.type;
  52016. const colorSpace = texture.colorSpace;
  52017. const transfer = ColorManagement.getTransfer( colorSpace );
  52018. let formatGPU;
  52019. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  52020. switch ( format ) {
  52021. case RGB_S3TC_DXT1_Format:
  52022. case RGBA_S3TC_DXT1_Format:
  52023. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  52024. break;
  52025. case RGBA_S3TC_DXT3_Format:
  52026. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  52027. break;
  52028. case RGBA_S3TC_DXT5_Format:
  52029. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  52030. break;
  52031. case RED_RGTC1_Format:
  52032. formatGPU = GPUTextureFormat.BC4RUnorm;
  52033. break;
  52034. case SIGNED_RED_RGTC1_Format:
  52035. formatGPU = GPUTextureFormat.BC4RSnorm;
  52036. break;
  52037. case RED_GREEN_RGTC2_Format:
  52038. formatGPU = GPUTextureFormat.BC5RGUnorm;
  52039. break;
  52040. case SIGNED_RED_GREEN_RGTC2_Format:
  52041. formatGPU = GPUTextureFormat.BC5RGSnorm;
  52042. break;
  52043. case RGBA_BPTC_Format:
  52044. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  52045. break;
  52046. case RGB_ETC2_Format:
  52047. case RGB_ETC1_Format:
  52048. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  52049. break;
  52050. case RGBA_ETC2_EAC_Format:
  52051. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  52052. break;
  52053. case R11_EAC_Format:
  52054. formatGPU = GPUTextureFormat.EACR11Unorm;
  52055. break;
  52056. case SIGNED_R11_EAC_Format:
  52057. formatGPU = GPUTextureFormat.EACR11Snorm;
  52058. break;
  52059. case RG11_EAC_Format:
  52060. formatGPU = GPUTextureFormat.EACRG11Unorm;
  52061. break;
  52062. case SIGNED_RG11_EAC_Format:
  52063. formatGPU = GPUTextureFormat.EACRG11Snorm;
  52064. break;
  52065. case RGBA_ASTC_4x4_Format:
  52066. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  52067. break;
  52068. case RGBA_ASTC_5x4_Format:
  52069. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  52070. break;
  52071. case RGBA_ASTC_5x5_Format:
  52072. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  52073. break;
  52074. case RGBA_ASTC_6x5_Format:
  52075. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  52076. break;
  52077. case RGBA_ASTC_6x6_Format:
  52078. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  52079. break;
  52080. case RGBA_ASTC_8x5_Format:
  52081. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  52082. break;
  52083. case RGBA_ASTC_8x6_Format:
  52084. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  52085. break;
  52086. case RGBA_ASTC_8x8_Format:
  52087. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  52088. break;
  52089. case RGBA_ASTC_10x5_Format:
  52090. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  52091. break;
  52092. case RGBA_ASTC_10x6_Format:
  52093. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  52094. break;
  52095. case RGBA_ASTC_10x8_Format:
  52096. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  52097. break;
  52098. case RGBA_ASTC_10x10_Format:
  52099. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  52100. break;
  52101. case RGBA_ASTC_12x10_Format:
  52102. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  52103. break;
  52104. case RGBA_ASTC_12x12_Format:
  52105. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  52106. break;
  52107. case RGBAFormat:
  52108. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  52109. break;
  52110. default:
  52111. error( 'WebGPURenderer: Unsupported texture format.', format );
  52112. }
  52113. } else {
  52114. switch ( format ) {
  52115. case RGBAFormat:
  52116. switch ( type ) {
  52117. case ByteType:
  52118. formatGPU = GPUTextureFormat.RGBA8Snorm;
  52119. break;
  52120. case ShortType:
  52121. formatGPU = GPUTextureFormat.RGBA16Sint;
  52122. break;
  52123. case UnsignedShortType:
  52124. formatGPU = GPUTextureFormat.RGBA16Uint;
  52125. break;
  52126. case UnsignedIntType:
  52127. formatGPU = GPUTextureFormat.RGBA32Uint;
  52128. break;
  52129. case IntType:
  52130. formatGPU = GPUTextureFormat.RGBA32Sint;
  52131. break;
  52132. case UnsignedByteType:
  52133. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  52134. break;
  52135. case HalfFloatType:
  52136. formatGPU = GPUTextureFormat.RGBA16Float;
  52137. break;
  52138. case FloatType:
  52139. formatGPU = GPUTextureFormat.RGBA32Float;
  52140. break;
  52141. default:
  52142. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  52143. }
  52144. break;
  52145. case RGBFormat:
  52146. switch ( type ) {
  52147. case UnsignedInt5999Type:
  52148. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  52149. break;
  52150. case UnsignedInt101111Type:
  52151. formatGPU = GPUTextureFormat.RG11B10UFloat;
  52152. break;
  52153. default:
  52154. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  52155. }
  52156. break;
  52157. case RedFormat:
  52158. switch ( type ) {
  52159. case ByteType:
  52160. formatGPU = GPUTextureFormat.R8Snorm;
  52161. break;
  52162. case ShortType:
  52163. formatGPU = GPUTextureFormat.R16Sint;
  52164. break;
  52165. case UnsignedShortType:
  52166. formatGPU = GPUTextureFormat.R16Uint;
  52167. break;
  52168. case UnsignedIntType:
  52169. formatGPU = GPUTextureFormat.R32Uint;
  52170. break;
  52171. case IntType:
  52172. formatGPU = GPUTextureFormat.R32Sint;
  52173. break;
  52174. case UnsignedByteType:
  52175. formatGPU = GPUTextureFormat.R8Unorm;
  52176. break;
  52177. case HalfFloatType:
  52178. formatGPU = GPUTextureFormat.R16Float;
  52179. break;
  52180. case FloatType:
  52181. formatGPU = GPUTextureFormat.R32Float;
  52182. break;
  52183. default:
  52184. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  52185. }
  52186. break;
  52187. case RGFormat:
  52188. switch ( type ) {
  52189. case ByteType:
  52190. formatGPU = GPUTextureFormat.RG8Snorm;
  52191. break;
  52192. case ShortType:
  52193. formatGPU = GPUTextureFormat.RG16Sint;
  52194. break;
  52195. case UnsignedShortType:
  52196. formatGPU = GPUTextureFormat.RG16Uint;
  52197. break;
  52198. case UnsignedIntType:
  52199. formatGPU = GPUTextureFormat.RG32Uint;
  52200. break;
  52201. case IntType:
  52202. formatGPU = GPUTextureFormat.RG32Sint;
  52203. break;
  52204. case UnsignedByteType:
  52205. formatGPU = GPUTextureFormat.RG8Unorm;
  52206. break;
  52207. case HalfFloatType:
  52208. formatGPU = GPUTextureFormat.RG16Float;
  52209. break;
  52210. case FloatType:
  52211. formatGPU = GPUTextureFormat.RG32Float;
  52212. break;
  52213. default:
  52214. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  52215. }
  52216. break;
  52217. case DepthFormat:
  52218. switch ( type ) {
  52219. case UnsignedShortType:
  52220. formatGPU = GPUTextureFormat.Depth16Unorm;
  52221. break;
  52222. case UnsignedIntType:
  52223. formatGPU = GPUTextureFormat.Depth24Plus;
  52224. break;
  52225. case FloatType:
  52226. formatGPU = GPUTextureFormat.Depth32Float;
  52227. break;
  52228. default:
  52229. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  52230. }
  52231. break;
  52232. case DepthStencilFormat:
  52233. switch ( type ) {
  52234. case UnsignedInt248Type:
  52235. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  52236. break;
  52237. case FloatType:
  52238. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  52239. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  52240. }
  52241. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  52242. break;
  52243. default:
  52244. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  52245. }
  52246. break;
  52247. case RedIntegerFormat:
  52248. switch ( type ) {
  52249. case IntType:
  52250. formatGPU = GPUTextureFormat.R32Sint;
  52251. break;
  52252. case UnsignedIntType:
  52253. formatGPU = GPUTextureFormat.R32Uint;
  52254. break;
  52255. default:
  52256. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  52257. }
  52258. break;
  52259. case RGIntegerFormat:
  52260. switch ( type ) {
  52261. case IntType:
  52262. formatGPU = GPUTextureFormat.RG32Sint;
  52263. break;
  52264. case UnsignedIntType:
  52265. formatGPU = GPUTextureFormat.RG32Uint;
  52266. break;
  52267. default:
  52268. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  52269. }
  52270. break;
  52271. case RGBAIntegerFormat:
  52272. switch ( type ) {
  52273. case IntType:
  52274. formatGPU = GPUTextureFormat.RGBA32Sint;
  52275. break;
  52276. case UnsignedIntType:
  52277. formatGPU = GPUTextureFormat.RGBA32Uint;
  52278. break;
  52279. default:
  52280. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  52281. }
  52282. break;
  52283. default:
  52284. error( 'WebGPURenderer: Unsupported texture format.', format );
  52285. }
  52286. }
  52287. return formatGPU;
  52288. }
  52289. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  52290. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  52291. const wgslTypeLib$1 = {
  52292. 'f32': 'float',
  52293. 'i32': 'int',
  52294. 'u32': 'uint',
  52295. 'bool': 'bool',
  52296. 'vec2<f32>': 'vec2',
  52297. 'vec2<i32>': 'ivec2',
  52298. 'vec2<u32>': 'uvec2',
  52299. 'vec2<bool>': 'bvec2',
  52300. 'vec2f': 'vec2',
  52301. 'vec2i': 'ivec2',
  52302. 'vec2u': 'uvec2',
  52303. 'vec2b': 'bvec2',
  52304. 'vec3<f32>': 'vec3',
  52305. 'vec3<i32>': 'ivec3',
  52306. 'vec3<u32>': 'uvec3',
  52307. 'vec3<bool>': 'bvec3',
  52308. 'vec3f': 'vec3',
  52309. 'vec3i': 'ivec3',
  52310. 'vec3u': 'uvec3',
  52311. 'vec3b': 'bvec3',
  52312. 'vec4<f32>': 'vec4',
  52313. 'vec4<i32>': 'ivec4',
  52314. 'vec4<u32>': 'uvec4',
  52315. 'vec4<bool>': 'bvec4',
  52316. 'vec4f': 'vec4',
  52317. 'vec4i': 'ivec4',
  52318. 'vec4u': 'uvec4',
  52319. 'vec4b': 'bvec4',
  52320. 'mat2x2<f32>': 'mat2',
  52321. 'mat2x2f': 'mat2',
  52322. 'mat3x3<f32>': 'mat3',
  52323. 'mat3x3f': 'mat3',
  52324. 'mat4x4<f32>': 'mat4',
  52325. 'mat4x4f': 'mat4',
  52326. 'sampler': 'sampler',
  52327. 'texture_1d': 'texture',
  52328. 'texture_2d': 'texture',
  52329. 'texture_2d_array': 'texture',
  52330. 'texture_multisampled_2d': 'cubeTexture',
  52331. 'texture_depth_2d': 'depthTexture',
  52332. 'texture_depth_2d_array': 'depthTexture',
  52333. 'texture_depth_multisampled_2d': 'depthTexture',
  52334. 'texture_depth_cube': 'depthTexture',
  52335. 'texture_depth_cube_array': 'depthTexture',
  52336. 'texture_3d': 'texture3D',
  52337. 'texture_cube': 'cubeTexture',
  52338. 'texture_cube_array': 'cubeTexture',
  52339. 'texture_storage_1d': 'storageTexture',
  52340. 'texture_storage_2d': 'storageTexture',
  52341. 'texture_storage_2d_array': 'storageTexture',
  52342. 'texture_storage_3d': 'storageTexture'
  52343. };
  52344. const parse = ( source ) => {
  52345. source = source.trim();
  52346. const declaration = source.match( declarationRegexp );
  52347. if ( declaration !== null && declaration.length === 4 ) {
  52348. const inputsCode = declaration[ 2 ];
  52349. const propsMatches = [];
  52350. let match = null;
  52351. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  52352. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  52353. }
  52354. // Process matches to correctly pair names and types
  52355. const inputs = [];
  52356. for ( let i = 0; i < propsMatches.length; i ++ ) {
  52357. const { name, type } = propsMatches[ i ];
  52358. let resolvedType = type;
  52359. if ( resolvedType.startsWith( 'ptr' ) ) {
  52360. resolvedType = 'pointer';
  52361. } else {
  52362. if ( resolvedType.startsWith( 'texture' ) ) {
  52363. resolvedType = type.split( '<' )[ 0 ];
  52364. }
  52365. resolvedType = wgslTypeLib$1[ resolvedType ];
  52366. }
  52367. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  52368. }
  52369. const blockCode = source.substring( declaration[ 0 ].length );
  52370. const outputType = declaration[ 3 ] || 'void';
  52371. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  52372. const type = wgslTypeLib$1[ outputType ] || outputType;
  52373. return {
  52374. type,
  52375. inputs,
  52376. name,
  52377. inputsCode,
  52378. blockCode,
  52379. outputType
  52380. };
  52381. } else {
  52382. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  52383. }
  52384. };
  52385. /**
  52386. * This class represents a WSL node function.
  52387. *
  52388. * @augments NodeFunction
  52389. */
  52390. class WGSLNodeFunction extends NodeFunction {
  52391. /**
  52392. * Constructs a new WGSL node function.
  52393. *
  52394. * @param {string} source - The WGSL source.
  52395. */
  52396. constructor( source ) {
  52397. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  52398. super( type, inputs, name );
  52399. this.inputsCode = inputsCode;
  52400. this.blockCode = blockCode;
  52401. this.outputType = outputType;
  52402. }
  52403. /**
  52404. * This method returns the WGSL code of the node function.
  52405. *
  52406. * @param {string} [name=this.name] - The function's name.
  52407. * @return {string} The shader code.
  52408. */
  52409. getCode( name = this.name ) {
  52410. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  52411. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  52412. }
  52413. }
  52414. /**
  52415. * A WGSL node parser.
  52416. *
  52417. * @augments NodeParser
  52418. */
  52419. class WGSLNodeParser extends NodeParser {
  52420. /**
  52421. * The method parses the given WGSL code an returns a node function.
  52422. *
  52423. * @param {string} source - The WGSL code.
  52424. * @return {WGSLNodeFunction} A node function.
  52425. */
  52426. parseFunction( source ) {
  52427. return new WGSLNodeFunction( source );
  52428. }
  52429. }
  52430. const accessNames = {
  52431. [ NodeAccess.READ_ONLY ]: 'read',
  52432. [ NodeAccess.WRITE_ONLY ]: 'write',
  52433. [ NodeAccess.READ_WRITE ]: 'read_write'
  52434. };
  52435. const wrapNames = {
  52436. [ RepeatWrapping ]: 'repeat',
  52437. [ ClampToEdgeWrapping ]: 'clamp',
  52438. [ MirroredRepeatWrapping ]: 'mirror'
  52439. };
  52440. const gpuShaderStageLib = {
  52441. 'vertex': GPUShaderStage.VERTEX,
  52442. 'fragment': GPUShaderStage.FRAGMENT,
  52443. 'compute': GPUShaderStage.COMPUTE
  52444. };
  52445. const supports = {
  52446. instance: true,
  52447. swizzleAssign: false,
  52448. storageBuffer: true
  52449. };
  52450. const wgslFnOpLib = {
  52451. '^^': 'tsl_xor'
  52452. };
  52453. const wgslTypeLib = {
  52454. float: 'f32',
  52455. int: 'i32',
  52456. uint: 'u32',
  52457. bool: 'bool',
  52458. color: 'vec3<f32>',
  52459. vec2: 'vec2<f32>',
  52460. ivec2: 'vec2<i32>',
  52461. uvec2: 'vec2<u32>',
  52462. bvec2: 'vec2<bool>',
  52463. vec3: 'vec3<f32>',
  52464. ivec3: 'vec3<i32>',
  52465. uvec3: 'vec3<u32>',
  52466. bvec3: 'vec3<bool>',
  52467. vec4: 'vec4<f32>',
  52468. ivec4: 'vec4<i32>',
  52469. uvec4: 'vec4<u32>',
  52470. bvec4: 'vec4<bool>',
  52471. mat2: 'mat2x2<f32>',
  52472. mat3: 'mat3x3<f32>',
  52473. mat4: 'mat4x4<f32>'
  52474. };
  52475. const wgslCodeCache = {};
  52476. const wgslPolyfill = {
  52477. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  52478. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  52479. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  52480. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  52481. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  52482. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  52483. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  52484. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  52485. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  52486. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  52487. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  52488. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  52489. biquadraticTexture: new CodeNode( /* wgsl */`
  52490. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  52491. let res = vec2f( iRes );
  52492. let uvScaled = coord * res;
  52493. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  52494. // https://www.shadertoy.com/view/WtyXRy
  52495. let uv = uvWrapping - 0.5;
  52496. let iuv = floor( uv );
  52497. let f = fract( uv );
  52498. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  52499. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  52500. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  52501. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  52502. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  52503. }
  52504. ` )
  52505. };
  52506. const wgslMethods = {
  52507. dFdx: 'dpdx',
  52508. dFdy: '- dpdy',
  52509. mod_float: 'tsl_mod_float',
  52510. mod_vec2: 'tsl_mod_vec2',
  52511. mod_vec3: 'tsl_mod_vec3',
  52512. mod_vec4: 'tsl_mod_vec4',
  52513. equals_bool: 'tsl_equals_bool',
  52514. equals_bvec2: 'tsl_equals_bvec2',
  52515. equals_bvec3: 'tsl_equals_bvec3',
  52516. equals_bvec4: 'tsl_equals_bvec4',
  52517. inversesqrt: 'inverseSqrt',
  52518. bitcast: 'bitcast<f32>',
  52519. floatpack_snorm_2x16: 'pack2x16snorm',
  52520. floatpack_unorm_2x16: 'pack2x16unorm',
  52521. floatpack_float16_2x16: 'pack2x16float',
  52522. floatunpack_snorm_2x16: 'unpack2x16snorm',
  52523. floatunpack_unorm_2x16: 'unpack2x16unorm',
  52524. floatunpack_float16_2x16: 'unpack2x16float'
  52525. };
  52526. //
  52527. let diagnostics = '';
  52528. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  52529. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  52530. }
  52531. /**
  52532. * A node builder targeting WGSL.
  52533. *
  52534. * This module generates WGSL shader code from node materials and also
  52535. * generates the respective bindings and vertex buffer definitions. These
  52536. * data are later used by the renderer to create render and compute pipelines
  52537. * for render objects.
  52538. *
  52539. * @augments NodeBuilder
  52540. */
  52541. class WGSLNodeBuilder extends NodeBuilder {
  52542. /**
  52543. * Constructs a new WGSL node builder renderer.
  52544. *
  52545. * @param {Object3D} object - The 3D object.
  52546. * @param {Renderer} renderer - The renderer.
  52547. */
  52548. constructor( object, renderer ) {
  52549. super( object, renderer, new WGSLNodeParser() );
  52550. /**
  52551. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  52552. * another dictionary which manages UBOs per group ('render','frame','object').
  52553. *
  52554. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  52555. */
  52556. this.uniformGroups = {};
  52557. /**
  52558. * A dictionary that holds the assigned binding indices for each uniform group.
  52559. * This ensures the same binding index is used across all shader stages.
  52560. *
  52561. * @type {Object<string,{index: number, id: number}>}
  52562. */
  52563. this.uniformGroupsBindings = {};
  52564. /**
  52565. * A dictionary that holds for each shader stage a Map of builtins.
  52566. *
  52567. * @type {Object<string,Map<string,Object>>}
  52568. */
  52569. this.builtins = {};
  52570. /**
  52571. * A dictionary that holds for each shader stage a Set of directives.
  52572. *
  52573. * @type {Object<string,Set<string>>}
  52574. */
  52575. this.directives = {};
  52576. /**
  52577. * A map for managing scope arrays. Only relevant for when using
  52578. * {@link WorkgroupInfoNode} in context of compute shaders.
  52579. *
  52580. * @type {Map<string,Object>}
  52581. */
  52582. this.scopedArrays = new Map();
  52583. }
  52584. /**
  52585. * Generates the WGSL snippet for sampled textures.
  52586. *
  52587. * @private
  52588. * @param {Texture} texture - The texture.
  52589. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52590. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52591. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52592. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52593. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52594. * @return {string} The WGSL snippet.
  52595. */
  52596. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52597. if ( shaderStage === 'fragment' ) {
  52598. if ( depthSnippet ) {
  52599. if ( offsetSnippet ) {
  52600. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  52601. }
  52602. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  52603. } else {
  52604. if ( offsetSnippet ) {
  52605. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  52606. }
  52607. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  52608. }
  52609. } else {
  52610. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  52611. }
  52612. }
  52613. /**
  52614. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52615. *
  52616. * @private
  52617. * @param {Texture} texture - The texture.
  52618. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52619. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52620. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52621. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52622. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52623. * @return {string} The WGSL snippet.
  52624. */
  52625. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52626. if ( this.isUnfilterable( texture ) === false ) {
  52627. if ( offsetSnippet ) {
  52628. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52629. }
  52630. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52631. } else if ( this.isFilteredTexture( texture ) ) {
  52632. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52633. } else {
  52634. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52635. }
  52636. }
  52637. /**
  52638. * Generates a wrap function used in context of textures.
  52639. *
  52640. * @param {Texture} texture - The texture to generate the function for.
  52641. * @return {string} The name of the generated function.
  52642. */
  52643. generateWrapFunction( texture ) {
  52644. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.is3DTexture || texture.isData3DTexture ? '3d' : '2d' }T`;
  52645. let nodeCode = wgslCodeCache[ functionName ];
  52646. if ( nodeCode === undefined ) {
  52647. const includes = [];
  52648. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  52649. const coordType = texture.is3DTexture || texture.isData3DTexture ? 'vec3f' : 'vec2f';
  52650. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  52651. const addWrapSnippet = ( wrap, axis ) => {
  52652. if ( wrap === RepeatWrapping ) {
  52653. includes.push( wgslPolyfill.repeatWrapping_float );
  52654. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  52655. } else if ( wrap === ClampToEdgeWrapping ) {
  52656. includes.push( wgslPolyfill.clampWrapping_float );
  52657. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  52658. } else if ( wrap === MirroredRepeatWrapping ) {
  52659. includes.push( wgslPolyfill.mirrorWrapping_float );
  52660. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  52661. } else {
  52662. code += `\t\tcoord.${ axis }`;
  52663. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  52664. }
  52665. };
  52666. addWrapSnippet( texture.wrapS, 'x' );
  52667. code += ',\n';
  52668. addWrapSnippet( texture.wrapT, 'y' );
  52669. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52670. code += ',\n';
  52671. addWrapSnippet( texture.wrapR, 'z' );
  52672. }
  52673. code += '\n\t);\n\n}\n';
  52674. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  52675. }
  52676. nodeCode.build( this );
  52677. return functionName;
  52678. }
  52679. /**
  52680. * Generates the array declaration string.
  52681. *
  52682. * @param {string} type - The type.
  52683. * @param {?number} [count] - The count.
  52684. * @return {string} The generated value as a shader string.
  52685. */
  52686. generateArrayDeclaration( type, count ) {
  52687. return `array< ${ this.getType( type ) }, ${ count } >`;
  52688. }
  52689. /**
  52690. * Generates a WGSL variable that holds the texture dimension of the given texture.
  52691. * It also returns information about the number of layers (elements) of an arrayed
  52692. * texture as well as the cube face count of cube textures.
  52693. *
  52694. * @param {Texture} texture - The texture to generate the function for.
  52695. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  52696. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52697. * @return {string} The name of the dimension variable.
  52698. */
  52699. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  52700. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  52701. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  52702. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  52703. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  52704. let textureDimensionsParams;
  52705. let dimensionType;
  52706. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  52707. const isMultisampled = primarySamples > 1;
  52708. if ( texture.is3DTexture || texture.isData3DTexture ) {
  52709. dimensionType = 'vec3<u32>';
  52710. } else {
  52711. // Regular 2D textures, depth textures, etc.
  52712. dimensionType = 'vec2<u32>';
  52713. }
  52714. // Build parameters string based on texture type and multisampling
  52715. if ( isMultisampled || texture.isStorageTexture ) {
  52716. textureDimensionsParams = textureProperty;
  52717. } else {
  52718. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  52719. }
  52720. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  52721. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  52722. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.is3DTexture || texture.isData3DTexture ) {
  52723. textureData.arrayLayerCount = new VarNode(
  52724. new ExpressionNode(
  52725. `textureNumLayers(${textureProperty})`,
  52726. 'u32'
  52727. )
  52728. );
  52729. }
  52730. // For cube textures, we know it's always 6 faces
  52731. if ( texture.isTextureCube ) {
  52732. textureData.cubeFaceCount = new VarNode(
  52733. new ExpressionNode( '6u', 'u32' )
  52734. );
  52735. }
  52736. }
  52737. return textureDimensionNode.build( this );
  52738. }
  52739. /**
  52740. * Generates the WGSL snippet for a manual filtered texture.
  52741. *
  52742. * @param {Texture} texture - The texture.
  52743. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52744. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52745. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52746. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52747. * @return {string} The WGSL snippet.
  52748. */
  52749. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52750. this._include( 'biquadraticTexture' );
  52751. const wrapFunction = this.generateWrapFunction( texture );
  52752. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52753. if ( offsetSnippet ) {
  52754. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  52755. }
  52756. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  52757. }
  52758. /**
  52759. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  52760. * Since it's a lookup, no sampling or filtering is applied.
  52761. *
  52762. * @param {Texture} texture - The texture.
  52763. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52764. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52765. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52766. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52767. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52768. * @return {string} The WGSL snippet.
  52769. */
  52770. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  52771. // Cube textures cannot use textureLoad in WGSL, must use textureSampleLevel
  52772. if ( texture.isCubeTexture === true ) {
  52773. if ( offsetSnippet ) {
  52774. uvSnippet = `${ uvSnippet } + vec3<f32>(${ offsetSnippet })`;
  52775. }
  52776. // Depth textures require integer level, regular textures use float
  52777. const levelType = texture.isDepthTexture ? 'u32' : 'f32';
  52778. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelType }( ${ levelSnippet } ) )`;
  52779. }
  52780. const wrapFunction = this.generateWrapFunction( texture );
  52781. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  52782. const vecType = texture.is3DTexture || texture.isData3DTexture ? 'vec3' : 'vec2';
  52783. const textureDimensionMargin = ( vecType === 'vec3' ) ? 'vec3<u32>( 1, 1, 1 )' : 'vec2<u32>( 1, 1 )';
  52784. if ( offsetSnippet ) {
  52785. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  52786. }
  52787. const clampMin = `${ vecType }<f32>( 0 )`;
  52788. const clampMax = `${ vecType }<f32>( ${ textureDimension } - ${ textureDimensionMargin } )`;
  52789. uvSnippet = `${ vecType }<u32>( clamp( floor( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) ), ${ clampMin }, ${ clampMax } ) )`;
  52790. return this.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, null );
  52791. }
  52792. /**
  52793. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  52794. *
  52795. * @param {Texture} texture - The texture.
  52796. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52797. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52798. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52799. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52800. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52801. * @return {string} The WGSL snippet.
  52802. */
  52803. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52804. const isStorageTexture = texture.isStorageTexture === true;
  52805. if ( levelSnippet === null && ! isStorageTexture ) levelSnippet = '0u';
  52806. if ( offsetSnippet ) {
  52807. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  52808. }
  52809. let snippet;
  52810. if ( depthSnippet ) {
  52811. // Storage textures don't take a level parameter in WGSL
  52812. if ( isStorageTexture ) {
  52813. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet } )`;
  52814. } else {
  52815. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  52816. }
  52817. } else {
  52818. // Storage textures don't take a level parameter in WGSL
  52819. if ( isStorageTexture ) {
  52820. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  52821. } else {
  52822. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  52823. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  52824. snippet += '.x';
  52825. }
  52826. }
  52827. }
  52828. return snippet;
  52829. }
  52830. /**
  52831. * Generates the WGSL snippet that writes a single texel to a texture.
  52832. *
  52833. * @param {Texture} texture - The texture.
  52834. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52835. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52836. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52837. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  52838. * @return {string} The WGSL snippet.
  52839. */
  52840. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  52841. let snippet;
  52842. if ( depthSnippet ) {
  52843. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  52844. } else {
  52845. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  52846. }
  52847. return snippet;
  52848. }
  52849. /**
  52850. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  52851. *
  52852. * @param {Texture} texture - The texture.
  52853. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  52854. */
  52855. isSampleCompare( texture ) {
  52856. return texture.isDepthTexture === true && texture.compareFunction !== null && this.renderer.hasCompatibility( Compatibility.TEXTURE_COMPARE );
  52857. }
  52858. /**
  52859. * Returns `true` if the given texture is unfilterable.
  52860. *
  52861. * @param {Texture} texture - The texture.
  52862. * @return {boolean} Whether the given texture is unfilterable or not.
  52863. */
  52864. isUnfilterable( texture ) {
  52865. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  52866. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  52867. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  52868. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  52869. }
  52870. /**
  52871. * Generates the WGSL snippet for sampling/loading the given texture.
  52872. *
  52873. * @param {Texture} texture - The texture.
  52874. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52875. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52876. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52877. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52878. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52879. * @return {string} The WGSL snippet.
  52880. */
  52881. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52882. let snippet = null;
  52883. if ( this.isUnfilterable( texture ) ) {
  52884. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  52885. } else {
  52886. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  52887. }
  52888. return snippet;
  52889. }
  52890. /**
  52891. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  52892. *
  52893. * @param {Texture} texture - The texture.
  52894. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52895. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52896. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  52897. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52898. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52899. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52900. * @return {string} The WGSL snippet.
  52901. */
  52902. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52903. if ( shaderStage === 'fragment' ) {
  52904. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  52905. if ( offsetSnippet ) {
  52906. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  52907. }
  52908. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  52909. } else {
  52910. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  52911. }
  52912. }
  52913. /**
  52914. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  52915. * against a reference value.
  52916. *
  52917. * @param {Texture} texture - The texture.
  52918. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52919. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52920. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  52921. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52922. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52923. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52924. * @return {string} The WGSL snippet.
  52925. */
  52926. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52927. if ( shaderStage === 'fragment' ) {
  52928. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  52929. if ( offsetSnippet ) {
  52930. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52931. }
  52932. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  52933. }
  52934. if ( offsetSnippet ) {
  52935. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  52936. }
  52937. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  52938. } else {
  52939. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  52940. }
  52941. }
  52942. /**
  52943. * Generates the WGSL snippet when sampling textures with explicit mip level.
  52944. *
  52945. * @param {Texture} texture - The texture.
  52946. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52947. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52948. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  52949. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52950. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52951. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52952. * @return {string} The WGSL snippet.
  52953. */
  52954. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  52955. if ( this.isUnfilterable( texture ) === false ) {
  52956. if ( offsetSnippet ) {
  52957. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  52958. }
  52959. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  52960. } else if ( this.isFilteredTexture( texture ) ) {
  52961. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  52962. } else {
  52963. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  52964. }
  52965. }
  52966. /**
  52967. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  52968. *
  52969. * @param {Texture} texture - The texture.
  52970. * @param {string} textureProperty - The name of the texture uniform in the shader.
  52971. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  52972. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  52973. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  52974. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  52975. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52976. * @return {string} The WGSL snippet.
  52977. */
  52978. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  52979. if ( shaderStage === 'fragment' ) {
  52980. if ( offsetSnippet ) {
  52981. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  52982. }
  52983. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  52984. } else {
  52985. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  52986. }
  52987. }
  52988. /**
  52989. * Returns a WGSL snippet that represents the property name of the given node.
  52990. *
  52991. * @param {Node} node - The node.
  52992. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  52993. * @return {string} The property name.
  52994. */
  52995. getPropertyName( node, shaderStage = this.shaderStage ) {
  52996. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  52997. if ( shaderStage === 'vertex' ) {
  52998. return `varyings.${ node.name }`;
  52999. }
  53000. } else if ( node.isNodeUniform === true ) {
  53001. const name = node.name;
  53002. const type = node.type;
  53003. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  53004. return name;
  53005. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  53006. if ( this.isCustomStruct( node ) ) {
  53007. return name;
  53008. }
  53009. return name + '.value';
  53010. } else {
  53011. return node.groupNode.name + '.' + name;
  53012. }
  53013. }
  53014. return super.getPropertyName( node );
  53015. }
  53016. /**
  53017. * Returns the output struct name.
  53018. *
  53019. * @return {string} The name of the output struct.
  53020. */
  53021. getOutputStructName() {
  53022. return 'output';
  53023. }
  53024. /**
  53025. * Returns the native shader operator name for a given generic name.
  53026. *
  53027. * @param {string} op - The operator name to resolve.
  53028. * @return {?string} The resolved operator name.
  53029. */
  53030. getFunctionOperator( op ) {
  53031. const fnOp = wgslFnOpLib[ op ];
  53032. if ( fnOp !== undefined ) {
  53033. this._include( fnOp );
  53034. return fnOp;
  53035. }
  53036. return null;
  53037. }
  53038. /**
  53039. * Returns the node access for the given node and shader stage.
  53040. *
  53041. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  53042. * @param {string} shaderStage - The shader stage.
  53043. * @return {string} The node access.
  53044. */
  53045. getNodeAccess( node, shaderStage ) {
  53046. if ( shaderStage !== 'compute' ) {
  53047. if ( node.isAtomic === true ) {
  53048. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  53049. return NodeAccess.READ_WRITE;
  53050. }
  53051. return NodeAccess.READ_ONLY;
  53052. }
  53053. return node.access;
  53054. }
  53055. /**
  53056. * Returns A WGSL snippet representing the storage access.
  53057. *
  53058. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  53059. * @param {string} shaderStage - The shader stage.
  53060. * @return {string} The WGSL snippet representing the storage access.
  53061. */
  53062. getStorageAccess( node, shaderStage ) {
  53063. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  53064. }
  53065. /**
  53066. * This method is one of the more important ones since it's responsible
  53067. * for generating a matching binding instance for the given uniform node.
  53068. *
  53069. * These bindings are later used in the renderer to create bind groups
  53070. * and layouts.
  53071. *
  53072. * @param {UniformNode} node - The uniform node.
  53073. * @param {string} type - The node data type.
  53074. * @param {string} shaderStage - The shader stage.
  53075. * @param {?string} [name=null] - An optional uniform name.
  53076. * @return {NodeUniform} The node uniform object.
  53077. */
  53078. getUniformFromNode( node, type, shaderStage, name = null ) {
  53079. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  53080. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  53081. if ( nodeData.uniformGPU === undefined ) {
  53082. let uniformGPU;
  53083. const group = node.groupNode;
  53084. const groupName = group.name;
  53085. const bindings = this.getBindGroupArray( groupName, shaderStage );
  53086. if ( type === 'texture' || type === 'cubeTexture' || type === 'cubeDepthTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  53087. let texture = null;
  53088. const access = this.getNodeAccess( node, shaderStage );
  53089. if ( type === 'texture' || type === 'storageTexture' ) {
  53090. if ( node.value.is3DTexture === true ) {
  53091. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  53092. } else {
  53093. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  53094. }
  53095. } else if ( type === 'cubeTexture' || type === 'cubeDepthTexture' ) {
  53096. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  53097. } else if ( type === 'texture3D' ) {
  53098. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  53099. }
  53100. texture.store = node.isStorageTextureNode === true;
  53101. texture.mipLevel = texture.store ? node.mipLevel : 0;
  53102. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  53103. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  53104. const needsSampler = node.value.isCubeTexture === true || ( this.isUnfilterable( node.value ) === false && texture.store === false );
  53105. if ( needsSampler ) {
  53106. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  53107. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  53108. bindings.push( sampler, texture );
  53109. uniformGPU = [ sampler, texture ];
  53110. } else {
  53111. bindings.push( texture );
  53112. uniformGPU = [ texture ];
  53113. }
  53114. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  53115. const sharedData = this.getSharedDataFromNode( node );
  53116. let buffer = sharedData.buffer;
  53117. if ( buffer === undefined ) {
  53118. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  53119. buffer = new bufferClass( node, group );
  53120. sharedData.buffer = buffer;
  53121. }
  53122. buffer.setVisibility( buffer.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  53123. bindings.push( buffer );
  53124. uniformGPU = buffer;
  53125. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  53126. } else {
  53127. let uniformsGroup = this.uniformGroups[ groupName ];
  53128. if ( uniformsGroup === undefined ) {
  53129. uniformsGroup = new NodeUniformsGroup( groupName, group );
  53130. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  53131. this.uniformGroups[ groupName ] = uniformsGroup;
  53132. bindings.push( uniformsGroup );
  53133. } else {
  53134. // Update visibility to include this shader stage (bitwise OR)
  53135. uniformsGroup.setVisibility( uniformsGroup.getVisibility() | gpuShaderStageLib[ shaderStage ] );
  53136. // Add to bindings for this stage if not already present
  53137. if ( bindings.indexOf( uniformsGroup ) === -1 ) {
  53138. bindings.push( uniformsGroup );
  53139. }
  53140. }
  53141. uniformGPU = this.getNodeUniform( uniformNode, type );
  53142. // Only add uniform if not already present in the group (check by name to avoid duplicates across stages)
  53143. const uniformName = uniformGPU.name;
  53144. const alreadyExists = uniformsGroup.uniforms.some( u => u.name === uniformName );
  53145. if ( ! alreadyExists ) {
  53146. uniformsGroup.addUniform( uniformGPU );
  53147. }
  53148. }
  53149. nodeData.uniformGPU = uniformGPU;
  53150. }
  53151. return uniformNode;
  53152. }
  53153. /**
  53154. * This method should be used whenever builtins are required in nodes.
  53155. * The internal builtins data structure will make sure builtins are
  53156. * defined in the WGSL source.
  53157. *
  53158. * @param {string} name - The builtin name.
  53159. * @param {string} property - The property name.
  53160. * @param {string} type - The node data type.
  53161. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53162. * @return {string} The property name.
  53163. */
  53164. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  53165. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  53166. if ( map.has( name ) === false ) {
  53167. map.set( name, {
  53168. name,
  53169. property,
  53170. type
  53171. } );
  53172. }
  53173. return property;
  53174. }
  53175. /**
  53176. * Returns `true` if the given builtin is defined in the given shader stage.
  53177. *
  53178. * @param {string} name - The builtin name.
  53179. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  53180. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  53181. */
  53182. hasBuiltin( name, shaderStage = this.shaderStage ) {
  53183. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  53184. }
  53185. /**
  53186. * Returns the vertex index builtin.
  53187. *
  53188. * @return {string} The vertex index.
  53189. */
  53190. getVertexIndex() {
  53191. if ( this.shaderStage === 'vertex' ) {
  53192. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  53193. }
  53194. return 'vertexIndex';
  53195. }
  53196. /**
  53197. * Builds the given shader node.
  53198. *
  53199. * @param {ShaderNodeInternal} shaderNode - The shader node.
  53200. * @return {string} The WGSL function code.
  53201. */
  53202. buildFunctionCode( shaderNode ) {
  53203. const layout = shaderNode.layout;
  53204. const flowData = this.flowShaderNode( shaderNode );
  53205. const parameters = [];
  53206. for ( const input of layout.inputs ) {
  53207. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  53208. }
  53209. //
  53210. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  53211. ${ flowData.vars }
  53212. ${ flowData.code }
  53213. `;
  53214. if ( flowData.result ) {
  53215. code += `\treturn ${ flowData.result };\n`;
  53216. }
  53217. code += '\n}\n';
  53218. //
  53219. return code;
  53220. }
  53221. /**
  53222. * Contextually returns either the vertex stage instance index builtin
  53223. * or the linearized index of an compute invocation within a grid of workgroups.
  53224. *
  53225. * @return {string} The instance index.
  53226. */
  53227. getInstanceIndex() {
  53228. if ( this.shaderStage === 'vertex' ) {
  53229. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  53230. }
  53231. return 'instanceIndex';
  53232. }
  53233. /**
  53234. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  53235. *
  53236. * @return {string} The invocation local index.
  53237. */
  53238. getInvocationLocalIndex() {
  53239. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  53240. }
  53241. /**
  53242. * Returns a builtin representing the size of a subgroup within the current shader.
  53243. *
  53244. * @return {string} The subgroup size.
  53245. */
  53246. getSubgroupSize() {
  53247. this.enableSubGroups();
  53248. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53249. }
  53250. /**
  53251. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  53252. *
  53253. * @return {string} The invocation subgroup index.
  53254. */
  53255. getInvocationSubgroupIndex() {
  53256. this.enableSubGroups();
  53257. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  53258. }
  53259. /**
  53260. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  53261. *
  53262. * @return {string} The subgroup index.
  53263. */
  53264. getSubgroupIndex() {
  53265. this.enableSubGroups();
  53266. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  53267. }
  53268. /**
  53269. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  53270. *
  53271. * @return {null} Null.
  53272. */
  53273. getDrawIndex() {
  53274. return null;
  53275. }
  53276. /**
  53277. * Returns the front facing builtin.
  53278. *
  53279. * @return {string} The front facing builtin.
  53280. */
  53281. getFrontFacing() {
  53282. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  53283. }
  53284. /**
  53285. * Returns the frag coord builtin.
  53286. *
  53287. * @return {string} The frag coord builtin.
  53288. */
  53289. getFragCoord() {
  53290. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  53291. }
  53292. /**
  53293. * Returns the frag depth builtin.
  53294. *
  53295. * @return {string} The frag depth builtin.
  53296. */
  53297. getFragDepth() {
  53298. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  53299. }
  53300. /**
  53301. * Returns the clip distances builtin.
  53302. *
  53303. * @return {string} The clip distances builtin.
  53304. */
  53305. getClipDistance() {
  53306. return 'varyings.hw_clip_distances';
  53307. }
  53308. /**
  53309. * Whether to flip texture data along its vertical axis or not.
  53310. *
  53311. * @return {boolean} Returns always `false` in context of WGSL.
  53312. */
  53313. isFlipY() {
  53314. return false;
  53315. }
  53316. /**
  53317. * Enables the given directive for the given shader stage.
  53318. *
  53319. * @param {string} name - The directive name.
  53320. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  53321. */
  53322. enableDirective( name, shaderStage = this.shaderStage ) {
  53323. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  53324. stage.add( name );
  53325. }
  53326. /**
  53327. * Returns the directives of the given shader stage as a WGSL string.
  53328. *
  53329. * @param {string} shaderStage - The shader stage.
  53330. * @return {string} A WGSL snippet that enables the directives of the given stage.
  53331. */
  53332. getDirectives( shaderStage ) {
  53333. const snippets = [];
  53334. const directives = this.directives[ shaderStage ];
  53335. if ( directives !== undefined ) {
  53336. for ( const directive of directives ) {
  53337. snippets.push( `enable ${directive};` );
  53338. }
  53339. }
  53340. return snippets.join( '\n' );
  53341. }
  53342. /**
  53343. * Enables the 'subgroups' directive.
  53344. */
  53345. enableSubGroups() {
  53346. this.enableDirective( 'subgroups' );
  53347. }
  53348. /**
  53349. * Enables the 'subgroups-f16' directive.
  53350. */
  53351. enableSubgroupsF16() {
  53352. this.enableDirective( 'subgroups-f16' );
  53353. }
  53354. /**
  53355. * Enables the 'clip_distances' directive.
  53356. */
  53357. enableClipDistances() {
  53358. this.enableDirective( 'clip_distances' );
  53359. }
  53360. /**
  53361. * Enables the 'f16' directive.
  53362. */
  53363. enableShaderF16() {
  53364. this.enableDirective( 'f16' );
  53365. }
  53366. /**
  53367. * Enables the 'dual_source_blending' directive.
  53368. */
  53369. enableDualSourceBlending() {
  53370. this.enableDirective( 'dual_source_blending' );
  53371. }
  53372. /**
  53373. * Enables hardware clipping.
  53374. *
  53375. * @param {string} planeCount - The clipping plane count.
  53376. */
  53377. enableHardwareClipping( planeCount ) {
  53378. this.enableClipDistances();
  53379. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  53380. }
  53381. /**
  53382. * Returns the builtins of the given shader stage as a WGSL string.
  53383. *
  53384. * @param {string} shaderStage - The shader stage.
  53385. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  53386. */
  53387. getBuiltins( shaderStage ) {
  53388. const snippets = [];
  53389. const builtins = this.builtins[ shaderStage ];
  53390. if ( builtins !== undefined ) {
  53391. for ( const { name, property, type } of builtins.values() ) {
  53392. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  53393. }
  53394. }
  53395. return snippets.join( ',\n\t' );
  53396. }
  53397. /**
  53398. * This method should be used when a new scoped buffer is used in context of
  53399. * compute shaders. It adds the array to the internal data structure which is
  53400. * later used to generate the respective WGSL.
  53401. *
  53402. * @param {string} name - The array name.
  53403. * @param {string} scope - The scope.
  53404. * @param {string} bufferType - The buffer type.
  53405. * @param {string} bufferCount - The buffer count.
  53406. * @return {string} The array name.
  53407. */
  53408. getScopedArray( name, scope, bufferType, bufferCount ) {
  53409. if ( this.scopedArrays.has( name ) === false ) {
  53410. this.scopedArrays.set( name, {
  53411. name,
  53412. scope,
  53413. bufferType,
  53414. bufferCount
  53415. } );
  53416. }
  53417. return name;
  53418. }
  53419. /**
  53420. * Returns the scoped arrays of the given shader stage as a WGSL string.
  53421. *
  53422. * @param {string} shaderStage - The shader stage.
  53423. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  53424. * Returns `undefined` when used in the vertex or fragment stage.
  53425. */
  53426. getScopedArrays( shaderStage ) {
  53427. if ( shaderStage !== 'compute' ) {
  53428. return;
  53429. }
  53430. const snippets = [];
  53431. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  53432. const type = this.getType( bufferType );
  53433. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  53434. }
  53435. return snippets.join( '\n' );
  53436. }
  53437. /**
  53438. * Returns the shader attributes of the given shader stage as a WGSL string.
  53439. *
  53440. * @param {string} shaderStage - The shader stage.
  53441. * @return {string} The WGSL snippet that defines the shader attributes.
  53442. */
  53443. getAttributes( shaderStage ) {
  53444. const snippets = [];
  53445. if ( shaderStage === 'compute' ) {
  53446. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  53447. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  53448. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  53449. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  53450. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  53451. this.enableDirective( 'subgroups', shaderStage );
  53452. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  53453. }
  53454. }
  53455. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  53456. const builtins = this.getBuiltins( 'attribute' );
  53457. if ( builtins ) snippets.push( builtins );
  53458. const attributes = this.getAttributesArray();
  53459. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  53460. const attribute = attributes[ index ];
  53461. const name = attribute.name;
  53462. const type = this.getType( attribute.type );
  53463. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  53464. }
  53465. }
  53466. return snippets.join( ',\n\t' );
  53467. }
  53468. /**
  53469. * Returns the members of the given struct type node as a WGSL string.
  53470. *
  53471. * @param {StructTypeNode} struct - The struct type node.
  53472. * @return {string} The WGSL snippet that defines the struct members.
  53473. */
  53474. getStructMembers( struct ) {
  53475. const snippets = [];
  53476. for ( const member of struct.members ) {
  53477. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  53478. let type = this.getType( member.type );
  53479. if ( member.atomic ) {
  53480. type = 'atomic< ' + type + ' >';
  53481. }
  53482. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  53483. }
  53484. if ( struct.output ) {
  53485. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  53486. }
  53487. return snippets.join( ',\n' );
  53488. }
  53489. /**
  53490. * Returns the structs of the given shader stage as a WGSL string.
  53491. *
  53492. * @param {string} shaderStage - The shader stage.
  53493. * @return {string} The WGSL snippet that defines the structs.
  53494. */
  53495. getStructs( shaderStage ) {
  53496. let result = '';
  53497. const structs = this.structs[ shaderStage ];
  53498. if ( structs.length > 0 ) {
  53499. const snippets = [];
  53500. for ( const struct of structs ) {
  53501. let snippet = `struct ${ struct.name } {\n`;
  53502. snippet += this.getStructMembers( struct );
  53503. snippet += '\n};';
  53504. snippets.push( snippet );
  53505. }
  53506. result = '\n' + snippets.join( '\n\n' ) + '\n';
  53507. }
  53508. return result;
  53509. }
  53510. /**
  53511. * Returns a WGSL string representing a variable.
  53512. *
  53513. * @param {string} type - The variable's type.
  53514. * @param {string} name - The variable's name.
  53515. * @param {?number} [count=null] - The array length.
  53516. * @return {string} The WGSL snippet that defines a variable.
  53517. */
  53518. getVar( type, name, count = null ) {
  53519. let snippet = `var ${ name } : `;
  53520. if ( count !== null ) {
  53521. snippet += this.generateArrayDeclaration( type, count );
  53522. } else {
  53523. snippet += this.getType( type );
  53524. }
  53525. return snippet;
  53526. }
  53527. /**
  53528. * Returns the variables of the given shader stage as a WGSL string.
  53529. *
  53530. * @param {string} shaderStage - The shader stage.
  53531. * @return {string} The WGSL snippet that defines the variables.
  53532. */
  53533. getVars( shaderStage ) {
  53534. const snippets = [];
  53535. const vars = this.vars[ shaderStage ];
  53536. if ( vars !== undefined ) {
  53537. for ( const variable of vars ) {
  53538. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  53539. }
  53540. }
  53541. return `\n${ snippets.join( '\n' ) }\n`;
  53542. }
  53543. /**
  53544. * Returns the varyings of the given shader stage as a WGSL string.
  53545. *
  53546. * @param {string} shaderStage - The shader stage.
  53547. * @return {string} The WGSL snippet that defines the varyings.
  53548. */
  53549. getVaryings( shaderStage ) {
  53550. const snippets = [];
  53551. if ( shaderStage === 'vertex' ) {
  53552. this.getBuiltin( 'position', 'builtinClipSpace', 'vec4<f32>', 'vertex' );
  53553. }
  53554. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  53555. const varyings = this.varyings;
  53556. const vars = this.vars[ shaderStage ];
  53557. for ( let index = 0; index < varyings.length; index ++ ) {
  53558. const varying = varyings[ index ];
  53559. if ( varying.needsInterpolation ) {
  53560. let attributesSnippet = `@location( ${index} )`;
  53561. if ( varying.interpolationType ) {
  53562. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  53563. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  53564. // Otherwise, optimize interpolation when sensible
  53565. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  53566. attributesSnippet += ' @interpolate(flat, either)';
  53567. }
  53568. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  53569. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  53570. vars.push( varying );
  53571. }
  53572. }
  53573. }
  53574. const builtins = this.getBuiltins( shaderStage );
  53575. if ( builtins ) snippets.push( builtins );
  53576. const code = snippets.join( ',\n\t' );
  53577. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  53578. }
  53579. isCustomStruct( nodeUniform ) {
  53580. const attribute = nodeUniform.value;
  53581. const bufferNode = nodeUniform.node;
  53582. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  53583. const isStructArray =
  53584. ( bufferNode.value && bufferNode.value.array ) &&
  53585. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  53586. return isAttributeStructType && ! isStructArray;
  53587. }
  53588. /**
  53589. * Returns the uniforms of the given shader stage as a WGSL string.
  53590. *
  53591. * @param {string} shaderStage - The shader stage.
  53592. * @return {string} The WGSL snippet that defines the uniforms.
  53593. */
  53594. getUniforms( shaderStage ) {
  53595. const uniforms = this.uniforms[ shaderStage ];
  53596. const bindingSnippets = [];
  53597. const bufferSnippets = [];
  53598. const structSnippets = [];
  53599. const uniformGroups = {};
  53600. for ( const uniform of uniforms ) {
  53601. const groupName = uniform.groupNode.name;
  53602. const uniformIndexes = this.bindingsIndexes[ groupName ];
  53603. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'cubeDepthTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  53604. const texture = uniform.node.value;
  53605. // Cube textures always need samplers (they use textureSampleLevel, not textureLoad)
  53606. const needsSampler = texture.isCubeTexture === true || ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true );
  53607. if ( needsSampler ) {
  53608. if ( this.isSampleCompare( texture ) ) {
  53609. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  53610. } else {
  53611. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  53612. }
  53613. }
  53614. let textureType;
  53615. let multisampled = '';
  53616. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  53617. if ( primarySamples > 1 ) {
  53618. multisampled = '_multisampled';
  53619. }
  53620. if ( texture.isCubeTexture === true && texture.isDepthTexture === true ) {
  53621. textureType = 'texture_depth_cube';
  53622. } else if ( texture.isCubeTexture === true ) {
  53623. textureType = 'texture_cube<f32>';
  53624. } else if ( texture.isDepthTexture === true ) {
  53625. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  53626. textureType = `texture${ multisampled }_2d<f32>`;
  53627. } else {
  53628. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  53629. }
  53630. } else if ( uniform.node.isStorageTextureNode === true ) {
  53631. const format = getFormat( texture );
  53632. const access = this.getStorageAccess( uniform.node, shaderStage );
  53633. const is3D = uniform.node.value.is3DTexture;
  53634. const isArrayTexture = uniform.node.value.isArrayTexture;
  53635. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  53636. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  53637. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  53638. textureType = 'texture_2d_array<f32>';
  53639. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  53640. textureType = 'texture_3d<f32>';
  53641. } else {
  53642. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  53643. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  53644. }
  53645. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  53646. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  53647. const bufferNode = uniform.node;
  53648. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  53649. const bufferCount = bufferNode.bufferCount;
  53650. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  53651. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  53652. if ( this.isCustomStruct( uniform ) ) {
  53653. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  53654. } else {
  53655. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  53656. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  53657. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  53658. }
  53659. } else {
  53660. const groupName = uniform.groupNode.name;
  53661. // Check if this group has already been processed in this shader stage
  53662. if ( uniformGroups[ groupName ] === undefined ) {
  53663. // Get the shared uniform group that contains uniforms from all stages
  53664. const sharedUniformGroup = this.uniformGroups[ groupName ];
  53665. if ( sharedUniformGroup !== undefined ) {
  53666. // Generate snippets for ALL uniforms in this shared group
  53667. const snippets = [];
  53668. for ( const sharedUniform of sharedUniformGroup.uniforms ) {
  53669. const type = sharedUniform.getType();
  53670. const vectorType = this.getType( this.getVectorType( type ) );
  53671. snippets.push( `\t${ sharedUniform.name } : ${ vectorType }` );
  53672. }
  53673. // Check if this group already has an assigned binding index (from another shader stage)
  53674. let groupBinding = this.uniformGroupsBindings[ groupName ];
  53675. if ( groupBinding === undefined ) {
  53676. // First time processing this group - assign a new binding index
  53677. groupBinding = {
  53678. index: uniformIndexes.binding ++,
  53679. id: uniformIndexes.group
  53680. };
  53681. this.uniformGroupsBindings[ groupName ] = groupBinding;
  53682. }
  53683. uniformGroups[ groupName ] = {
  53684. index: groupBinding.index,
  53685. id: groupBinding.id,
  53686. snippets: snippets
  53687. };
  53688. }
  53689. }
  53690. }
  53691. }
  53692. for ( const name in uniformGroups ) {
  53693. const group = uniformGroups[ name ];
  53694. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  53695. }
  53696. const code = [ ...bindingSnippets, ...bufferSnippets, ...structSnippets ].join( '\n' );
  53697. return code;
  53698. }
  53699. /**
  53700. * Controls the code build of the shader stages.
  53701. */
  53702. buildCode() {
  53703. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  53704. this.sortBindingGroups();
  53705. for ( const shaderStage in shadersData ) {
  53706. this.shaderStage = shaderStage;
  53707. const stageData = shadersData[ shaderStage ];
  53708. stageData.uniforms = this.getUniforms( shaderStage );
  53709. stageData.attributes = this.getAttributes( shaderStage );
  53710. stageData.varyings = this.getVaryings( shaderStage );
  53711. stageData.structs = this.getStructs( shaderStage );
  53712. stageData.vars = this.getVars( shaderStage );
  53713. stageData.codes = this.getCodes( shaderStage );
  53714. stageData.directives = this.getDirectives( shaderStage );
  53715. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  53716. //
  53717. let flow = '// code\n\n';
  53718. flow += this.flowCode[ shaderStage ];
  53719. const flowNodes = this.flowNodes[ shaderStage ];
  53720. const mainNode = flowNodes[ flowNodes.length - 1 ];
  53721. const outputNode = mainNode.outputNode;
  53722. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  53723. for ( const node of flowNodes ) {
  53724. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  53725. const slotName = node.name;
  53726. if ( slotName ) {
  53727. if ( flow.length > 0 ) flow += '\n';
  53728. flow += `\t// flow -> ${ slotName }\n`;
  53729. }
  53730. flow += `${ flowSlotData.code }\n\t`;
  53731. if ( node === mainNode && shaderStage !== 'compute' ) {
  53732. flow += '// result\n\n\t';
  53733. if ( shaderStage === 'vertex' ) {
  53734. flow += `varyings.builtinClipSpace = ${ flowSlotData.result };`;
  53735. } else if ( shaderStage === 'fragment' ) {
  53736. if ( isOutputStruct ) {
  53737. stageData.returnType = outputNode.getNodeType( this );
  53738. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  53739. flow += `return ${ flowSlotData.result };`;
  53740. } else {
  53741. let structSnippet = '\t@location(0) color: vec4<f32>';
  53742. const builtins = this.getBuiltins( 'output' );
  53743. if ( builtins ) structSnippet += ',\n\t' + builtins;
  53744. stageData.returnType = 'OutputStruct';
  53745. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  53746. stageData.structs += '\nvar<private> output : OutputStruct;';
  53747. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  53748. }
  53749. }
  53750. }
  53751. }
  53752. stageData.flow = flow;
  53753. }
  53754. this.shaderStage = null;
  53755. if ( this.material !== null ) {
  53756. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  53757. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  53758. } else {
  53759. // Early strictly validated in computeNode
  53760. const workgroupSize = this.object.workgroupSize;
  53761. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  53762. }
  53763. }
  53764. /**
  53765. * Returns the native shader method name for a given generic name.
  53766. *
  53767. * @param {string} method - The method name to resolve.
  53768. * @param {?string} [output=null] - An optional output.
  53769. * @return {string} The resolved WGSL method name.
  53770. */
  53771. getMethod( method, output = null ) {
  53772. let wgslMethod;
  53773. if ( output !== null ) {
  53774. wgslMethod = this._getWGSLMethod( method + '_' + output );
  53775. }
  53776. if ( wgslMethod === undefined ) {
  53777. wgslMethod = this._getWGSLMethod( method );
  53778. }
  53779. return wgslMethod || method;
  53780. }
  53781. /**
  53782. * Returns the bitcast method name for a given input and outputType.
  53783. *
  53784. * @param {string} type - The output type to bitcast to.
  53785. * @return {string} The resolved WGSL bitcast invocation.
  53786. */
  53787. getBitcastMethod( type ) {
  53788. const dataType = this.getType( type );
  53789. return `bitcast<${ dataType }>`;
  53790. }
  53791. /**
  53792. * Returns the float packing method name for a given numeric encoding.
  53793. *
  53794. * @param {string} encoding - The numeric encoding that describes how the float values are mapped to the integer range.
  53795. * @returns {string} The resolve WGSL float packing method name.
  53796. */
  53797. getFloatPackingMethod( encoding ) {
  53798. return this.getMethod( `floatpack_${ encoding }_2x16` );
  53799. }
  53800. /**
  53801. * Returns the float unpacking method name for a given numeric encoding.
  53802. *
  53803. * @param {string} encoding - The numeric encoding that describes how the integer values are mapped to the float range.
  53804. * @returns {string} The resolve WGSL float unpacking method name.
  53805. */
  53806. getFloatUnpackingMethod( encoding ) {
  53807. return this.getMethod( `floatunpack_${ encoding }_2x16` );
  53808. }
  53809. /**
  53810. * Returns the native snippet for a ternary operation.
  53811. *
  53812. * @param {string} condSnippet - The condition determining which expression gets resolved.
  53813. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  53814. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  53815. * @return {string} The resolved method name.
  53816. */
  53817. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  53818. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  53819. }
  53820. /**
  53821. * Returns the WGSL type of the given node data type.
  53822. *
  53823. * @param {string} type - The node data type.
  53824. * @return {string} The WGSL type.
  53825. */
  53826. getType( type ) {
  53827. return wgslTypeLib[ type ] || type;
  53828. }
  53829. /**
  53830. * Whether the requested feature is available or not.
  53831. *
  53832. * @param {string} name - The requested feature.
  53833. * @return {boolean} Whether the requested feature is supported or not.
  53834. */
  53835. isAvailable( name ) {
  53836. let result = supports[ name ];
  53837. if ( result === undefined ) {
  53838. if ( name === 'float32Filterable' ) {
  53839. result = this.renderer.hasFeature( 'float32-filterable' );
  53840. } else if ( name === 'clipDistance' ) {
  53841. result = this.renderer.hasFeature( 'clip-distances' );
  53842. }
  53843. supports[ name ] = result;
  53844. }
  53845. return result;
  53846. }
  53847. /**
  53848. * Returns the native shader method name for a given generic name.
  53849. *
  53850. * @private
  53851. * @param {string} method - The method name to resolve.
  53852. * @return {string} The resolved WGSL method name.
  53853. */
  53854. _getWGSLMethod( method ) {
  53855. if ( wgslPolyfill[ method ] !== undefined ) {
  53856. this._include( method );
  53857. }
  53858. return wgslMethods[ method ];
  53859. }
  53860. /**
  53861. * Includes the given method name into the current
  53862. * function node.
  53863. *
  53864. * @private
  53865. * @param {string} name - The method name to include.
  53866. * @return {CodeNode} The respective code node.
  53867. */
  53868. _include( name ) {
  53869. const codeNode = wgslPolyfill[ name ];
  53870. codeNode.build( this );
  53871. this.addInclude( codeNode );
  53872. return codeNode;
  53873. }
  53874. /**
  53875. * Returns a WGSL vertex shader based on the given shader data.
  53876. *
  53877. * @private
  53878. * @param {Object} shaderData - The shader data.
  53879. * @return {string} The vertex shader.
  53880. */
  53881. _getWGSLVertexCode( shaderData ) {
  53882. return `${ this.getSignature() }
  53883. // directives
  53884. ${shaderData.directives}
  53885. // structs
  53886. ${shaderData.structs}
  53887. // uniforms
  53888. ${shaderData.uniforms}
  53889. // varyings
  53890. ${shaderData.varyings}
  53891. var<private> varyings : VaryingsStruct;
  53892. // codes
  53893. ${shaderData.codes}
  53894. @vertex
  53895. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  53896. // vars
  53897. ${shaderData.vars}
  53898. // flow
  53899. ${shaderData.flow}
  53900. return varyings;
  53901. }
  53902. `;
  53903. }
  53904. /**
  53905. * Returns a WGSL fragment shader based on the given shader data.
  53906. *
  53907. * @private
  53908. * @param {Object} shaderData - The shader data.
  53909. * @return {string} The vertex shader.
  53910. */
  53911. _getWGSLFragmentCode( shaderData ) {
  53912. return `${ this.getSignature() }
  53913. // global
  53914. ${ diagnostics }
  53915. // structs
  53916. ${shaderData.structs}
  53917. // uniforms
  53918. ${shaderData.uniforms}
  53919. // codes
  53920. ${shaderData.codes}
  53921. @fragment
  53922. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  53923. // vars
  53924. ${shaderData.vars}
  53925. // flow
  53926. ${shaderData.flow}
  53927. }
  53928. `;
  53929. }
  53930. /**
  53931. * Returns a WGSL compute shader based on the given shader data.
  53932. *
  53933. * @private
  53934. * @param {Object} shaderData - The shader data.
  53935. * @param {string} workgroupSize - The workgroup size.
  53936. * @return {string} The vertex shader.
  53937. */
  53938. _getWGSLComputeCode( shaderData, workgroupSize ) {
  53939. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  53940. return `${ this.getSignature() }
  53941. // directives
  53942. ${ shaderData.directives }
  53943. // system
  53944. var<private> instanceIndex : u32;
  53945. // locals
  53946. ${ shaderData.scopedArrays }
  53947. // structs
  53948. ${ shaderData.structs }
  53949. // uniforms
  53950. ${ shaderData.uniforms }
  53951. // codes
  53952. ${ shaderData.codes }
  53953. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  53954. fn main( ${ shaderData.attributes } ) {
  53955. // system
  53956. instanceIndex = globalId.x
  53957. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  53958. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  53959. // vars
  53960. ${ shaderData.vars }
  53961. // flow
  53962. ${ shaderData.flow }
  53963. }
  53964. `;
  53965. }
  53966. /**
  53967. * Returns a WGSL struct based on the given name and variables.
  53968. *
  53969. * @private
  53970. * @param {string} name - The struct name.
  53971. * @param {string} vars - The struct variables.
  53972. * @return {string} The WGSL snippet representing a struct.
  53973. */
  53974. _getWGSLStruct( name, vars ) {
  53975. return `
  53976. struct ${name} {
  53977. ${vars}
  53978. };`;
  53979. }
  53980. /**
  53981. * Returns a WGSL struct binding.
  53982. *
  53983. * @private
  53984. * @param {string} name - The struct name.
  53985. * @param {string} vars - The struct variables.
  53986. * @param {string} access - The access.
  53987. * @param {number} [binding=0] - The binding index.
  53988. * @param {number} [group=0] - The group index.
  53989. * @return {string} The WGSL snippet representing a struct binding.
  53990. */
  53991. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  53992. const structName = name + 'Struct';
  53993. const structSnippet = this._getWGSLStruct( structName, vars );
  53994. return `${structSnippet}
  53995. @binding( ${ binding } ) @group( ${ group } )
  53996. var<${access}> ${ name } : ${ structName };`;
  53997. }
  53998. }
  53999. /**
  54000. * A WebGPU backend utility module with common helpers.
  54001. *
  54002. * @private
  54003. */
  54004. class WebGPUUtils {
  54005. /**
  54006. * Constructs a new utility object.
  54007. *
  54008. * @param {WebGPUBackend} backend - The WebGPU backend.
  54009. */
  54010. constructor( backend ) {
  54011. /**
  54012. * A reference to the WebGPU backend.
  54013. *
  54014. * @type {WebGPUBackend}
  54015. */
  54016. this.backend = backend;
  54017. }
  54018. /**
  54019. * Returns the depth/stencil GPU format for the given render context.
  54020. *
  54021. * @param {RenderContext} renderContext - The render context.
  54022. * @return {string} The depth/stencil GPU texture format.
  54023. */
  54024. getCurrentDepthStencilFormat( renderContext ) {
  54025. let format;
  54026. if ( renderContext.depth ) {
  54027. if ( renderContext.depthTexture !== null ) {
  54028. format = this.getTextureFormatGPU( renderContext.depthTexture );
  54029. } else if ( renderContext.stencil ) {
  54030. format = GPUTextureFormat.Depth24PlusStencil8;
  54031. } else {
  54032. format = GPUTextureFormat.Depth24Plus;
  54033. }
  54034. }
  54035. return format;
  54036. }
  54037. /**
  54038. * Returns the GPU format for the given texture.
  54039. *
  54040. * @param {Texture} texture - The texture.
  54041. * @return {string} The GPU texture format.
  54042. */
  54043. getTextureFormatGPU( texture ) {
  54044. return this.backend.get( texture ).format;
  54045. }
  54046. /**
  54047. * Returns an object that defines the multi-sampling state of the given texture.
  54048. *
  54049. * @param {Texture} texture - The texture.
  54050. * @return {Object} The multi-sampling state.
  54051. */
  54052. getTextureSampleData( texture ) {
  54053. let samples;
  54054. if ( texture.isFramebufferTexture ) {
  54055. samples = 1;
  54056. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  54057. const renderer = this.backend.renderer;
  54058. const renderTarget = renderer.getRenderTarget();
  54059. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  54060. } else if ( texture.renderTarget ) {
  54061. samples = texture.renderTarget.samples;
  54062. }
  54063. samples = samples || 1;
  54064. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  54065. const primarySamples = isMSAA ? 1 : samples;
  54066. return { samples, primarySamples, isMSAA };
  54067. }
  54068. /**
  54069. * Returns the default color attachment's GPU format of the current render context.
  54070. *
  54071. * @param {RenderContext} renderContext - The render context.
  54072. * @return {string} The GPU texture format of the default color attachment.
  54073. */
  54074. getCurrentColorFormat( renderContext ) {
  54075. let format;
  54076. if ( renderContext.textures !== null ) {
  54077. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  54078. } else {
  54079. format = this.getPreferredCanvasFormat(); // default context format
  54080. }
  54081. return format;
  54082. }
  54083. /**
  54084. * Returns the GPU formats of all color attachments of the current render context.
  54085. *
  54086. * @param {RenderContext} renderContext - The render context.
  54087. * @return {Array<string>} The GPU texture formats of all color attachments.
  54088. */
  54089. getCurrentColorFormats( renderContext ) {
  54090. if ( renderContext.textures !== null ) {
  54091. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  54092. } else {
  54093. return [ this.getPreferredCanvasFormat() ]; // default context format
  54094. }
  54095. }
  54096. /**
  54097. * Returns the output color space of the current render context.
  54098. *
  54099. * @param {RenderContext} renderContext - The render context.
  54100. * @return {string} The output color space.
  54101. */
  54102. getCurrentColorSpace( renderContext ) {
  54103. if ( renderContext.textures !== null ) {
  54104. return renderContext.textures[ 0 ].colorSpace;
  54105. }
  54106. return this.backend.renderer.outputColorSpace;
  54107. }
  54108. /**
  54109. * Returns GPU primitive topology for the given object and material.
  54110. *
  54111. * @param {Object3D} object - The 3D object.
  54112. * @param {Material} material - The material.
  54113. * @return {string} The GPU primitive topology.
  54114. */
  54115. getPrimitiveTopology( object, material ) {
  54116. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  54117. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  54118. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  54119. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  54120. }
  54121. /**
  54122. * Returns a modified sample count from the given sample count value.
  54123. *
  54124. * That is required since WebGPU only supports either 1 or 4.
  54125. *
  54126. * @param {number} sampleCount - The input sample count.
  54127. * @return {number} The (potentially updated) output sample count.
  54128. */
  54129. getSampleCount( sampleCount ) {
  54130. return sampleCount >= 4 ? 4 : 1;
  54131. }
  54132. /**
  54133. * Returns the sample count of the given render context.
  54134. *
  54135. * @param {RenderContext} renderContext - The render context.
  54136. * @return {number} The sample count.
  54137. */
  54138. getSampleCountRenderContext( renderContext ) {
  54139. if ( renderContext.textures !== null ) {
  54140. return this.getSampleCount( renderContext.sampleCount );
  54141. }
  54142. return this.getSampleCount( this.backend.renderer.currentSamples );
  54143. }
  54144. /**
  54145. * Returns the preferred canvas format.
  54146. *
  54147. * There is a separate method for this so it's possible to
  54148. * honor edge cases for specific devices.
  54149. *
  54150. * @return {string} The GPU texture format of the canvas.
  54151. */
  54152. getPreferredCanvasFormat() {
  54153. const parameters = this.backend.parameters;
  54154. const bufferType = parameters.outputType;
  54155. if ( bufferType === undefined ) {
  54156. return navigator.gpu.getPreferredCanvasFormat();
  54157. } else if ( bufferType === UnsignedByteType ) {
  54158. return GPUTextureFormat.BGRA8Unorm;
  54159. } else if ( bufferType === HalfFloatType ) {
  54160. return GPUTextureFormat.RGBA16Float;
  54161. } else {
  54162. throw new Error( 'Unsupported output buffer type.' );
  54163. }
  54164. }
  54165. }
  54166. const typedArraysToVertexFormatPrefix = new Map( [
  54167. [ Int8Array, [ 'sint8', 'snorm8' ]],
  54168. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  54169. [ Int16Array, [ 'sint16', 'snorm16' ]],
  54170. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  54171. [ Int32Array, [ 'sint32', 'snorm32' ]],
  54172. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  54173. [ Float32Array, [ 'float32', ]],
  54174. ] );
  54175. if ( typeof Float16Array !== 'undefined' ) {
  54176. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  54177. }
  54178. const typedAttributeToVertexFormatPrefix = new Map( [
  54179. [ Float16BufferAttribute, [ 'float16', ]],
  54180. ] );
  54181. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  54182. [ Int32Array, 'sint32' ],
  54183. [ Int16Array, 'sint32' ], // patch for INT16
  54184. [ Uint32Array, 'uint32' ],
  54185. [ Uint16Array, 'uint32' ], // patch for UINT16
  54186. [ Float32Array, 'float32' ]
  54187. ] );
  54188. /**
  54189. * A WebGPU backend utility module for managing shader attributes.
  54190. *
  54191. * @private
  54192. */
  54193. class WebGPUAttributeUtils {
  54194. /**
  54195. * Constructs a new utility object.
  54196. *
  54197. * @param {WebGPUBackend} backend - The WebGPU backend.
  54198. */
  54199. constructor( backend ) {
  54200. /**
  54201. * A reference to the WebGPU backend.
  54202. *
  54203. * @type {WebGPUBackend}
  54204. */
  54205. this.backend = backend;
  54206. }
  54207. /**
  54208. * Creates the GPU buffer for the given buffer attribute.
  54209. *
  54210. * @param {BufferAttribute} attribute - The buffer attribute.
  54211. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  54212. */
  54213. createAttribute( attribute, usage ) {
  54214. const bufferAttribute = this._getBufferAttribute( attribute );
  54215. const backend = this.backend;
  54216. const bufferData = backend.get( bufferAttribute );
  54217. let buffer = bufferData.buffer;
  54218. if ( buffer === undefined ) {
  54219. const device = backend.device;
  54220. let array = bufferAttribute.array;
  54221. // patch for INT16 and UINT16
  54222. if ( attribute.normalized === false ) {
  54223. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  54224. array = new Int32Array( array );
  54225. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  54226. array = new Uint32Array( array );
  54227. if ( usage & GPUBufferUsage.INDEX ) {
  54228. for ( let i = 0; i < array.length; i ++ ) {
  54229. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  54230. }
  54231. }
  54232. }
  54233. }
  54234. bufferAttribute.array = array;
  54235. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  54236. array = new array.constructor( bufferAttribute.count * 4 );
  54237. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54238. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54239. }
  54240. // Update BufferAttribute
  54241. bufferAttribute.itemSize = 4;
  54242. bufferAttribute.array = array;
  54243. bufferData._force3to4BytesAlignment = true;
  54244. }
  54245. // ensure 4 byte alignment
  54246. const byteLength = array.byteLength;
  54247. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  54248. buffer = device.createBuffer( {
  54249. label: bufferAttribute.name,
  54250. size: size,
  54251. usage: usage,
  54252. mappedAtCreation: true
  54253. } );
  54254. new array.constructor( buffer.getMappedRange() ).set( array );
  54255. buffer.unmap();
  54256. bufferData.buffer = buffer;
  54257. }
  54258. }
  54259. /**
  54260. * Updates the GPU buffer of the given buffer attribute.
  54261. *
  54262. * @param {BufferAttribute} attribute - The buffer attribute.
  54263. */
  54264. updateAttribute( attribute ) {
  54265. const bufferAttribute = this._getBufferAttribute( attribute );
  54266. const backend = this.backend;
  54267. const device = backend.device;
  54268. const bufferData = backend.get( bufferAttribute );
  54269. const buffer = backend.get( bufferAttribute ).buffer;
  54270. let array = bufferAttribute.array;
  54271. // if storage buffer ensure 4 byte alignment
  54272. if ( bufferData._force3to4BytesAlignment === true ) {
  54273. array = new array.constructor( bufferAttribute.count * 4 );
  54274. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  54275. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  54276. }
  54277. bufferAttribute.array = array;
  54278. }
  54279. const updateRanges = bufferAttribute.updateRanges;
  54280. if ( updateRanges.length === 0 ) {
  54281. // Not using update ranges
  54282. device.queue.writeBuffer(
  54283. buffer,
  54284. 0,
  54285. array,
  54286. 0
  54287. );
  54288. } else {
  54289. const isTyped = isTypedArray( array );
  54290. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54291. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54292. const range = updateRanges[ i ];
  54293. let dataOffset, size;
  54294. if ( bufferData._force3to4BytesAlignment === true ) {
  54295. const vertexStart = Math.floor( range.start / 3 );
  54296. const vertexCount = Math.ceil( range.count / 3 );
  54297. dataOffset = vertexStart * 4 * byteOffsetFactor;
  54298. size = vertexCount * 4 * byteOffsetFactor;
  54299. } else {
  54300. dataOffset = range.start * byteOffsetFactor;
  54301. size = range.count * byteOffsetFactor;
  54302. }
  54303. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54304. device.queue.writeBuffer(
  54305. buffer,
  54306. bufferOffset,
  54307. array,
  54308. dataOffset,
  54309. size
  54310. );
  54311. }
  54312. bufferAttribute.clearUpdateRanges();
  54313. }
  54314. }
  54315. /**
  54316. * This method creates the vertex buffer layout data which are
  54317. * require when creating a render pipeline for the given render object.
  54318. *
  54319. * @param {RenderObject} renderObject - The render object.
  54320. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  54321. */
  54322. createShaderVertexBuffers( renderObject ) {
  54323. const attributes = renderObject.getAttributes();
  54324. const vertexBuffers = new Map();
  54325. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  54326. const geometryAttribute = attributes[ slot ];
  54327. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  54328. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  54329. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  54330. if ( vertexBufferLayout === undefined ) {
  54331. let arrayStride, stepMode;
  54332. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  54333. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  54334. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54335. } else {
  54336. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  54337. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  54338. }
  54339. // patch for INT16 and UINT16
  54340. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  54341. arrayStride = 4;
  54342. }
  54343. vertexBufferLayout = {
  54344. arrayStride,
  54345. attributes: [],
  54346. stepMode
  54347. };
  54348. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  54349. }
  54350. const format = this._getVertexFormat( geometryAttribute );
  54351. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  54352. vertexBufferLayout.attributes.push( {
  54353. shaderLocation: slot,
  54354. offset,
  54355. format
  54356. } );
  54357. }
  54358. return Array.from( vertexBuffers.values() );
  54359. }
  54360. /**
  54361. * Destroys the GPU buffer of the given buffer attribute.
  54362. *
  54363. * @param {BufferAttribute} attribute - The buffer attribute.
  54364. */
  54365. destroyAttribute( attribute ) {
  54366. const backend = this.backend;
  54367. const data = backend.get( this._getBufferAttribute( attribute ) );
  54368. data.buffer.destroy();
  54369. backend.delete( attribute );
  54370. }
  54371. /**
  54372. * This method performs a readback operation by moving buffer data from
  54373. * a storage buffer attribute from the GPU to the CPU.
  54374. *
  54375. * @async
  54376. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  54377. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  54378. */
  54379. async getArrayBufferAsync( attribute ) {
  54380. const backend = this.backend;
  54381. const device = backend.device;
  54382. const data = backend.get( this._getBufferAttribute( attribute ) );
  54383. const bufferGPU = data.buffer;
  54384. const size = bufferGPU.size;
  54385. const readBufferGPU = device.createBuffer( {
  54386. label: `${ attribute.name }_readback`,
  54387. size,
  54388. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  54389. } );
  54390. const cmdEncoder = device.createCommandEncoder( {
  54391. label: `readback_encoder_${ attribute.name }`
  54392. } );
  54393. cmdEncoder.copyBufferToBuffer(
  54394. bufferGPU,
  54395. 0,
  54396. readBufferGPU,
  54397. 0,
  54398. size
  54399. );
  54400. const gpuCommands = cmdEncoder.finish();
  54401. device.queue.submit( [ gpuCommands ] );
  54402. await readBufferGPU.mapAsync( GPUMapMode.READ );
  54403. const arrayBuffer = readBufferGPU.getMappedRange();
  54404. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  54405. readBufferGPU.unmap();
  54406. return dstBuffer.buffer;
  54407. }
  54408. /**
  54409. * Returns the vertex format of the given buffer attribute.
  54410. *
  54411. * @private
  54412. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  54413. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  54414. */
  54415. _getVertexFormat( geometryAttribute ) {
  54416. const { itemSize, normalized } = geometryAttribute;
  54417. const ArrayType = geometryAttribute.array.constructor;
  54418. const AttributeType = geometryAttribute.constructor;
  54419. let format;
  54420. if ( itemSize === 1 ) {
  54421. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  54422. } else {
  54423. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  54424. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  54425. if ( prefix ) {
  54426. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  54427. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  54428. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  54429. if ( paddedItemSize % 1 ) {
  54430. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  54431. }
  54432. format = `${prefix}x${paddedItemSize}`;
  54433. }
  54434. }
  54435. if ( ! format ) {
  54436. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  54437. }
  54438. return format;
  54439. }
  54440. /**
  54441. * Utility method for handling interleaved buffer attributes correctly.
  54442. * To process them, their `InterleavedBuffer` is returned.
  54443. *
  54444. * @private
  54445. * @param {BufferAttribute} attribute - The attribute.
  54446. * @return {BufferAttribute|InterleavedBuffer}
  54447. */
  54448. _getBufferAttribute( attribute ) {
  54449. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  54450. return attribute;
  54451. }
  54452. }
  54453. /**
  54454. * Class representing a WebGPU bind group layout.
  54455. *
  54456. * @private
  54457. */
  54458. class BindGroupLayout {
  54459. /**
  54460. * Constructs a new layout.
  54461. *
  54462. * @param {GPUBindGroupLayout} layoutGPU - A GPU Bind Group Layout.
  54463. */
  54464. constructor( layoutGPU ) {
  54465. /**
  54466. * The current GPUBindGroupLayout.
  54467. *
  54468. * @type {GPUBindGroupLayout}
  54469. */
  54470. this.layoutGPU = layoutGPU;
  54471. /**
  54472. * The number of bind groups that use this layout.
  54473. *
  54474. * @type {number}
  54475. */
  54476. this.usedTimes = 0;
  54477. }
  54478. }
  54479. /**
  54480. * A WebGPU backend utility module for managing bindings.
  54481. *
  54482. * When reading the documentation it's helpful to keep in mind that
  54483. * all class definitions starting with 'GPU*' are modules from the
  54484. * WebGPU API. So for example `BindGroup` is a class from the engine
  54485. * whereas `GPUBindGroup` is a class from WebGPU.
  54486. *
  54487. * @private
  54488. */
  54489. class WebGPUBindingUtils {
  54490. /**
  54491. * Constructs a new utility object.
  54492. *
  54493. * @param {WebGPUBackend} backend - The WebGPU backend.
  54494. */
  54495. constructor( backend ) {
  54496. /**
  54497. * A reference to the WebGPU backend.
  54498. *
  54499. * @type {WebGPUBackend}
  54500. */
  54501. this.backend = backend;
  54502. /**
  54503. * A cache that maps combinations of layout entries to existing bind group layouts.
  54504. *
  54505. * @private
  54506. * @type {Map<string, BindGroupLayout>}
  54507. */
  54508. this._bindGroupLayoutCache = new Map();
  54509. }
  54510. /**
  54511. * Creates a GPU bind group layout for the given bind group.
  54512. *
  54513. * @param {BindGroup} bindGroup - The bind group.
  54514. * @return {GPUBindGroupLayout} The GPU bind group layout.
  54515. */
  54516. createBindingsLayout( bindGroup ) {
  54517. const backend = this.backend;
  54518. const device = backend.device;
  54519. const bindingsData = backend.get( bindGroup );
  54520. // check if the the bind group already has a layout
  54521. if ( bindingsData.layout ) {
  54522. return bindingsData.layout.layoutGPU;
  54523. }
  54524. // if not, assing one
  54525. const entries = this._createLayoutEntries( bindGroup );
  54526. const bindGroupLayoutKey = JSON.stringify( entries );
  54527. // try to find an existing layout in the cache
  54528. let bindGroupLayout = this._bindGroupLayoutCache.get( bindGroupLayoutKey );
  54529. // if not create a new one
  54530. if ( bindGroupLayout === undefined ) {
  54531. bindGroupLayout = new BindGroupLayout( device.createBindGroupLayout( { entries } ) );
  54532. this._bindGroupLayoutCache.set( bindGroupLayoutKey, bindGroupLayout );
  54533. }
  54534. bindGroupLayout.usedTimes ++;
  54535. bindingsData.layout = bindGroupLayout;
  54536. bindingsData.layoutKey = bindGroupLayoutKey;
  54537. return bindGroupLayout.layoutGPU;
  54538. }
  54539. /**
  54540. * Creates bindings from the given bind group definition.
  54541. *
  54542. * @param {BindGroup} bindGroup - The bind group.
  54543. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54544. * @param {number} cacheIndex - The cache index.
  54545. * @param {number} version - The version.
  54546. */
  54547. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  54548. const { backend } = this;
  54549. const bindingsData = backend.get( bindGroup );
  54550. // setup (static) binding layout and (dynamic) binding group
  54551. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  54552. let bindGroupGPU;
  54553. if ( cacheIndex > 0 ) {
  54554. if ( bindingsData.groups === undefined ) {
  54555. bindingsData.groups = [];
  54556. bindingsData.versions = [];
  54557. }
  54558. if ( bindingsData.versions[ cacheIndex ] === version ) {
  54559. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  54560. }
  54561. }
  54562. if ( bindGroupGPU === undefined ) {
  54563. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  54564. if ( cacheIndex > 0 ) {
  54565. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  54566. bindingsData.versions[ cacheIndex ] = version;
  54567. }
  54568. }
  54569. bindingsData.group = bindGroupGPU;
  54570. }
  54571. /**
  54572. * Updates a buffer binding.
  54573. *
  54574. * @param {Buffer} binding - The buffer binding to update.
  54575. */
  54576. updateBinding( binding ) {
  54577. const backend = this.backend;
  54578. const device = backend.device;
  54579. const array = binding.buffer; // cpu
  54580. const buffer = backend.get( binding ).buffer; // gpu
  54581. const updateRanges = binding.updateRanges;
  54582. if ( updateRanges.length === 0 ) {
  54583. device.queue.writeBuffer(
  54584. buffer,
  54585. 0,
  54586. array,
  54587. 0
  54588. );
  54589. } else {
  54590. const isTyped = isTypedArray( array );
  54591. const byteOffsetFactor = isTyped ? 1 : array.BYTES_PER_ELEMENT;
  54592. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  54593. const range = updateRanges[ i ];
  54594. const dataOffset = range.start * byteOffsetFactor;
  54595. const size = range.count * byteOffsetFactor;
  54596. const bufferOffset = dataOffset * ( isTyped ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  54597. device.queue.writeBuffer(
  54598. buffer,
  54599. bufferOffset,
  54600. array,
  54601. dataOffset,
  54602. size
  54603. );
  54604. }
  54605. }
  54606. }
  54607. /**
  54608. * Creates a GPU bind group for the camera index.
  54609. *
  54610. * @param {Uint32Array} data - The index data.
  54611. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54612. * @return {GPUBindGroup} The GPU bind group.
  54613. */
  54614. createBindGroupIndex( data, layoutGPU ) {
  54615. const backend = this.backend;
  54616. const device = backend.device;
  54617. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54618. const index = data[ 0 ];
  54619. const buffer = device.createBuffer( {
  54620. label: 'bindingCameraIndex_' + index,
  54621. size: 16, // uint(4) * 4
  54622. usage: usage
  54623. } );
  54624. device.queue.writeBuffer( buffer, 0, data, 0 );
  54625. const entries = [ { binding: 0, resource: { buffer } } ];
  54626. return device.createBindGroup( {
  54627. label: 'bindGroupCameraIndex_' + index,
  54628. layout: layoutGPU,
  54629. entries
  54630. } );
  54631. }
  54632. /**
  54633. * Creates a GPU bind group for the given bind group and GPU layout.
  54634. *
  54635. * @param {BindGroup} bindGroup - The bind group.
  54636. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  54637. * @return {GPUBindGroup} The GPU bind group.
  54638. */
  54639. createBindGroup( bindGroup, layoutGPU ) {
  54640. const backend = this.backend;
  54641. const device = backend.device;
  54642. let bindingPoint = 0;
  54643. const entriesGPU = [];
  54644. for ( const binding of bindGroup.bindings ) {
  54645. if ( binding.isUniformBuffer ) {
  54646. const bindingData = backend.get( binding );
  54647. if ( bindingData.buffer === undefined ) {
  54648. const byteLength = binding.byteLength;
  54649. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  54650. const visibilities = [];
  54651. if ( binding.visibility & GPUShaderStage.VERTEX ) {
  54652. visibilities.push( 'vertex' );
  54653. }
  54654. if ( binding.visibility & GPUShaderStage.FRAGMENT ) {
  54655. visibilities.push( 'fragment' );
  54656. }
  54657. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54658. visibilities.push( 'compute' );
  54659. }
  54660. const bufferVisibility = `(${visibilities.join( ',' )})`;
  54661. const bufferGPU = device.createBuffer( {
  54662. label: `bindingBuffer${binding.id}_${binding.name}_${bufferVisibility}`,
  54663. size: byteLength,
  54664. usage: usage
  54665. } );
  54666. bindingData.buffer = bufferGPU;
  54667. }
  54668. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  54669. } else if ( binding.isStorageBuffer ) {
  54670. const buffer = backend.get( binding.attribute ).buffer;
  54671. entriesGPU.push( { binding: bindingPoint, resource: { buffer: buffer } } );
  54672. } else if ( binding.isSampledTexture ) {
  54673. const textureData = backend.get( binding.texture );
  54674. let resourceGPU;
  54675. if ( textureData.externalTexture !== undefined ) {
  54676. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  54677. } else {
  54678. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  54679. const baseMipLevel = binding.store ? binding.mipLevel : 0;
  54680. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  54681. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  54682. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  54683. }
  54684. propertyName += `-${ mipLevelCount }-${ baseMipLevel }`;
  54685. resourceGPU = textureData[ propertyName ];
  54686. if ( resourceGPU === undefined ) {
  54687. const aspectGPU = GPUTextureAspect.All;
  54688. let dimensionViewGPU;
  54689. if ( binding.isSampledCubeTexture ) {
  54690. dimensionViewGPU = GPUTextureViewDimension.Cube;
  54691. } else if ( binding.isSampledTexture3D ) {
  54692. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  54693. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54694. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  54695. } else {
  54696. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  54697. }
  54698. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount, baseMipLevel } );
  54699. }
  54700. }
  54701. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  54702. } else if ( binding.isSampler ) {
  54703. const textureGPU = backend.get( binding.texture );
  54704. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  54705. }
  54706. bindingPoint ++;
  54707. }
  54708. return device.createBindGroup( {
  54709. label: 'bindGroup_' + bindGroup.name,
  54710. layout: layoutGPU,
  54711. entries: entriesGPU
  54712. } );
  54713. }
  54714. /**
  54715. * Creates a GPU bind group layout entries for the given bind group.
  54716. *
  54717. * @private
  54718. * @param {BindGroup} bindGroup - The bind group.
  54719. * @return {Array<GPUBindGroupLayoutEntry>} The GPU bind group layout entries.
  54720. */
  54721. _createLayoutEntries( bindGroup ) {
  54722. const entries = [];
  54723. let index = 0;
  54724. for ( const binding of bindGroup.bindings ) {
  54725. const backend = this.backend;
  54726. const bindingGPU = {
  54727. binding: index,
  54728. visibility: binding.visibility
  54729. };
  54730. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  54731. const buffer = {}; // GPUBufferBindingLayout
  54732. if ( binding.isStorageBuffer ) {
  54733. if ( binding.visibility & GPUShaderStage.COMPUTE ) {
  54734. // compute
  54735. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  54736. buffer.type = GPUBufferBindingType.Storage;
  54737. } else {
  54738. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54739. }
  54740. } else {
  54741. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  54742. }
  54743. }
  54744. bindingGPU.buffer = buffer;
  54745. } else if ( binding.isSampledTexture && binding.store ) {
  54746. const storageTexture = {}; // GPUStorageTextureBindingLayout
  54747. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  54748. const access = binding.access;
  54749. if ( access === NodeAccess.READ_WRITE ) {
  54750. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  54751. } else if ( access === NodeAccess.WRITE_ONLY ) {
  54752. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  54753. } else {
  54754. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  54755. }
  54756. if ( binding.texture.isArrayTexture ) {
  54757. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54758. } else if ( binding.texture.is3DTexture ) {
  54759. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  54760. }
  54761. bindingGPU.storageTexture = storageTexture;
  54762. } else if ( binding.isSampledTexture ) {
  54763. const texture = {}; // GPUTextureBindingLayout
  54764. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  54765. if ( primarySamples > 1 ) {
  54766. texture.multisampled = true;
  54767. if ( ! binding.texture.isDepthTexture ) {
  54768. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54769. }
  54770. }
  54771. if ( binding.texture.isDepthTexture ) {
  54772. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  54773. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54774. } else {
  54775. texture.sampleType = GPUTextureSampleType.Depth;
  54776. }
  54777. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  54778. const type = binding.texture.type;
  54779. if ( type === IntType ) {
  54780. texture.sampleType = GPUTextureSampleType.SInt;
  54781. } else if ( type === UnsignedIntType ) {
  54782. texture.sampleType = GPUTextureSampleType.UInt;
  54783. } else if ( type === FloatType ) {
  54784. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  54785. texture.sampleType = GPUTextureSampleType.Float;
  54786. } else {
  54787. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  54788. }
  54789. }
  54790. }
  54791. if ( binding.isSampledCubeTexture ) {
  54792. texture.viewDimension = GPUTextureViewDimension.Cube;
  54793. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  54794. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  54795. } else if ( binding.isSampledTexture3D ) {
  54796. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  54797. }
  54798. bindingGPU.texture = texture;
  54799. } else if ( binding.isSampler ) {
  54800. const sampler = {}; // GPUSamplerBindingLayout
  54801. if ( binding.texture.isDepthTexture ) {
  54802. if ( binding.texture.compareFunction !== null && backend.hasCompatibility( Compatibility.TEXTURE_COMPARE ) ) {
  54803. sampler.type = GPUSamplerBindingType.Comparison;
  54804. } else {
  54805. // Depth textures without compare must use non-filtering sampler
  54806. sampler.type = GPUSamplerBindingType.NonFiltering;
  54807. }
  54808. }
  54809. bindingGPU.sampler = sampler;
  54810. } else {
  54811. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  54812. }
  54813. entries.push( bindingGPU );
  54814. index ++;
  54815. }
  54816. return entries;
  54817. }
  54818. /**
  54819. * Delete the data associated with a bind group.
  54820. *
  54821. * @param {BindGroup} bindGroup - The bind group.
  54822. */
  54823. deleteBindGroupData( bindGroup ) {
  54824. const { backend } = this;
  54825. const bindingsData = backend.get( bindGroup );
  54826. if ( bindingsData.layout ) {
  54827. bindingsData.layout.usedTimes --;
  54828. if ( bindingsData.layout.usedTimes === 0 ) {
  54829. this._bindGroupLayoutCache.delete( bindingsData.layoutKey );
  54830. }
  54831. bindingsData.layout = undefined;
  54832. bindingsData.layoutKey = undefined;
  54833. }
  54834. }
  54835. /**
  54836. * Frees internal resources.
  54837. */
  54838. dispose() {
  54839. this._bindGroupLayoutCache.clear();
  54840. }
  54841. }
  54842. /**
  54843. * A WebGPU backend utility module for managing pipelines.
  54844. *
  54845. * @private
  54846. */
  54847. class WebGPUPipelineUtils {
  54848. /**
  54849. * Constructs a new utility object.
  54850. *
  54851. * @param {WebGPUBackend} backend - The WebGPU backend.
  54852. */
  54853. constructor( backend ) {
  54854. /**
  54855. * A reference to the WebGPU backend.
  54856. *
  54857. * @type {WebGPUBackend}
  54858. */
  54859. this.backend = backend;
  54860. /**
  54861. * A Weak Map that tracks the active pipeline for render or compute passes.
  54862. *
  54863. * @private
  54864. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  54865. */
  54866. this._activePipelines = new WeakMap();
  54867. }
  54868. /**
  54869. * Sets the given pipeline for the given pass. The method makes sure to only set the
  54870. * pipeline when necessary.
  54871. *
  54872. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  54873. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  54874. */
  54875. setPipeline( pass, pipeline ) {
  54876. const currentPipeline = this._activePipelines.get( pass );
  54877. if ( currentPipeline !== pipeline ) {
  54878. pass.setPipeline( pipeline );
  54879. this._activePipelines.set( pass, pipeline );
  54880. }
  54881. }
  54882. /**
  54883. * Returns the sample count derived from the given render context.
  54884. *
  54885. * @private
  54886. * @param {RenderContext} renderContext - The render context.
  54887. * @return {number} The sample count.
  54888. */
  54889. _getSampleCount( renderContext ) {
  54890. return this.backend.utils.getSampleCountRenderContext( renderContext );
  54891. }
  54892. /**
  54893. * Creates a render pipeline for the given render object.
  54894. *
  54895. * @param {RenderObject} renderObject - The render object.
  54896. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54897. */
  54898. createRenderPipeline( renderObject, promises ) {
  54899. const { object, material, geometry, pipeline } = renderObject;
  54900. const { vertexProgram, fragmentProgram } = pipeline;
  54901. const backend = this.backend;
  54902. const device = backend.device;
  54903. const utils = backend.utils;
  54904. const pipelineData = backend.get( pipeline );
  54905. // bind group layouts
  54906. const bindGroupLayouts = [];
  54907. for ( const bindGroup of renderObject.getBindings() ) {
  54908. const bindingsData = backend.get( bindGroup );
  54909. const { layoutGPU } = bindingsData.layout;
  54910. bindGroupLayouts.push( layoutGPU );
  54911. }
  54912. // vertex buffers
  54913. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  54914. // material blending
  54915. let materialBlending;
  54916. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  54917. materialBlending = this._getBlending( material );
  54918. }
  54919. // stencil
  54920. let stencilFront = {};
  54921. if ( material.stencilWrite === true ) {
  54922. stencilFront = {
  54923. compare: this._getStencilCompare( material ),
  54924. failOp: this._getStencilOperation( material.stencilFail ),
  54925. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  54926. passOp: this._getStencilOperation( material.stencilZPass )
  54927. };
  54928. }
  54929. const colorWriteMask = this._getColorWriteMask( material );
  54930. const targets = [];
  54931. if ( renderObject.context.textures !== null ) {
  54932. const textures = renderObject.context.textures;
  54933. const mrt = renderObject.context.mrt;
  54934. for ( let i = 0; i < textures.length; i ++ ) {
  54935. const texture = textures[ i ];
  54936. const colorFormat = utils.getTextureFormatGPU( texture );
  54937. // mrt blending
  54938. let blending;
  54939. if ( mrt !== null ) {
  54940. const blendMode = mrt.getBlendMode( texture.name );
  54941. if ( blendMode.blending === MaterialBlending ) {
  54942. blending = materialBlending;
  54943. } else if ( blendMode.blending !== NoBlending ) {
  54944. blending = this._getBlending( blendMode );
  54945. }
  54946. } else {
  54947. blending = materialBlending;
  54948. }
  54949. targets.push( {
  54950. format: colorFormat,
  54951. blend: blending,
  54952. writeMask: colorWriteMask
  54953. } );
  54954. }
  54955. } else {
  54956. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54957. targets.push( {
  54958. format: colorFormat,
  54959. blend: materialBlending,
  54960. writeMask: colorWriteMask
  54961. } );
  54962. }
  54963. const vertexModule = backend.get( vertexProgram ).module;
  54964. const fragmentModule = backend.get( fragmentProgram ).module;
  54965. const primitiveState = this._getPrimitiveState( object, geometry, material );
  54966. const depthCompare = this._getDepthCompare( material );
  54967. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54968. const sampleCount = this._getSampleCount( renderObject.context );
  54969. const pipelineDescriptor = {
  54970. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  54971. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  54972. fragment: Object.assign( {}, fragmentModule, { targets } ),
  54973. primitive: primitiveState,
  54974. multisample: {
  54975. count: sampleCount,
  54976. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  54977. },
  54978. layout: device.createPipelineLayout( {
  54979. bindGroupLayouts
  54980. } )
  54981. };
  54982. const depthStencil = {};
  54983. const renderDepth = renderObject.context.depth;
  54984. const renderStencil = renderObject.context.stencil;
  54985. if ( renderDepth === true || renderStencil === true ) {
  54986. if ( renderDepth === true ) {
  54987. depthStencil.format = depthStencilFormat;
  54988. depthStencil.depthWriteEnabled = material.depthWrite;
  54989. depthStencil.depthCompare = depthCompare;
  54990. }
  54991. if ( renderStencil === true ) {
  54992. depthStencil.stencilFront = stencilFront;
  54993. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  54994. depthStencil.stencilReadMask = material.stencilFuncMask;
  54995. depthStencil.stencilWriteMask = material.stencilWriteMask;
  54996. }
  54997. if ( material.polygonOffset === true ) {
  54998. depthStencil.depthBias = material.polygonOffsetUnits;
  54999. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  55000. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  55001. }
  55002. pipelineDescriptor.depthStencil = depthStencil;
  55003. }
  55004. // create pipeline
  55005. device.pushErrorScope( 'validation' );
  55006. if ( promises === null ) {
  55007. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  55008. device.popErrorScope().then( ( err ) => {
  55009. if ( err !== null ) {
  55010. pipelineData.error = true;
  55011. error( err.message );
  55012. }
  55013. } );
  55014. } else {
  55015. const p = new Promise( async ( resolve /*, reject*/ ) => {
  55016. try {
  55017. pipelineData.pipeline = await device.createRenderPipelineAsync( pipelineDescriptor );
  55018. } catch ( err ) { }
  55019. const errorScope = await device.popErrorScope();
  55020. if ( errorScope !== null ) {
  55021. pipelineData.error = true;
  55022. error( errorScope.message );
  55023. }
  55024. resolve();
  55025. } );
  55026. promises.push( p );
  55027. }
  55028. }
  55029. /**
  55030. * Creates GPU render bundle encoder for the given render context.
  55031. *
  55032. * @param {RenderContext} renderContext - The render context.
  55033. * @param {?string} [label='renderBundleEncoder'] - The label.
  55034. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  55035. */
  55036. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  55037. const backend = this.backend;
  55038. const { utils, device } = backend;
  55039. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  55040. const colorFormats = utils.getCurrentColorFormats( renderContext );
  55041. const sampleCount = this._getSampleCount( renderContext );
  55042. const descriptor = {
  55043. label,
  55044. colorFormats,
  55045. depthStencilFormat,
  55046. sampleCount
  55047. };
  55048. return device.createRenderBundleEncoder( descriptor );
  55049. }
  55050. /**
  55051. * Creates a compute pipeline for the given compute node.
  55052. *
  55053. * @param {ComputePipeline} pipeline - The compute pipeline.
  55054. * @param {Array<BindGroup>} bindings - The bindings.
  55055. */
  55056. createComputePipeline( pipeline, bindings ) {
  55057. const backend = this.backend;
  55058. const device = backend.device;
  55059. const computeProgram = backend.get( pipeline.computeProgram ).module;
  55060. const pipelineGPU = backend.get( pipeline );
  55061. // bind group layouts
  55062. const bindGroupLayouts = [];
  55063. for ( const bindingsGroup of bindings ) {
  55064. const bindingsData = backend.get( bindingsGroup );
  55065. const { layoutGPU } = bindingsData.layout;
  55066. bindGroupLayouts.push( layoutGPU );
  55067. }
  55068. pipelineGPU.pipeline = device.createComputePipeline( {
  55069. compute: computeProgram,
  55070. layout: device.createPipelineLayout( {
  55071. bindGroupLayouts
  55072. } )
  55073. } );
  55074. }
  55075. /**
  55076. * Returns the blending state as a descriptor object required
  55077. * for the pipeline creation.
  55078. *
  55079. * @private
  55080. * @param {Material|BlendMode} object - The object containing blending information.
  55081. * @return {Object} The blending state.
  55082. */
  55083. _getBlending( object ) {
  55084. let color, alpha;
  55085. const blending = object.blending;
  55086. const blendSrc = object.blendSrc;
  55087. const blendDst = object.blendDst;
  55088. const blendEquation = object.blendEquation;
  55089. if ( blending === CustomBlending ) {
  55090. const blendSrcAlpha = object.blendSrcAlpha !== null ? object.blendSrcAlpha : blendSrc;
  55091. const blendDstAlpha = object.blendDstAlpha !== null ? object.blendDstAlpha : blendDst;
  55092. const blendEquationAlpha = object.blendEquationAlpha !== null ? object.blendEquationAlpha : blendEquation;
  55093. color = {
  55094. srcFactor: this._getBlendFactor( blendSrc ),
  55095. dstFactor: this._getBlendFactor( blendDst ),
  55096. operation: this._getBlendOperation( blendEquation )
  55097. };
  55098. alpha = {
  55099. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  55100. dstFactor: this._getBlendFactor( blendDstAlpha ),
  55101. operation: this._getBlendOperation( blendEquationAlpha )
  55102. };
  55103. } else {
  55104. const premultipliedAlpha = object.premultipliedAlpha;
  55105. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  55106. color = {
  55107. srcFactor: srcRGB,
  55108. dstFactor: dstRGB,
  55109. operation: GPUBlendOperation.Add
  55110. };
  55111. alpha = {
  55112. srcFactor: srcAlpha,
  55113. dstFactor: dstAlpha,
  55114. operation: GPUBlendOperation.Add
  55115. };
  55116. };
  55117. if ( premultipliedAlpha ) {
  55118. switch ( blending ) {
  55119. case NormalBlending:
  55120. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  55121. break;
  55122. case AdditiveBlending:
  55123. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  55124. break;
  55125. case SubtractiveBlending:
  55126. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  55127. break;
  55128. case MultiplyBlending:
  55129. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  55130. break;
  55131. }
  55132. } else {
  55133. switch ( blending ) {
  55134. case NormalBlending:
  55135. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  55136. break;
  55137. case AdditiveBlending:
  55138. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  55139. break;
  55140. case SubtractiveBlending:
  55141. error( `WebGPURenderer: "SubtractiveBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  55142. break;
  55143. case MultiplyBlending:
  55144. error( `WebGPURenderer: "MultiplyBlending" requires "${ object.isMaterial ? 'material' : 'blendMode' }.premultipliedAlpha = true".` );
  55145. break;
  55146. }
  55147. }
  55148. }
  55149. if ( color !== undefined && alpha !== undefined ) {
  55150. return { color, alpha };
  55151. } else {
  55152. error( 'WebGPURenderer: Invalid blending: ', blending );
  55153. }
  55154. }
  55155. /**
  55156. * Returns the GPU blend factor which is required for the pipeline creation.
  55157. *
  55158. * @private
  55159. * @param {number} blend - The blend factor as a three.js constant.
  55160. * @return {string} The GPU blend factor.
  55161. */
  55162. _getBlendFactor( blend ) {
  55163. let blendFactor;
  55164. switch ( blend ) {
  55165. case ZeroFactor:
  55166. blendFactor = GPUBlendFactor.Zero;
  55167. break;
  55168. case OneFactor:
  55169. blendFactor = GPUBlendFactor.One;
  55170. break;
  55171. case SrcColorFactor:
  55172. blendFactor = GPUBlendFactor.Src;
  55173. break;
  55174. case OneMinusSrcColorFactor:
  55175. blendFactor = GPUBlendFactor.OneMinusSrc;
  55176. break;
  55177. case SrcAlphaFactor:
  55178. blendFactor = GPUBlendFactor.SrcAlpha;
  55179. break;
  55180. case OneMinusSrcAlphaFactor:
  55181. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  55182. break;
  55183. case DstColorFactor:
  55184. blendFactor = GPUBlendFactor.Dst;
  55185. break;
  55186. case OneMinusDstColorFactor:
  55187. blendFactor = GPUBlendFactor.OneMinusDst;
  55188. break;
  55189. case DstAlphaFactor:
  55190. blendFactor = GPUBlendFactor.DstAlpha;
  55191. break;
  55192. case OneMinusDstAlphaFactor:
  55193. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  55194. break;
  55195. case SrcAlphaSaturateFactor:
  55196. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  55197. break;
  55198. case BlendColorFactor:
  55199. blendFactor = GPUBlendFactor.Constant;
  55200. break;
  55201. case OneMinusBlendColorFactor:
  55202. blendFactor = GPUBlendFactor.OneMinusConstant;
  55203. break;
  55204. default:
  55205. error( 'WebGPURenderer: Blend factor not supported.', blend );
  55206. }
  55207. return blendFactor;
  55208. }
  55209. /**
  55210. * Returns the GPU stencil compare function which is required for the pipeline creation.
  55211. *
  55212. * @private
  55213. * @param {Material} material - The material.
  55214. * @return {string} The GPU stencil compare function.
  55215. */
  55216. _getStencilCompare( material ) {
  55217. let stencilCompare;
  55218. const stencilFunc = material.stencilFunc;
  55219. switch ( stencilFunc ) {
  55220. case NeverStencilFunc:
  55221. stencilCompare = GPUCompareFunction.Never;
  55222. break;
  55223. case AlwaysStencilFunc:
  55224. stencilCompare = GPUCompareFunction.Always;
  55225. break;
  55226. case LessStencilFunc:
  55227. stencilCompare = GPUCompareFunction.Less;
  55228. break;
  55229. case LessEqualStencilFunc:
  55230. stencilCompare = GPUCompareFunction.LessEqual;
  55231. break;
  55232. case EqualStencilFunc:
  55233. stencilCompare = GPUCompareFunction.Equal;
  55234. break;
  55235. case GreaterEqualStencilFunc:
  55236. stencilCompare = GPUCompareFunction.GreaterEqual;
  55237. break;
  55238. case GreaterStencilFunc:
  55239. stencilCompare = GPUCompareFunction.Greater;
  55240. break;
  55241. case NotEqualStencilFunc:
  55242. stencilCompare = GPUCompareFunction.NotEqual;
  55243. break;
  55244. default:
  55245. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  55246. }
  55247. return stencilCompare;
  55248. }
  55249. /**
  55250. * Returns the GPU stencil operation which is required for the pipeline creation.
  55251. *
  55252. * @private
  55253. * @param {number} op - A three.js constant defining the stencil operation.
  55254. * @return {string} The GPU stencil operation.
  55255. */
  55256. _getStencilOperation( op ) {
  55257. let stencilOperation;
  55258. switch ( op ) {
  55259. case KeepStencilOp:
  55260. stencilOperation = GPUStencilOperation.Keep;
  55261. break;
  55262. case ZeroStencilOp:
  55263. stencilOperation = GPUStencilOperation.Zero;
  55264. break;
  55265. case ReplaceStencilOp:
  55266. stencilOperation = GPUStencilOperation.Replace;
  55267. break;
  55268. case InvertStencilOp:
  55269. stencilOperation = GPUStencilOperation.Invert;
  55270. break;
  55271. case IncrementStencilOp:
  55272. stencilOperation = GPUStencilOperation.IncrementClamp;
  55273. break;
  55274. case DecrementStencilOp:
  55275. stencilOperation = GPUStencilOperation.DecrementClamp;
  55276. break;
  55277. case IncrementWrapStencilOp:
  55278. stencilOperation = GPUStencilOperation.IncrementWrap;
  55279. break;
  55280. case DecrementWrapStencilOp:
  55281. stencilOperation = GPUStencilOperation.DecrementWrap;
  55282. break;
  55283. default:
  55284. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  55285. }
  55286. return stencilOperation;
  55287. }
  55288. /**
  55289. * Returns the GPU blend operation which is required for the pipeline creation.
  55290. *
  55291. * @private
  55292. * @param {number} blendEquation - A three.js constant defining the blend equation.
  55293. * @return {string} The GPU blend operation.
  55294. */
  55295. _getBlendOperation( blendEquation ) {
  55296. let blendOperation;
  55297. switch ( blendEquation ) {
  55298. case AddEquation:
  55299. blendOperation = GPUBlendOperation.Add;
  55300. break;
  55301. case SubtractEquation:
  55302. blendOperation = GPUBlendOperation.Subtract;
  55303. break;
  55304. case ReverseSubtractEquation:
  55305. blendOperation = GPUBlendOperation.ReverseSubtract;
  55306. break;
  55307. case MinEquation:
  55308. blendOperation = GPUBlendOperation.Min;
  55309. break;
  55310. case MaxEquation:
  55311. blendOperation = GPUBlendOperation.Max;
  55312. break;
  55313. default:
  55314. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  55315. }
  55316. return blendOperation;
  55317. }
  55318. /**
  55319. * Returns the primitive state as a descriptor object required
  55320. * for the pipeline creation.
  55321. *
  55322. * @private
  55323. * @param {Object3D} object - The 3D object.
  55324. * @param {BufferGeometry} geometry - The geometry.
  55325. * @param {Material} material - The material.
  55326. * @return {Object} The primitive state.
  55327. */
  55328. _getPrimitiveState( object, geometry, material ) {
  55329. const descriptor = {};
  55330. const utils = this.backend.utils;
  55331. //
  55332. descriptor.topology = utils.getPrimitiveTopology( object, material );
  55333. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  55334. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  55335. }
  55336. //
  55337. let flipSided = ( material.side === BackSide );
  55338. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  55339. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  55340. //
  55341. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  55342. return descriptor;
  55343. }
  55344. /**
  55345. * Returns the GPU color write mask which is required for the pipeline creation.
  55346. *
  55347. * @private
  55348. * @param {Material} material - The material.
  55349. * @return {number} The GPU color write mask.
  55350. */
  55351. _getColorWriteMask( material ) {
  55352. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  55353. }
  55354. /**
  55355. * Returns the GPU depth compare function which is required for the pipeline creation.
  55356. *
  55357. * @private
  55358. * @param {Material} material - The material.
  55359. * @return {string} The GPU depth compare function.
  55360. */
  55361. _getDepthCompare( material ) {
  55362. let depthCompare;
  55363. if ( material.depthTest === false ) {
  55364. depthCompare = GPUCompareFunction.Always;
  55365. } else {
  55366. const depthFunc = material.depthFunc;
  55367. switch ( depthFunc ) {
  55368. case NeverDepth:
  55369. depthCompare = GPUCompareFunction.Never;
  55370. break;
  55371. case AlwaysDepth:
  55372. depthCompare = GPUCompareFunction.Always;
  55373. break;
  55374. case LessDepth:
  55375. depthCompare = GPUCompareFunction.Less;
  55376. break;
  55377. case LessEqualDepth:
  55378. depthCompare = GPUCompareFunction.LessEqual;
  55379. break;
  55380. case EqualDepth:
  55381. depthCompare = GPUCompareFunction.Equal;
  55382. break;
  55383. case GreaterEqualDepth:
  55384. depthCompare = GPUCompareFunction.GreaterEqual;
  55385. break;
  55386. case GreaterDepth:
  55387. depthCompare = GPUCompareFunction.Greater;
  55388. break;
  55389. case NotEqualDepth:
  55390. depthCompare = GPUCompareFunction.NotEqual;
  55391. break;
  55392. default:
  55393. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  55394. }
  55395. }
  55396. return depthCompare;
  55397. }
  55398. }
  55399. /**
  55400. * Manages a pool of WebGPU timestamp queries for performance measurement.
  55401. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  55402. *
  55403. * @augments TimestampQueryPool
  55404. */
  55405. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  55406. /**
  55407. * Creates a new WebGPU timestamp query pool.
  55408. *
  55409. * @param {GPUDevice} device - The WebGPU device to create queries on.
  55410. * @param {string} type - The type identifier for this query pool.
  55411. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  55412. */
  55413. constructor( device, type, maxQueries = 2048 ) {
  55414. super( maxQueries );
  55415. this.device = device;
  55416. this.type = type;
  55417. this.querySet = this.device.createQuerySet( {
  55418. type: 'timestamp',
  55419. count: this.maxQueries,
  55420. label: `queryset_global_timestamp_${type}`
  55421. } );
  55422. const bufferSize = this.maxQueries * 8;
  55423. this.resolveBuffer = this.device.createBuffer( {
  55424. label: `buffer_timestamp_resolve_${type}`,
  55425. size: bufferSize,
  55426. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  55427. } );
  55428. this.resultBuffer = this.device.createBuffer( {
  55429. label: `buffer_timestamp_result_${type}`,
  55430. size: bufferSize,
  55431. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  55432. } );
  55433. }
  55434. /**
  55435. * Allocates a pair of queries for a given render context.
  55436. *
  55437. * @param {string} uid - A unique identifier for the render context.
  55438. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  55439. */
  55440. allocateQueriesForContext( uid ) {
  55441. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  55442. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  55443. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  55444. return null;
  55445. }
  55446. const baseOffset = this.currentQueryIndex;
  55447. this.currentQueryIndex += 2;
  55448. this.queryOffsets.set( uid, baseOffset );
  55449. return baseOffset;
  55450. }
  55451. /**
  55452. * Asynchronously resolves all pending queries and returns the total duration.
  55453. * If there's already a pending resolve operation, returns that promise instead.
  55454. *
  55455. * @async
  55456. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  55457. */
  55458. async resolveQueriesAsync() {
  55459. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  55460. return this.lastValue;
  55461. }
  55462. if ( this.pendingResolve ) {
  55463. return this.pendingResolve;
  55464. }
  55465. this.pendingResolve = this._resolveQueries();
  55466. try {
  55467. const result = await this.pendingResolve;
  55468. return result;
  55469. } finally {
  55470. this.pendingResolve = null;
  55471. }
  55472. }
  55473. /**
  55474. * Internal method to resolve queries and calculate total duration.
  55475. *
  55476. * @async
  55477. * @private
  55478. * @returns {Promise<number>} The total duration in milliseconds.
  55479. */
  55480. async _resolveQueries() {
  55481. if ( this.isDisposed ) {
  55482. return this.lastValue;
  55483. }
  55484. try {
  55485. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55486. return this.lastValue;
  55487. }
  55488. const currentOffsets = new Map( this.queryOffsets );
  55489. const queryCount = this.currentQueryIndex;
  55490. const bytesUsed = queryCount * 8;
  55491. // Reset state before GPU work
  55492. this.currentQueryIndex = 0;
  55493. this.queryOffsets.clear();
  55494. const commandEncoder = this.device.createCommandEncoder();
  55495. commandEncoder.resolveQuerySet(
  55496. this.querySet,
  55497. 0,
  55498. queryCount,
  55499. this.resolveBuffer,
  55500. 0
  55501. );
  55502. commandEncoder.copyBufferToBuffer(
  55503. this.resolveBuffer,
  55504. 0,
  55505. this.resultBuffer,
  55506. 0,
  55507. bytesUsed
  55508. );
  55509. const commandBuffer = commandEncoder.finish();
  55510. this.device.queue.submit( [ commandBuffer ] );
  55511. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  55512. return this.lastValue;
  55513. }
  55514. // Create and track the mapping operation
  55515. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  55516. if ( this.isDisposed ) {
  55517. if ( this.resultBuffer.mapState === 'mapped' ) {
  55518. this.resultBuffer.unmap();
  55519. }
  55520. return this.lastValue;
  55521. }
  55522. //
  55523. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  55524. const framesDuration = {};
  55525. const frames = [];
  55526. for ( const [ uid, baseOffset ] of currentOffsets ) {
  55527. const match = uid.match( /^(.*):f(\d+)$/ );
  55528. const frame = parseInt( match[ 2 ] );
  55529. if ( frames.includes( frame ) === false ) {
  55530. frames.push( frame );
  55531. }
  55532. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  55533. const startTime = times[ baseOffset ];
  55534. const endTime = times[ baseOffset + 1 ];
  55535. const duration = Number( endTime - startTime ) / 1e6;
  55536. this.timestamps.set( uid, duration );
  55537. framesDuration[ frame ] += duration;
  55538. }
  55539. // Return the total duration of the last frame
  55540. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  55541. this.resultBuffer.unmap();
  55542. this.lastValue = totalDuration;
  55543. this.frames = frames;
  55544. return totalDuration;
  55545. } catch ( e ) {
  55546. error( 'Error resolving queries:', e );
  55547. if ( this.resultBuffer.mapState === 'mapped' ) {
  55548. this.resultBuffer.unmap();
  55549. }
  55550. return this.lastValue;
  55551. }
  55552. }
  55553. /**
  55554. * Dispose of the query pool.
  55555. *
  55556. * @async
  55557. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  55558. */
  55559. async dispose() {
  55560. if ( this.isDisposed ) {
  55561. return;
  55562. }
  55563. this.isDisposed = true;
  55564. // Wait for pending resolve operation
  55565. if ( this.pendingResolve ) {
  55566. try {
  55567. await this.pendingResolve;
  55568. } catch ( e ) {
  55569. error( 'Error waiting for pending resolve:', e );
  55570. }
  55571. }
  55572. // Ensure buffer is unmapped before destroying
  55573. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  55574. try {
  55575. this.resultBuffer.unmap();
  55576. } catch ( e ) {
  55577. error( 'Error unmapping buffer:', e );
  55578. }
  55579. }
  55580. // Destroy resources
  55581. if ( this.querySet ) {
  55582. this.querySet.destroy();
  55583. this.querySet = null;
  55584. }
  55585. if ( this.resolveBuffer ) {
  55586. this.resolveBuffer.destroy();
  55587. this.resolveBuffer = null;
  55588. }
  55589. if ( this.resultBuffer ) {
  55590. this.resultBuffer.destroy();
  55591. this.resultBuffer = null;
  55592. }
  55593. this.queryOffsets.clear();
  55594. this.pendingResolve = null;
  55595. }
  55596. }
  55597. /*// debugger tools
  55598. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  55599. //*/
  55600. /**
  55601. * A backend implementation targeting WebGPU.
  55602. *
  55603. * @private
  55604. * @augments Backend
  55605. */
  55606. class WebGPUBackend extends Backend {
  55607. /**
  55608. * WebGPUBackend options.
  55609. *
  55610. * @typedef {Object} WebGPUBackend~Options
  55611. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  55612. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  55613. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  55614. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  55615. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55616. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  55617. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  55618. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  55619. * @property {string} [powerPreference=undefined] - The power preference.
  55620. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  55621. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  55622. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  55623. */
  55624. /**
  55625. * Constructs a new WebGPU backend.
  55626. *
  55627. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  55628. */
  55629. constructor( parameters = {} ) {
  55630. super( parameters );
  55631. /**
  55632. * This flag can be used for type testing.
  55633. *
  55634. * @type {boolean}
  55635. * @readonly
  55636. * @default true
  55637. */
  55638. this.isWebGPUBackend = true;
  55639. // some parameters require default values other than "undefined"
  55640. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  55641. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  55642. /**
  55643. * Indicates whether the backend is in WebGPU compatibility mode or not.
  55644. * The backend must be initialized before the property can be evaluated.
  55645. *
  55646. * @type {?boolean}
  55647. * @readonly
  55648. * @default null
  55649. */
  55650. this.compatibilityMode = null;
  55651. /**
  55652. * A reference to the device.
  55653. *
  55654. * @type {?GPUDevice}
  55655. * @default null
  55656. */
  55657. this.device = null;
  55658. /**
  55659. * A reference to the default render pass descriptor.
  55660. *
  55661. * @type {?Object}
  55662. * @default null
  55663. */
  55664. this.defaultRenderPassdescriptor = null;
  55665. /**
  55666. * A reference to a backend module holding common utility functions.
  55667. *
  55668. * @type {WebGPUUtils}
  55669. */
  55670. this.utils = new WebGPUUtils( this );
  55671. /**
  55672. * A reference to a backend module holding shader attribute-related
  55673. * utility functions.
  55674. *
  55675. * @type {WebGPUAttributeUtils}
  55676. */
  55677. this.attributeUtils = new WebGPUAttributeUtils( this );
  55678. /**
  55679. * A reference to a backend module holding shader binding-related
  55680. * utility functions.
  55681. *
  55682. * @type {WebGPUBindingUtils}
  55683. */
  55684. this.bindingUtils = new WebGPUBindingUtils( this );
  55685. /**
  55686. * A reference to a backend module holding shader pipeline-related
  55687. * utility functions.
  55688. *
  55689. * @type {WebGPUPipelineUtils}
  55690. */
  55691. this.pipelineUtils = new WebGPUPipelineUtils( this );
  55692. /**
  55693. * A reference to a backend module holding shader texture-related
  55694. * utility functions.
  55695. *
  55696. * @type {WebGPUTextureUtils}
  55697. */
  55698. this.textureUtils = new WebGPUTextureUtils( this );
  55699. /**
  55700. * A map that manages the resolve buffers for occlusion queries.
  55701. *
  55702. * @type {Map<number,GPUBuffer>}
  55703. */
  55704. this.occludedResolveCache = new Map();
  55705. // compatibility checks
  55706. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  55707. /**
  55708. * A map of compatibility checks.
  55709. *
  55710. * @type {Object}
  55711. */
  55712. this._compatibility = {
  55713. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  55714. };
  55715. }
  55716. /**
  55717. * Initializes the backend so it is ready for usage.
  55718. *
  55719. * @async
  55720. * @param {Renderer} renderer - The renderer.
  55721. * @return {Promise} A Promise that resolves when the backend has been initialized.
  55722. */
  55723. async init( renderer ) {
  55724. await super.init( renderer );
  55725. //
  55726. const parameters = this.parameters;
  55727. // create the device if it is not passed with parameters
  55728. let device;
  55729. if ( parameters.device === undefined ) {
  55730. const adapterOptions = {
  55731. powerPreference: parameters.powerPreference,
  55732. featureLevel: 'compatibility'
  55733. };
  55734. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  55735. if ( adapter === null ) {
  55736. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  55737. }
  55738. // feature support
  55739. const features = Object.values( GPUFeatureName );
  55740. const supportedFeatures = [];
  55741. for ( const name of features ) {
  55742. if ( adapter.features.has( name ) ) {
  55743. supportedFeatures.push( name );
  55744. }
  55745. }
  55746. const deviceDescriptor = {
  55747. requiredFeatures: supportedFeatures,
  55748. requiredLimits: parameters.requiredLimits
  55749. };
  55750. device = await adapter.requestDevice( deviceDescriptor );
  55751. } else {
  55752. device = parameters.device;
  55753. }
  55754. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  55755. device.lost.then( ( info ) => {
  55756. if ( info.reason === 'destroyed' ) return;
  55757. const deviceLossInfo = {
  55758. api: 'WebGPU',
  55759. message: info.message || 'Unknown reason',
  55760. reason: info.reason || null,
  55761. originalEvent: info
  55762. };
  55763. renderer.onDeviceLost( deviceLossInfo );
  55764. } );
  55765. this.device = device;
  55766. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  55767. this.updateSize();
  55768. }
  55769. /**
  55770. * A reference to the context.
  55771. *
  55772. * @type {?GPUCanvasContext}
  55773. * @default null
  55774. */
  55775. get context() {
  55776. const canvasTarget = this.renderer.getCanvasTarget();
  55777. const canvasData = this.get( canvasTarget );
  55778. let context = canvasData.context;
  55779. if ( context === undefined ) {
  55780. const parameters = this.parameters;
  55781. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  55782. context = parameters.context;
  55783. } else {
  55784. context = canvasTarget.domElement.getContext( 'webgpu' );
  55785. }
  55786. // OffscreenCanvas does not have setAttribute, see #22811
  55787. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  55788. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  55789. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  55790. context.configure( {
  55791. device: this.device,
  55792. format: this.utils.getPreferredCanvasFormat(),
  55793. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  55794. alphaMode: alphaMode,
  55795. toneMapping: {
  55796. mode: toneMappingMode
  55797. }
  55798. } );
  55799. canvasData.context = context;
  55800. }
  55801. return context;
  55802. }
  55803. /**
  55804. * The coordinate system of the backend.
  55805. *
  55806. * @type {number}
  55807. * @readonly
  55808. */
  55809. get coordinateSystem() {
  55810. return WebGPUCoordinateSystem;
  55811. }
  55812. /**
  55813. * This method performs a readback operation by moving buffer data from
  55814. * a storage buffer attribute from the GPU to the CPU.
  55815. *
  55816. * @async
  55817. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  55818. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  55819. */
  55820. async getArrayBufferAsync( attribute ) {
  55821. return await this.attributeUtils.getArrayBufferAsync( attribute );
  55822. }
  55823. /**
  55824. * Returns the backend's rendering context.
  55825. *
  55826. * @return {GPUCanvasContext} The rendering context.
  55827. */
  55828. getContext() {
  55829. return this.context;
  55830. }
  55831. /**
  55832. * Returns the default render pass descriptor.
  55833. *
  55834. * In WebGPU, the default framebuffer must be configured
  55835. * like custom framebuffers so the backend needs a render
  55836. * pass descriptor even when rendering directly to screen.
  55837. *
  55838. * @private
  55839. * @return {Object} The render pass descriptor.
  55840. */
  55841. _getDefaultRenderPassDescriptor() {
  55842. const renderer = this.renderer;
  55843. const canvasTarget = renderer.getCanvasTarget();
  55844. const canvasData = this.get( canvasTarget );
  55845. const samples = renderer.currentSamples;
  55846. let descriptor = canvasData.descriptor;
  55847. if ( descriptor === undefined || canvasData.samples !== samples ) {
  55848. descriptor = {
  55849. colorAttachments: [ {
  55850. view: null
  55851. } ]
  55852. };
  55853. if ( renderer.depth === true || renderer.stencil === true ) {
  55854. descriptor.depthStencilAttachment = {
  55855. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  55856. };
  55857. }
  55858. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55859. if ( samples > 0 ) {
  55860. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  55861. } else {
  55862. colorAttachment.resolveTarget = undefined;
  55863. }
  55864. canvasData.descriptor = descriptor;
  55865. canvasData.samples = samples;
  55866. }
  55867. const colorAttachment = descriptor.colorAttachments[ 0 ];
  55868. if ( samples > 0 ) {
  55869. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  55870. } else {
  55871. colorAttachment.view = this.context.getCurrentTexture().createView();
  55872. }
  55873. return descriptor;
  55874. }
  55875. /**
  55876. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  55877. *
  55878. * @param {RenderContext} renderContext - The render context.
  55879. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  55880. *
  55881. * @private
  55882. */
  55883. _isRenderCameraDepthArray( renderContext ) {
  55884. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  55885. }
  55886. /**
  55887. * Returns the render pass descriptor for the given render context.
  55888. *
  55889. * @private
  55890. * @param {RenderContext} renderContext - The render context.
  55891. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  55892. * @return {Object} The render pass descriptor.
  55893. */
  55894. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  55895. const renderTarget = renderContext.renderTarget;
  55896. const renderTargetData = this.get( renderTarget );
  55897. let descriptors = renderTargetData.descriptors;
  55898. if ( descriptors === undefined ||
  55899. renderTargetData.width !== renderTarget.width ||
  55900. renderTargetData.height !== renderTarget.height ||
  55901. renderTargetData.samples !== renderTarget.samples
  55902. ) {
  55903. descriptors = {};
  55904. renderTargetData.descriptors = descriptors;
  55905. }
  55906. const cacheKey = renderContext.getCacheKey();
  55907. let descriptorBase = descriptors[ cacheKey ];
  55908. if ( descriptorBase === undefined ) {
  55909. const textures = renderContext.textures;
  55910. const textureViews = [];
  55911. let sliceIndex;
  55912. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  55913. for ( let i = 0; i < textures.length; i ++ ) {
  55914. const textureData = this.get( textures[ i ] );
  55915. const viewDescriptor = {
  55916. label: `colorAttachment_${ i }`,
  55917. baseMipLevel: renderContext.activeMipmapLevel,
  55918. mipLevelCount: 1,
  55919. baseArrayLayer: renderContext.activeCubeFace,
  55920. arrayLayerCount: 1,
  55921. dimension: GPUTextureViewDimension.TwoD
  55922. };
  55923. if ( renderTarget.isRenderTarget3D ) {
  55924. sliceIndex = renderContext.activeCubeFace;
  55925. viewDescriptor.baseArrayLayer = 0;
  55926. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  55927. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55928. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  55929. if ( isRenderCameraDepthArray === true ) {
  55930. const cameras = renderContext.camera.cameras;
  55931. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  55932. const layerViewDescriptor = {
  55933. ...viewDescriptor,
  55934. baseArrayLayer: layer,
  55935. arrayLayerCount: 1,
  55936. dimension: GPUTextureViewDimension.TwoD
  55937. };
  55938. const textureView = textureData.texture.createView( layerViewDescriptor );
  55939. textureViews.push( {
  55940. view: textureView,
  55941. resolveTarget: undefined,
  55942. depthSlice: undefined
  55943. } );
  55944. }
  55945. } else {
  55946. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  55947. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  55948. }
  55949. }
  55950. if ( isRenderCameraDepthArray !== true ) {
  55951. const textureView = textureData.texture.createView( viewDescriptor );
  55952. let view, resolveTarget;
  55953. if ( textureData.msaaTexture !== undefined ) {
  55954. view = textureData.msaaTexture.createView();
  55955. resolveTarget = textureView;
  55956. } else {
  55957. view = textureView;
  55958. resolveTarget = undefined;
  55959. }
  55960. textureViews.push( {
  55961. view,
  55962. resolveTarget,
  55963. depthSlice: sliceIndex
  55964. } );
  55965. }
  55966. }
  55967. descriptorBase = { textureViews };
  55968. if ( renderContext.depth ) {
  55969. const depthTextureData = this.get( renderContext.depthTexture );
  55970. const options = {};
  55971. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  55972. options.dimension = GPUTextureViewDimension.TwoD;
  55973. options.arrayLayerCount = 1;
  55974. options.baseArrayLayer = renderContext.activeCubeFace;
  55975. }
  55976. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  55977. }
  55978. descriptors[ cacheKey ] = descriptorBase;
  55979. renderTargetData.width = renderTarget.width;
  55980. renderTargetData.height = renderTarget.height;
  55981. renderTargetData.samples = renderTarget.samples;
  55982. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  55983. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  55984. }
  55985. const descriptor = {
  55986. colorAttachments: []
  55987. };
  55988. // Apply dynamic properties to cached views
  55989. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  55990. const viewInfo = descriptorBase.textureViews[ i ];
  55991. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  55992. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  55993. clearValue = colorAttachmentsConfig.clearValue;
  55994. }
  55995. descriptor.colorAttachments.push( {
  55996. view: viewInfo.view,
  55997. depthSlice: viewInfo.depthSlice,
  55998. resolveTarget: viewInfo.resolveTarget,
  55999. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  56000. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  56001. clearValue: clearValue
  56002. } );
  56003. }
  56004. if ( descriptorBase.depthStencilView ) {
  56005. descriptor.depthStencilAttachment = {
  56006. view: descriptorBase.depthStencilView
  56007. };
  56008. }
  56009. return descriptor;
  56010. }
  56011. /**
  56012. * This method is executed at the beginning of a render call and prepares
  56013. * the WebGPU state for upcoming render calls
  56014. *
  56015. * @param {RenderContext} renderContext - The render context.
  56016. */
  56017. beginRender( renderContext ) {
  56018. const renderContextData = this.get( renderContext );
  56019. //
  56020. const device = this.device;
  56021. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56022. let occlusionQuerySet;
  56023. if ( occlusionQueryCount > 0 ) {
  56024. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  56025. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  56026. // Get a reference to the array of objects with queries. The renderContextData property
  56027. // can be changed by another render pass before the buffer.mapAsyc() completes.
  56028. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  56029. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  56030. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  56031. //
  56032. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  56033. renderContextData.occlusionQuerySet = occlusionQuerySet;
  56034. renderContextData.occlusionQueryIndex = 0;
  56035. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  56036. renderContextData.lastOcclusionObject = null;
  56037. }
  56038. let descriptor;
  56039. if ( renderContext.textures === null ) {
  56040. descriptor = this._getDefaultRenderPassDescriptor();
  56041. } else {
  56042. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  56043. }
  56044. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  56045. descriptor.occlusionQuerySet = occlusionQuerySet;
  56046. const depthStencilAttachment = descriptor.depthStencilAttachment;
  56047. if ( renderContext.textures !== null ) {
  56048. const colorAttachments = descriptor.colorAttachments;
  56049. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  56050. const colorAttachment = colorAttachments[ i ];
  56051. if ( renderContext.clearColor ) {
  56052. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  56053. colorAttachment.loadOp = GPULoadOp.Clear;
  56054. } else {
  56055. colorAttachment.loadOp = GPULoadOp.Load;
  56056. }
  56057. colorAttachment.storeOp = GPUStoreOp.Store;
  56058. }
  56059. } else {
  56060. const colorAttachment = descriptor.colorAttachments[ 0 ];
  56061. if ( renderContext.clearColor ) {
  56062. colorAttachment.clearValue = renderContext.clearColorValue;
  56063. colorAttachment.loadOp = GPULoadOp.Clear;
  56064. } else {
  56065. colorAttachment.loadOp = GPULoadOp.Load;
  56066. }
  56067. colorAttachment.storeOp = GPUStoreOp.Store;
  56068. }
  56069. //
  56070. if ( renderContext.depth ) {
  56071. if ( renderContext.clearDepth ) {
  56072. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  56073. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56074. } else {
  56075. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56076. }
  56077. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56078. }
  56079. if ( renderContext.stencil ) {
  56080. if ( renderContext.clearStencil ) {
  56081. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  56082. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56083. } else {
  56084. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56085. }
  56086. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56087. }
  56088. //
  56089. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  56090. // shadow arrays - prepare bundle encoders for each camera in an array camera
  56091. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  56092. const cameras = renderContext.camera.cameras;
  56093. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  56094. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  56095. } else {
  56096. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  56097. }
  56098. // Create bundle encoders for each layer
  56099. renderContextData.bundleEncoders = [];
  56100. renderContextData.bundleSets = [];
  56101. // Create separate bundle encoders for each camera in the array
  56102. for ( let i = 0; i < cameras.length; i ++ ) {
  56103. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  56104. renderContext,
  56105. 'renderBundleArrayCamera_' + i
  56106. );
  56107. // Initialize state tracking for this bundle
  56108. const bundleSets = {
  56109. attributes: {},
  56110. bindingGroups: [],
  56111. pipeline: null,
  56112. index: null
  56113. };
  56114. renderContextData.bundleEncoders.push( bundleEncoder );
  56115. renderContextData.bundleSets.push( bundleSets );
  56116. }
  56117. // We'll complete the bundles in finishRender
  56118. renderContextData.currentPass = null;
  56119. } else {
  56120. const currentPass = encoder.beginRenderPass( descriptor );
  56121. renderContextData.currentPass = currentPass;
  56122. if ( renderContext.viewport ) {
  56123. this.updateViewport( renderContext );
  56124. }
  56125. if ( renderContext.scissor ) {
  56126. this.updateScissor( renderContext );
  56127. }
  56128. }
  56129. //
  56130. renderContextData.descriptor = descriptor;
  56131. renderContextData.encoder = encoder;
  56132. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56133. renderContextData.renderBundles = [];
  56134. }
  56135. /**
  56136. * This method creates layer descriptors for each camera in an array camera
  56137. * to prepare for rendering to a depth array texture.
  56138. *
  56139. * @param {RenderContext} renderContext - The render context.
  56140. * @param {Object} renderContextData - The render context data.
  56141. * @param {Object} descriptor - The render pass descriptor.
  56142. * @param {ArrayCamera} cameras - The array camera.
  56143. *
  56144. * @private
  56145. */
  56146. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  56147. const depthStencilAttachment = descriptor.depthStencilAttachment;
  56148. renderContextData.layerDescriptors = [];
  56149. const depthTextureData = this.get( renderContext.depthTexture );
  56150. if ( ! depthTextureData.viewCache ) {
  56151. depthTextureData.viewCache = [];
  56152. }
  56153. for ( let i = 0; i < cameras.length; i ++ ) {
  56154. const layerDescriptor = {
  56155. ...descriptor,
  56156. colorAttachments: [ {
  56157. ...descriptor.colorAttachments[ 0 ],
  56158. view: descriptor.colorAttachments[ i ].view
  56159. } ]
  56160. };
  56161. if ( descriptor.depthStencilAttachment ) {
  56162. const layerIndex = i;
  56163. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  56164. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  56165. dimension: GPUTextureViewDimension.TwoD,
  56166. baseArrayLayer: i,
  56167. arrayLayerCount: 1
  56168. } );
  56169. }
  56170. layerDescriptor.depthStencilAttachment = {
  56171. view: depthTextureData.viewCache[ layerIndex ],
  56172. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  56173. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  56174. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  56175. };
  56176. if ( renderContext.stencil ) {
  56177. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  56178. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  56179. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  56180. }
  56181. } else {
  56182. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  56183. }
  56184. renderContextData.layerDescriptors.push( layerDescriptor );
  56185. }
  56186. }
  56187. /**
  56188. * This method updates the layer descriptors for each camera in an array camera
  56189. * to prepare for rendering to a depth array texture.
  56190. *
  56191. * @param {RenderContext} renderContext - The render context.
  56192. * @param {Object} renderContextData - The render context data.
  56193. * @param {ArrayCamera} cameras - The array camera.
  56194. *
  56195. */
  56196. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  56197. for ( let i = 0; i < cameras.length; i ++ ) {
  56198. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56199. if ( layerDescriptor.depthStencilAttachment ) {
  56200. const depthAttachment = layerDescriptor.depthStencilAttachment;
  56201. if ( renderContext.depth ) {
  56202. if ( renderContext.clearDepth ) {
  56203. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  56204. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  56205. } else {
  56206. depthAttachment.depthLoadOp = GPULoadOp.Load;
  56207. }
  56208. }
  56209. if ( renderContext.stencil ) {
  56210. if ( renderContext.clearStencil ) {
  56211. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  56212. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  56213. } else {
  56214. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  56215. }
  56216. }
  56217. }
  56218. }
  56219. }
  56220. /**
  56221. * This method is executed at the end of a render call and finalizes work
  56222. * after draw calls.
  56223. *
  56224. * @param {RenderContext} renderContext - The render context.
  56225. */
  56226. finishRender( renderContext ) {
  56227. const renderContextData = this.get( renderContext );
  56228. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56229. if ( renderContextData.renderBundles.length > 0 ) {
  56230. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  56231. }
  56232. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  56233. renderContextData.currentPass.endOcclusionQuery();
  56234. }
  56235. // shadow arrays - Execute bundles for each layer
  56236. const encoder = renderContextData.encoder;
  56237. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  56238. const bundles = [];
  56239. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  56240. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56241. bundles.push( bundleEncoder.finish() );
  56242. }
  56243. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  56244. if ( i < bundles.length ) {
  56245. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  56246. const renderPass = encoder.beginRenderPass( layerDescriptor );
  56247. if ( renderContext.viewport ) {
  56248. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56249. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56250. }
  56251. if ( renderContext.scissor ) {
  56252. const { x, y, width, height } = renderContext.scissorValue;
  56253. renderPass.setScissorRect( x, y, width, height );
  56254. }
  56255. renderPass.executeBundles( [ bundles[ i ] ] );
  56256. renderPass.end();
  56257. }
  56258. }
  56259. } else if ( renderContextData.currentPass ) {
  56260. renderContextData.currentPass.end();
  56261. }
  56262. if ( occlusionQueryCount > 0 ) {
  56263. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  56264. //
  56265. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  56266. if ( queryResolveBuffer === undefined ) {
  56267. queryResolveBuffer = this.device.createBuffer(
  56268. {
  56269. size: bufferSize,
  56270. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  56271. }
  56272. );
  56273. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  56274. }
  56275. //
  56276. const readBuffer = this.device.createBuffer(
  56277. {
  56278. size: bufferSize,
  56279. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  56280. }
  56281. );
  56282. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  56283. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  56284. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  56285. renderContextData.occlusionQueryBuffer = readBuffer;
  56286. //
  56287. this.resolveOccludedAsync( renderContext );
  56288. }
  56289. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  56290. //
  56291. if ( renderContext.textures !== null ) {
  56292. const textures = renderContext.textures;
  56293. for ( let i = 0; i < textures.length; i ++ ) {
  56294. const texture = textures[ i ];
  56295. if ( texture.generateMipmaps === true ) {
  56296. this.textureUtils.generateMipmaps( texture );
  56297. }
  56298. }
  56299. }
  56300. }
  56301. /**
  56302. * Returns `true` if the given 3D object is fully occluded by other
  56303. * 3D objects in the scene.
  56304. *
  56305. * @param {RenderContext} renderContext - The render context.
  56306. * @param {Object3D} object - The 3D object to test.
  56307. * @return {boolean} Whether the 3D object is fully occluded or not.
  56308. */
  56309. isOccluded( renderContext, object ) {
  56310. const renderContextData = this.get( renderContext );
  56311. return renderContextData.occluded && renderContextData.occluded.has( object );
  56312. }
  56313. /**
  56314. * This method processes the result of occlusion queries and writes it
  56315. * into render context data.
  56316. *
  56317. * @async
  56318. * @param {RenderContext} renderContext - The render context.
  56319. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  56320. */
  56321. async resolveOccludedAsync( renderContext ) {
  56322. const renderContextData = this.get( renderContext );
  56323. // handle occlusion query results
  56324. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  56325. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  56326. const occluded = new WeakSet();
  56327. renderContextData.currentOcclusionQueryObjects = null;
  56328. renderContextData.currentOcclusionQueryBuffer = null;
  56329. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  56330. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  56331. const results = new BigUint64Array( buffer );
  56332. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  56333. if ( results[ i ] === BigInt( 0 ) ) {
  56334. occluded.add( currentOcclusionQueryObjects[ i ] );
  56335. }
  56336. }
  56337. currentOcclusionQueryBuffer.destroy();
  56338. renderContextData.occluded = occluded;
  56339. }
  56340. }
  56341. /**
  56342. * Updates the viewport with the values from the given render context.
  56343. *
  56344. * @param {RenderContext} renderContext - The render context.
  56345. */
  56346. updateViewport( renderContext ) {
  56347. const { currentPass } = this.get( renderContext );
  56348. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  56349. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  56350. }
  56351. /**
  56352. * Updates the scissor with the values from the given render context.
  56353. *
  56354. * @param {RenderContext} renderContext - The render context.
  56355. */
  56356. updateScissor( renderContext ) {
  56357. const { currentPass } = this.get( renderContext );
  56358. const { x, y, width, height } = renderContext.scissorValue;
  56359. currentPass.setScissorRect( x, y, width, height );
  56360. }
  56361. /**
  56362. * Returns the clear color and alpha into a single
  56363. * color object.
  56364. *
  56365. * @return {Color4} The clear color.
  56366. */
  56367. getClearColor() {
  56368. const clearColor = super.getClearColor();
  56369. // only premultiply alpha when alphaMode is "premultiplied"
  56370. if ( this.renderer.alpha === true ) {
  56371. clearColor.r *= clearColor.a;
  56372. clearColor.g *= clearColor.a;
  56373. clearColor.b *= clearColor.a;
  56374. }
  56375. return clearColor;
  56376. }
  56377. /**
  56378. * Performs a clear operation.
  56379. *
  56380. * @param {boolean} color - Whether the color buffer should be cleared or not.
  56381. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  56382. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  56383. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  56384. */
  56385. clear( color, depth, stencil, renderTargetContext = null ) {
  56386. const device = this.device;
  56387. const renderer = this.renderer;
  56388. let colorAttachments = [];
  56389. let depthStencilAttachment;
  56390. let clearValue;
  56391. let supportsDepth;
  56392. let supportsStencil;
  56393. if ( color ) {
  56394. const clearColor = this.getClearColor();
  56395. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  56396. }
  56397. if ( renderTargetContext === null ) {
  56398. supportsDepth = renderer.depth;
  56399. supportsStencil = renderer.stencil;
  56400. const descriptor = this._getDefaultRenderPassDescriptor();
  56401. if ( color ) {
  56402. colorAttachments = descriptor.colorAttachments;
  56403. const colorAttachment = colorAttachments[ 0 ];
  56404. colorAttachment.clearValue = clearValue;
  56405. colorAttachment.loadOp = GPULoadOp.Clear;
  56406. colorAttachment.storeOp = GPUStoreOp.Store;
  56407. }
  56408. if ( supportsDepth || supportsStencil ) {
  56409. depthStencilAttachment = descriptor.depthStencilAttachment;
  56410. }
  56411. } else {
  56412. supportsDepth = renderTargetContext.depth;
  56413. supportsStencil = renderTargetContext.stencil;
  56414. const clearConfig = {
  56415. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  56416. clearValue: color ? clearValue : undefined
  56417. };
  56418. if ( supportsDepth ) {
  56419. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  56420. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  56421. clearConfig.depthStoreOp = GPUStoreOp.Store;
  56422. }
  56423. if ( supportsStencil ) {
  56424. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  56425. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  56426. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  56427. }
  56428. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  56429. colorAttachments = descriptor.colorAttachments;
  56430. depthStencilAttachment = descriptor.depthStencilAttachment;
  56431. }
  56432. if ( supportsDepth && depthStencilAttachment ) {
  56433. if ( depth ) {
  56434. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  56435. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  56436. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56437. } else {
  56438. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  56439. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  56440. }
  56441. }
  56442. //
  56443. if ( supportsStencil && depthStencilAttachment ) {
  56444. if ( stencil ) {
  56445. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  56446. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  56447. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56448. } else {
  56449. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  56450. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  56451. }
  56452. }
  56453. //
  56454. const encoder = device.createCommandEncoder( { label: 'clear' } );
  56455. const currentPass = encoder.beginRenderPass( {
  56456. colorAttachments,
  56457. depthStencilAttachment
  56458. } );
  56459. currentPass.end();
  56460. device.queue.submit( [ encoder.finish() ] );
  56461. }
  56462. // compute
  56463. /**
  56464. * This method is executed at the beginning of a compute call and
  56465. * prepares the state for upcoming compute tasks.
  56466. *
  56467. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56468. */
  56469. beginCompute( computeGroup ) {
  56470. const groupGPU = this.get( computeGroup );
  56471. //
  56472. const descriptor = {
  56473. label: 'computeGroup_' + computeGroup.id
  56474. };
  56475. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  56476. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  56477. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  56478. }
  56479. /**
  56480. * Executes a compute command for the given compute node.
  56481. *
  56482. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  56483. * @param {Node} computeNode - The compute node.
  56484. * @param {Array<BindGroup>} bindings - The bindings.
  56485. * @param {ComputePipeline} pipeline - The compute pipeline.
  56486. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  56487. * - A single number representing count, or
  56488. * - An array [x, y, z] representing dispatch size, or
  56489. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  56490. */
  56491. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  56492. const computeNodeData = this.get( computeNode );
  56493. const { passEncoderGPU } = this.get( computeGroup );
  56494. // pipeline
  56495. const pipelineGPU = this.get( pipeline ).pipeline;
  56496. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56497. // bind groups
  56498. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56499. const bindGroup = bindings[ i ];
  56500. const bindingsData = this.get( bindGroup );
  56501. passEncoderGPU.setBindGroup( i, bindingsData.group );
  56502. }
  56503. if ( dispatchSize === null ) {
  56504. dispatchSize = computeNode.count;
  56505. }
  56506. // When the dispatchSize is set with a StorageBuffer from the GPU.
  56507. if ( dispatchSize && typeof dispatchSize === 'object' && dispatchSize.isIndirectStorageBufferAttribute ) {
  56508. const dispatchBuffer = this.get( dispatchSize ).buffer;
  56509. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  56510. return;
  56511. }
  56512. if ( typeof dispatchSize === 'number' ) {
  56513. // If a single number is given, we calculate the dispatch size based on the workgroup size
  56514. const count = dispatchSize;
  56515. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  56516. // cache dispatch size to avoid recalculating it every time
  56517. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  56518. computeNodeData.count = count;
  56519. const workgroupSize = computeNode.workgroupSize;
  56520. let size = workgroupSize[ 0 ];
  56521. for ( let i = 1; i < workgroupSize.length; i ++ )
  56522. size *= workgroupSize[ i ];
  56523. const dispatchCount = Math.ceil( count / size );
  56524. //
  56525. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  56526. dispatchSize = [ dispatchCount, 1, 1 ];
  56527. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  56528. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  56529. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  56530. }
  56531. computeNodeData.dispatchSize = dispatchSize;
  56532. }
  56533. dispatchSize = computeNodeData.dispatchSize;
  56534. }
  56535. //
  56536. passEncoderGPU.dispatchWorkgroups(
  56537. dispatchSize[ 0 ],
  56538. dispatchSize[ 1 ] || 1,
  56539. dispatchSize[ 2 ] || 1
  56540. );
  56541. }
  56542. /**
  56543. * This method is executed at the end of a compute call and
  56544. * finalizes work after compute tasks.
  56545. *
  56546. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  56547. */
  56548. finishCompute( computeGroup ) {
  56549. const groupData = this.get( computeGroup );
  56550. groupData.passEncoderGPU.end();
  56551. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  56552. }
  56553. // render object
  56554. /**
  56555. * Executes a draw command for the given render object.
  56556. *
  56557. * @param {RenderObject} renderObject - The render object to draw.
  56558. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  56559. */
  56560. draw( renderObject, info ) {
  56561. const { object, material, context, pipeline } = renderObject;
  56562. const bindings = renderObject.getBindings();
  56563. const renderContextData = this.get( context );
  56564. const pipelineData = this.get( pipeline );
  56565. const pipelineGPU = pipelineData.pipeline;
  56566. if ( pipelineData.error === true ) return;
  56567. const index = renderObject.getIndex();
  56568. const hasIndex = ( index !== null );
  56569. const drawParams = renderObject.getDrawParameters();
  56570. if ( drawParams === null ) return;
  56571. // pipeline
  56572. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  56573. // pipeline
  56574. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  56575. currentSets.pipeline = pipelineGPU;
  56576. // bind groups
  56577. const currentBindingGroups = currentSets.bindingGroups;
  56578. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  56579. const bindGroup = bindings[ i ];
  56580. const bindingsData = this.get( bindGroup );
  56581. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  56582. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  56583. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  56584. }
  56585. }
  56586. // attributes
  56587. // index
  56588. if ( hasIndex === true ) {
  56589. if ( currentSets.index !== index ) {
  56590. const buffer = this.get( index ).buffer;
  56591. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  56592. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  56593. currentSets.index = index;
  56594. }
  56595. }
  56596. // vertex buffers
  56597. const vertexBuffers = renderObject.getVertexBuffers();
  56598. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  56599. const vertexBuffer = vertexBuffers[ i ];
  56600. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  56601. const buffer = this.get( vertexBuffer ).buffer;
  56602. passEncoderGPU.setVertexBuffer( i, buffer );
  56603. currentSets.attributes[ i ] = vertexBuffer;
  56604. }
  56605. }
  56606. // stencil
  56607. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  56608. passEncoderGPU.setStencilReference( material.stencilRef );
  56609. renderContextData.currentStencilRef = material.stencilRef;
  56610. }
  56611. };
  56612. // Define draw function
  56613. const draw = ( passEncoderGPU, currentSets ) => {
  56614. setPipelineAndBindings( passEncoderGPU, currentSets );
  56615. if ( object.isBatchedMesh === true ) {
  56616. const starts = object._multiDrawStarts;
  56617. const counts = object._multiDrawCounts;
  56618. const drawCount = object._multiDrawCount;
  56619. const drawInstances = object._multiDrawInstances;
  56620. if ( drawInstances !== null ) {
  56621. // @deprecated, r174
  56622. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  56623. }
  56624. for ( let i = 0; i < drawCount; i ++ ) {
  56625. const count = drawInstances ? drawInstances[ i ] : 1;
  56626. const firstInstance = count > 1 ? 0 : i;
  56627. if ( hasIndex === true ) {
  56628. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  56629. } else {
  56630. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  56631. }
  56632. info.update( object, counts[ i ], count );
  56633. }
  56634. } else if ( hasIndex === true ) {
  56635. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  56636. const indirect = renderObject.getIndirect();
  56637. if ( indirect !== null ) {
  56638. const buffer = this.get( indirect ).buffer;
  56639. const indirectOffset = renderObject.getIndirectOffset();
  56640. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56641. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56642. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  56643. }
  56644. } else {
  56645. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  56646. }
  56647. info.update( object, indexCount, instanceCount );
  56648. } else {
  56649. const { vertexCount, instanceCount, firstVertex } = drawParams;
  56650. const indirect = renderObject.getIndirect();
  56651. if ( indirect !== null ) {
  56652. const buffer = this.get( indirect ).buffer;
  56653. const indirectOffset = renderObject.getIndirectOffset();
  56654. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  56655. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  56656. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  56657. }
  56658. } else {
  56659. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  56660. }
  56661. info.update( object, vertexCount, instanceCount );
  56662. }
  56663. };
  56664. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  56665. const cameraData = this.get( renderObject.camera );
  56666. const cameras = renderObject.camera.cameras;
  56667. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  56668. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  56669. const bindingsData = this.get( cameraIndex );
  56670. const indexesGPU = [];
  56671. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  56672. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56673. data[ 0 ] = i;
  56674. const { layoutGPU } = bindingsData.layout;
  56675. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  56676. indexesGPU.push( bindGroupIndex );
  56677. }
  56678. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  56679. }
  56680. const pixelRatio = this.renderer.getPixelRatio();
  56681. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  56682. const subCamera = cameras[ i ];
  56683. if ( object.layers.test( subCamera.layers ) ) {
  56684. const vp = subCamera.viewport;
  56685. let pass = renderContextData.currentPass;
  56686. let sets = renderContextData.currentSets;
  56687. if ( renderContextData.bundleEncoders ) {
  56688. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  56689. const bundleSets = renderContextData.bundleSets[ i ];
  56690. pass = bundleEncoder;
  56691. sets = bundleSets;
  56692. }
  56693. if ( vp ) {
  56694. pass.setViewport(
  56695. Math.floor( vp.x * pixelRatio ),
  56696. Math.floor( vp.y * pixelRatio ),
  56697. Math.floor( vp.width * pixelRatio ),
  56698. Math.floor( vp.height * pixelRatio ),
  56699. context.viewportValue.minDepth,
  56700. context.viewportValue.maxDepth
  56701. );
  56702. }
  56703. // Set camera index binding for this layer
  56704. if ( cameraIndex && cameraData.indexesGPU ) {
  56705. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  56706. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  56707. }
  56708. draw( pass, sets );
  56709. }
  56710. }
  56711. } else {
  56712. // Regular single camera rendering
  56713. if ( renderContextData.currentPass ) {
  56714. // Handle occlusion queries
  56715. if ( renderContextData.occlusionQuerySet !== undefined ) {
  56716. const lastObject = renderContextData.lastOcclusionObject;
  56717. if ( lastObject !== object ) {
  56718. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  56719. renderContextData.currentPass.endOcclusionQuery();
  56720. renderContextData.occlusionQueryIndex ++;
  56721. }
  56722. if ( object.occlusionTest === true ) {
  56723. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  56724. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  56725. }
  56726. renderContextData.lastOcclusionObject = object;
  56727. }
  56728. }
  56729. draw( renderContextData.currentPass, renderContextData.currentSets );
  56730. }
  56731. }
  56732. }
  56733. // cache key
  56734. /**
  56735. * Returns `true` if the render pipeline requires an update.
  56736. *
  56737. * @param {RenderObject} renderObject - The render object.
  56738. * @return {boolean} Whether the render pipeline requires an update or not.
  56739. */
  56740. needsRenderUpdate( renderObject ) {
  56741. const data = this.get( renderObject );
  56742. const { object, material } = renderObject;
  56743. const utils = this.utils;
  56744. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  56745. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  56746. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  56747. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  56748. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  56749. let needsUpdate = false;
  56750. if ( data.material !== material || data.materialVersion !== material.version ||
  56751. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  56752. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  56753. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  56754. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  56755. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  56756. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  56757. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  56758. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  56759. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  56760. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  56761. data.primitiveTopology !== primitiveTopology ||
  56762. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  56763. ) {
  56764. data.material = material; data.materialVersion = material.version;
  56765. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  56766. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  56767. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  56768. data.colorWrite = material.colorWrite;
  56769. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  56770. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  56771. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  56772. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  56773. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  56774. data.sampleCount = sampleCount;
  56775. data.colorSpace = colorSpace;
  56776. data.colorFormat = colorFormat;
  56777. data.depthStencilFormat = depthStencilFormat;
  56778. data.primitiveTopology = primitiveTopology;
  56779. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  56780. needsUpdate = true;
  56781. }
  56782. return needsUpdate;
  56783. }
  56784. /**
  56785. * Returns a cache key that is used to identify render pipelines.
  56786. *
  56787. * @param {RenderObject} renderObject - The render object.
  56788. * @return {string} The cache key.
  56789. */
  56790. getRenderCacheKey( renderObject ) {
  56791. const { object, material } = renderObject;
  56792. const utils = this.utils;
  56793. const renderContext = renderObject.context;
  56794. // meshes with negative scale have a different frontFace render pipeline
  56795. // descriptor value so the following must be honored in the cache key
  56796. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  56797. return [
  56798. material.transparent, material.blending, material.premultipliedAlpha,
  56799. material.blendSrc, material.blendDst, material.blendEquation,
  56800. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  56801. material.colorWrite,
  56802. material.depthWrite, material.depthTest, material.depthFunc,
  56803. material.stencilWrite, material.stencilFunc,
  56804. material.stencilFail, material.stencilZFail, material.stencilZPass,
  56805. material.stencilFuncMask, material.stencilWriteMask,
  56806. material.side,
  56807. frontFaceCW,
  56808. utils.getSampleCountRenderContext( renderContext ),
  56809. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  56810. utils.getPrimitiveTopology( object, material ),
  56811. renderObject.getGeometryCacheKey(),
  56812. renderObject.clippingContextCacheKey
  56813. ].join();
  56814. }
  56815. // textures
  56816. /**
  56817. * Updates a GPU sampler for the given texture.
  56818. *
  56819. * @param {Texture} texture - The texture to update the sampler for.
  56820. * @return {string} The current sampler key.
  56821. */
  56822. updateSampler( texture ) {
  56823. return this.textureUtils.updateSampler( texture );
  56824. }
  56825. /**
  56826. * Creates a default texture for the given texture that can be used
  56827. * as a placeholder until the actual texture is ready for usage.
  56828. *
  56829. * @param {Texture} texture - The texture to create a default texture for.
  56830. * @return {boolean} Whether the sampler has been updated or not.
  56831. */
  56832. createDefaultTexture( texture ) {
  56833. return this.textureUtils.createDefaultTexture( texture );
  56834. }
  56835. /**
  56836. * Defines a texture on the GPU for the given texture object.
  56837. *
  56838. * @param {Texture} texture - The texture.
  56839. * @param {Object} [options={}] - Optional configuration parameter.
  56840. */
  56841. createTexture( texture, options ) {
  56842. this.textureUtils.createTexture( texture, options );
  56843. }
  56844. /**
  56845. * Uploads the updated texture data to the GPU.
  56846. *
  56847. * @param {Texture} texture - The texture.
  56848. * @param {Object} [options={}] - Optional configuration parameter.
  56849. */
  56850. updateTexture( texture, options ) {
  56851. this.textureUtils.updateTexture( texture, options );
  56852. }
  56853. /**
  56854. * Generates mipmaps for the given texture.
  56855. *
  56856. * @param {Texture} texture - The texture.
  56857. */
  56858. generateMipmaps( texture ) {
  56859. this.textureUtils.generateMipmaps( texture );
  56860. }
  56861. /**
  56862. * Destroys the GPU data for the given texture object.
  56863. *
  56864. * @param {Texture} texture - The texture.
  56865. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  56866. */
  56867. destroyTexture( texture, isDefaultTexture = false ) {
  56868. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  56869. }
  56870. /**
  56871. * Returns texture data as a typed array.
  56872. *
  56873. * @async
  56874. * @param {Texture} texture - The texture to copy.
  56875. * @param {number} x - The x coordinate of the copy origin.
  56876. * @param {number} y - The y coordinate of the copy origin.
  56877. * @param {number} width - The width of the copy.
  56878. * @param {number} height - The height of the copy.
  56879. * @param {number} faceIndex - The face index.
  56880. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  56881. */
  56882. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  56883. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  56884. }
  56885. /**
  56886. * Inits a time stamp query for the given render context.
  56887. *
  56888. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  56889. * @param {number} uid - Unique id for the context (e.g. render context id).
  56890. * @param {Object} descriptor - The query descriptor.
  56891. */
  56892. initTimestampQuery( type, uid, descriptor ) {
  56893. if ( ! this.trackTimestamp ) return;
  56894. if ( ! this.timestampQueryPool[ type ] ) {
  56895. // TODO: Variable maxQueries?
  56896. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  56897. }
  56898. const timestampQueryPool = this.timestampQueryPool[ type ];
  56899. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  56900. descriptor.timestampWrites = {
  56901. querySet: timestampQueryPool.querySet,
  56902. beginningOfPassWriteIndex: baseOffset,
  56903. endOfPassWriteIndex: baseOffset + 1,
  56904. };
  56905. }
  56906. // node builder
  56907. /**
  56908. * Returns a node builder for the given render object.
  56909. *
  56910. * @param {RenderObject} object - The render object.
  56911. * @param {Renderer} renderer - The renderer.
  56912. * @return {WGSLNodeBuilder} The node builder.
  56913. */
  56914. createNodeBuilder( object, renderer ) {
  56915. return new WGSLNodeBuilder( object, renderer );
  56916. }
  56917. // program
  56918. /**
  56919. * Creates a shader program from the given programmable stage.
  56920. *
  56921. * @param {ProgrammableStage} program - The programmable stage.
  56922. */
  56923. createProgram( program ) {
  56924. const programGPU = this.get( program );
  56925. programGPU.module = {
  56926. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  56927. entryPoint: 'main'
  56928. };
  56929. }
  56930. /**
  56931. * Destroys the shader program of the given programmable stage.
  56932. *
  56933. * @param {ProgrammableStage} program - The programmable stage.
  56934. */
  56935. destroyProgram( program ) {
  56936. this.delete( program );
  56937. }
  56938. // pipelines
  56939. /**
  56940. * Creates a render pipeline for the given render object.
  56941. *
  56942. * @param {RenderObject} renderObject - The render object.
  56943. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  56944. */
  56945. createRenderPipeline( renderObject, promises ) {
  56946. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  56947. }
  56948. /**
  56949. * Creates a compute pipeline for the given compute node.
  56950. *
  56951. * @param {ComputePipeline} computePipeline - The compute pipeline.
  56952. * @param {Array<BindGroup>} bindings - The bindings.
  56953. */
  56954. createComputePipeline( computePipeline, bindings ) {
  56955. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  56956. }
  56957. /**
  56958. * Prepares the state for encoding render bundles.
  56959. *
  56960. * @param {RenderContext} renderContext - The render context.
  56961. */
  56962. beginBundle( renderContext ) {
  56963. const renderContextData = this.get( renderContext );
  56964. renderContextData._currentPass = renderContextData.currentPass;
  56965. renderContextData._currentSets = renderContextData.currentSets;
  56966. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  56967. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  56968. }
  56969. /**
  56970. * After processing render bundles this method finalizes related work.
  56971. *
  56972. * @param {RenderContext} renderContext - The render context.
  56973. * @param {RenderBundle} bundle - The render bundle.
  56974. */
  56975. finishBundle( renderContext, bundle ) {
  56976. const renderContextData = this.get( renderContext );
  56977. const bundleEncoder = renderContextData.currentPass;
  56978. const bundleGPU = bundleEncoder.finish();
  56979. this.get( bundle ).bundleGPU = bundleGPU;
  56980. // restore render pass state
  56981. renderContextData.currentSets = renderContextData._currentSets;
  56982. renderContextData.currentPass = renderContextData._currentPass;
  56983. }
  56984. /**
  56985. * Adds a render bundle to the render context data.
  56986. *
  56987. * @param {RenderContext} renderContext - The render context.
  56988. * @param {RenderBundle} bundle - The render bundle to add.
  56989. */
  56990. addBundle( renderContext, bundle ) {
  56991. const renderContextData = this.get( renderContext );
  56992. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  56993. }
  56994. // bindings
  56995. /**
  56996. * Creates bindings from the given bind group definition.
  56997. *
  56998. * @param {BindGroup} bindGroup - The bind group.
  56999. * @param {Array<BindGroup>} bindings - Array of bind groups.
  57000. * @param {number} cacheIndex - The cache index.
  57001. * @param {number} version - The version.
  57002. */
  57003. createBindings( bindGroup, bindings, cacheIndex, version ) {
  57004. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  57005. }
  57006. /**
  57007. * Updates the given bind group definition.
  57008. *
  57009. * @param {BindGroup} bindGroup - The bind group.
  57010. * @param {Array<BindGroup>} bindings - Array of bind groups.
  57011. * @param {number} cacheIndex - The cache index.
  57012. * @param {number} version - The version.
  57013. */
  57014. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  57015. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  57016. }
  57017. /**
  57018. * Updates a buffer binding.
  57019. *
  57020. * @param {Buffer} binding - The buffer binding to update.
  57021. */
  57022. updateBinding( binding ) {
  57023. this.bindingUtils.updateBinding( binding );
  57024. }
  57025. /**
  57026. * Delete data associated with the current bind group.
  57027. *
  57028. * @param {BindGroup} bindGroup - The bind group.
  57029. */
  57030. deleteBindGroupData( bindGroup ) {
  57031. this.bindingUtils.deleteBindGroupData( bindGroup );
  57032. }
  57033. // attributes
  57034. /**
  57035. * Creates the buffer of an indexed shader attribute.
  57036. *
  57037. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  57038. */
  57039. createIndexAttribute( attribute ) {
  57040. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  57041. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  57042. usage |= GPUBufferUsage.STORAGE;
  57043. }
  57044. this.attributeUtils.createAttribute( attribute, usage );
  57045. }
  57046. /**
  57047. * Creates the GPU buffer of a shader attribute.
  57048. *
  57049. * @param {BufferAttribute} attribute - The buffer attribute.
  57050. */
  57051. createAttribute( attribute ) {
  57052. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57053. }
  57054. /**
  57055. * Creates the GPU buffer of a storage attribute.
  57056. *
  57057. * @param {BufferAttribute} attribute - The buffer attribute.
  57058. */
  57059. createStorageAttribute( attribute ) {
  57060. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57061. }
  57062. /**
  57063. * Creates the GPU buffer of an indirect storage attribute.
  57064. *
  57065. * @param {BufferAttribute} attribute - The buffer attribute.
  57066. */
  57067. createIndirectStorageAttribute( attribute ) {
  57068. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  57069. }
  57070. /**
  57071. * Updates the GPU buffer of a shader attribute.
  57072. *
  57073. * @param {BufferAttribute} attribute - The buffer attribute to update.
  57074. */
  57075. updateAttribute( attribute ) {
  57076. this.attributeUtils.updateAttribute( attribute );
  57077. }
  57078. /**
  57079. * Destroys the GPU buffer of a shader attribute.
  57080. *
  57081. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  57082. */
  57083. destroyAttribute( attribute ) {
  57084. this.attributeUtils.destroyAttribute( attribute );
  57085. }
  57086. // canvas
  57087. /**
  57088. * Triggers an update of the default render pass descriptor.
  57089. */
  57090. updateSize() {
  57091. this.delete( this.renderer.getCanvasTarget() );
  57092. }
  57093. // utils public
  57094. /**
  57095. * Returns the maximum anisotropy texture filtering value.
  57096. *
  57097. * @return {number} The maximum anisotropy texture filtering value.
  57098. */
  57099. getMaxAnisotropy() {
  57100. return 16;
  57101. }
  57102. /**
  57103. * Checks if the given feature is supported by the backend.
  57104. *
  57105. * @param {string} name - The feature's name.
  57106. * @return {boolean} Whether the feature is supported or not.
  57107. */
  57108. hasFeature( name ) {
  57109. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  57110. return this.device.features.has( name );
  57111. }
  57112. /**
  57113. * Copies data of the given source texture to the given destination texture.
  57114. *
  57115. * @param {Texture} srcTexture - The source texture.
  57116. * @param {Texture} dstTexture - The destination texture.
  57117. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  57118. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  57119. * @param {number} [srcLevel=0] - The mipmap level to copy.
  57120. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  57121. */
  57122. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  57123. let dstX = 0;
  57124. let dstY = 0;
  57125. let dstZ = 0;
  57126. let srcX = 0;
  57127. let srcY = 0;
  57128. let srcZ = 0;
  57129. let srcWidth = srcTexture.image.width;
  57130. let srcHeight = srcTexture.image.height;
  57131. let srcDepth = 1;
  57132. if ( srcRegion !== null ) {
  57133. if ( srcRegion.isBox3 === true ) {
  57134. srcX = srcRegion.min.x;
  57135. srcY = srcRegion.min.y;
  57136. srcZ = srcRegion.min.z;
  57137. srcWidth = srcRegion.max.x - srcRegion.min.x;
  57138. srcHeight = srcRegion.max.y - srcRegion.min.y;
  57139. srcDepth = srcRegion.max.z - srcRegion.min.z;
  57140. } else {
  57141. // Assume it's a Box2
  57142. srcX = srcRegion.min.x;
  57143. srcY = srcRegion.min.y;
  57144. srcWidth = srcRegion.max.x - srcRegion.min.x;
  57145. srcHeight = srcRegion.max.y - srcRegion.min.y;
  57146. srcDepth = 1;
  57147. }
  57148. }
  57149. if ( dstPosition !== null ) {
  57150. dstX = dstPosition.x;
  57151. dstY = dstPosition.y;
  57152. dstZ = dstPosition.z || 0;
  57153. }
  57154. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  57155. const sourceGPU = this.get( srcTexture ).texture;
  57156. const destinationGPU = this.get( dstTexture ).texture;
  57157. encoder.copyTextureToTexture(
  57158. {
  57159. texture: sourceGPU,
  57160. mipLevel: srcLevel,
  57161. origin: { x: srcX, y: srcY, z: srcZ }
  57162. },
  57163. {
  57164. texture: destinationGPU,
  57165. mipLevel: dstLevel,
  57166. origin: { x: dstX, y: dstY, z: dstZ }
  57167. },
  57168. [
  57169. srcWidth,
  57170. srcHeight,
  57171. srcDepth
  57172. ]
  57173. );
  57174. this.device.queue.submit( [ encoder.finish() ] );
  57175. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  57176. this.textureUtils.generateMipmaps( dstTexture );
  57177. }
  57178. }
  57179. /**
  57180. * Copies the current bound framebuffer to the given texture.
  57181. *
  57182. * @param {Texture} texture - The destination texture.
  57183. * @param {RenderContext} renderContext - The render context.
  57184. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  57185. */
  57186. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  57187. const renderContextData = this.get( renderContext );
  57188. let sourceGPU = null;
  57189. if ( renderContext.renderTarget ) {
  57190. if ( texture.isDepthTexture ) {
  57191. sourceGPU = this.get( renderContext.depthTexture ).texture;
  57192. } else {
  57193. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  57194. }
  57195. } else {
  57196. if ( texture.isDepthTexture ) {
  57197. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  57198. } else {
  57199. sourceGPU = this.context.getCurrentTexture();
  57200. }
  57201. }
  57202. const destinationGPU = this.get( texture ).texture;
  57203. if ( sourceGPU.format !== destinationGPU.format ) {
  57204. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  57205. return;
  57206. }
  57207. let encoder;
  57208. if ( renderContextData.currentPass ) {
  57209. renderContextData.currentPass.end();
  57210. encoder = renderContextData.encoder;
  57211. } else {
  57212. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  57213. }
  57214. encoder.copyTextureToTexture(
  57215. {
  57216. texture: sourceGPU,
  57217. origin: [ rectangle.x, rectangle.y, 0 ],
  57218. },
  57219. {
  57220. texture: destinationGPU
  57221. },
  57222. [
  57223. rectangle.z,
  57224. rectangle.w
  57225. ]
  57226. );
  57227. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  57228. // might be out-of-sync, see #31768
  57229. if ( texture.generateMipmaps ) {
  57230. this.textureUtils.generateMipmaps( texture, encoder );
  57231. }
  57232. if ( renderContextData.currentPass ) {
  57233. const { descriptor } = renderContextData;
  57234. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  57235. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  57236. }
  57237. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  57238. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  57239. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  57240. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  57241. if ( renderContext.viewport ) {
  57242. this.updateViewport( renderContext );
  57243. }
  57244. if ( renderContext.scissor ) {
  57245. this.updateScissor( renderContext );
  57246. }
  57247. } else {
  57248. this.device.queue.submit( [ encoder.finish() ] );
  57249. }
  57250. }
  57251. /**
  57252. * Checks if the given compatibility is supported by the backend.
  57253. *
  57254. * @param {string} name - The compatibility name.
  57255. * @return {boolean} Whether the compatibility is supported or not.
  57256. */
  57257. hasCompatibility( name ) {
  57258. if ( this._compatibility[ Compatibility.TEXTURE_COMPARE ] !== undefined ) {
  57259. return this._compatibility[ Compatibility.TEXTURE_COMPARE ];
  57260. }
  57261. return super.hasCompatibility( name );
  57262. }
  57263. dispose() {
  57264. this.bindingUtils.dispose();
  57265. this.textureUtils.dispose();
  57266. if ( this.occludedResolveCache ) {
  57267. for ( const buffer of this.occludedResolveCache.values() ) {
  57268. buffer.destroy();
  57269. }
  57270. this.occludedResolveCache.clear();
  57271. }
  57272. if ( this.timestampQueryPool ) {
  57273. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  57274. if ( queryPool !== null ) queryPool.dispose();
  57275. }
  57276. }
  57277. if ( this.parameters.device === undefined && this.device !== null ) {
  57278. this.device.destroy();
  57279. }
  57280. }
  57281. }
  57282. /**
  57283. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57284. *
  57285. * @augments SpotLight
  57286. */
  57287. class IESSpotLight extends SpotLight {
  57288. /**
  57289. * Constructs a new IES spot light.
  57290. *
  57291. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57292. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57293. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57294. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57295. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57296. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57297. */
  57298. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57299. super( color, intensity, distance, angle, penumbra, decay );
  57300. /**
  57301. * TODO
  57302. *
  57303. * @type {?Texture}
  57304. * @default null
  57305. */
  57306. this.iesMap = null;
  57307. }
  57308. copy( source, recursive ) {
  57309. super.copy( source, recursive );
  57310. this.iesMap = source.iesMap;
  57311. return this;
  57312. }
  57313. }
  57314. /**
  57315. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  57316. *
  57317. * @augments SpotLight
  57318. */
  57319. class ProjectorLight extends SpotLight {
  57320. /**
  57321. * Constructs a new projector light.
  57322. *
  57323. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  57324. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  57325. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  57326. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  57327. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  57328. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  57329. */
  57330. constructor( color, intensity, distance, angle, penumbra, decay ) {
  57331. super( color, intensity, distance, angle, penumbra, decay );
  57332. /**
  57333. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  57334. *
  57335. * @type {?number}
  57336. * @default null
  57337. */
  57338. this.aspect = null;
  57339. }
  57340. copy( source, recursive ) {
  57341. super.copy( source, recursive );
  57342. this.aspect = source.aspect;
  57343. return this;
  57344. }
  57345. }
  57346. /**
  57347. * This version of a node library represents the standard version
  57348. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  57349. * techniques and materials to node-based implementations.
  57350. *
  57351. * @private
  57352. * @augments NodeLibrary
  57353. */
  57354. class StandardNodeLibrary extends NodeLibrary {
  57355. /**
  57356. * Constructs a new standard node library.
  57357. */
  57358. constructor() {
  57359. super();
  57360. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  57361. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  57362. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  57363. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  57364. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  57365. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  57366. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  57367. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  57368. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  57369. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  57370. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  57371. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  57372. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  57373. this.addLight( PointLightNode, PointLight );
  57374. this.addLight( DirectionalLightNode, DirectionalLight );
  57375. this.addLight( RectAreaLightNode, RectAreaLight );
  57376. this.addLight( SpotLightNode, SpotLight );
  57377. this.addLight( AmbientLightNode, AmbientLight );
  57378. this.addLight( HemisphereLightNode, HemisphereLight );
  57379. this.addLight( LightProbeNode, LightProbe );
  57380. this.addLight( IESSpotLightNode, IESSpotLight );
  57381. this.addLight( ProjectorLightNode, ProjectorLight );
  57382. this.addToneMapping( linearToneMapping, LinearToneMapping );
  57383. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  57384. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  57385. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  57386. this.addToneMapping( agxToneMapping, AgXToneMapping );
  57387. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  57388. }
  57389. }
  57390. /*
  57391. const debugHandler = {
  57392. get: function ( target, name ) {
  57393. // Add |update
  57394. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  57395. return target[ name ];
  57396. }
  57397. };
  57398. */
  57399. /**
  57400. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  57401. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  57402. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  57403. *
  57404. * @augments Renderer
  57405. */
  57406. class WebGPURenderer extends Renderer {
  57407. /**
  57408. * WebGPURenderer options.
  57409. *
  57410. * @typedef {Object} WebGPURenderer~Options
  57411. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  57412. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  57413. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  57414. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  57415. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  57416. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  57417. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  57418. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  57419. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  57420. * @property {number} [outputBufferType=HalfFloatType] - Defines the type of output buffers. The default `HalfFloatType` is recommend for best
  57421. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  57422. */
  57423. /**
  57424. * Constructs a new WebGPU renderer.
  57425. *
  57426. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  57427. */
  57428. constructor( parameters = {} ) {
  57429. let BackendClass;
  57430. if ( parameters.forceWebGL ) {
  57431. BackendClass = WebGLBackend;
  57432. } else {
  57433. BackendClass = WebGPUBackend;
  57434. parameters.getFallback = () => {
  57435. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  57436. return new WebGLBackend( parameters );
  57437. };
  57438. }
  57439. const backend = new BackendClass( parameters );
  57440. //super( new Proxy( backend, debugHandler ) );
  57441. super( backend, parameters );
  57442. /**
  57443. * The generic default value is overwritten with the
  57444. * standard node library for type mapping.
  57445. *
  57446. * @type {StandardNodeLibrary}
  57447. */
  57448. this.library = new StandardNodeLibrary();
  57449. /**
  57450. * This flag can be used for type testing.
  57451. *
  57452. * @type {boolean}
  57453. * @readonly
  57454. * @default true
  57455. */
  57456. this.isWebGPURenderer = true;
  57457. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  57458. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  57459. }
  57460. }
  57461. }
  57462. /**
  57463. * A specialized group which enables applications access to the
  57464. * Render Bundle API of WebGPU. The group with all its descendant nodes
  57465. * are considered as one render bundle and processed as such by
  57466. * the renderer.
  57467. *
  57468. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  57469. * With a WebGL backend, the group can technically be rendered but without
  57470. * any performance improvements.
  57471. *
  57472. * @augments Group
  57473. */
  57474. class BundleGroup extends Group {
  57475. /**
  57476. * Constructs a new bundle group.
  57477. */
  57478. constructor() {
  57479. super();
  57480. /**
  57481. * This flag can be used for type testing.
  57482. *
  57483. * @type {boolean}
  57484. * @readonly
  57485. * @default true
  57486. */
  57487. this.isBundleGroup = true;
  57488. /**
  57489. * This property is only relevant for detecting types
  57490. * during serialization/deserialization. It should always
  57491. * match the class name.
  57492. *
  57493. * @type {string}
  57494. * @readonly
  57495. * @default 'BundleGroup'
  57496. */
  57497. this.type = 'BundleGroup';
  57498. /**
  57499. * Whether the bundle is static or not. When set to `true`, the structure
  57500. * is assumed to be static and does not change. E.g. no new objects are
  57501. * added to the group.
  57502. *
  57503. * If a change is required, an update can still be forced by setting the
  57504. * `needsUpdate` flag to `true`.
  57505. *
  57506. * @type {boolean}
  57507. * @default true
  57508. */
  57509. this.static = true;
  57510. /**
  57511. * The bundle group's version.
  57512. *
  57513. * @type {number}
  57514. * @readonly
  57515. * @default 0
  57516. */
  57517. this.version = 0;
  57518. }
  57519. /**
  57520. * Set this property to `true` when the bundle group has changed.
  57521. *
  57522. * @type {boolean}
  57523. * @default false
  57524. * @param {boolean} value
  57525. */
  57526. set needsUpdate( value ) {
  57527. if ( value === true ) this.version ++;
  57528. }
  57529. }
  57530. /**
  57531. * This module is responsible to manage the rendering pipeline setups in apps.
  57532. * You usually create a single instance of this class and use it to define
  57533. * the output of your render pipeline and post processing effect chain.
  57534. * ```js
  57535. * const renderPipeline = new RenderPipeline( renderer );
  57536. *
  57537. * const scenePass = pass( scene, camera );
  57538. *
  57539. * renderPipeline.outputNode = scenePass;
  57540. * ```
  57541. *
  57542. * Note: This module can only be used with `WebGPURenderer`.
  57543. */
  57544. class RenderPipeline {
  57545. /**
  57546. * Constructs a new render pipeline management module.
  57547. *
  57548. * @param {Renderer} renderer - A reference to the renderer.
  57549. * @param {Node<vec4>} outputNode - An optional output node.
  57550. */
  57551. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  57552. /**
  57553. * A reference to the renderer.
  57554. *
  57555. * @type {Renderer}
  57556. */
  57557. this.renderer = renderer;
  57558. /**
  57559. * A node which defines the final output of the rendering
  57560. * pipeline. This is usually the last node in a chain
  57561. * of effect nodes.
  57562. *
  57563. * @type {Node<vec4>}
  57564. */
  57565. this.outputNode = outputNode;
  57566. /**
  57567. * Whether the default output tone mapping and color
  57568. * space transformation should be enabled or not.
  57569. *
  57570. * It is enabled by default by it must be disabled when
  57571. * effects must be executed after tone mapping and color
  57572. * space conversion. A typical example is FXAA which
  57573. * requires sRGB input.
  57574. *
  57575. * When set to `false`, the app must control the output
  57576. * transformation with `RenderOutputNode`.
  57577. *
  57578. * ```js
  57579. * const outputPass = renderOutput( scenePass );
  57580. * ```
  57581. *
  57582. * @type {boolean}
  57583. */
  57584. this.outputColorTransform = true;
  57585. /**
  57586. * Must be set to `true` when the output node changes.
  57587. *
  57588. * @type {Node<vec4>}
  57589. */
  57590. this.needsUpdate = true;
  57591. const material = new NodeMaterial();
  57592. material.name = 'RenderPipeline';
  57593. /**
  57594. * The full screen quad that is used to render
  57595. * the effects.
  57596. *
  57597. * @private
  57598. * @type {QuadMesh}
  57599. */
  57600. this._quadMesh = new QuadMesh( material );
  57601. this._quadMesh.name = 'Render Pipeline';
  57602. /**
  57603. * The context of the render pipeline stack.
  57604. *
  57605. * @private
  57606. * @type {?Object}
  57607. * @default null
  57608. */
  57609. this._context = null;
  57610. }
  57611. /**
  57612. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  57613. * the application must use this version of `render()` inside
  57614. * its animation loop (not the one from the renderer).
  57615. */
  57616. render() {
  57617. const renderer = this.renderer;
  57618. this._update();
  57619. if ( this._context.onBeforeRenderPipeline !== null ) this._context.onBeforeRenderPipeline();
  57620. const toneMapping = renderer.toneMapping;
  57621. const outputColorSpace = renderer.outputColorSpace;
  57622. renderer.toneMapping = NoToneMapping;
  57623. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  57624. //
  57625. const currentXR = renderer.xr.enabled;
  57626. renderer.xr.enabled = false;
  57627. this._quadMesh.render( renderer );
  57628. renderer.xr.enabled = currentXR;
  57629. //
  57630. renderer.toneMapping = toneMapping;
  57631. renderer.outputColorSpace = outputColorSpace;
  57632. if ( this._context.onAfterRenderPipeline !== null ) this._context.onAfterRenderPipeline();
  57633. }
  57634. /**
  57635. * Returns the current context of the render pipeline stack.
  57636. *
  57637. * @readonly
  57638. * @type {?Object}
  57639. */
  57640. get context() {
  57641. return this._context;
  57642. }
  57643. /**
  57644. * Frees internal resources.
  57645. */
  57646. dispose() {
  57647. this._quadMesh.material.dispose();
  57648. }
  57649. /**
  57650. * Updates the state of the module.
  57651. *
  57652. * @private
  57653. */
  57654. _update() {
  57655. if ( this.needsUpdate === true ) {
  57656. const renderer = this.renderer;
  57657. const toneMapping = renderer.toneMapping;
  57658. const outputColorSpace = renderer.outputColorSpace;
  57659. const context = {
  57660. renderPipeline: this,
  57661. onBeforeRenderPipeline: null,
  57662. onAfterRenderPipeline: null
  57663. };
  57664. let outputNode = this.outputNode;
  57665. if ( this.outputColorTransform === true ) {
  57666. outputNode = outputNode.context( context );
  57667. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  57668. } else {
  57669. context.toneMapping = toneMapping;
  57670. context.outputColorSpace = outputColorSpace;
  57671. outputNode = outputNode.context( context );
  57672. }
  57673. this._context = context;
  57674. this._quadMesh.material.fragmentNode = outputNode;
  57675. this._quadMesh.material.needsUpdate = true;
  57676. this.needsUpdate = false;
  57677. }
  57678. }
  57679. /**
  57680. * When `RenderPipeline` is used to apply rendering pipeline and post processing effects,
  57681. * the application must use this version of `renderAsync()` inside
  57682. * its animation loop (not the one from the renderer).
  57683. *
  57684. * @async
  57685. * @deprecated
  57686. * @return {Promise} A Promise that resolves when the render has been finished.
  57687. */
  57688. async renderAsync() {
  57689. warnOnce( 'RenderPipeline: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.' ); // @deprecated r181
  57690. await this.renderer.init();
  57691. this.render();
  57692. }
  57693. }
  57694. /**
  57695. * @deprecated since r183. Use {@link RenderPipeline} instead. PostProcessing has been renamed to RenderPipeline.
  57696. *
  57697. * This class is a wrapper for backward compatibility and will be removed in a future version.
  57698. */
  57699. class PostProcessing extends RenderPipeline {
  57700. /**
  57701. * Constructs a new post processing management module.
  57702. *
  57703. * @param {Renderer} renderer - A reference to the renderer.
  57704. * @param {Node<vec4>} outputNode - An optional output node.
  57705. * @deprecated since r183. Use {@link RenderPipeline} instead.
  57706. */
  57707. constructor( renderer, outputNode ) {
  57708. warnOnce( 'PostProcessing: "PostProcessing" has been renamed to "RenderPipeline". Please update your code to use "THREE.RenderPipeline" instead.' ); // @deprecated, r183
  57709. super( renderer, outputNode );
  57710. }
  57711. }
  57712. /**
  57713. * This special type of texture is intended for compute shaders.
  57714. * It can be used to compute the data of a texture with a compute shader.
  57715. *
  57716. * Note: This type of texture can only be used with `WebGPURenderer`
  57717. * and a WebGPU backend.
  57718. *
  57719. * @augments Texture
  57720. */
  57721. class StorageTexture extends Texture {
  57722. /**
  57723. * Constructs a new storage texture.
  57724. *
  57725. * @param {number} [width=1] - The storage texture's width.
  57726. * @param {number} [height=1] - The storage texture's height.
  57727. */
  57728. constructor( width = 1, height = 1 ) {
  57729. super();
  57730. /**
  57731. * The image object which just represents the texture's dimension.
  57732. *
  57733. * @type {{width: number, height: number}}
  57734. */
  57735. this.image = { width, height };
  57736. /**
  57737. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57738. *
  57739. * @type {number}
  57740. */
  57741. this.magFilter = LinearFilter;
  57742. /**
  57743. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57744. *
  57745. * @type {number}
  57746. */
  57747. this.minFilter = LinearFilter;
  57748. /**
  57749. * This flag can be used for type testing.
  57750. *
  57751. * @type {boolean}
  57752. * @readonly
  57753. * @default true
  57754. */
  57755. this.isStorageTexture = true;
  57756. /**
  57757. * When `true`, mipmaps will be auto-generated after compute writes.
  57758. * When `false`, mipmaps must be written manually via compute shaders.
  57759. *
  57760. * @type {boolean}
  57761. * @default true
  57762. */
  57763. this.mipmapsAutoUpdate = true;
  57764. }
  57765. /**
  57766. * Sets the size of the storage texture.
  57767. *
  57768. * @param {number} width - The new width of the storage texture.
  57769. * @param {number} height - The new height of the storage texture.
  57770. */
  57771. setSize( width, height ) {
  57772. if ( this.image.width !== width || this.image.height !== height ) {
  57773. this.image.width = width;
  57774. this.image.height = height;
  57775. this.dispose();
  57776. }
  57777. }
  57778. }
  57779. /**
  57780. * This special type of texture is intended for compute shaders.
  57781. * It can be used to compute the data of a texture with a compute shader.
  57782. *
  57783. * Note: This type of texture can only be used with `WebGPURenderer`
  57784. * and a WebGPU backend.
  57785. *
  57786. * @augments Texture
  57787. */
  57788. class Storage3DTexture extends Texture {
  57789. /**
  57790. * Constructs a new storage texture.
  57791. *
  57792. * @param {number} [width=1] - The storage texture's width.
  57793. * @param {number} [height=1] - The storage texture's height.
  57794. * @param {number} [depth=1] - The storage texture's depth.
  57795. */
  57796. constructor( width = 1, height = 1, depth = 1 ) {
  57797. super();
  57798. //inherited from texture. Must be false for 3DTexture
  57799. this.isArrayTexture = false;
  57800. /**
  57801. * The image object which just represents the texture's dimension.
  57802. *
  57803. * @type {{width: number, height: number, depth: number}}
  57804. */
  57805. this.image = { width, height, depth };
  57806. /**
  57807. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57808. *
  57809. * @type {number}
  57810. */
  57811. this.magFilter = LinearFilter;
  57812. /**
  57813. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57814. *
  57815. * @type {number}
  57816. */
  57817. this.minFilter = LinearFilter;
  57818. /**
  57819. * This defines how the texture is wrapped in the depth direction and corresponds to
  57820. * *W* in UVW mapping.
  57821. *
  57822. * @type {number}
  57823. */
  57824. this.wrapR = ClampToEdgeWrapping;
  57825. /**
  57826. * This flag can be used for type testing.
  57827. *
  57828. * @type {boolean}
  57829. * @readonly
  57830. * @default true
  57831. */
  57832. this.isStorageTexture = true;
  57833. /**
  57834. * Indicates whether this texture is a 3D texture.
  57835. *
  57836. * @type {boolean}
  57837. *
  57838. */
  57839. this.is3DTexture = true;
  57840. }
  57841. /**
  57842. * Sets the size of the storage 3d texture.
  57843. *
  57844. * @param {number} width - The new width of the storage texture.
  57845. * @param {number} height - The new height of the storage texture.
  57846. * @param {number} depth - The new depth of the storage texture.
  57847. */
  57848. setSize( width, height, depth ) {
  57849. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57850. this.image.width = width;
  57851. this.image.height = height;
  57852. this.image.depth = depth;
  57853. this.dispose();
  57854. }
  57855. }
  57856. }
  57857. /**
  57858. * This special type of texture is intended for compute shaders.
  57859. * It can be used to compute the data of a texture with a compute shader.
  57860. *
  57861. * Note: This type of texture can only be used with `WebGPURenderer`
  57862. * and a WebGPU backend.
  57863. *
  57864. * @augments Texture
  57865. */
  57866. class StorageArrayTexture extends Texture {
  57867. /**
  57868. * Constructs a new storage texture.
  57869. *
  57870. * @param {number} [width=1] - The storage texture's width.
  57871. * @param {number} [height=1] - The storage texture's height.
  57872. * @param {number} [depth=1] - The storage texture's depth.
  57873. */
  57874. constructor( width = 1, height = 1, depth = 1 ) {
  57875. super();
  57876. //inherited from texture
  57877. this.isArrayTexture = true;
  57878. /**
  57879. * The image object which just represents the texture's dimension.
  57880. *
  57881. * @type {{width: number, height: number, depth: number}}
  57882. */
  57883. this.image = { width, height, depth };
  57884. /**
  57885. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  57886. *
  57887. * @type {number}
  57888. */
  57889. this.magFilter = LinearFilter;
  57890. /**
  57891. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  57892. *
  57893. * @type {number}
  57894. */
  57895. this.minFilter = LinearFilter;
  57896. /**
  57897. * This flag can be used for type testing.
  57898. *
  57899. * @type {boolean}
  57900. * @readonly
  57901. * @default true
  57902. */
  57903. this.isStorageTexture = true;
  57904. }
  57905. /**
  57906. * Sets the size of the storage array texture.
  57907. *
  57908. * @param {number} width - The new width of the storage texture.
  57909. * @param {number} height - The new height of the storage texture.
  57910. * @param {number} depth - The new depth of the storage texture.
  57911. */
  57912. setSize( width, height, depth ) {
  57913. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  57914. this.image.width = width;
  57915. this.image.height = height;
  57916. this.image.depth = depth;
  57917. this.dispose();
  57918. }
  57919. }
  57920. }
  57921. /**
  57922. * This special type of buffer attribute is intended for compute shaders.
  57923. * It can be used to encode draw parameters for indirect draw calls.
  57924. *
  57925. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  57926. * and a WebGPU backend.
  57927. *
  57928. * @augments StorageBufferAttribute
  57929. */
  57930. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  57931. /**
  57932. * Constructs a new storage buffer attribute.
  57933. *
  57934. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  57935. * The subsequent parameter is then obsolete.
  57936. * @param {number} itemSize - The item size.
  57937. */
  57938. constructor( count, itemSize ) {
  57939. super( count, itemSize, Uint32Array );
  57940. /**
  57941. * This flag can be used for type testing.
  57942. *
  57943. * @type {boolean}
  57944. * @readonly
  57945. * @default true
  57946. */
  57947. this.isIndirectStorageBufferAttribute = true;
  57948. }
  57949. }
  57950. /**
  57951. * A loader for loading node objects in the three.js JSON Object/Scene format.
  57952. *
  57953. * @augments Loader
  57954. */
  57955. class NodeLoader extends Loader {
  57956. /**
  57957. * Constructs a new node loader.
  57958. *
  57959. * @param {LoadingManager} [manager] - A reference to a loading manager.
  57960. */
  57961. constructor( manager ) {
  57962. super( manager );
  57963. /**
  57964. * Represents a dictionary of textures.
  57965. *
  57966. * @type {Object<string,Texture>}
  57967. */
  57968. this.textures = {};
  57969. /**
  57970. * Represents a dictionary of node types.
  57971. *
  57972. * @type {Object<string,Node.constructor>}
  57973. */
  57974. this.nodes = {};
  57975. }
  57976. /**
  57977. * Loads the node definitions from the given URL.
  57978. *
  57979. * @param {string} url - The path/URL of the file to be loaded.
  57980. * @param {Function} onLoad - Will be called when load completes.
  57981. * @param {Function} onProgress - Will be called while load progresses.
  57982. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  57983. */
  57984. load( url, onLoad, onProgress, onError ) {
  57985. const loader = new FileLoader( this.manager );
  57986. loader.setPath( this.path );
  57987. loader.setRequestHeader( this.requestHeader );
  57988. loader.setWithCredentials( this.withCredentials );
  57989. loader.load( url, ( text ) => {
  57990. try {
  57991. onLoad( this.parse( JSON.parse( text ) ) );
  57992. } catch ( e ) {
  57993. if ( onError ) {
  57994. onError( e );
  57995. } else {
  57996. error( e );
  57997. }
  57998. this.manager.itemError( url );
  57999. }
  58000. }, onProgress, onError );
  58001. }
  58002. /**
  58003. * Parse the node dependencies for the loaded node.
  58004. *
  58005. * @param {Array<Object>} [json] - The JSON definition
  58006. * @return {Object<string,Node>} A dictionary with node dependencies.
  58007. */
  58008. parseNodes( json ) {
  58009. const nodes = {};
  58010. if ( json !== undefined ) {
  58011. for ( const nodeJSON of json ) {
  58012. const { uuid, type } = nodeJSON;
  58013. nodes[ uuid ] = this.createNodeFromType( type );
  58014. nodes[ uuid ].uuid = uuid;
  58015. }
  58016. const meta = { nodes, textures: this.textures };
  58017. for ( const nodeJSON of json ) {
  58018. nodeJSON.meta = meta;
  58019. const node = nodes[ nodeJSON.uuid ];
  58020. node.deserialize( nodeJSON );
  58021. delete nodeJSON.meta;
  58022. }
  58023. }
  58024. return nodes;
  58025. }
  58026. /**
  58027. * Parses the node from the given JSON.
  58028. *
  58029. * @param {Object} json - The JSON definition
  58030. * @param {string} json.type - The node type.
  58031. * @param {string} json.uuid - The node UUID.
  58032. * @param {Array<Object>} [json.nodes] - The node dependencies.
  58033. * @param {Object} [json.meta] - The meta data.
  58034. * @return {Node} The parsed node.
  58035. */
  58036. parse( json ) {
  58037. const node = this.createNodeFromType( json.type );
  58038. node.uuid = json.uuid;
  58039. const nodes = this.parseNodes( json.nodes );
  58040. const meta = { nodes, textures: this.textures };
  58041. json.meta = meta;
  58042. node.deserialize( json );
  58043. delete json.meta;
  58044. return node;
  58045. }
  58046. /**
  58047. * Defines the dictionary of textures.
  58048. *
  58049. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  58050. * @return {NodeLoader} A reference to this loader.
  58051. */
  58052. setTextures( value ) {
  58053. this.textures = value;
  58054. return this;
  58055. }
  58056. /**
  58057. * Defines the dictionary of node types.
  58058. *
  58059. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58060. * @return {NodeLoader} A reference to this loader.
  58061. */
  58062. setNodes( value ) {
  58063. this.nodes = value;
  58064. return this;
  58065. }
  58066. /**
  58067. * Creates a node object from the given type.
  58068. *
  58069. * @param {string} type - The node type.
  58070. * @return {Node} The created node instance.
  58071. */
  58072. createNodeFromType( type ) {
  58073. if ( this.nodes[ type ] === undefined ) {
  58074. error( 'NodeLoader: Node type not found:', type );
  58075. return float();
  58076. }
  58077. return new this.nodes[ type ]();
  58078. }
  58079. }
  58080. /**
  58081. * A special type of material loader for loading node materials.
  58082. *
  58083. * @augments MaterialLoader
  58084. */
  58085. class NodeMaterialLoader extends MaterialLoader {
  58086. /**
  58087. * Constructs a new node material loader.
  58088. *
  58089. * @param {LoadingManager} [manager] - A reference to a loading manager.
  58090. */
  58091. constructor( manager ) {
  58092. super( manager );
  58093. /**
  58094. * Represents a dictionary of node types.
  58095. *
  58096. * @type {Object<string,Node.constructor>}
  58097. */
  58098. this.nodes = {};
  58099. /**
  58100. * Represents a dictionary of node material types.
  58101. *
  58102. * @type {Object<string,NodeMaterial.constructor>}
  58103. */
  58104. this.nodeMaterials = {};
  58105. }
  58106. /**
  58107. * Parses the node material from the given JSON.
  58108. *
  58109. * @param {Object} json - The JSON definition
  58110. * @return {NodeMaterial}. The parsed material.
  58111. */
  58112. parse( json ) {
  58113. const material = super.parse( json );
  58114. const nodes = this.nodes;
  58115. const inputNodes = json.inputNodes;
  58116. for ( const property in inputNodes ) {
  58117. const uuid = inputNodes[ property ];
  58118. material[ property ] = nodes[ uuid ];
  58119. }
  58120. return material;
  58121. }
  58122. /**
  58123. * Defines the dictionary of node types.
  58124. *
  58125. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58126. * @return {NodeLoader} A reference to this loader.
  58127. */
  58128. setNodes( value ) {
  58129. this.nodes = value;
  58130. return this;
  58131. }
  58132. /**
  58133. * Defines the dictionary of node material types.
  58134. *
  58135. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  58136. * @return {NodeLoader} A reference to this loader.
  58137. */
  58138. setNodeMaterials( value ) {
  58139. this.nodeMaterials = value;
  58140. return this;
  58141. }
  58142. /**
  58143. * Creates a node material from the given type.
  58144. *
  58145. * @param {string} type - The node material type.
  58146. * @return {Node} The created node material instance.
  58147. */
  58148. createMaterialFromType( type ) {
  58149. const materialClass = this.nodeMaterials[ type ];
  58150. if ( materialClass !== undefined ) {
  58151. return new materialClass();
  58152. }
  58153. return super.createMaterialFromType( type );
  58154. }
  58155. }
  58156. /**
  58157. * A special type of object loader for loading 3D objects using
  58158. * node materials.
  58159. *
  58160. * @augments ObjectLoader
  58161. */
  58162. class NodeObjectLoader extends ObjectLoader {
  58163. /**
  58164. * Constructs a new node object loader.
  58165. *
  58166. * @param {LoadingManager} [manager] - A reference to a loading manager.
  58167. */
  58168. constructor( manager ) {
  58169. super( manager );
  58170. /**
  58171. * Represents a dictionary of node types.
  58172. *
  58173. * @type {Object<string,Node.constructor>}
  58174. */
  58175. this.nodes = {};
  58176. /**
  58177. * Represents a dictionary of node material types.
  58178. *
  58179. * @type {Object<string,NodeMaterial.constructor>}
  58180. */
  58181. this.nodeMaterials = {};
  58182. /**
  58183. * A reference to hold the `nodes` JSON property.
  58184. *
  58185. * @private
  58186. * @type {?Object[]}
  58187. */
  58188. this._nodesJSON = null;
  58189. }
  58190. /**
  58191. * Defines the dictionary of node types.
  58192. *
  58193. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  58194. * @return {NodeObjectLoader} A reference to this loader.
  58195. */
  58196. setNodes( value ) {
  58197. this.nodes = value;
  58198. return this;
  58199. }
  58200. /**
  58201. * Defines the dictionary of node material types.
  58202. *
  58203. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  58204. * @return {NodeObjectLoader} A reference to this loader.
  58205. */
  58206. setNodeMaterials( value ) {
  58207. this.nodeMaterials = value;
  58208. return this;
  58209. }
  58210. /**
  58211. * Parses the node objects from the given JSON.
  58212. *
  58213. * @param {Object} json - The JSON definition
  58214. * @param {Function} onLoad - The onLoad callback function.
  58215. * @return {Object3D}. The parsed 3D object.
  58216. */
  58217. parse( json, onLoad ) {
  58218. this._nodesJSON = json.nodes;
  58219. const data = super.parse( json, onLoad );
  58220. this._nodesJSON = null; // dispose
  58221. return data;
  58222. }
  58223. /**
  58224. * Parses the node objects from the given JSON and textures.
  58225. *
  58226. * @param {Object[]} json - The JSON definition
  58227. * @param {Object<string,Texture>} textures - The texture library.
  58228. * @return {Object<string,Node>}. The parsed nodes.
  58229. */
  58230. parseNodes( json, textures ) {
  58231. if ( json !== undefined ) {
  58232. const loader = new NodeLoader();
  58233. loader.setNodes( this.nodes );
  58234. loader.setTextures( textures );
  58235. return loader.parseNodes( json );
  58236. }
  58237. return {};
  58238. }
  58239. /**
  58240. * Parses the node objects from the given JSON and textures.
  58241. *
  58242. * @param {Object} json - The JSON definition
  58243. * @param {Object<string,Texture>} textures - The texture library.
  58244. * @return {Object<string,NodeMaterial>}. The parsed materials.
  58245. */
  58246. parseMaterials( json, textures ) {
  58247. const materials = {};
  58248. if ( json !== undefined ) {
  58249. const nodes = this.parseNodes( this._nodesJSON, textures );
  58250. const loader = new NodeMaterialLoader();
  58251. loader.setTextures( textures );
  58252. loader.setNodes( nodes );
  58253. loader.setNodeMaterials( this.nodeMaterials );
  58254. for ( let i = 0, l = json.length; i < l; i ++ ) {
  58255. const data = json[ i ];
  58256. materials[ data.uuid ] = loader.parse( data );
  58257. }
  58258. }
  58259. return materials;
  58260. }
  58261. }
  58262. /**
  58263. * In earlier three.js versions, clipping was defined globally
  58264. * on the renderer or on material level. This special version of
  58265. * `THREE.Group` allows to encode the clipping state into the scene
  58266. * graph. Meaning if you create an instance of this group, all
  58267. * descendant 3D objects will be affected by the respective clipping
  58268. * planes.
  58269. *
  58270. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  58271. *
  58272. * @augments Group
  58273. */
  58274. class ClippingGroup extends Group {
  58275. /**
  58276. * Constructs a new clipping group.
  58277. */
  58278. constructor() {
  58279. super();
  58280. /**
  58281. * This flag can be used for type testing.
  58282. *
  58283. * @type {boolean}
  58284. * @readonly
  58285. * @default true
  58286. */
  58287. this.isClippingGroup = true;
  58288. /**
  58289. * An array with clipping planes.
  58290. *
  58291. * @type {Array<Plane>}
  58292. */
  58293. this.clippingPlanes = [];
  58294. /**
  58295. * Whether clipping should be enabled or not.
  58296. *
  58297. * @type {boolean}
  58298. * @default true
  58299. */
  58300. this.enabled = true;
  58301. /**
  58302. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  58303. *
  58304. * @type {boolean}
  58305. * @default false
  58306. */
  58307. this.clipIntersection = false;
  58308. /**
  58309. * Whether shadows should be clipped or not.
  58310. *
  58311. * @type {boolean}
  58312. * @default false
  58313. */
  58314. this.clipShadows = false;
  58315. }
  58316. }
  58317. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AtomicFunctionNode, AttributeNode, BackSide, BarrierNode, BasicEnvironmentNode, BasicLightMapNode, BasicShadowMap, BatchNode, BitcastNode, BitcountNode, BlendMode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BuiltinNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CanvasTarget, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, ClippingNode, CodeNode, Color, ColorManagement, ColorSpaceNode, Compatibility, ComputeBuiltinNode, ComputeNode, ConditionalNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeDepthTexture, CubeMapNode, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, FlipNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InputNode, InspectorBase, InspectorNode, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, IsolateNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialBlending, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalGAPacking, NormalMapNode, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OutputStructNode, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, PMREMNode, PackFloatNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointShadowNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, R11_EAC_Format, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, 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, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceBaseNode, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderPipeline, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, SampleNode, Scene, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubgroupFunctionNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnpackFloatNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VelocityNode, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, WorkgroupInfoNode, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号