three.webgpu.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '168dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap$1 = 0;
  14. const PCFShadowMap$1 = 1;
  15. const PCFSoftShadowMap$1 = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const DisplayP3ColorSpace = 'display-p3';
  168. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  169. const LinearTransfer = 'linear';
  170. const SRGBTransfer = 'srgb';
  171. const Rec709Primaries = 'rec709';
  172. const P3Primaries = 'p3';
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const NeverCompare = 512;
  190. const LessCompare = 513;
  191. const EqualCompare = 514;
  192. const LessEqualCompare = 515;
  193. const GreaterCompare = 516;
  194. const NotEqualCompare = 517;
  195. const GreaterEqualCompare = 518;
  196. const AlwaysCompare = 519;
  197. const StaticDrawUsage = 35044;
  198. const DynamicDrawUsage = 35048;
  199. const StreamDrawUsage = 35040;
  200. const StaticReadUsage = 35045;
  201. const DynamicReadUsage = 35049;
  202. const StreamReadUsage = 35041;
  203. const StaticCopyUsage = 35046;
  204. const DynamicCopyUsage = 35050;
  205. const StreamCopyUsage = 35042;
  206. const GLSL1 = '100';
  207. const GLSL3 = '300 es';
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp$1( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep$1( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize$1( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp$1,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep$1,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize$1,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp$1( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32$1( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache$1 = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache$1 ) return;
  976. _cache$1[ message ] = true;
  977. console.warn( message );
  978. }
  979. /**
  980. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  981. * or clipping. Based on W3C specifications for sRGB and Display P3,
  982. * and ICC specifications for the D50 connection space. Values in/out
  983. * are _linear_ sRGB and _linear_ Display P3.
  984. *
  985. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  986. *
  987. * Reference:
  988. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  989. */
  990. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  991. 0.8224621, 0.177538, 0.0,
  992. 0.0331941, 0.9668058, 0.0,
  993. 0.0170827, 0.0723974, 0.9105199,
  994. );
  995. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  996. 1.2249401, - 0.2249404, 0.0,
  997. - 0.0420569, 1.0420571, 0.0,
  998. - 0.0196376, - 0.0786361, 1.0982735
  999. );
  1000. /**
  1001. * Defines supported color spaces by transfer function and primaries,
  1002. * and provides conversions to/from the Linear-sRGB reference space.
  1003. */
  1004. const COLOR_SPACES = {
  1005. [ LinearSRGBColorSpace ]: {
  1006. transfer: LinearTransfer,
  1007. primaries: Rec709Primaries,
  1008. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1009. toReference: ( color ) => color,
  1010. fromReference: ( color ) => color,
  1011. },
  1012. [ SRGBColorSpace ]: {
  1013. transfer: SRGBTransfer,
  1014. primaries: Rec709Primaries,
  1015. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1016. toReference: ( color ) => color.convertSRGBToLinear(),
  1017. fromReference: ( color ) => color.convertLinearToSRGB(),
  1018. },
  1019. [ LinearDisplayP3ColorSpace ]: {
  1020. transfer: LinearTransfer,
  1021. primaries: P3Primaries,
  1022. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1023. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1024. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1025. },
  1026. [ DisplayP3ColorSpace ]: {
  1027. transfer: SRGBTransfer,
  1028. primaries: P3Primaries,
  1029. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1030. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1031. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1032. },
  1033. };
  1034. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1035. const ColorManagement = {
  1036. enabled: true,
  1037. _workingColorSpace: LinearSRGBColorSpace,
  1038. get workingColorSpace() {
  1039. return this._workingColorSpace;
  1040. },
  1041. set workingColorSpace( colorSpace ) {
  1042. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1043. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1044. }
  1045. this._workingColorSpace = colorSpace;
  1046. },
  1047. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1048. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1049. return color;
  1050. }
  1051. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1052. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1053. return targetFromReference( sourceToReference( color ) );
  1054. },
  1055. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1056. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1057. },
  1058. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1059. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1060. },
  1061. getPrimaries: function ( colorSpace ) {
  1062. return COLOR_SPACES[ colorSpace ].primaries;
  1063. },
  1064. getTransfer: function ( colorSpace ) {
  1065. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1066. return COLOR_SPACES[ colorSpace ].transfer;
  1067. },
  1068. getLuminanceCoefficients: function ( target, colorSpace = this._workingColorSpace ) {
  1069. return target.fromArray( COLOR_SPACES[ colorSpace ].luminanceCoefficients );
  1070. },
  1071. };
  1072. function SRGBToLinear( c ) {
  1073. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1074. }
  1075. function LinearToSRGB( c ) {
  1076. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1077. }
  1078. let _canvas;
  1079. class ImageUtils {
  1080. static getDataURL( image ) {
  1081. if ( /^data:/i.test( image.src ) ) {
  1082. return image.src;
  1083. }
  1084. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1085. return image.src;
  1086. }
  1087. let canvas;
  1088. if ( image instanceof HTMLCanvasElement ) {
  1089. canvas = image;
  1090. } else {
  1091. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1092. _canvas.width = image.width;
  1093. _canvas.height = image.height;
  1094. const context = _canvas.getContext( '2d' );
  1095. if ( image instanceof ImageData ) {
  1096. context.putImageData( image, 0, 0 );
  1097. } else {
  1098. context.drawImage( image, 0, 0, image.width, image.height );
  1099. }
  1100. canvas = _canvas;
  1101. }
  1102. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1103. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1104. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1105. } else {
  1106. return canvas.toDataURL( 'image/png' );
  1107. }
  1108. }
  1109. static sRGBToLinear( image ) {
  1110. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1111. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1112. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1113. const canvas = createElementNS( 'canvas' );
  1114. canvas.width = image.width;
  1115. canvas.height = image.height;
  1116. const context = canvas.getContext( '2d' );
  1117. context.drawImage( image, 0, 0, image.width, image.height );
  1118. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1119. const data = imageData.data;
  1120. for ( let i = 0; i < data.length; i ++ ) {
  1121. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1122. }
  1123. context.putImageData( imageData, 0, 0 );
  1124. return canvas;
  1125. } else if ( image.data ) {
  1126. const data = image.data.slice( 0 );
  1127. for ( let i = 0; i < data.length; i ++ ) {
  1128. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1129. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1130. } else {
  1131. // assuming float
  1132. data[ i ] = SRGBToLinear( data[ i ] );
  1133. }
  1134. }
  1135. return {
  1136. data: data,
  1137. width: image.width,
  1138. height: image.height
  1139. };
  1140. } else {
  1141. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1142. return image;
  1143. }
  1144. }
  1145. }
  1146. let _sourceId = 0;
  1147. class Source {
  1148. constructor( data = null ) {
  1149. this.isSource = true;
  1150. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1151. this.uuid = generateUUID();
  1152. this.data = data;
  1153. this.dataReady = true;
  1154. this.version = 0;
  1155. }
  1156. set needsUpdate( value ) {
  1157. if ( value === true ) this.version ++;
  1158. }
  1159. toJSON( meta ) {
  1160. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1161. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1162. return meta.images[ this.uuid ];
  1163. }
  1164. const output = {
  1165. uuid: this.uuid,
  1166. url: ''
  1167. };
  1168. const data = this.data;
  1169. if ( data !== null ) {
  1170. let url;
  1171. if ( Array.isArray( data ) ) {
  1172. // cube texture
  1173. url = [];
  1174. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1175. if ( data[ i ].isDataTexture ) {
  1176. url.push( serializeImage( data[ i ].image ) );
  1177. } else {
  1178. url.push( serializeImage( data[ i ] ) );
  1179. }
  1180. }
  1181. } else {
  1182. // texture
  1183. url = serializeImage( data );
  1184. }
  1185. output.url = url;
  1186. }
  1187. if ( ! isRootObject ) {
  1188. meta.images[ this.uuid ] = output;
  1189. }
  1190. return output;
  1191. }
  1192. }
  1193. function serializeImage( image ) {
  1194. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1195. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1196. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1197. // default images
  1198. return ImageUtils.getDataURL( image );
  1199. } else {
  1200. if ( image.data ) {
  1201. // images of DataTexture
  1202. return {
  1203. data: Array.from( image.data ),
  1204. width: image.width,
  1205. height: image.height,
  1206. type: image.data.constructor.name
  1207. };
  1208. } else {
  1209. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1210. return {};
  1211. }
  1212. }
  1213. }
  1214. let _textureId = 0;
  1215. class Texture extends EventDispatcher {
  1216. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1217. super();
  1218. this.isTexture = true;
  1219. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1220. this.uuid = generateUUID();
  1221. this.name = '';
  1222. this.source = new Source( image );
  1223. this.mipmaps = [];
  1224. this.mapping = mapping;
  1225. this.channel = 0;
  1226. this.wrapS = wrapS;
  1227. this.wrapT = wrapT;
  1228. this.magFilter = magFilter;
  1229. this.minFilter = minFilter;
  1230. this.anisotropy = anisotropy;
  1231. this.format = format;
  1232. this.internalFormat = null;
  1233. this.type = type;
  1234. this.offset = new Vector2( 0, 0 );
  1235. this.repeat = new Vector2( 1, 1 );
  1236. this.center = new Vector2( 0, 0 );
  1237. this.rotation = 0;
  1238. this.matrixAutoUpdate = true;
  1239. this.matrix = new Matrix3();
  1240. this.generateMipmaps = true;
  1241. this.premultiplyAlpha = false;
  1242. this.flipY = true;
  1243. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1244. this.colorSpace = colorSpace;
  1245. this.userData = {};
  1246. this.version = 0;
  1247. this.onUpdate = null;
  1248. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1249. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1250. }
  1251. get image() {
  1252. return this.source.data;
  1253. }
  1254. set image( value = null ) {
  1255. this.source.data = value;
  1256. }
  1257. updateMatrix() {
  1258. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1259. }
  1260. clone() {
  1261. return new this.constructor().copy( this );
  1262. }
  1263. copy( source ) {
  1264. this.name = source.name;
  1265. this.source = source.source;
  1266. this.mipmaps = source.mipmaps.slice( 0 );
  1267. this.mapping = source.mapping;
  1268. this.channel = source.channel;
  1269. this.wrapS = source.wrapS;
  1270. this.wrapT = source.wrapT;
  1271. this.magFilter = source.magFilter;
  1272. this.minFilter = source.minFilter;
  1273. this.anisotropy = source.anisotropy;
  1274. this.format = source.format;
  1275. this.internalFormat = source.internalFormat;
  1276. this.type = source.type;
  1277. this.offset.copy( source.offset );
  1278. this.repeat.copy( source.repeat );
  1279. this.center.copy( source.center );
  1280. this.rotation = source.rotation;
  1281. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1282. this.matrix.copy( source.matrix );
  1283. this.generateMipmaps = source.generateMipmaps;
  1284. this.premultiplyAlpha = source.premultiplyAlpha;
  1285. this.flipY = source.flipY;
  1286. this.unpackAlignment = source.unpackAlignment;
  1287. this.colorSpace = source.colorSpace;
  1288. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1289. this.needsUpdate = true;
  1290. return this;
  1291. }
  1292. toJSON( meta ) {
  1293. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1294. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1295. return meta.textures[ this.uuid ];
  1296. }
  1297. const output = {
  1298. metadata: {
  1299. version: 4.6,
  1300. type: 'Texture',
  1301. generator: 'Texture.toJSON'
  1302. },
  1303. uuid: this.uuid,
  1304. name: this.name,
  1305. image: this.source.toJSON( meta ).uuid,
  1306. mapping: this.mapping,
  1307. channel: this.channel,
  1308. repeat: [ this.repeat.x, this.repeat.y ],
  1309. offset: [ this.offset.x, this.offset.y ],
  1310. center: [ this.center.x, this.center.y ],
  1311. rotation: this.rotation,
  1312. wrap: [ this.wrapS, this.wrapT ],
  1313. format: this.format,
  1314. internalFormat: this.internalFormat,
  1315. type: this.type,
  1316. colorSpace: this.colorSpace,
  1317. minFilter: this.minFilter,
  1318. magFilter: this.magFilter,
  1319. anisotropy: this.anisotropy,
  1320. flipY: this.flipY,
  1321. generateMipmaps: this.generateMipmaps,
  1322. premultiplyAlpha: this.premultiplyAlpha,
  1323. unpackAlignment: this.unpackAlignment
  1324. };
  1325. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1326. if ( ! isRootObject ) {
  1327. meta.textures[ this.uuid ] = output;
  1328. }
  1329. return output;
  1330. }
  1331. dispose() {
  1332. this.dispatchEvent( { type: 'dispose' } );
  1333. }
  1334. transformUv( uv ) {
  1335. if ( this.mapping !== UVMapping ) return uv;
  1336. uv.applyMatrix3( this.matrix );
  1337. if ( uv.x < 0 || uv.x > 1 ) {
  1338. switch ( this.wrapS ) {
  1339. case RepeatWrapping:
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. break;
  1342. case ClampToEdgeWrapping:
  1343. uv.x = uv.x < 0 ? 0 : 1;
  1344. break;
  1345. case MirroredRepeatWrapping:
  1346. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1347. uv.x = Math.ceil( uv.x ) - uv.x;
  1348. } else {
  1349. uv.x = uv.x - Math.floor( uv.x );
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. if ( uv.y < 0 || uv.y > 1 ) {
  1355. switch ( this.wrapT ) {
  1356. case RepeatWrapping:
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. break;
  1359. case ClampToEdgeWrapping:
  1360. uv.y = uv.y < 0 ? 0 : 1;
  1361. break;
  1362. case MirroredRepeatWrapping:
  1363. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1364. uv.y = Math.ceil( uv.y ) - uv.y;
  1365. } else {
  1366. uv.y = uv.y - Math.floor( uv.y );
  1367. }
  1368. break;
  1369. }
  1370. }
  1371. if ( this.flipY ) {
  1372. uv.y = 1 - uv.y;
  1373. }
  1374. return uv;
  1375. }
  1376. set needsUpdate( value ) {
  1377. if ( value === true ) {
  1378. this.version ++;
  1379. this.source.needsUpdate = true;
  1380. }
  1381. }
  1382. set needsPMREMUpdate( value ) {
  1383. if ( value === true ) {
  1384. this.pmremVersion ++;
  1385. }
  1386. }
  1387. }
  1388. Texture.DEFAULT_IMAGE = null;
  1389. Texture.DEFAULT_MAPPING = UVMapping;
  1390. Texture.DEFAULT_ANISOTROPY = 1;
  1391. class Vector4 {
  1392. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1393. Vector4.prototype.isVector4 = true;
  1394. this.x = x;
  1395. this.y = y;
  1396. this.z = z;
  1397. this.w = w;
  1398. }
  1399. get width() {
  1400. return this.z;
  1401. }
  1402. set width( value ) {
  1403. this.z = value;
  1404. }
  1405. get height() {
  1406. return this.w;
  1407. }
  1408. set height( value ) {
  1409. this.w = value;
  1410. }
  1411. set( x, y, z, w ) {
  1412. this.x = x;
  1413. this.y = y;
  1414. this.z = z;
  1415. this.w = w;
  1416. return this;
  1417. }
  1418. setScalar( scalar ) {
  1419. this.x = scalar;
  1420. this.y = scalar;
  1421. this.z = scalar;
  1422. this.w = scalar;
  1423. return this;
  1424. }
  1425. setX( x ) {
  1426. this.x = x;
  1427. return this;
  1428. }
  1429. setY( y ) {
  1430. this.y = y;
  1431. return this;
  1432. }
  1433. setZ( z ) {
  1434. this.z = z;
  1435. return this;
  1436. }
  1437. setW( w ) {
  1438. this.w = w;
  1439. return this;
  1440. }
  1441. setComponent( index, value ) {
  1442. switch ( index ) {
  1443. case 0: this.x = value; break;
  1444. case 1: this.y = value; break;
  1445. case 2: this.z = value; break;
  1446. case 3: this.w = value; break;
  1447. default: throw new Error( 'index is out of range: ' + index );
  1448. }
  1449. return this;
  1450. }
  1451. getComponent( index ) {
  1452. switch ( index ) {
  1453. case 0: return this.x;
  1454. case 1: return this.y;
  1455. case 2: return this.z;
  1456. case 3: return this.w;
  1457. default: throw new Error( 'index is out of range: ' + index );
  1458. }
  1459. }
  1460. clone() {
  1461. return new this.constructor( this.x, this.y, this.z, this.w );
  1462. }
  1463. copy( v ) {
  1464. this.x = v.x;
  1465. this.y = v.y;
  1466. this.z = v.z;
  1467. this.w = ( v.w !== undefined ) ? v.w : 1;
  1468. return this;
  1469. }
  1470. add( v ) {
  1471. this.x += v.x;
  1472. this.y += v.y;
  1473. this.z += v.z;
  1474. this.w += v.w;
  1475. return this;
  1476. }
  1477. addScalar( s ) {
  1478. this.x += s;
  1479. this.y += s;
  1480. this.z += s;
  1481. this.w += s;
  1482. return this;
  1483. }
  1484. addVectors( a, b ) {
  1485. this.x = a.x + b.x;
  1486. this.y = a.y + b.y;
  1487. this.z = a.z + b.z;
  1488. this.w = a.w + b.w;
  1489. return this;
  1490. }
  1491. addScaledVector( v, s ) {
  1492. this.x += v.x * s;
  1493. this.y += v.y * s;
  1494. this.z += v.z * s;
  1495. this.w += v.w * s;
  1496. return this;
  1497. }
  1498. sub( v ) {
  1499. this.x -= v.x;
  1500. this.y -= v.y;
  1501. this.z -= v.z;
  1502. this.w -= v.w;
  1503. return this;
  1504. }
  1505. subScalar( s ) {
  1506. this.x -= s;
  1507. this.y -= s;
  1508. this.z -= s;
  1509. this.w -= s;
  1510. return this;
  1511. }
  1512. subVectors( a, b ) {
  1513. this.x = a.x - b.x;
  1514. this.y = a.y - b.y;
  1515. this.z = a.z - b.z;
  1516. this.w = a.w - b.w;
  1517. return this;
  1518. }
  1519. multiply( v ) {
  1520. this.x *= v.x;
  1521. this.y *= v.y;
  1522. this.z *= v.z;
  1523. this.w *= v.w;
  1524. return this;
  1525. }
  1526. multiplyScalar( scalar ) {
  1527. this.x *= scalar;
  1528. this.y *= scalar;
  1529. this.z *= scalar;
  1530. this.w *= scalar;
  1531. return this;
  1532. }
  1533. applyMatrix4( m ) {
  1534. const x = this.x, y = this.y, z = this.z, w = this.w;
  1535. const e = m.elements;
  1536. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1537. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1538. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1539. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1540. return this;
  1541. }
  1542. divideScalar( scalar ) {
  1543. return this.multiplyScalar( 1 / scalar );
  1544. }
  1545. setAxisAngleFromQuaternion( q ) {
  1546. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1547. // q is assumed to be normalized
  1548. this.w = 2 * Math.acos( q.w );
  1549. const s = Math.sqrt( 1 - q.w * q.w );
  1550. if ( s < 0.0001 ) {
  1551. this.x = 1;
  1552. this.y = 0;
  1553. this.z = 0;
  1554. } else {
  1555. this.x = q.x / s;
  1556. this.y = q.y / s;
  1557. this.z = q.z / s;
  1558. }
  1559. return this;
  1560. }
  1561. setAxisAngleFromRotationMatrix( m ) {
  1562. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1563. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1564. let angle, x, y, z; // variables for result
  1565. const epsilon = 0.01, // margin to allow for rounding errors
  1566. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1567. te = m.elements,
  1568. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1569. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1570. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1571. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1572. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1573. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1574. // singularity found
  1575. // first check for identity matrix which must have +1 for all terms
  1576. // in leading diagonal and zero in other terms
  1577. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1578. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1579. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1580. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1581. // this singularity is identity matrix so angle = 0
  1582. this.set( 1, 0, 0, 0 );
  1583. return this; // zero angle, arbitrary axis
  1584. }
  1585. // otherwise this singularity is angle = 180
  1586. angle = Math.PI;
  1587. const xx = ( m11 + 1 ) / 2;
  1588. const yy = ( m22 + 1 ) / 2;
  1589. const zz = ( m33 + 1 ) / 2;
  1590. const xy = ( m12 + m21 ) / 4;
  1591. const xz = ( m13 + m31 ) / 4;
  1592. const yz = ( m23 + m32 ) / 4;
  1593. if ( ( xx > yy ) && ( xx > zz ) ) {
  1594. // m11 is the largest diagonal term
  1595. if ( xx < epsilon ) {
  1596. x = 0;
  1597. y = 0.707106781;
  1598. z = 0.707106781;
  1599. } else {
  1600. x = Math.sqrt( xx );
  1601. y = xy / x;
  1602. z = xz / x;
  1603. }
  1604. } else if ( yy > zz ) {
  1605. // m22 is the largest diagonal term
  1606. if ( yy < epsilon ) {
  1607. x = 0.707106781;
  1608. y = 0;
  1609. z = 0.707106781;
  1610. } else {
  1611. y = Math.sqrt( yy );
  1612. x = xy / y;
  1613. z = yz / y;
  1614. }
  1615. } else {
  1616. // m33 is the largest diagonal term so base result on this
  1617. if ( zz < epsilon ) {
  1618. x = 0.707106781;
  1619. y = 0.707106781;
  1620. z = 0;
  1621. } else {
  1622. z = Math.sqrt( zz );
  1623. x = xz / z;
  1624. y = yz / z;
  1625. }
  1626. }
  1627. this.set( x, y, z, angle );
  1628. return this; // return 180 deg rotation
  1629. }
  1630. // as we have reached here there are no singularities so we can handle normally
  1631. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1632. ( m13 - m31 ) * ( m13 - m31 ) +
  1633. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1634. if ( Math.abs( s ) < 0.001 ) s = 1;
  1635. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1636. // caught by singularity test above, but I've left it in just in case
  1637. this.x = ( m32 - m23 ) / s;
  1638. this.y = ( m13 - m31 ) / s;
  1639. this.z = ( m21 - m12 ) / s;
  1640. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1641. return this;
  1642. }
  1643. setFromMatrixPosition( m ) {
  1644. const e = m.elements;
  1645. this.x = e[ 12 ];
  1646. this.y = e[ 13 ];
  1647. this.z = e[ 14 ];
  1648. this.w = e[ 15 ];
  1649. return this;
  1650. }
  1651. min( v ) {
  1652. this.x = Math.min( this.x, v.x );
  1653. this.y = Math.min( this.y, v.y );
  1654. this.z = Math.min( this.z, v.z );
  1655. this.w = Math.min( this.w, v.w );
  1656. return this;
  1657. }
  1658. max( v ) {
  1659. this.x = Math.max( this.x, v.x );
  1660. this.y = Math.max( this.y, v.y );
  1661. this.z = Math.max( this.z, v.z );
  1662. this.w = Math.max( this.w, v.w );
  1663. return this;
  1664. }
  1665. clamp( min, max ) {
  1666. // assumes min < max, componentwise
  1667. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1668. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1669. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1670. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1671. return this;
  1672. }
  1673. clampScalar( minVal, maxVal ) {
  1674. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1675. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1676. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1677. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1678. return this;
  1679. }
  1680. clampLength( min, max ) {
  1681. const length = this.length();
  1682. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1683. }
  1684. floor() {
  1685. this.x = Math.floor( this.x );
  1686. this.y = Math.floor( this.y );
  1687. this.z = Math.floor( this.z );
  1688. this.w = Math.floor( this.w );
  1689. return this;
  1690. }
  1691. ceil() {
  1692. this.x = Math.ceil( this.x );
  1693. this.y = Math.ceil( this.y );
  1694. this.z = Math.ceil( this.z );
  1695. this.w = Math.ceil( this.w );
  1696. return this;
  1697. }
  1698. round() {
  1699. this.x = Math.round( this.x );
  1700. this.y = Math.round( this.y );
  1701. this.z = Math.round( this.z );
  1702. this.w = Math.round( this.w );
  1703. return this;
  1704. }
  1705. roundToZero() {
  1706. this.x = Math.trunc( this.x );
  1707. this.y = Math.trunc( this.y );
  1708. this.z = Math.trunc( this.z );
  1709. this.w = Math.trunc( this.w );
  1710. return this;
  1711. }
  1712. negate() {
  1713. this.x = - this.x;
  1714. this.y = - this.y;
  1715. this.z = - this.z;
  1716. this.w = - this.w;
  1717. return this;
  1718. }
  1719. dot( v ) {
  1720. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1721. }
  1722. lengthSq() {
  1723. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1724. }
  1725. length() {
  1726. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1727. }
  1728. manhattanLength() {
  1729. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1730. }
  1731. normalize() {
  1732. return this.divideScalar( this.length() || 1 );
  1733. }
  1734. setLength( length ) {
  1735. return this.normalize().multiplyScalar( length );
  1736. }
  1737. lerp( v, alpha ) {
  1738. this.x += ( v.x - this.x ) * alpha;
  1739. this.y += ( v.y - this.y ) * alpha;
  1740. this.z += ( v.z - this.z ) * alpha;
  1741. this.w += ( v.w - this.w ) * alpha;
  1742. return this;
  1743. }
  1744. lerpVectors( v1, v2, alpha ) {
  1745. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1746. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1747. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1748. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1749. return this;
  1750. }
  1751. equals( v ) {
  1752. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1753. }
  1754. fromArray( array, offset = 0 ) {
  1755. this.x = array[ offset ];
  1756. this.y = array[ offset + 1 ];
  1757. this.z = array[ offset + 2 ];
  1758. this.w = array[ offset + 3 ];
  1759. return this;
  1760. }
  1761. toArray( array = [], offset = 0 ) {
  1762. array[ offset ] = this.x;
  1763. array[ offset + 1 ] = this.y;
  1764. array[ offset + 2 ] = this.z;
  1765. array[ offset + 3 ] = this.w;
  1766. return array;
  1767. }
  1768. fromBufferAttribute( attribute, index ) {
  1769. this.x = attribute.getX( index );
  1770. this.y = attribute.getY( index );
  1771. this.z = attribute.getZ( index );
  1772. this.w = attribute.getW( index );
  1773. return this;
  1774. }
  1775. random() {
  1776. this.x = Math.random();
  1777. this.y = Math.random();
  1778. this.z = Math.random();
  1779. this.w = Math.random();
  1780. return this;
  1781. }
  1782. *[ Symbol.iterator ]() {
  1783. yield this.x;
  1784. yield this.y;
  1785. yield this.z;
  1786. yield this.w;
  1787. }
  1788. }
  1789. /*
  1790. In options, we can specify:
  1791. * Texture parameters for an auto-generated target texture
  1792. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1793. */
  1794. class RenderTarget extends EventDispatcher {
  1795. constructor( width = 1, height = 1, options = {} ) {
  1796. super();
  1797. this.isRenderTarget = true;
  1798. this.width = width;
  1799. this.height = height;
  1800. this.depth = 1;
  1801. this.scissor = new Vector4( 0, 0, width, height );
  1802. this.scissorTest = false;
  1803. this.viewport = new Vector4( 0, 0, width, height );
  1804. const image = { width: width, height: height, depth: 1 };
  1805. options = Object.assign( {
  1806. generateMipmaps: false,
  1807. internalFormat: null,
  1808. minFilter: LinearFilter,
  1809. depthBuffer: true,
  1810. stencilBuffer: false,
  1811. resolveDepthBuffer: true,
  1812. resolveStencilBuffer: true,
  1813. depthTexture: null,
  1814. samples: 0,
  1815. count: 1
  1816. }, options );
  1817. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1818. texture.flipY = false;
  1819. texture.generateMipmaps = options.generateMipmaps;
  1820. texture.internalFormat = options.internalFormat;
  1821. this.textures = [];
  1822. const count = options.count;
  1823. for ( let i = 0; i < count; i ++ ) {
  1824. this.textures[ i ] = texture.clone();
  1825. this.textures[ i ].isRenderTargetTexture = true;
  1826. }
  1827. this.depthBuffer = options.depthBuffer;
  1828. this.stencilBuffer = options.stencilBuffer;
  1829. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1830. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1831. this.depthTexture = options.depthTexture;
  1832. this.samples = options.samples;
  1833. }
  1834. get texture() {
  1835. return this.textures[ 0 ];
  1836. }
  1837. set texture( value ) {
  1838. this.textures[ 0 ] = value;
  1839. }
  1840. setSize( width, height, depth = 1 ) {
  1841. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1842. this.width = width;
  1843. this.height = height;
  1844. this.depth = depth;
  1845. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1846. this.textures[ i ].image.width = width;
  1847. this.textures[ i ].image.height = height;
  1848. this.textures[ i ].image.depth = depth;
  1849. }
  1850. this.dispose();
  1851. }
  1852. this.viewport.set( 0, 0, width, height );
  1853. this.scissor.set( 0, 0, width, height );
  1854. }
  1855. clone() {
  1856. return new this.constructor().copy( this );
  1857. }
  1858. copy( source ) {
  1859. this.width = source.width;
  1860. this.height = source.height;
  1861. this.depth = source.depth;
  1862. this.scissor.copy( source.scissor );
  1863. this.scissorTest = source.scissorTest;
  1864. this.viewport.copy( source.viewport );
  1865. this.textures.length = 0;
  1866. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1867. this.textures[ i ] = source.textures[ i ].clone();
  1868. this.textures[ i ].isRenderTargetTexture = true;
  1869. }
  1870. // ensure image object is not shared, see #20328
  1871. const image = Object.assign( {}, source.texture.image );
  1872. this.texture.source = new Source( image );
  1873. this.depthBuffer = source.depthBuffer;
  1874. this.stencilBuffer = source.stencilBuffer;
  1875. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1876. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1877. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1878. this.samples = source.samples;
  1879. return this;
  1880. }
  1881. dispose() {
  1882. this.dispatchEvent( { type: 'dispose' } );
  1883. }
  1884. }
  1885. class WebGLRenderTarget extends RenderTarget {
  1886. constructor( width = 1, height = 1, options = {} ) {
  1887. super( width, height, options );
  1888. this.isWebGLRenderTarget = true;
  1889. }
  1890. }
  1891. class DataArrayTexture extends Texture {
  1892. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1893. super( null );
  1894. this.isDataArrayTexture = true;
  1895. this.image = { data, width, height, depth };
  1896. this.magFilter = NearestFilter;
  1897. this.minFilter = NearestFilter;
  1898. this.wrapR = ClampToEdgeWrapping;
  1899. this.generateMipmaps = false;
  1900. this.flipY = false;
  1901. this.unpackAlignment = 1;
  1902. this.layerUpdates = new Set();
  1903. }
  1904. addLayerUpdate( layerIndex ) {
  1905. this.layerUpdates.add( layerIndex );
  1906. }
  1907. clearLayerUpdates() {
  1908. this.layerUpdates.clear();
  1909. }
  1910. }
  1911. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1912. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1913. super( width, height, options );
  1914. this.isWebGLArrayRenderTarget = true;
  1915. this.depth = depth;
  1916. this.texture = new DataArrayTexture( null, width, height, depth );
  1917. this.texture.isRenderTargetTexture = true;
  1918. }
  1919. }
  1920. class Data3DTexture extends Texture {
  1921. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1922. // We're going to add .setXXX() methods for setting properties later.
  1923. // Users can still set in DataTexture3D directly.
  1924. //
  1925. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1926. // texture.anisotropy = 16;
  1927. //
  1928. // See #14839
  1929. super( null );
  1930. this.isData3DTexture = true;
  1931. this.image = { data, width, height, depth };
  1932. this.magFilter = NearestFilter;
  1933. this.minFilter = NearestFilter;
  1934. this.wrapR = ClampToEdgeWrapping;
  1935. this.generateMipmaps = false;
  1936. this.flipY = false;
  1937. this.unpackAlignment = 1;
  1938. }
  1939. }
  1940. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1941. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1942. super( width, height, options );
  1943. this.isWebGL3DRenderTarget = true;
  1944. this.depth = depth;
  1945. this.texture = new Data3DTexture( null, width, height, depth );
  1946. this.texture.isRenderTargetTexture = true;
  1947. }
  1948. }
  1949. class Quaternion {
  1950. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1951. this.isQuaternion = true;
  1952. this._x = x;
  1953. this._y = y;
  1954. this._z = z;
  1955. this._w = w;
  1956. }
  1957. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1958. // fuzz-free, array-based Quaternion SLERP operation
  1959. let x0 = src0[ srcOffset0 + 0 ],
  1960. y0 = src0[ srcOffset0 + 1 ],
  1961. z0 = src0[ srcOffset0 + 2 ],
  1962. w0 = src0[ srcOffset0 + 3 ];
  1963. const x1 = src1[ srcOffset1 + 0 ],
  1964. y1 = src1[ srcOffset1 + 1 ],
  1965. z1 = src1[ srcOffset1 + 2 ],
  1966. w1 = src1[ srcOffset1 + 3 ];
  1967. if ( t === 0 ) {
  1968. dst[ dstOffset + 0 ] = x0;
  1969. dst[ dstOffset + 1 ] = y0;
  1970. dst[ dstOffset + 2 ] = z0;
  1971. dst[ dstOffset + 3 ] = w0;
  1972. return;
  1973. }
  1974. if ( t === 1 ) {
  1975. dst[ dstOffset + 0 ] = x1;
  1976. dst[ dstOffset + 1 ] = y1;
  1977. dst[ dstOffset + 2 ] = z1;
  1978. dst[ dstOffset + 3 ] = w1;
  1979. return;
  1980. }
  1981. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1982. let s = 1 - t;
  1983. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1984. dir = ( cos >= 0 ? 1 : - 1 ),
  1985. sqrSin = 1 - cos * cos;
  1986. // Skip the Slerp for tiny steps to avoid numeric problems:
  1987. if ( sqrSin > Number.EPSILON ) {
  1988. const sin = Math.sqrt( sqrSin ),
  1989. len = Math.atan2( sin, cos * dir );
  1990. s = Math.sin( s * len ) / sin;
  1991. t = Math.sin( t * len ) / sin;
  1992. }
  1993. const tDir = t * dir;
  1994. x0 = x0 * s + x1 * tDir;
  1995. y0 = y0 * s + y1 * tDir;
  1996. z0 = z0 * s + z1 * tDir;
  1997. w0 = w0 * s + w1 * tDir;
  1998. // Normalize in case we just did a lerp:
  1999. if ( s === 1 - t ) {
  2000. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2001. x0 *= f;
  2002. y0 *= f;
  2003. z0 *= f;
  2004. w0 *= f;
  2005. }
  2006. }
  2007. dst[ dstOffset ] = x0;
  2008. dst[ dstOffset + 1 ] = y0;
  2009. dst[ dstOffset + 2 ] = z0;
  2010. dst[ dstOffset + 3 ] = w0;
  2011. }
  2012. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2013. const x0 = src0[ srcOffset0 ];
  2014. const y0 = src0[ srcOffset0 + 1 ];
  2015. const z0 = src0[ srcOffset0 + 2 ];
  2016. const w0 = src0[ srcOffset0 + 3 ];
  2017. const x1 = src1[ srcOffset1 ];
  2018. const y1 = src1[ srcOffset1 + 1 ];
  2019. const z1 = src1[ srcOffset1 + 2 ];
  2020. const w1 = src1[ srcOffset1 + 3 ];
  2021. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2022. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2023. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2024. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2025. return dst;
  2026. }
  2027. get x() {
  2028. return this._x;
  2029. }
  2030. set x( value ) {
  2031. this._x = value;
  2032. this._onChangeCallback();
  2033. }
  2034. get y() {
  2035. return this._y;
  2036. }
  2037. set y( value ) {
  2038. this._y = value;
  2039. this._onChangeCallback();
  2040. }
  2041. get z() {
  2042. return this._z;
  2043. }
  2044. set z( value ) {
  2045. this._z = value;
  2046. this._onChangeCallback();
  2047. }
  2048. get w() {
  2049. return this._w;
  2050. }
  2051. set w( value ) {
  2052. this._w = value;
  2053. this._onChangeCallback();
  2054. }
  2055. set( x, y, z, w ) {
  2056. this._x = x;
  2057. this._y = y;
  2058. this._z = z;
  2059. this._w = w;
  2060. this._onChangeCallback();
  2061. return this;
  2062. }
  2063. clone() {
  2064. return new this.constructor( this._x, this._y, this._z, this._w );
  2065. }
  2066. copy( quaternion ) {
  2067. this._x = quaternion.x;
  2068. this._y = quaternion.y;
  2069. this._z = quaternion.z;
  2070. this._w = quaternion.w;
  2071. this._onChangeCallback();
  2072. return this;
  2073. }
  2074. setFromEuler( euler, update = true ) {
  2075. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2076. // http://www.mathworks.com/matlabcentral/fileexchange/
  2077. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2078. // content/SpinCalc.m
  2079. const cos = Math.cos;
  2080. const sin = Math.sin;
  2081. const c1 = cos( x / 2 );
  2082. const c2 = cos( y / 2 );
  2083. const c3 = cos( z / 2 );
  2084. const s1 = sin( x / 2 );
  2085. const s2 = sin( y / 2 );
  2086. const s3 = sin( z / 2 );
  2087. switch ( order ) {
  2088. case 'XYZ':
  2089. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2090. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2091. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2092. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2093. break;
  2094. case 'YXZ':
  2095. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2096. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2097. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2098. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2099. break;
  2100. case 'ZXY':
  2101. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2102. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2103. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2104. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2105. break;
  2106. case 'ZYX':
  2107. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2108. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2109. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2110. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2111. break;
  2112. case 'YZX':
  2113. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2114. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2115. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2116. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2117. break;
  2118. case 'XZY':
  2119. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2120. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2121. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2122. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2123. break;
  2124. default:
  2125. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2126. }
  2127. if ( update === true ) this._onChangeCallback();
  2128. return this;
  2129. }
  2130. setFromAxisAngle( axis, angle ) {
  2131. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2132. // assumes axis is normalized
  2133. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2134. this._x = axis.x * s;
  2135. this._y = axis.y * s;
  2136. this._z = axis.z * s;
  2137. this._w = Math.cos( halfAngle );
  2138. this._onChangeCallback();
  2139. return this;
  2140. }
  2141. setFromRotationMatrix( m ) {
  2142. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2143. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2144. const te = m.elements,
  2145. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2146. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2147. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2148. trace = m11 + m22 + m33;
  2149. if ( trace > 0 ) {
  2150. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2151. this._w = 0.25 / s;
  2152. this._x = ( m32 - m23 ) * s;
  2153. this._y = ( m13 - m31 ) * s;
  2154. this._z = ( m21 - m12 ) * s;
  2155. } else if ( m11 > m22 && m11 > m33 ) {
  2156. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2157. this._w = ( m32 - m23 ) / s;
  2158. this._x = 0.25 * s;
  2159. this._y = ( m12 + m21 ) / s;
  2160. this._z = ( m13 + m31 ) / s;
  2161. } else if ( m22 > m33 ) {
  2162. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2163. this._w = ( m13 - m31 ) / s;
  2164. this._x = ( m12 + m21 ) / s;
  2165. this._y = 0.25 * s;
  2166. this._z = ( m23 + m32 ) / s;
  2167. } else {
  2168. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2169. this._w = ( m21 - m12 ) / s;
  2170. this._x = ( m13 + m31 ) / s;
  2171. this._y = ( m23 + m32 ) / s;
  2172. this._z = 0.25 * s;
  2173. }
  2174. this._onChangeCallback();
  2175. return this;
  2176. }
  2177. setFromUnitVectors( vFrom, vTo ) {
  2178. // assumes direction vectors vFrom and vTo are normalized
  2179. let r = vFrom.dot( vTo ) + 1;
  2180. if ( r < Number.EPSILON ) {
  2181. // vFrom and vTo point in opposite directions
  2182. r = 0;
  2183. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2184. this._x = - vFrom.y;
  2185. this._y = vFrom.x;
  2186. this._z = 0;
  2187. this._w = r;
  2188. } else {
  2189. this._x = 0;
  2190. this._y = - vFrom.z;
  2191. this._z = vFrom.y;
  2192. this._w = r;
  2193. }
  2194. } else {
  2195. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2196. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2197. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2198. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2199. this._w = r;
  2200. }
  2201. return this.normalize();
  2202. }
  2203. angleTo( q ) {
  2204. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2205. }
  2206. rotateTowards( q, step ) {
  2207. const angle = this.angleTo( q );
  2208. if ( angle === 0 ) return this;
  2209. const t = Math.min( 1, step / angle );
  2210. this.slerp( q, t );
  2211. return this;
  2212. }
  2213. identity() {
  2214. return this.set( 0, 0, 0, 1 );
  2215. }
  2216. invert() {
  2217. // quaternion is assumed to have unit length
  2218. return this.conjugate();
  2219. }
  2220. conjugate() {
  2221. this._x *= - 1;
  2222. this._y *= - 1;
  2223. this._z *= - 1;
  2224. this._onChangeCallback();
  2225. return this;
  2226. }
  2227. dot( v ) {
  2228. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2229. }
  2230. lengthSq() {
  2231. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2232. }
  2233. length() {
  2234. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2235. }
  2236. normalize() {
  2237. let l = this.length();
  2238. if ( l === 0 ) {
  2239. this._x = 0;
  2240. this._y = 0;
  2241. this._z = 0;
  2242. this._w = 1;
  2243. } else {
  2244. l = 1 / l;
  2245. this._x = this._x * l;
  2246. this._y = this._y * l;
  2247. this._z = this._z * l;
  2248. this._w = this._w * l;
  2249. }
  2250. this._onChangeCallback();
  2251. return this;
  2252. }
  2253. multiply( q ) {
  2254. return this.multiplyQuaternions( this, q );
  2255. }
  2256. premultiply( q ) {
  2257. return this.multiplyQuaternions( q, this );
  2258. }
  2259. multiplyQuaternions( a, b ) {
  2260. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2261. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2262. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2263. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2264. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2265. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2266. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2267. this._onChangeCallback();
  2268. return this;
  2269. }
  2270. slerp( qb, t ) {
  2271. if ( t === 0 ) return this;
  2272. if ( t === 1 ) return this.copy( qb );
  2273. const x = this._x, y = this._y, z = this._z, w = this._w;
  2274. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2275. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2276. if ( cosHalfTheta < 0 ) {
  2277. this._w = - qb._w;
  2278. this._x = - qb._x;
  2279. this._y = - qb._y;
  2280. this._z = - qb._z;
  2281. cosHalfTheta = - cosHalfTheta;
  2282. } else {
  2283. this.copy( qb );
  2284. }
  2285. if ( cosHalfTheta >= 1.0 ) {
  2286. this._w = w;
  2287. this._x = x;
  2288. this._y = y;
  2289. this._z = z;
  2290. return this;
  2291. }
  2292. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2293. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2294. const s = 1 - t;
  2295. this._w = s * w + t * this._w;
  2296. this._x = s * x + t * this._x;
  2297. this._y = s * y + t * this._y;
  2298. this._z = s * z + t * this._z;
  2299. this.normalize(); // normalize calls _onChangeCallback()
  2300. return this;
  2301. }
  2302. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2303. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2304. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2305. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2306. this._w = ( w * ratioA + this._w * ratioB );
  2307. this._x = ( x * ratioA + this._x * ratioB );
  2308. this._y = ( y * ratioA + this._y * ratioB );
  2309. this._z = ( z * ratioA + this._z * ratioB );
  2310. this._onChangeCallback();
  2311. return this;
  2312. }
  2313. slerpQuaternions( qa, qb, t ) {
  2314. return this.copy( qa ).slerp( qb, t );
  2315. }
  2316. random() {
  2317. // sets this quaternion to a uniform random unit quaternnion
  2318. // Ken Shoemake
  2319. // Uniform random rotations
  2320. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2321. const theta1 = 2 * Math.PI * Math.random();
  2322. const theta2 = 2 * Math.PI * Math.random();
  2323. const x0 = Math.random();
  2324. const r1 = Math.sqrt( 1 - x0 );
  2325. const r2 = Math.sqrt( x0 );
  2326. return this.set(
  2327. r1 * Math.sin( theta1 ),
  2328. r1 * Math.cos( theta1 ),
  2329. r2 * Math.sin( theta2 ),
  2330. r2 * Math.cos( theta2 ),
  2331. );
  2332. }
  2333. equals( quaternion ) {
  2334. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2335. }
  2336. fromArray( array, offset = 0 ) {
  2337. this._x = array[ offset ];
  2338. this._y = array[ offset + 1 ];
  2339. this._z = array[ offset + 2 ];
  2340. this._w = array[ offset + 3 ];
  2341. this._onChangeCallback();
  2342. return this;
  2343. }
  2344. toArray( array = [], offset = 0 ) {
  2345. array[ offset ] = this._x;
  2346. array[ offset + 1 ] = this._y;
  2347. array[ offset + 2 ] = this._z;
  2348. array[ offset + 3 ] = this._w;
  2349. return array;
  2350. }
  2351. fromBufferAttribute( attribute, index ) {
  2352. this._x = attribute.getX( index );
  2353. this._y = attribute.getY( index );
  2354. this._z = attribute.getZ( index );
  2355. this._w = attribute.getW( index );
  2356. this._onChangeCallback();
  2357. return this;
  2358. }
  2359. toJSON() {
  2360. return this.toArray();
  2361. }
  2362. _onChange( callback ) {
  2363. this._onChangeCallback = callback;
  2364. return this;
  2365. }
  2366. _onChangeCallback() {}
  2367. *[ Symbol.iterator ]() {
  2368. yield this._x;
  2369. yield this._y;
  2370. yield this._z;
  2371. yield this._w;
  2372. }
  2373. }
  2374. class Vector3 {
  2375. constructor( x = 0, y = 0, z = 0 ) {
  2376. Vector3.prototype.isVector3 = true;
  2377. this.x = x;
  2378. this.y = y;
  2379. this.z = z;
  2380. }
  2381. set( x, y, z ) {
  2382. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2383. this.x = x;
  2384. this.y = y;
  2385. this.z = z;
  2386. return this;
  2387. }
  2388. setScalar( scalar ) {
  2389. this.x = scalar;
  2390. this.y = scalar;
  2391. this.z = scalar;
  2392. return this;
  2393. }
  2394. setX( x ) {
  2395. this.x = x;
  2396. return this;
  2397. }
  2398. setY( y ) {
  2399. this.y = y;
  2400. return this;
  2401. }
  2402. setZ( z ) {
  2403. this.z = z;
  2404. return this;
  2405. }
  2406. setComponent( index, value ) {
  2407. switch ( index ) {
  2408. case 0: this.x = value; break;
  2409. case 1: this.y = value; break;
  2410. case 2: this.z = value; break;
  2411. default: throw new Error( 'index is out of range: ' + index );
  2412. }
  2413. return this;
  2414. }
  2415. getComponent( index ) {
  2416. switch ( index ) {
  2417. case 0: return this.x;
  2418. case 1: return this.y;
  2419. case 2: return this.z;
  2420. default: throw new Error( 'index is out of range: ' + index );
  2421. }
  2422. }
  2423. clone() {
  2424. return new this.constructor( this.x, this.y, this.z );
  2425. }
  2426. copy( v ) {
  2427. this.x = v.x;
  2428. this.y = v.y;
  2429. this.z = v.z;
  2430. return this;
  2431. }
  2432. add( v ) {
  2433. this.x += v.x;
  2434. this.y += v.y;
  2435. this.z += v.z;
  2436. return this;
  2437. }
  2438. addScalar( s ) {
  2439. this.x += s;
  2440. this.y += s;
  2441. this.z += s;
  2442. return this;
  2443. }
  2444. addVectors( a, b ) {
  2445. this.x = a.x + b.x;
  2446. this.y = a.y + b.y;
  2447. this.z = a.z + b.z;
  2448. return this;
  2449. }
  2450. addScaledVector( v, s ) {
  2451. this.x += v.x * s;
  2452. this.y += v.y * s;
  2453. this.z += v.z * s;
  2454. return this;
  2455. }
  2456. sub( v ) {
  2457. this.x -= v.x;
  2458. this.y -= v.y;
  2459. this.z -= v.z;
  2460. return this;
  2461. }
  2462. subScalar( s ) {
  2463. this.x -= s;
  2464. this.y -= s;
  2465. this.z -= s;
  2466. return this;
  2467. }
  2468. subVectors( a, b ) {
  2469. this.x = a.x - b.x;
  2470. this.y = a.y - b.y;
  2471. this.z = a.z - b.z;
  2472. return this;
  2473. }
  2474. multiply( v ) {
  2475. this.x *= v.x;
  2476. this.y *= v.y;
  2477. this.z *= v.z;
  2478. return this;
  2479. }
  2480. multiplyScalar( scalar ) {
  2481. this.x *= scalar;
  2482. this.y *= scalar;
  2483. this.z *= scalar;
  2484. return this;
  2485. }
  2486. multiplyVectors( a, b ) {
  2487. this.x = a.x * b.x;
  2488. this.y = a.y * b.y;
  2489. this.z = a.z * b.z;
  2490. return this;
  2491. }
  2492. applyEuler( euler ) {
  2493. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2494. }
  2495. applyAxisAngle( axis, angle ) {
  2496. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2497. }
  2498. applyMatrix3( m ) {
  2499. const x = this.x, y = this.y, z = this.z;
  2500. const e = m.elements;
  2501. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2502. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2503. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2504. return this;
  2505. }
  2506. applyNormalMatrix( m ) {
  2507. return this.applyMatrix3( m ).normalize();
  2508. }
  2509. applyMatrix4( m ) {
  2510. const x = this.x, y = this.y, z = this.z;
  2511. const e = m.elements;
  2512. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2513. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2514. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2515. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2516. return this;
  2517. }
  2518. applyQuaternion( q ) {
  2519. // quaternion q is assumed to have unit length
  2520. const vx = this.x, vy = this.y, vz = this.z;
  2521. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2522. // t = 2 * cross( q.xyz, v );
  2523. const tx = 2 * ( qy * vz - qz * vy );
  2524. const ty = 2 * ( qz * vx - qx * vz );
  2525. const tz = 2 * ( qx * vy - qy * vx );
  2526. // v + q.w * t + cross( q.xyz, t );
  2527. this.x = vx + qw * tx + qy * tz - qz * ty;
  2528. this.y = vy + qw * ty + qz * tx - qx * tz;
  2529. this.z = vz + qw * tz + qx * ty - qy * tx;
  2530. return this;
  2531. }
  2532. project( camera ) {
  2533. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2534. }
  2535. unproject( camera ) {
  2536. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2537. }
  2538. transformDirection( m ) {
  2539. // input: THREE.Matrix4 affine matrix
  2540. // vector interpreted as a direction
  2541. const x = this.x, y = this.y, z = this.z;
  2542. const e = m.elements;
  2543. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2544. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2545. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2546. return this.normalize();
  2547. }
  2548. divide( v ) {
  2549. this.x /= v.x;
  2550. this.y /= v.y;
  2551. this.z /= v.z;
  2552. return this;
  2553. }
  2554. divideScalar( scalar ) {
  2555. return this.multiplyScalar( 1 / scalar );
  2556. }
  2557. min( v ) {
  2558. this.x = Math.min( this.x, v.x );
  2559. this.y = Math.min( this.y, v.y );
  2560. this.z = Math.min( this.z, v.z );
  2561. return this;
  2562. }
  2563. max( v ) {
  2564. this.x = Math.max( this.x, v.x );
  2565. this.y = Math.max( this.y, v.y );
  2566. this.z = Math.max( this.z, v.z );
  2567. return this;
  2568. }
  2569. clamp( min, max ) {
  2570. // assumes min < max, componentwise
  2571. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2572. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2573. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2574. return this;
  2575. }
  2576. clampScalar( minVal, maxVal ) {
  2577. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2578. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2579. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2580. return this;
  2581. }
  2582. clampLength( min, max ) {
  2583. const length = this.length();
  2584. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2585. }
  2586. floor() {
  2587. this.x = Math.floor( this.x );
  2588. this.y = Math.floor( this.y );
  2589. this.z = Math.floor( this.z );
  2590. return this;
  2591. }
  2592. ceil() {
  2593. this.x = Math.ceil( this.x );
  2594. this.y = Math.ceil( this.y );
  2595. this.z = Math.ceil( this.z );
  2596. return this;
  2597. }
  2598. round() {
  2599. this.x = Math.round( this.x );
  2600. this.y = Math.round( this.y );
  2601. this.z = Math.round( this.z );
  2602. return this;
  2603. }
  2604. roundToZero() {
  2605. this.x = Math.trunc( this.x );
  2606. this.y = Math.trunc( this.y );
  2607. this.z = Math.trunc( this.z );
  2608. return this;
  2609. }
  2610. negate() {
  2611. this.x = - this.x;
  2612. this.y = - this.y;
  2613. this.z = - this.z;
  2614. return this;
  2615. }
  2616. dot( v ) {
  2617. return this.x * v.x + this.y * v.y + this.z * v.z;
  2618. }
  2619. // TODO lengthSquared?
  2620. lengthSq() {
  2621. return this.x * this.x + this.y * this.y + this.z * this.z;
  2622. }
  2623. length() {
  2624. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2625. }
  2626. manhattanLength() {
  2627. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2628. }
  2629. normalize() {
  2630. return this.divideScalar( this.length() || 1 );
  2631. }
  2632. setLength( length ) {
  2633. return this.normalize().multiplyScalar( length );
  2634. }
  2635. lerp( v, alpha ) {
  2636. this.x += ( v.x - this.x ) * alpha;
  2637. this.y += ( v.y - this.y ) * alpha;
  2638. this.z += ( v.z - this.z ) * alpha;
  2639. return this;
  2640. }
  2641. lerpVectors( v1, v2, alpha ) {
  2642. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2643. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2644. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2645. return this;
  2646. }
  2647. cross( v ) {
  2648. return this.crossVectors( this, v );
  2649. }
  2650. crossVectors( a, b ) {
  2651. const ax = a.x, ay = a.y, az = a.z;
  2652. const bx = b.x, by = b.y, bz = b.z;
  2653. this.x = ay * bz - az * by;
  2654. this.y = az * bx - ax * bz;
  2655. this.z = ax * by - ay * bx;
  2656. return this;
  2657. }
  2658. projectOnVector( v ) {
  2659. const denominator = v.lengthSq();
  2660. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2661. const scalar = v.dot( this ) / denominator;
  2662. return this.copy( v ).multiplyScalar( scalar );
  2663. }
  2664. projectOnPlane( planeNormal ) {
  2665. _vector$c.copy( this ).projectOnVector( planeNormal );
  2666. return this.sub( _vector$c );
  2667. }
  2668. reflect( normal ) {
  2669. // reflect incident vector off plane orthogonal to normal
  2670. // normal is assumed to have unit length
  2671. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2672. }
  2673. angleTo( v ) {
  2674. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2675. if ( denominator === 0 ) return Math.PI / 2;
  2676. const theta = this.dot( v ) / denominator;
  2677. // clamp, to handle numerical problems
  2678. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2679. }
  2680. distanceTo( v ) {
  2681. return Math.sqrt( this.distanceToSquared( v ) );
  2682. }
  2683. distanceToSquared( v ) {
  2684. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2685. return dx * dx + dy * dy + dz * dz;
  2686. }
  2687. manhattanDistanceTo( v ) {
  2688. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2689. }
  2690. setFromSpherical( s ) {
  2691. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2692. }
  2693. setFromSphericalCoords( radius, phi, theta ) {
  2694. const sinPhiRadius = Math.sin( phi ) * radius;
  2695. this.x = sinPhiRadius * Math.sin( theta );
  2696. this.y = Math.cos( phi ) * radius;
  2697. this.z = sinPhiRadius * Math.cos( theta );
  2698. return this;
  2699. }
  2700. setFromCylindrical( c ) {
  2701. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2702. }
  2703. setFromCylindricalCoords( radius, theta, y ) {
  2704. this.x = radius * Math.sin( theta );
  2705. this.y = y;
  2706. this.z = radius * Math.cos( theta );
  2707. return this;
  2708. }
  2709. setFromMatrixPosition( m ) {
  2710. const e = m.elements;
  2711. this.x = e[ 12 ];
  2712. this.y = e[ 13 ];
  2713. this.z = e[ 14 ];
  2714. return this;
  2715. }
  2716. setFromMatrixScale( m ) {
  2717. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2718. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2719. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2720. this.x = sx;
  2721. this.y = sy;
  2722. this.z = sz;
  2723. return this;
  2724. }
  2725. setFromMatrixColumn( m, index ) {
  2726. return this.fromArray( m.elements, index * 4 );
  2727. }
  2728. setFromMatrix3Column( m, index ) {
  2729. return this.fromArray( m.elements, index * 3 );
  2730. }
  2731. setFromEuler( e ) {
  2732. this.x = e._x;
  2733. this.y = e._y;
  2734. this.z = e._z;
  2735. return this;
  2736. }
  2737. setFromColor( c ) {
  2738. this.x = c.r;
  2739. this.y = c.g;
  2740. this.z = c.b;
  2741. return this;
  2742. }
  2743. equals( v ) {
  2744. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2745. }
  2746. fromArray( array, offset = 0 ) {
  2747. this.x = array[ offset ];
  2748. this.y = array[ offset + 1 ];
  2749. this.z = array[ offset + 2 ];
  2750. return this;
  2751. }
  2752. toArray( array = [], offset = 0 ) {
  2753. array[ offset ] = this.x;
  2754. array[ offset + 1 ] = this.y;
  2755. array[ offset + 2 ] = this.z;
  2756. return array;
  2757. }
  2758. fromBufferAttribute( attribute, index ) {
  2759. this.x = attribute.getX( index );
  2760. this.y = attribute.getY( index );
  2761. this.z = attribute.getZ( index );
  2762. return this;
  2763. }
  2764. random() {
  2765. this.x = Math.random();
  2766. this.y = Math.random();
  2767. this.z = Math.random();
  2768. return this;
  2769. }
  2770. randomDirection() {
  2771. // https://mathworld.wolfram.com/SpherePointPicking.html
  2772. const theta = Math.random() * Math.PI * 2;
  2773. const u = Math.random() * 2 - 1;
  2774. const c = Math.sqrt( 1 - u * u );
  2775. this.x = c * Math.cos( theta );
  2776. this.y = u;
  2777. this.z = c * Math.sin( theta );
  2778. return this;
  2779. }
  2780. *[ Symbol.iterator ]() {
  2781. yield this.x;
  2782. yield this.y;
  2783. yield this.z;
  2784. }
  2785. }
  2786. const _vector$c = /*@__PURE__*/ new Vector3();
  2787. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2788. class Box3 {
  2789. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2790. this.isBox3 = true;
  2791. this.min = min;
  2792. this.max = max;
  2793. }
  2794. set( min, max ) {
  2795. this.min.copy( min );
  2796. this.max.copy( max );
  2797. return this;
  2798. }
  2799. setFromArray( array ) {
  2800. this.makeEmpty();
  2801. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2802. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2803. }
  2804. return this;
  2805. }
  2806. setFromBufferAttribute( attribute ) {
  2807. this.makeEmpty();
  2808. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2809. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2810. }
  2811. return this;
  2812. }
  2813. setFromPoints( points ) {
  2814. this.makeEmpty();
  2815. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2816. this.expandByPoint( points[ i ] );
  2817. }
  2818. return this;
  2819. }
  2820. setFromCenterAndSize( center, size ) {
  2821. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2822. this.min.copy( center ).sub( halfSize );
  2823. this.max.copy( center ).add( halfSize );
  2824. return this;
  2825. }
  2826. setFromObject( object, precise = false ) {
  2827. this.makeEmpty();
  2828. return this.expandByObject( object, precise );
  2829. }
  2830. clone() {
  2831. return new this.constructor().copy( this );
  2832. }
  2833. copy( box ) {
  2834. this.min.copy( box.min );
  2835. this.max.copy( box.max );
  2836. return this;
  2837. }
  2838. makeEmpty() {
  2839. this.min.x = this.min.y = this.min.z = + Infinity;
  2840. this.max.x = this.max.y = this.max.z = - Infinity;
  2841. return this;
  2842. }
  2843. isEmpty() {
  2844. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2845. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2846. }
  2847. getCenter( target ) {
  2848. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2849. }
  2850. getSize( target ) {
  2851. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2852. }
  2853. expandByPoint( point ) {
  2854. this.min.min( point );
  2855. this.max.max( point );
  2856. return this;
  2857. }
  2858. expandByVector( vector ) {
  2859. this.min.sub( vector );
  2860. this.max.add( vector );
  2861. return this;
  2862. }
  2863. expandByScalar( scalar ) {
  2864. this.min.addScalar( - scalar );
  2865. this.max.addScalar( scalar );
  2866. return this;
  2867. }
  2868. expandByObject( object, precise = false ) {
  2869. // Computes the world-axis-aligned bounding box of an object (including its children),
  2870. // accounting for both the object's, and children's, world transforms
  2871. object.updateWorldMatrix( false, false );
  2872. const geometry = object.geometry;
  2873. if ( geometry !== undefined ) {
  2874. const positionAttribute = geometry.getAttribute( 'position' );
  2875. // precise AABB computation based on vertex data requires at least a position attribute.
  2876. // instancing isn't supported so far and uses the normal (conservative) code path.
  2877. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2878. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2879. if ( object.isMesh === true ) {
  2880. object.getVertexPosition( i, _vector$b );
  2881. } else {
  2882. _vector$b.fromBufferAttribute( positionAttribute, i );
  2883. }
  2884. _vector$b.applyMatrix4( object.matrixWorld );
  2885. this.expandByPoint( _vector$b );
  2886. }
  2887. } else {
  2888. if ( object.boundingBox !== undefined ) {
  2889. // object-level bounding box
  2890. if ( object.boundingBox === null ) {
  2891. object.computeBoundingBox();
  2892. }
  2893. _box$4.copy( object.boundingBox );
  2894. } else {
  2895. // geometry-level bounding box
  2896. if ( geometry.boundingBox === null ) {
  2897. geometry.computeBoundingBox();
  2898. }
  2899. _box$4.copy( geometry.boundingBox );
  2900. }
  2901. _box$4.applyMatrix4( object.matrixWorld );
  2902. this.union( _box$4 );
  2903. }
  2904. }
  2905. const children = object.children;
  2906. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2907. this.expandByObject( children[ i ], precise );
  2908. }
  2909. return this;
  2910. }
  2911. containsPoint( point ) {
  2912. return point.x >= this.min.x && point.x <= this.max.x &&
  2913. point.y >= this.min.y && point.y <= this.max.y &&
  2914. point.z >= this.min.z && point.z <= this.max.z;
  2915. }
  2916. containsBox( box ) {
  2917. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2918. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2919. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2920. }
  2921. getParameter( point, target ) {
  2922. // This can potentially have a divide by zero if the box
  2923. // has a size dimension of 0.
  2924. return target.set(
  2925. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2926. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2927. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2928. );
  2929. }
  2930. intersectsBox( box ) {
  2931. // using 6 splitting planes to rule out intersections.
  2932. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2933. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2934. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2935. }
  2936. intersectsSphere( sphere ) {
  2937. // Find the point on the AABB closest to the sphere center.
  2938. this.clampPoint( sphere.center, _vector$b );
  2939. // If that point is inside the sphere, the AABB and sphere intersect.
  2940. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2941. }
  2942. intersectsPlane( plane ) {
  2943. // We compute the minimum and maximum dot product values. If those values
  2944. // are on the same side (back or front) of the plane, then there is no intersection.
  2945. let min, max;
  2946. if ( plane.normal.x > 0 ) {
  2947. min = plane.normal.x * this.min.x;
  2948. max = plane.normal.x * this.max.x;
  2949. } else {
  2950. min = plane.normal.x * this.max.x;
  2951. max = plane.normal.x * this.min.x;
  2952. }
  2953. if ( plane.normal.y > 0 ) {
  2954. min += plane.normal.y * this.min.y;
  2955. max += plane.normal.y * this.max.y;
  2956. } else {
  2957. min += plane.normal.y * this.max.y;
  2958. max += plane.normal.y * this.min.y;
  2959. }
  2960. if ( plane.normal.z > 0 ) {
  2961. min += plane.normal.z * this.min.z;
  2962. max += plane.normal.z * this.max.z;
  2963. } else {
  2964. min += plane.normal.z * this.max.z;
  2965. max += plane.normal.z * this.min.z;
  2966. }
  2967. return ( min <= - plane.constant && max >= - plane.constant );
  2968. }
  2969. intersectsTriangle( triangle ) {
  2970. if ( this.isEmpty() ) {
  2971. return false;
  2972. }
  2973. // compute box center and extents
  2974. this.getCenter( _center );
  2975. _extents.subVectors( this.max, _center );
  2976. // translate triangle to aabb origin
  2977. _v0$2.subVectors( triangle.a, _center );
  2978. _v1$7.subVectors( triangle.b, _center );
  2979. _v2$4.subVectors( triangle.c, _center );
  2980. // compute edge vectors for triangle
  2981. _f0.subVectors( _v1$7, _v0$2 );
  2982. _f1.subVectors( _v2$4, _v1$7 );
  2983. _f2.subVectors( _v0$2, _v2$4 );
  2984. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2985. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2986. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2987. let axes = [
  2988. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2989. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2990. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2991. ];
  2992. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2993. return false;
  2994. }
  2995. // test 3 face normals from the aabb
  2996. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2997. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2998. return false;
  2999. }
  3000. // finally testing the face normal of the triangle
  3001. // use already existing triangle edge vectors here
  3002. _triangleNormal.crossVectors( _f0, _f1 );
  3003. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3004. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3005. }
  3006. clampPoint( point, target ) {
  3007. return target.copy( point ).clamp( this.min, this.max );
  3008. }
  3009. distanceToPoint( point ) {
  3010. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3011. }
  3012. getBoundingSphere( target ) {
  3013. if ( this.isEmpty() ) {
  3014. target.makeEmpty();
  3015. } else {
  3016. this.getCenter( target.center );
  3017. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3018. }
  3019. return target;
  3020. }
  3021. intersect( box ) {
  3022. this.min.max( box.min );
  3023. this.max.min( box.max );
  3024. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3025. if ( this.isEmpty() ) this.makeEmpty();
  3026. return this;
  3027. }
  3028. union( box ) {
  3029. this.min.min( box.min );
  3030. this.max.max( box.max );
  3031. return this;
  3032. }
  3033. applyMatrix4( matrix ) {
  3034. // transform of empty box is an empty box.
  3035. if ( this.isEmpty() ) return this;
  3036. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3037. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3038. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3039. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3040. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3041. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3042. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3043. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3044. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3045. this.setFromPoints( _points );
  3046. return this;
  3047. }
  3048. translate( offset ) {
  3049. this.min.add( offset );
  3050. this.max.add( offset );
  3051. return this;
  3052. }
  3053. equals( box ) {
  3054. return box.min.equals( this.min ) && box.max.equals( this.max );
  3055. }
  3056. }
  3057. const _points = [
  3058. /*@__PURE__*/ new Vector3(),
  3059. /*@__PURE__*/ new Vector3(),
  3060. /*@__PURE__*/ new Vector3(),
  3061. /*@__PURE__*/ new Vector3(),
  3062. /*@__PURE__*/ new Vector3(),
  3063. /*@__PURE__*/ new Vector3(),
  3064. /*@__PURE__*/ new Vector3(),
  3065. /*@__PURE__*/ new Vector3()
  3066. ];
  3067. const _vector$b = /*@__PURE__*/ new Vector3();
  3068. const _box$4 = /*@__PURE__*/ new Box3();
  3069. // triangle centered vertices
  3070. const _v0$2 = /*@__PURE__*/ new Vector3();
  3071. const _v1$7 = /*@__PURE__*/ new Vector3();
  3072. const _v2$4 = /*@__PURE__*/ new Vector3();
  3073. // triangle edge vectors
  3074. const _f0 = /*@__PURE__*/ new Vector3();
  3075. const _f1 = /*@__PURE__*/ new Vector3();
  3076. const _f2 = /*@__PURE__*/ new Vector3();
  3077. const _center = /*@__PURE__*/ new Vector3();
  3078. const _extents = /*@__PURE__*/ new Vector3();
  3079. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3080. const _testAxis = /*@__PURE__*/ new Vector3();
  3081. function satForAxes( axes, v0, v1, v2, extents ) {
  3082. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3083. _testAxis.fromArray( axes, i );
  3084. // project the aabb onto the separating axis
  3085. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3086. // project all 3 vertices of the triangle onto the separating axis
  3087. const p0 = v0.dot( _testAxis );
  3088. const p1 = v1.dot( _testAxis );
  3089. const p2 = v2.dot( _testAxis );
  3090. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3091. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3092. // points of the projected triangle are outside the projected half-length of the aabb
  3093. // the axis is separating and we can exit
  3094. return false;
  3095. }
  3096. }
  3097. return true;
  3098. }
  3099. const _box$3 = /*@__PURE__*/ new Box3();
  3100. const _v1$6 = /*@__PURE__*/ new Vector3();
  3101. const _v2$3 = /*@__PURE__*/ new Vector3();
  3102. class Sphere {
  3103. constructor( center = new Vector3(), radius = - 1 ) {
  3104. this.isSphere = true;
  3105. this.center = center;
  3106. this.radius = radius;
  3107. }
  3108. set( center, radius ) {
  3109. this.center.copy( center );
  3110. this.radius = radius;
  3111. return this;
  3112. }
  3113. setFromPoints( points, optionalCenter ) {
  3114. const center = this.center;
  3115. if ( optionalCenter !== undefined ) {
  3116. center.copy( optionalCenter );
  3117. } else {
  3118. _box$3.setFromPoints( points ).getCenter( center );
  3119. }
  3120. let maxRadiusSq = 0;
  3121. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3122. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3123. }
  3124. this.radius = Math.sqrt( maxRadiusSq );
  3125. return this;
  3126. }
  3127. copy( sphere ) {
  3128. this.center.copy( sphere.center );
  3129. this.radius = sphere.radius;
  3130. return this;
  3131. }
  3132. isEmpty() {
  3133. return ( this.radius < 0 );
  3134. }
  3135. makeEmpty() {
  3136. this.center.set( 0, 0, 0 );
  3137. this.radius = - 1;
  3138. return this;
  3139. }
  3140. containsPoint( point ) {
  3141. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3142. }
  3143. distanceToPoint( point ) {
  3144. return ( point.distanceTo( this.center ) - this.radius );
  3145. }
  3146. intersectsSphere( sphere ) {
  3147. const radiusSum = this.radius + sphere.radius;
  3148. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3149. }
  3150. intersectsBox( box ) {
  3151. return box.intersectsSphere( this );
  3152. }
  3153. intersectsPlane( plane ) {
  3154. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3155. }
  3156. clampPoint( point, target ) {
  3157. const deltaLengthSq = this.center.distanceToSquared( point );
  3158. target.copy( point );
  3159. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3160. target.sub( this.center ).normalize();
  3161. target.multiplyScalar( this.radius ).add( this.center );
  3162. }
  3163. return target;
  3164. }
  3165. getBoundingBox( target ) {
  3166. if ( this.isEmpty() ) {
  3167. // Empty sphere produces empty bounding box
  3168. target.makeEmpty();
  3169. return target;
  3170. }
  3171. target.set( this.center, this.center );
  3172. target.expandByScalar( this.radius );
  3173. return target;
  3174. }
  3175. applyMatrix4( matrix ) {
  3176. this.center.applyMatrix4( matrix );
  3177. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3178. return this;
  3179. }
  3180. translate( offset ) {
  3181. this.center.add( offset );
  3182. return this;
  3183. }
  3184. expandByPoint( point ) {
  3185. if ( this.isEmpty() ) {
  3186. this.center.copy( point );
  3187. this.radius = 0;
  3188. return this;
  3189. }
  3190. _v1$6.subVectors( point, this.center );
  3191. const lengthSq = _v1$6.lengthSq();
  3192. if ( lengthSq > ( this.radius * this.radius ) ) {
  3193. // calculate the minimal sphere
  3194. const length = Math.sqrt( lengthSq );
  3195. const delta = ( length - this.radius ) * 0.5;
  3196. this.center.addScaledVector( _v1$6, delta / length );
  3197. this.radius += delta;
  3198. }
  3199. return this;
  3200. }
  3201. union( sphere ) {
  3202. if ( sphere.isEmpty() ) {
  3203. return this;
  3204. }
  3205. if ( this.isEmpty() ) {
  3206. this.copy( sphere );
  3207. return this;
  3208. }
  3209. if ( this.center.equals( sphere.center ) === true ) {
  3210. this.radius = Math.max( this.radius, sphere.radius );
  3211. } else {
  3212. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3213. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3214. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3215. }
  3216. return this;
  3217. }
  3218. equals( sphere ) {
  3219. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3220. }
  3221. clone() {
  3222. return new this.constructor().copy( this );
  3223. }
  3224. }
  3225. const _vector$a = /*@__PURE__*/ new Vector3();
  3226. const _segCenter = /*@__PURE__*/ new Vector3();
  3227. const _segDir = /*@__PURE__*/ new Vector3();
  3228. const _diff = /*@__PURE__*/ new Vector3();
  3229. const _edge1 = /*@__PURE__*/ new Vector3();
  3230. const _edge2 = /*@__PURE__*/ new Vector3();
  3231. const _normal$2 = /*@__PURE__*/ new Vector3();
  3232. class Ray {
  3233. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3234. this.origin = origin;
  3235. this.direction = direction;
  3236. }
  3237. set( origin, direction ) {
  3238. this.origin.copy( origin );
  3239. this.direction.copy( direction );
  3240. return this;
  3241. }
  3242. copy( ray ) {
  3243. this.origin.copy( ray.origin );
  3244. this.direction.copy( ray.direction );
  3245. return this;
  3246. }
  3247. at( t, target ) {
  3248. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3249. }
  3250. lookAt( v ) {
  3251. this.direction.copy( v ).sub( this.origin ).normalize();
  3252. return this;
  3253. }
  3254. recast( t ) {
  3255. this.origin.copy( this.at( t, _vector$a ) );
  3256. return this;
  3257. }
  3258. closestPointToPoint( point, target ) {
  3259. target.subVectors( point, this.origin );
  3260. const directionDistance = target.dot( this.direction );
  3261. if ( directionDistance < 0 ) {
  3262. return target.copy( this.origin );
  3263. }
  3264. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3265. }
  3266. distanceToPoint( point ) {
  3267. return Math.sqrt( this.distanceSqToPoint( point ) );
  3268. }
  3269. distanceSqToPoint( point ) {
  3270. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3271. // point behind the ray
  3272. if ( directionDistance < 0 ) {
  3273. return this.origin.distanceToSquared( point );
  3274. }
  3275. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3276. return _vector$a.distanceToSquared( point );
  3277. }
  3278. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3279. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3280. // It returns the min distance between the ray and the segment
  3281. // defined by v0 and v1
  3282. // It can also set two optional targets :
  3283. // - The closest point on the ray
  3284. // - The closest point on the segment
  3285. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3286. _segDir.copy( v1 ).sub( v0 ).normalize();
  3287. _diff.copy( this.origin ).sub( _segCenter );
  3288. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3289. const a01 = - this.direction.dot( _segDir );
  3290. const b0 = _diff.dot( this.direction );
  3291. const b1 = - _diff.dot( _segDir );
  3292. const c = _diff.lengthSq();
  3293. const det = Math.abs( 1 - a01 * a01 );
  3294. let s0, s1, sqrDist, extDet;
  3295. if ( det > 0 ) {
  3296. // The ray and segment are not parallel.
  3297. s0 = a01 * b1 - b0;
  3298. s1 = a01 * b0 - b1;
  3299. extDet = segExtent * det;
  3300. if ( s0 >= 0 ) {
  3301. if ( s1 >= - extDet ) {
  3302. if ( s1 <= extDet ) {
  3303. // region 0
  3304. // Minimum at interior points of ray and segment.
  3305. const invDet = 1 / det;
  3306. s0 *= invDet;
  3307. s1 *= invDet;
  3308. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3309. } else {
  3310. // region 1
  3311. s1 = segExtent;
  3312. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3313. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3314. }
  3315. } else {
  3316. // region 5
  3317. s1 = - segExtent;
  3318. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3319. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3320. }
  3321. } else {
  3322. if ( s1 <= - extDet ) {
  3323. // region 4
  3324. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3325. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3326. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3327. } else if ( s1 <= extDet ) {
  3328. // region 3
  3329. s0 = 0;
  3330. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3331. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3332. } else {
  3333. // region 2
  3334. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3335. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3337. }
  3338. }
  3339. } else {
  3340. // Ray and segment are parallel.
  3341. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3342. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3344. }
  3345. if ( optionalPointOnRay ) {
  3346. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3347. }
  3348. if ( optionalPointOnSegment ) {
  3349. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3350. }
  3351. return sqrDist;
  3352. }
  3353. intersectSphere( sphere, target ) {
  3354. _vector$a.subVectors( sphere.center, this.origin );
  3355. const tca = _vector$a.dot( this.direction );
  3356. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3357. const radius2 = sphere.radius * sphere.radius;
  3358. if ( d2 > radius2 ) return null;
  3359. const thc = Math.sqrt( radius2 - d2 );
  3360. // t0 = first intersect point - entrance on front of sphere
  3361. const t0 = tca - thc;
  3362. // t1 = second intersect point - exit point on back of sphere
  3363. const t1 = tca + thc;
  3364. // test to see if t1 is behind the ray - if so, return null
  3365. if ( t1 < 0 ) return null;
  3366. // test to see if t0 is behind the ray:
  3367. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3368. // in order to always return an intersect point that is in front of the ray.
  3369. if ( t0 < 0 ) return this.at( t1, target );
  3370. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3371. return this.at( t0, target );
  3372. }
  3373. intersectsSphere( sphere ) {
  3374. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3375. }
  3376. distanceToPlane( plane ) {
  3377. const denominator = plane.normal.dot( this.direction );
  3378. if ( denominator === 0 ) {
  3379. // line is coplanar, return origin
  3380. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3381. return 0;
  3382. }
  3383. // Null is preferable to undefined since undefined means.... it is undefined
  3384. return null;
  3385. }
  3386. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3387. // Return if the ray never intersects the plane
  3388. return t >= 0 ? t : null;
  3389. }
  3390. intersectPlane( plane, target ) {
  3391. const t = this.distanceToPlane( plane );
  3392. if ( t === null ) {
  3393. return null;
  3394. }
  3395. return this.at( t, target );
  3396. }
  3397. intersectsPlane( plane ) {
  3398. // check if the ray lies on the plane first
  3399. const distToPoint = plane.distanceToPoint( this.origin );
  3400. if ( distToPoint === 0 ) {
  3401. return true;
  3402. }
  3403. const denominator = plane.normal.dot( this.direction );
  3404. if ( denominator * distToPoint < 0 ) {
  3405. return true;
  3406. }
  3407. // ray origin is behind the plane (and is pointing behind it)
  3408. return false;
  3409. }
  3410. intersectBox( box, target ) {
  3411. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3412. const invdirx = 1 / this.direction.x,
  3413. invdiry = 1 / this.direction.y,
  3414. invdirz = 1 / this.direction.z;
  3415. const origin = this.origin;
  3416. if ( invdirx >= 0 ) {
  3417. tmin = ( box.min.x - origin.x ) * invdirx;
  3418. tmax = ( box.max.x - origin.x ) * invdirx;
  3419. } else {
  3420. tmin = ( box.max.x - origin.x ) * invdirx;
  3421. tmax = ( box.min.x - origin.x ) * invdirx;
  3422. }
  3423. if ( invdiry >= 0 ) {
  3424. tymin = ( box.min.y - origin.y ) * invdiry;
  3425. tymax = ( box.max.y - origin.y ) * invdiry;
  3426. } else {
  3427. tymin = ( box.max.y - origin.y ) * invdiry;
  3428. tymax = ( box.min.y - origin.y ) * invdiry;
  3429. }
  3430. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3431. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3432. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3433. if ( invdirz >= 0 ) {
  3434. tzmin = ( box.min.z - origin.z ) * invdirz;
  3435. tzmax = ( box.max.z - origin.z ) * invdirz;
  3436. } else {
  3437. tzmin = ( box.max.z - origin.z ) * invdirz;
  3438. tzmax = ( box.min.z - origin.z ) * invdirz;
  3439. }
  3440. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3441. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3442. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3443. //return point closest to the ray (positive side)
  3444. if ( tmax < 0 ) return null;
  3445. return this.at( tmin >= 0 ? tmin : tmax, target );
  3446. }
  3447. intersectsBox( box ) {
  3448. return this.intersectBox( box, _vector$a ) !== null;
  3449. }
  3450. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3451. // Compute the offset origin, edges, and normal.
  3452. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3453. _edge1.subVectors( b, a );
  3454. _edge2.subVectors( c, a );
  3455. _normal$2.crossVectors( _edge1, _edge2 );
  3456. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3457. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3458. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3459. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3460. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3461. let DdN = this.direction.dot( _normal$2 );
  3462. let sign;
  3463. if ( DdN > 0 ) {
  3464. if ( backfaceCulling ) return null;
  3465. sign = 1;
  3466. } else if ( DdN < 0 ) {
  3467. sign = - 1;
  3468. DdN = - DdN;
  3469. } else {
  3470. return null;
  3471. }
  3472. _diff.subVectors( this.origin, a );
  3473. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3474. // b1 < 0, no intersection
  3475. if ( DdQxE2 < 0 ) {
  3476. return null;
  3477. }
  3478. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3479. // b2 < 0, no intersection
  3480. if ( DdE1xQ < 0 ) {
  3481. return null;
  3482. }
  3483. // b1+b2 > 1, no intersection
  3484. if ( DdQxE2 + DdE1xQ > DdN ) {
  3485. return null;
  3486. }
  3487. // Line intersects triangle, check if ray does.
  3488. const QdN = - sign * _diff.dot( _normal$2 );
  3489. // t < 0, no intersection
  3490. if ( QdN < 0 ) {
  3491. return null;
  3492. }
  3493. // Ray intersects triangle.
  3494. return this.at( QdN / DdN, target );
  3495. }
  3496. applyMatrix4( matrix4 ) {
  3497. this.origin.applyMatrix4( matrix4 );
  3498. this.direction.transformDirection( matrix4 );
  3499. return this;
  3500. }
  3501. equals( ray ) {
  3502. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3503. }
  3504. clone() {
  3505. return new this.constructor().copy( this );
  3506. }
  3507. }
  3508. class Matrix4 {
  3509. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3510. Matrix4.prototype.isMatrix4 = true;
  3511. this.elements = [
  3512. 1, 0, 0, 0,
  3513. 0, 1, 0, 0,
  3514. 0, 0, 1, 0,
  3515. 0, 0, 0, 1
  3516. ];
  3517. if ( n11 !== undefined ) {
  3518. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3519. }
  3520. }
  3521. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3522. const te = this.elements;
  3523. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3524. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3525. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3526. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3527. return this;
  3528. }
  3529. identity() {
  3530. this.set(
  3531. 1, 0, 0, 0,
  3532. 0, 1, 0, 0,
  3533. 0, 0, 1, 0,
  3534. 0, 0, 0, 1
  3535. );
  3536. return this;
  3537. }
  3538. clone() {
  3539. return new Matrix4().fromArray( this.elements );
  3540. }
  3541. copy( m ) {
  3542. const te = this.elements;
  3543. const me = m.elements;
  3544. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3545. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3546. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3547. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3548. return this;
  3549. }
  3550. copyPosition( m ) {
  3551. const te = this.elements, me = m.elements;
  3552. te[ 12 ] = me[ 12 ];
  3553. te[ 13 ] = me[ 13 ];
  3554. te[ 14 ] = me[ 14 ];
  3555. return this;
  3556. }
  3557. setFromMatrix3( m ) {
  3558. const me = m.elements;
  3559. this.set(
  3560. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3561. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3562. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3563. 0, 0, 0, 1
  3564. );
  3565. return this;
  3566. }
  3567. extractBasis( xAxis, yAxis, zAxis ) {
  3568. xAxis.setFromMatrixColumn( this, 0 );
  3569. yAxis.setFromMatrixColumn( this, 1 );
  3570. zAxis.setFromMatrixColumn( this, 2 );
  3571. return this;
  3572. }
  3573. makeBasis( xAxis, yAxis, zAxis ) {
  3574. this.set(
  3575. xAxis.x, yAxis.x, zAxis.x, 0,
  3576. xAxis.y, yAxis.y, zAxis.y, 0,
  3577. xAxis.z, yAxis.z, zAxis.z, 0,
  3578. 0, 0, 0, 1
  3579. );
  3580. return this;
  3581. }
  3582. extractRotation( m ) {
  3583. // this method does not support reflection matrices
  3584. const te = this.elements;
  3585. const me = m.elements;
  3586. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3587. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3588. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3589. te[ 0 ] = me[ 0 ] * scaleX;
  3590. te[ 1 ] = me[ 1 ] * scaleX;
  3591. te[ 2 ] = me[ 2 ] * scaleX;
  3592. te[ 3 ] = 0;
  3593. te[ 4 ] = me[ 4 ] * scaleY;
  3594. te[ 5 ] = me[ 5 ] * scaleY;
  3595. te[ 6 ] = me[ 6 ] * scaleY;
  3596. te[ 7 ] = 0;
  3597. te[ 8 ] = me[ 8 ] * scaleZ;
  3598. te[ 9 ] = me[ 9 ] * scaleZ;
  3599. te[ 10 ] = me[ 10 ] * scaleZ;
  3600. te[ 11 ] = 0;
  3601. te[ 12 ] = 0;
  3602. te[ 13 ] = 0;
  3603. te[ 14 ] = 0;
  3604. te[ 15 ] = 1;
  3605. return this;
  3606. }
  3607. makeRotationFromEuler( euler ) {
  3608. const te = this.elements;
  3609. const x = euler.x, y = euler.y, z = euler.z;
  3610. const a = Math.cos( x ), b = Math.sin( x );
  3611. const c = Math.cos( y ), d = Math.sin( y );
  3612. const e = Math.cos( z ), f = Math.sin( z );
  3613. if ( euler.order === 'XYZ' ) {
  3614. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3615. te[ 0 ] = c * e;
  3616. te[ 4 ] = - c * f;
  3617. te[ 8 ] = d;
  3618. te[ 1 ] = af + be * d;
  3619. te[ 5 ] = ae - bf * d;
  3620. te[ 9 ] = - b * c;
  3621. te[ 2 ] = bf - ae * d;
  3622. te[ 6 ] = be + af * d;
  3623. te[ 10 ] = a * c;
  3624. } else if ( euler.order === 'YXZ' ) {
  3625. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3626. te[ 0 ] = ce + df * b;
  3627. te[ 4 ] = de * b - cf;
  3628. te[ 8 ] = a * d;
  3629. te[ 1 ] = a * f;
  3630. te[ 5 ] = a * e;
  3631. te[ 9 ] = - b;
  3632. te[ 2 ] = cf * b - de;
  3633. te[ 6 ] = df + ce * b;
  3634. te[ 10 ] = a * c;
  3635. } else if ( euler.order === 'ZXY' ) {
  3636. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3637. te[ 0 ] = ce - df * b;
  3638. te[ 4 ] = - a * f;
  3639. te[ 8 ] = de + cf * b;
  3640. te[ 1 ] = cf + de * b;
  3641. te[ 5 ] = a * e;
  3642. te[ 9 ] = df - ce * b;
  3643. te[ 2 ] = - a * d;
  3644. te[ 6 ] = b;
  3645. te[ 10 ] = a * c;
  3646. } else if ( euler.order === 'ZYX' ) {
  3647. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3648. te[ 0 ] = c * e;
  3649. te[ 4 ] = be * d - af;
  3650. te[ 8 ] = ae * d + bf;
  3651. te[ 1 ] = c * f;
  3652. te[ 5 ] = bf * d + ae;
  3653. te[ 9 ] = af * d - be;
  3654. te[ 2 ] = - d;
  3655. te[ 6 ] = b * c;
  3656. te[ 10 ] = a * c;
  3657. } else if ( euler.order === 'YZX' ) {
  3658. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3659. te[ 0 ] = c * e;
  3660. te[ 4 ] = bd - ac * f;
  3661. te[ 8 ] = bc * f + ad;
  3662. te[ 1 ] = f;
  3663. te[ 5 ] = a * e;
  3664. te[ 9 ] = - b * e;
  3665. te[ 2 ] = - d * e;
  3666. te[ 6 ] = ad * f + bc;
  3667. te[ 10 ] = ac - bd * f;
  3668. } else if ( euler.order === 'XZY' ) {
  3669. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3670. te[ 0 ] = c * e;
  3671. te[ 4 ] = - f;
  3672. te[ 8 ] = d * e;
  3673. te[ 1 ] = ac * f + bd;
  3674. te[ 5 ] = a * e;
  3675. te[ 9 ] = ad * f - bc;
  3676. te[ 2 ] = bc * f - ad;
  3677. te[ 6 ] = b * e;
  3678. te[ 10 ] = bd * f + ac;
  3679. }
  3680. // bottom row
  3681. te[ 3 ] = 0;
  3682. te[ 7 ] = 0;
  3683. te[ 11 ] = 0;
  3684. // last column
  3685. te[ 12 ] = 0;
  3686. te[ 13 ] = 0;
  3687. te[ 14 ] = 0;
  3688. te[ 15 ] = 1;
  3689. return this;
  3690. }
  3691. makeRotationFromQuaternion( q ) {
  3692. return this.compose( _zero, q, _one );
  3693. }
  3694. lookAt( eye, target, up ) {
  3695. const te = this.elements;
  3696. _z.subVectors( eye, target );
  3697. if ( _z.lengthSq() === 0 ) {
  3698. // eye and target are in the same position
  3699. _z.z = 1;
  3700. }
  3701. _z.normalize();
  3702. _x.crossVectors( up, _z );
  3703. if ( _x.lengthSq() === 0 ) {
  3704. // up and z are parallel
  3705. if ( Math.abs( up.z ) === 1 ) {
  3706. _z.x += 0.0001;
  3707. } else {
  3708. _z.z += 0.0001;
  3709. }
  3710. _z.normalize();
  3711. _x.crossVectors( up, _z );
  3712. }
  3713. _x.normalize();
  3714. _y.crossVectors( _z, _x );
  3715. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3716. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3717. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3718. return this;
  3719. }
  3720. multiply( m ) {
  3721. return this.multiplyMatrices( this, m );
  3722. }
  3723. premultiply( m ) {
  3724. return this.multiplyMatrices( m, this );
  3725. }
  3726. multiplyMatrices( a, b ) {
  3727. const ae = a.elements;
  3728. const be = b.elements;
  3729. const te = this.elements;
  3730. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3731. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3732. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3733. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3734. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3735. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3736. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3737. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3738. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3739. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3740. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3741. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3742. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3743. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3744. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3745. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3746. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3747. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3748. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3749. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3750. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3751. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3752. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3753. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3754. return this;
  3755. }
  3756. multiplyScalar( s ) {
  3757. const te = this.elements;
  3758. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3759. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3760. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3761. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3762. return this;
  3763. }
  3764. determinant() {
  3765. const te = this.elements;
  3766. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3767. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3768. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3769. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3770. //TODO: make this more efficient
  3771. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3772. return (
  3773. n41 * (
  3774. + n14 * n23 * n32
  3775. - n13 * n24 * n32
  3776. - n14 * n22 * n33
  3777. + n12 * n24 * n33
  3778. + n13 * n22 * n34
  3779. - n12 * n23 * n34
  3780. ) +
  3781. n42 * (
  3782. + n11 * n23 * n34
  3783. - n11 * n24 * n33
  3784. + n14 * n21 * n33
  3785. - n13 * n21 * n34
  3786. + n13 * n24 * n31
  3787. - n14 * n23 * n31
  3788. ) +
  3789. n43 * (
  3790. + n11 * n24 * n32
  3791. - n11 * n22 * n34
  3792. - n14 * n21 * n32
  3793. + n12 * n21 * n34
  3794. + n14 * n22 * n31
  3795. - n12 * n24 * n31
  3796. ) +
  3797. n44 * (
  3798. - n13 * n22 * n31
  3799. - n11 * n23 * n32
  3800. + n11 * n22 * n33
  3801. + n13 * n21 * n32
  3802. - n12 * n21 * n33
  3803. + n12 * n23 * n31
  3804. )
  3805. );
  3806. }
  3807. transpose() {
  3808. const te = this.elements;
  3809. let tmp;
  3810. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3811. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3812. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3813. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3814. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3815. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3816. return this;
  3817. }
  3818. setPosition( x, y, z ) {
  3819. const te = this.elements;
  3820. if ( x.isVector3 ) {
  3821. te[ 12 ] = x.x;
  3822. te[ 13 ] = x.y;
  3823. te[ 14 ] = x.z;
  3824. } else {
  3825. te[ 12 ] = x;
  3826. te[ 13 ] = y;
  3827. te[ 14 ] = z;
  3828. }
  3829. return this;
  3830. }
  3831. invert() {
  3832. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3833. const te = this.elements,
  3834. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3835. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3836. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3837. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3838. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3839. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3840. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3841. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3842. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3843. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3844. const detInv = 1 / det;
  3845. te[ 0 ] = t11 * detInv;
  3846. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3847. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3848. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3849. te[ 4 ] = t12 * detInv;
  3850. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3851. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3852. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3853. te[ 8 ] = t13 * detInv;
  3854. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3855. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3856. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3857. te[ 12 ] = t14 * detInv;
  3858. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3859. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3860. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3861. return this;
  3862. }
  3863. scale( v ) {
  3864. const te = this.elements;
  3865. const x = v.x, y = v.y, z = v.z;
  3866. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3867. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3868. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3869. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3870. return this;
  3871. }
  3872. getMaxScaleOnAxis() {
  3873. const te = this.elements;
  3874. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3875. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3876. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3877. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3878. }
  3879. makeTranslation( x, y, z ) {
  3880. if ( x.isVector3 ) {
  3881. this.set(
  3882. 1, 0, 0, x.x,
  3883. 0, 1, 0, x.y,
  3884. 0, 0, 1, x.z,
  3885. 0, 0, 0, 1
  3886. );
  3887. } else {
  3888. this.set(
  3889. 1, 0, 0, x,
  3890. 0, 1, 0, y,
  3891. 0, 0, 1, z,
  3892. 0, 0, 0, 1
  3893. );
  3894. }
  3895. return this;
  3896. }
  3897. makeRotationX( theta ) {
  3898. const c = Math.cos( theta ), s = Math.sin( theta );
  3899. this.set(
  3900. 1, 0, 0, 0,
  3901. 0, c, - s, 0,
  3902. 0, s, c, 0,
  3903. 0, 0, 0, 1
  3904. );
  3905. return this;
  3906. }
  3907. makeRotationY( theta ) {
  3908. const c = Math.cos( theta ), s = Math.sin( theta );
  3909. this.set(
  3910. c, 0, s, 0,
  3911. 0, 1, 0, 0,
  3912. - s, 0, c, 0,
  3913. 0, 0, 0, 1
  3914. );
  3915. return this;
  3916. }
  3917. makeRotationZ( theta ) {
  3918. const c = Math.cos( theta ), s = Math.sin( theta );
  3919. this.set(
  3920. c, - s, 0, 0,
  3921. s, c, 0, 0,
  3922. 0, 0, 1, 0,
  3923. 0, 0, 0, 1
  3924. );
  3925. return this;
  3926. }
  3927. makeRotationAxis( axis, angle ) {
  3928. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3929. const c = Math.cos( angle );
  3930. const s = Math.sin( angle );
  3931. const t = 1 - c;
  3932. const x = axis.x, y = axis.y, z = axis.z;
  3933. const tx = t * x, ty = t * y;
  3934. this.set(
  3935. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3936. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3937. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3938. 0, 0, 0, 1
  3939. );
  3940. return this;
  3941. }
  3942. makeScale( x, y, z ) {
  3943. this.set(
  3944. x, 0, 0, 0,
  3945. 0, y, 0, 0,
  3946. 0, 0, z, 0,
  3947. 0, 0, 0, 1
  3948. );
  3949. return this;
  3950. }
  3951. makeShear( xy, xz, yx, yz, zx, zy ) {
  3952. this.set(
  3953. 1, yx, zx, 0,
  3954. xy, 1, zy, 0,
  3955. xz, yz, 1, 0,
  3956. 0, 0, 0, 1
  3957. );
  3958. return this;
  3959. }
  3960. compose( position, quaternion, scale ) {
  3961. const te = this.elements;
  3962. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3963. const x2 = x + x, y2 = y + y, z2 = z + z;
  3964. const xx = x * x2, xy = x * y2, xz = x * z2;
  3965. const yy = y * y2, yz = y * z2, zz = z * z2;
  3966. const wx = w * x2, wy = w * y2, wz = w * z2;
  3967. const sx = scale.x, sy = scale.y, sz = scale.z;
  3968. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3969. te[ 1 ] = ( xy + wz ) * sx;
  3970. te[ 2 ] = ( xz - wy ) * sx;
  3971. te[ 3 ] = 0;
  3972. te[ 4 ] = ( xy - wz ) * sy;
  3973. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3974. te[ 6 ] = ( yz + wx ) * sy;
  3975. te[ 7 ] = 0;
  3976. te[ 8 ] = ( xz + wy ) * sz;
  3977. te[ 9 ] = ( yz - wx ) * sz;
  3978. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3979. te[ 11 ] = 0;
  3980. te[ 12 ] = position.x;
  3981. te[ 13 ] = position.y;
  3982. te[ 14 ] = position.z;
  3983. te[ 15 ] = 1;
  3984. return this;
  3985. }
  3986. decompose( position, quaternion, scale ) {
  3987. const te = this.elements;
  3988. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3989. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3990. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3991. // if determine is negative, we need to invert one scale
  3992. const det = this.determinant();
  3993. if ( det < 0 ) sx = - sx;
  3994. position.x = te[ 12 ];
  3995. position.y = te[ 13 ];
  3996. position.z = te[ 14 ];
  3997. // scale the rotation part
  3998. _m1$2.copy( this );
  3999. const invSX = 1 / sx;
  4000. const invSY = 1 / sy;
  4001. const invSZ = 1 / sz;
  4002. _m1$2.elements[ 0 ] *= invSX;
  4003. _m1$2.elements[ 1 ] *= invSX;
  4004. _m1$2.elements[ 2 ] *= invSX;
  4005. _m1$2.elements[ 4 ] *= invSY;
  4006. _m1$2.elements[ 5 ] *= invSY;
  4007. _m1$2.elements[ 6 ] *= invSY;
  4008. _m1$2.elements[ 8 ] *= invSZ;
  4009. _m1$2.elements[ 9 ] *= invSZ;
  4010. _m1$2.elements[ 10 ] *= invSZ;
  4011. quaternion.setFromRotationMatrix( _m1$2 );
  4012. scale.x = sx;
  4013. scale.y = sy;
  4014. scale.z = sz;
  4015. return this;
  4016. }
  4017. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4018. const te = this.elements;
  4019. const x = 2 * near / ( right - left );
  4020. const y = 2 * near / ( top - bottom );
  4021. const a = ( right + left ) / ( right - left );
  4022. const b = ( top + bottom ) / ( top - bottom );
  4023. let c, d;
  4024. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4025. c = - ( far + near ) / ( far - near );
  4026. d = ( - 2 * far * near ) / ( far - near );
  4027. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4028. c = - far / ( far - near );
  4029. d = ( - far * near ) / ( far - near );
  4030. } else {
  4031. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4032. }
  4033. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4034. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4035. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4036. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4037. return this;
  4038. }
  4039. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4040. const te = this.elements;
  4041. const w = 1.0 / ( right - left );
  4042. const h = 1.0 / ( top - bottom );
  4043. const p = 1.0 / ( far - near );
  4044. const x = ( right + left ) * w;
  4045. const y = ( top + bottom ) * h;
  4046. let z, zInv;
  4047. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4048. z = ( far + near ) * p;
  4049. zInv = - 2 * p;
  4050. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4051. z = near * p;
  4052. zInv = - 1 * p;
  4053. } else {
  4054. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4055. }
  4056. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4057. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4058. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4059. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4060. return this;
  4061. }
  4062. equals( matrix ) {
  4063. const te = this.elements;
  4064. const me = matrix.elements;
  4065. for ( let i = 0; i < 16; i ++ ) {
  4066. if ( te[ i ] !== me[ i ] ) return false;
  4067. }
  4068. return true;
  4069. }
  4070. fromArray( array, offset = 0 ) {
  4071. for ( let i = 0; i < 16; i ++ ) {
  4072. this.elements[ i ] = array[ i + offset ];
  4073. }
  4074. return this;
  4075. }
  4076. toArray( array = [], offset = 0 ) {
  4077. const te = this.elements;
  4078. array[ offset ] = te[ 0 ];
  4079. array[ offset + 1 ] = te[ 1 ];
  4080. array[ offset + 2 ] = te[ 2 ];
  4081. array[ offset + 3 ] = te[ 3 ];
  4082. array[ offset + 4 ] = te[ 4 ];
  4083. array[ offset + 5 ] = te[ 5 ];
  4084. array[ offset + 6 ] = te[ 6 ];
  4085. array[ offset + 7 ] = te[ 7 ];
  4086. array[ offset + 8 ] = te[ 8 ];
  4087. array[ offset + 9 ] = te[ 9 ];
  4088. array[ offset + 10 ] = te[ 10 ];
  4089. array[ offset + 11 ] = te[ 11 ];
  4090. array[ offset + 12 ] = te[ 12 ];
  4091. array[ offset + 13 ] = te[ 13 ];
  4092. array[ offset + 14 ] = te[ 14 ];
  4093. array[ offset + 15 ] = te[ 15 ];
  4094. return array;
  4095. }
  4096. }
  4097. const _v1$5 = /*@__PURE__*/ new Vector3();
  4098. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4099. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4100. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4101. const _x = /*@__PURE__*/ new Vector3();
  4102. const _y = /*@__PURE__*/ new Vector3();
  4103. const _z = /*@__PURE__*/ new Vector3();
  4104. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4105. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4106. class Euler {
  4107. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4108. this.isEuler = true;
  4109. this._x = x;
  4110. this._y = y;
  4111. this._z = z;
  4112. this._order = order;
  4113. }
  4114. get x() {
  4115. return this._x;
  4116. }
  4117. set x( value ) {
  4118. this._x = value;
  4119. this._onChangeCallback();
  4120. }
  4121. get y() {
  4122. return this._y;
  4123. }
  4124. set y( value ) {
  4125. this._y = value;
  4126. this._onChangeCallback();
  4127. }
  4128. get z() {
  4129. return this._z;
  4130. }
  4131. set z( value ) {
  4132. this._z = value;
  4133. this._onChangeCallback();
  4134. }
  4135. get order() {
  4136. return this._order;
  4137. }
  4138. set order( value ) {
  4139. this._order = value;
  4140. this._onChangeCallback();
  4141. }
  4142. set( x, y, z, order = this._order ) {
  4143. this._x = x;
  4144. this._y = y;
  4145. this._z = z;
  4146. this._order = order;
  4147. this._onChangeCallback();
  4148. return this;
  4149. }
  4150. clone() {
  4151. return new this.constructor( this._x, this._y, this._z, this._order );
  4152. }
  4153. copy( euler ) {
  4154. this._x = euler._x;
  4155. this._y = euler._y;
  4156. this._z = euler._z;
  4157. this._order = euler._order;
  4158. this._onChangeCallback();
  4159. return this;
  4160. }
  4161. setFromRotationMatrix( m, order = this._order, update = true ) {
  4162. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4163. const te = m.elements;
  4164. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4165. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4166. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4167. switch ( order ) {
  4168. case 'XYZ':
  4169. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4170. if ( Math.abs( m13 ) < 0.9999999 ) {
  4171. this._x = Math.atan2( - m23, m33 );
  4172. this._z = Math.atan2( - m12, m11 );
  4173. } else {
  4174. this._x = Math.atan2( m32, m22 );
  4175. this._z = 0;
  4176. }
  4177. break;
  4178. case 'YXZ':
  4179. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4180. if ( Math.abs( m23 ) < 0.9999999 ) {
  4181. this._y = Math.atan2( m13, m33 );
  4182. this._z = Math.atan2( m21, m22 );
  4183. } else {
  4184. this._y = Math.atan2( - m31, m11 );
  4185. this._z = 0;
  4186. }
  4187. break;
  4188. case 'ZXY':
  4189. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4190. if ( Math.abs( m32 ) < 0.9999999 ) {
  4191. this._y = Math.atan2( - m31, m33 );
  4192. this._z = Math.atan2( - m12, m22 );
  4193. } else {
  4194. this._y = 0;
  4195. this._z = Math.atan2( m21, m11 );
  4196. }
  4197. break;
  4198. case 'ZYX':
  4199. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4200. if ( Math.abs( m31 ) < 0.9999999 ) {
  4201. this._x = Math.atan2( m32, m33 );
  4202. this._z = Math.atan2( m21, m11 );
  4203. } else {
  4204. this._x = 0;
  4205. this._z = Math.atan2( - m12, m22 );
  4206. }
  4207. break;
  4208. case 'YZX':
  4209. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4210. if ( Math.abs( m21 ) < 0.9999999 ) {
  4211. this._x = Math.atan2( - m23, m22 );
  4212. this._y = Math.atan2( - m31, m11 );
  4213. } else {
  4214. this._x = 0;
  4215. this._y = Math.atan2( m13, m33 );
  4216. }
  4217. break;
  4218. case 'XZY':
  4219. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4220. if ( Math.abs( m12 ) < 0.9999999 ) {
  4221. this._x = Math.atan2( m32, m22 );
  4222. this._y = Math.atan2( m13, m11 );
  4223. } else {
  4224. this._x = Math.atan2( - m23, m33 );
  4225. this._y = 0;
  4226. }
  4227. break;
  4228. default:
  4229. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4230. }
  4231. this._order = order;
  4232. if ( update === true ) this._onChangeCallback();
  4233. return this;
  4234. }
  4235. setFromQuaternion( q, order, update ) {
  4236. _matrix$2.makeRotationFromQuaternion( q );
  4237. return this.setFromRotationMatrix( _matrix$2, order, update );
  4238. }
  4239. setFromVector3( v, order = this._order ) {
  4240. return this.set( v.x, v.y, v.z, order );
  4241. }
  4242. reorder( newOrder ) {
  4243. // WARNING: this discards revolution information -bhouston
  4244. _quaternion$3.setFromEuler( this );
  4245. return this.setFromQuaternion( _quaternion$3, newOrder );
  4246. }
  4247. equals( euler ) {
  4248. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4249. }
  4250. fromArray( array ) {
  4251. this._x = array[ 0 ];
  4252. this._y = array[ 1 ];
  4253. this._z = array[ 2 ];
  4254. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4255. this._onChangeCallback();
  4256. return this;
  4257. }
  4258. toArray( array = [], offset = 0 ) {
  4259. array[ offset ] = this._x;
  4260. array[ offset + 1 ] = this._y;
  4261. array[ offset + 2 ] = this._z;
  4262. array[ offset + 3 ] = this._order;
  4263. return array;
  4264. }
  4265. _onChange( callback ) {
  4266. this._onChangeCallback = callback;
  4267. return this;
  4268. }
  4269. _onChangeCallback() {}
  4270. *[ Symbol.iterator ]() {
  4271. yield this._x;
  4272. yield this._y;
  4273. yield this._z;
  4274. yield this._order;
  4275. }
  4276. }
  4277. Euler.DEFAULT_ORDER = 'XYZ';
  4278. class Layers {
  4279. constructor() {
  4280. this.mask = 1 | 0;
  4281. }
  4282. set( channel ) {
  4283. this.mask = ( 1 << channel | 0 ) >>> 0;
  4284. }
  4285. enable( channel ) {
  4286. this.mask |= 1 << channel | 0;
  4287. }
  4288. enableAll() {
  4289. this.mask = 0xffffffff | 0;
  4290. }
  4291. toggle( channel ) {
  4292. this.mask ^= 1 << channel | 0;
  4293. }
  4294. disable( channel ) {
  4295. this.mask &= ~ ( 1 << channel | 0 );
  4296. }
  4297. disableAll() {
  4298. this.mask = 0;
  4299. }
  4300. test( layers ) {
  4301. return ( this.mask & layers.mask ) !== 0;
  4302. }
  4303. isEnabled( channel ) {
  4304. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4305. }
  4306. }
  4307. let _object3DId = 0;
  4308. const _v1$4 = /*@__PURE__*/ new Vector3();
  4309. const _q1 = /*@__PURE__*/ new Quaternion();
  4310. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4311. const _target$1 = /*@__PURE__*/ new Vector3();
  4312. const _position$3 = /*@__PURE__*/ new Vector3();
  4313. const _scale$2 = /*@__PURE__*/ new Vector3();
  4314. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4315. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4316. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4317. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4318. const _addedEvent = { type: 'added' };
  4319. const _removedEvent = { type: 'removed' };
  4320. const _childaddedEvent = { type: 'childadded', child: null };
  4321. const _childremovedEvent = { type: 'childremoved', child: null };
  4322. class Object3D extends EventDispatcher {
  4323. constructor() {
  4324. super();
  4325. this.isObject3D = true;
  4326. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4327. this.uuid = generateUUID();
  4328. this.name = '';
  4329. this.type = 'Object3D';
  4330. this.parent = null;
  4331. this.children = [];
  4332. this.up = Object3D.DEFAULT_UP.clone();
  4333. const position = new Vector3();
  4334. const rotation = new Euler();
  4335. const quaternion = new Quaternion();
  4336. const scale = new Vector3( 1, 1, 1 );
  4337. function onRotationChange() {
  4338. quaternion.setFromEuler( rotation, false );
  4339. }
  4340. function onQuaternionChange() {
  4341. rotation.setFromQuaternion( quaternion, undefined, false );
  4342. }
  4343. rotation._onChange( onRotationChange );
  4344. quaternion._onChange( onQuaternionChange );
  4345. Object.defineProperties( this, {
  4346. position: {
  4347. configurable: true,
  4348. enumerable: true,
  4349. value: position
  4350. },
  4351. rotation: {
  4352. configurable: true,
  4353. enumerable: true,
  4354. value: rotation
  4355. },
  4356. quaternion: {
  4357. configurable: true,
  4358. enumerable: true,
  4359. value: quaternion
  4360. },
  4361. scale: {
  4362. configurable: true,
  4363. enumerable: true,
  4364. value: scale
  4365. },
  4366. modelViewMatrix: {
  4367. value: new Matrix4()
  4368. },
  4369. normalMatrix: {
  4370. value: new Matrix3()
  4371. }
  4372. } );
  4373. this.matrix = new Matrix4();
  4374. this.matrixWorld = new Matrix4();
  4375. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4376. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4377. this.matrixWorldNeedsUpdate = false;
  4378. this.layers = new Layers();
  4379. this.visible = true;
  4380. this.castShadow = false;
  4381. this.receiveShadow = false;
  4382. this.frustumCulled = true;
  4383. this.renderOrder = 0;
  4384. this.animations = [];
  4385. this.userData = {};
  4386. }
  4387. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4388. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4389. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4390. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4391. applyMatrix4( matrix ) {
  4392. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4393. this.matrix.premultiply( matrix );
  4394. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4395. }
  4396. applyQuaternion( q ) {
  4397. this.quaternion.premultiply( q );
  4398. return this;
  4399. }
  4400. setRotationFromAxisAngle( axis, angle ) {
  4401. // assumes axis is normalized
  4402. this.quaternion.setFromAxisAngle( axis, angle );
  4403. }
  4404. setRotationFromEuler( euler ) {
  4405. this.quaternion.setFromEuler( euler, true );
  4406. }
  4407. setRotationFromMatrix( m ) {
  4408. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4409. this.quaternion.setFromRotationMatrix( m );
  4410. }
  4411. setRotationFromQuaternion( q ) {
  4412. // assumes q is normalized
  4413. this.quaternion.copy( q );
  4414. }
  4415. rotateOnAxis( axis, angle ) {
  4416. // rotate object on axis in object space
  4417. // axis is assumed to be normalized
  4418. _q1.setFromAxisAngle( axis, angle );
  4419. this.quaternion.multiply( _q1 );
  4420. return this;
  4421. }
  4422. rotateOnWorldAxis( axis, angle ) {
  4423. // rotate object on axis in world space
  4424. // axis is assumed to be normalized
  4425. // method assumes no rotated parent
  4426. _q1.setFromAxisAngle( axis, angle );
  4427. this.quaternion.premultiply( _q1 );
  4428. return this;
  4429. }
  4430. rotateX( angle ) {
  4431. return this.rotateOnAxis( _xAxis, angle );
  4432. }
  4433. rotateY( angle ) {
  4434. return this.rotateOnAxis( _yAxis, angle );
  4435. }
  4436. rotateZ( angle ) {
  4437. return this.rotateOnAxis( _zAxis, angle );
  4438. }
  4439. translateOnAxis( axis, distance ) {
  4440. // translate object by distance along axis in object space
  4441. // axis is assumed to be normalized
  4442. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4443. this.position.add( _v1$4.multiplyScalar( distance ) );
  4444. return this;
  4445. }
  4446. translateX( distance ) {
  4447. return this.translateOnAxis( _xAxis, distance );
  4448. }
  4449. translateY( distance ) {
  4450. return this.translateOnAxis( _yAxis, distance );
  4451. }
  4452. translateZ( distance ) {
  4453. return this.translateOnAxis( _zAxis, distance );
  4454. }
  4455. localToWorld( vector ) {
  4456. this.updateWorldMatrix( true, false );
  4457. return vector.applyMatrix4( this.matrixWorld );
  4458. }
  4459. worldToLocal( vector ) {
  4460. this.updateWorldMatrix( true, false );
  4461. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4462. }
  4463. lookAt( x, y, z ) {
  4464. // This method does not support objects having non-uniformly-scaled parent(s)
  4465. if ( x.isVector3 ) {
  4466. _target$1.copy( x );
  4467. } else {
  4468. _target$1.set( x, y, z );
  4469. }
  4470. const parent = this.parent;
  4471. this.updateWorldMatrix( true, false );
  4472. _position$3.setFromMatrixPosition( this.matrixWorld );
  4473. if ( this.isCamera || this.isLight ) {
  4474. _m1$1.lookAt( _position$3, _target$1, this.up );
  4475. } else {
  4476. _m1$1.lookAt( _target$1, _position$3, this.up );
  4477. }
  4478. this.quaternion.setFromRotationMatrix( _m1$1 );
  4479. if ( parent ) {
  4480. _m1$1.extractRotation( parent.matrixWorld );
  4481. _q1.setFromRotationMatrix( _m1$1 );
  4482. this.quaternion.premultiply( _q1.invert() );
  4483. }
  4484. }
  4485. add( object ) {
  4486. if ( arguments.length > 1 ) {
  4487. for ( let i = 0; i < arguments.length; i ++ ) {
  4488. this.add( arguments[ i ] );
  4489. }
  4490. return this;
  4491. }
  4492. if ( object === this ) {
  4493. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4494. return this;
  4495. }
  4496. if ( object && object.isObject3D ) {
  4497. object.removeFromParent();
  4498. object.parent = this;
  4499. this.children.push( object );
  4500. object.dispatchEvent( _addedEvent );
  4501. _childaddedEvent.child = object;
  4502. this.dispatchEvent( _childaddedEvent );
  4503. _childaddedEvent.child = null;
  4504. } else {
  4505. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4506. }
  4507. return this;
  4508. }
  4509. remove( object ) {
  4510. if ( arguments.length > 1 ) {
  4511. for ( let i = 0; i < arguments.length; i ++ ) {
  4512. this.remove( arguments[ i ] );
  4513. }
  4514. return this;
  4515. }
  4516. const index = this.children.indexOf( object );
  4517. if ( index !== - 1 ) {
  4518. object.parent = null;
  4519. this.children.splice( index, 1 );
  4520. object.dispatchEvent( _removedEvent );
  4521. _childremovedEvent.child = object;
  4522. this.dispatchEvent( _childremovedEvent );
  4523. _childremovedEvent.child = null;
  4524. }
  4525. return this;
  4526. }
  4527. removeFromParent() {
  4528. const parent = this.parent;
  4529. if ( parent !== null ) {
  4530. parent.remove( this );
  4531. }
  4532. return this;
  4533. }
  4534. clear() {
  4535. return this.remove( ... this.children );
  4536. }
  4537. attach( object ) {
  4538. // adds object as a child of this, while maintaining the object's world transform
  4539. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4540. this.updateWorldMatrix( true, false );
  4541. _m1$1.copy( this.matrixWorld ).invert();
  4542. if ( object.parent !== null ) {
  4543. object.parent.updateWorldMatrix( true, false );
  4544. _m1$1.multiply( object.parent.matrixWorld );
  4545. }
  4546. object.applyMatrix4( _m1$1 );
  4547. object.removeFromParent();
  4548. object.parent = this;
  4549. this.children.push( object );
  4550. object.updateWorldMatrix( false, true );
  4551. object.dispatchEvent( _addedEvent );
  4552. _childaddedEvent.child = object;
  4553. this.dispatchEvent( _childaddedEvent );
  4554. _childaddedEvent.child = null;
  4555. return this;
  4556. }
  4557. getObjectById( id ) {
  4558. return this.getObjectByProperty( 'id', id );
  4559. }
  4560. getObjectByName( name ) {
  4561. return this.getObjectByProperty( 'name', name );
  4562. }
  4563. getObjectByProperty( name, value ) {
  4564. if ( this[ name ] === value ) return this;
  4565. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4566. const child = this.children[ i ];
  4567. const object = child.getObjectByProperty( name, value );
  4568. if ( object !== undefined ) {
  4569. return object;
  4570. }
  4571. }
  4572. return undefined;
  4573. }
  4574. getObjectsByProperty( name, value, result = [] ) {
  4575. if ( this[ name ] === value ) result.push( this );
  4576. const children = this.children;
  4577. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4578. children[ i ].getObjectsByProperty( name, value, result );
  4579. }
  4580. return result;
  4581. }
  4582. getWorldPosition( target ) {
  4583. this.updateWorldMatrix( true, false );
  4584. return target.setFromMatrixPosition( this.matrixWorld );
  4585. }
  4586. getWorldQuaternion( target ) {
  4587. this.updateWorldMatrix( true, false );
  4588. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4589. return target;
  4590. }
  4591. getWorldScale( target ) {
  4592. this.updateWorldMatrix( true, false );
  4593. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4594. return target;
  4595. }
  4596. getWorldDirection( target ) {
  4597. this.updateWorldMatrix( true, false );
  4598. const e = this.matrixWorld.elements;
  4599. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4600. }
  4601. raycast( /* raycaster, intersects */ ) {}
  4602. traverse( callback ) {
  4603. callback( this );
  4604. const children = this.children;
  4605. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4606. children[ i ].traverse( callback );
  4607. }
  4608. }
  4609. traverseVisible( callback ) {
  4610. if ( this.visible === false ) return;
  4611. callback( this );
  4612. const children = this.children;
  4613. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4614. children[ i ].traverseVisible( callback );
  4615. }
  4616. }
  4617. traverseAncestors( callback ) {
  4618. const parent = this.parent;
  4619. if ( parent !== null ) {
  4620. callback( parent );
  4621. parent.traverseAncestors( callback );
  4622. }
  4623. }
  4624. updateMatrix() {
  4625. this.matrix.compose( this.position, this.quaternion, this.scale );
  4626. this.matrixWorldNeedsUpdate = true;
  4627. }
  4628. updateMatrixWorld( force ) {
  4629. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4630. if ( this.matrixWorldNeedsUpdate || force ) {
  4631. if ( this.matrixWorldAutoUpdate === true ) {
  4632. if ( this.parent === null ) {
  4633. this.matrixWorld.copy( this.matrix );
  4634. } else {
  4635. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4636. }
  4637. }
  4638. this.matrixWorldNeedsUpdate = false;
  4639. force = true;
  4640. }
  4641. // make sure descendants are updated if required
  4642. const children = this.children;
  4643. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4644. const child = children[ i ];
  4645. child.updateMatrixWorld( force );
  4646. }
  4647. }
  4648. updateWorldMatrix( updateParents, updateChildren ) {
  4649. const parent = this.parent;
  4650. if ( updateParents === true && parent !== null ) {
  4651. parent.updateWorldMatrix( true, false );
  4652. }
  4653. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4654. if ( this.matrixWorldAutoUpdate === true ) {
  4655. if ( this.parent === null ) {
  4656. this.matrixWorld.copy( this.matrix );
  4657. } else {
  4658. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4659. }
  4660. }
  4661. // make sure descendants are updated
  4662. if ( updateChildren === true ) {
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. const child = children[ i ];
  4666. child.updateWorldMatrix( false, true );
  4667. }
  4668. }
  4669. }
  4670. toJSON( meta ) {
  4671. // meta is a string when called from JSON.stringify
  4672. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4673. const output = {};
  4674. // meta is a hash used to collect geometries, materials.
  4675. // not providing it implies that this is the root object
  4676. // being serialized.
  4677. if ( isRootObject ) {
  4678. // initialize meta obj
  4679. meta = {
  4680. geometries: {},
  4681. materials: {},
  4682. textures: {},
  4683. images: {},
  4684. shapes: {},
  4685. skeletons: {},
  4686. animations: {},
  4687. nodes: {}
  4688. };
  4689. output.metadata = {
  4690. version: 4.6,
  4691. type: 'Object',
  4692. generator: 'Object3D.toJSON'
  4693. };
  4694. }
  4695. // standard Object3D serialization
  4696. const object = {};
  4697. object.uuid = this.uuid;
  4698. object.type = this.type;
  4699. if ( this.name !== '' ) object.name = this.name;
  4700. if ( this.castShadow === true ) object.castShadow = true;
  4701. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4702. if ( this.visible === false ) object.visible = false;
  4703. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4704. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4705. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4706. object.layers = this.layers.mask;
  4707. object.matrix = this.matrix.toArray();
  4708. object.up = this.up.toArray();
  4709. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4710. // object specific properties
  4711. if ( this.isInstancedMesh ) {
  4712. object.type = 'InstancedMesh';
  4713. object.count = this.count;
  4714. object.instanceMatrix = this.instanceMatrix.toJSON();
  4715. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4716. }
  4717. if ( this.isBatchedMesh ) {
  4718. object.type = 'BatchedMesh';
  4719. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4720. object.sortObjects = this.sortObjects;
  4721. object.drawRanges = this._drawRanges;
  4722. object.reservedRanges = this._reservedRanges;
  4723. object.visibility = this._visibility;
  4724. object.active = this._active;
  4725. object.bounds = this._bounds.map( bound => ( {
  4726. boxInitialized: bound.boxInitialized,
  4727. boxMin: bound.box.min.toArray(),
  4728. boxMax: bound.box.max.toArray(),
  4729. sphereInitialized: bound.sphereInitialized,
  4730. sphereRadius: bound.sphere.radius,
  4731. sphereCenter: bound.sphere.center.toArray()
  4732. } ) );
  4733. object.maxInstanceCount = this._maxInstanceCount;
  4734. object.maxVertexCount = this._maxVertexCount;
  4735. object.maxIndexCount = this._maxIndexCount;
  4736. object.geometryInitialized = this._geometryInitialized;
  4737. object.geometryCount = this._geometryCount;
  4738. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4739. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4740. if ( this.boundingSphere !== null ) {
  4741. object.boundingSphere = {
  4742. center: object.boundingSphere.center.toArray(),
  4743. radius: object.boundingSphere.radius
  4744. };
  4745. }
  4746. if ( this.boundingBox !== null ) {
  4747. object.boundingBox = {
  4748. min: object.boundingBox.min.toArray(),
  4749. max: object.boundingBox.max.toArray()
  4750. };
  4751. }
  4752. }
  4753. //
  4754. function serialize( library, element ) {
  4755. if ( library[ element.uuid ] === undefined ) {
  4756. library[ element.uuid ] = element.toJSON( meta );
  4757. }
  4758. return element.uuid;
  4759. }
  4760. if ( this.isScene ) {
  4761. if ( this.background ) {
  4762. if ( this.background.isColor ) {
  4763. object.background = this.background.toJSON();
  4764. } else if ( this.background.isTexture ) {
  4765. object.background = this.background.toJSON( meta ).uuid;
  4766. }
  4767. }
  4768. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4769. object.environment = this.environment.toJSON( meta ).uuid;
  4770. }
  4771. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4772. object.geometry = serialize( meta.geometries, this.geometry );
  4773. const parameters = this.geometry.parameters;
  4774. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4775. const shapes = parameters.shapes;
  4776. if ( Array.isArray( shapes ) ) {
  4777. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4778. const shape = shapes[ i ];
  4779. serialize( meta.shapes, shape );
  4780. }
  4781. } else {
  4782. serialize( meta.shapes, shapes );
  4783. }
  4784. }
  4785. }
  4786. if ( this.isSkinnedMesh ) {
  4787. object.bindMode = this.bindMode;
  4788. object.bindMatrix = this.bindMatrix.toArray();
  4789. if ( this.skeleton !== undefined ) {
  4790. serialize( meta.skeletons, this.skeleton );
  4791. object.skeleton = this.skeleton.uuid;
  4792. }
  4793. }
  4794. if ( this.material !== undefined ) {
  4795. if ( Array.isArray( this.material ) ) {
  4796. const uuids = [];
  4797. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4798. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4799. }
  4800. object.material = uuids;
  4801. } else {
  4802. object.material = serialize( meta.materials, this.material );
  4803. }
  4804. }
  4805. //
  4806. if ( this.children.length > 0 ) {
  4807. object.children = [];
  4808. for ( let i = 0; i < this.children.length; i ++ ) {
  4809. object.children.push( this.children[ i ].toJSON( meta ).object );
  4810. }
  4811. }
  4812. //
  4813. if ( this.animations.length > 0 ) {
  4814. object.animations = [];
  4815. for ( let i = 0; i < this.animations.length; i ++ ) {
  4816. const animation = this.animations[ i ];
  4817. object.animations.push( serialize( meta.animations, animation ) );
  4818. }
  4819. }
  4820. if ( isRootObject ) {
  4821. const geometries = extractFromCache( meta.geometries );
  4822. const materials = extractFromCache( meta.materials );
  4823. const textures = extractFromCache( meta.textures );
  4824. const images = extractFromCache( meta.images );
  4825. const shapes = extractFromCache( meta.shapes );
  4826. const skeletons = extractFromCache( meta.skeletons );
  4827. const animations = extractFromCache( meta.animations );
  4828. const nodes = extractFromCache( meta.nodes );
  4829. if ( geometries.length > 0 ) output.geometries = geometries;
  4830. if ( materials.length > 0 ) output.materials = materials;
  4831. if ( textures.length > 0 ) output.textures = textures;
  4832. if ( images.length > 0 ) output.images = images;
  4833. if ( shapes.length > 0 ) output.shapes = shapes;
  4834. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4835. if ( animations.length > 0 ) output.animations = animations;
  4836. if ( nodes.length > 0 ) output.nodes = nodes;
  4837. }
  4838. output.object = object;
  4839. return output;
  4840. // extract data from the cache hash
  4841. // remove metadata on each item
  4842. // and return as array
  4843. function extractFromCache( cache ) {
  4844. const values = [];
  4845. for ( const key in cache ) {
  4846. const data = cache[ key ];
  4847. delete data.metadata;
  4848. values.push( data );
  4849. }
  4850. return values;
  4851. }
  4852. }
  4853. clone( recursive ) {
  4854. return new this.constructor().copy( this, recursive );
  4855. }
  4856. copy( source, recursive = true ) {
  4857. this.name = source.name;
  4858. this.up.copy( source.up );
  4859. this.position.copy( source.position );
  4860. this.rotation.order = source.rotation.order;
  4861. this.quaternion.copy( source.quaternion );
  4862. this.scale.copy( source.scale );
  4863. this.matrix.copy( source.matrix );
  4864. this.matrixWorld.copy( source.matrixWorld );
  4865. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4866. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4867. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4868. this.layers.mask = source.layers.mask;
  4869. this.visible = source.visible;
  4870. this.castShadow = source.castShadow;
  4871. this.receiveShadow = source.receiveShadow;
  4872. this.frustumCulled = source.frustumCulled;
  4873. this.renderOrder = source.renderOrder;
  4874. this.animations = source.animations.slice();
  4875. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4876. if ( recursive === true ) {
  4877. for ( let i = 0; i < source.children.length; i ++ ) {
  4878. const child = source.children[ i ];
  4879. this.add( child.clone() );
  4880. }
  4881. }
  4882. return this;
  4883. }
  4884. }
  4885. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4886. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4887. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4888. const _v0$1 = /*@__PURE__*/ new Vector3();
  4889. const _v1$3 = /*@__PURE__*/ new Vector3();
  4890. const _v2$2 = /*@__PURE__*/ new Vector3();
  4891. const _v3$2 = /*@__PURE__*/ new Vector3();
  4892. const _vab = /*@__PURE__*/ new Vector3();
  4893. const _vac = /*@__PURE__*/ new Vector3();
  4894. const _vbc = /*@__PURE__*/ new Vector3();
  4895. const _vap = /*@__PURE__*/ new Vector3();
  4896. const _vbp = /*@__PURE__*/ new Vector3();
  4897. const _vcp = /*@__PURE__*/ new Vector3();
  4898. class Triangle {
  4899. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4900. this.a = a;
  4901. this.b = b;
  4902. this.c = c;
  4903. }
  4904. static getNormal( a, b, c, target ) {
  4905. target.subVectors( c, b );
  4906. _v0$1.subVectors( a, b );
  4907. target.cross( _v0$1 );
  4908. const targetLengthSq = target.lengthSq();
  4909. if ( targetLengthSq > 0 ) {
  4910. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4911. }
  4912. return target.set( 0, 0, 0 );
  4913. }
  4914. // static/instance method to calculate barycentric coordinates
  4915. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4916. static getBarycoord( point, a, b, c, target ) {
  4917. _v0$1.subVectors( c, a );
  4918. _v1$3.subVectors( b, a );
  4919. _v2$2.subVectors( point, a );
  4920. const dot00 = _v0$1.dot( _v0$1 );
  4921. const dot01 = _v0$1.dot( _v1$3 );
  4922. const dot02 = _v0$1.dot( _v2$2 );
  4923. const dot11 = _v1$3.dot( _v1$3 );
  4924. const dot12 = _v1$3.dot( _v2$2 );
  4925. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4926. // collinear or singular triangle
  4927. if ( denom === 0 ) {
  4928. target.set( 0, 0, 0 );
  4929. return null;
  4930. }
  4931. const invDenom = 1 / denom;
  4932. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4933. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4934. // barycentric coordinates must always sum to 1
  4935. return target.set( 1 - u - v, v, u );
  4936. }
  4937. static containsPoint( point, a, b, c ) {
  4938. // if the triangle is degenerate then we can't contain a point
  4939. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4940. return false;
  4941. }
  4942. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4943. }
  4944. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4945. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4946. target.x = 0;
  4947. target.y = 0;
  4948. if ( 'z' in target ) target.z = 0;
  4949. if ( 'w' in target ) target.w = 0;
  4950. return null;
  4951. }
  4952. target.setScalar( 0 );
  4953. target.addScaledVector( v1, _v3$2.x );
  4954. target.addScaledVector( v2, _v3$2.y );
  4955. target.addScaledVector( v3, _v3$2.z );
  4956. return target;
  4957. }
  4958. static isFrontFacing( a, b, c, direction ) {
  4959. _v0$1.subVectors( c, b );
  4960. _v1$3.subVectors( a, b );
  4961. // strictly front facing
  4962. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4963. }
  4964. set( a, b, c ) {
  4965. this.a.copy( a );
  4966. this.b.copy( b );
  4967. this.c.copy( c );
  4968. return this;
  4969. }
  4970. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4971. this.a.copy( points[ i0 ] );
  4972. this.b.copy( points[ i1 ] );
  4973. this.c.copy( points[ i2 ] );
  4974. return this;
  4975. }
  4976. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4977. this.a.fromBufferAttribute( attribute, i0 );
  4978. this.b.fromBufferAttribute( attribute, i1 );
  4979. this.c.fromBufferAttribute( attribute, i2 );
  4980. return this;
  4981. }
  4982. clone() {
  4983. return new this.constructor().copy( this );
  4984. }
  4985. copy( triangle ) {
  4986. this.a.copy( triangle.a );
  4987. this.b.copy( triangle.b );
  4988. this.c.copy( triangle.c );
  4989. return this;
  4990. }
  4991. getArea() {
  4992. _v0$1.subVectors( this.c, this.b );
  4993. _v1$3.subVectors( this.a, this.b );
  4994. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4995. }
  4996. getMidpoint( target ) {
  4997. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4998. }
  4999. getNormal( target ) {
  5000. return Triangle.getNormal( this.a, this.b, this.c, target );
  5001. }
  5002. getPlane( target ) {
  5003. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5004. }
  5005. getBarycoord( point, target ) {
  5006. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5007. }
  5008. getInterpolation( point, v1, v2, v3, target ) {
  5009. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5010. }
  5011. containsPoint( point ) {
  5012. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5013. }
  5014. isFrontFacing( direction ) {
  5015. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5016. }
  5017. intersectsBox( box ) {
  5018. return box.intersectsTriangle( this );
  5019. }
  5020. closestPointToPoint( p, target ) {
  5021. const a = this.a, b = this.b, c = this.c;
  5022. let v, w;
  5023. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5024. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5025. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5026. // basically, we're distinguishing which of the voronoi regions of the triangle
  5027. // the point lies in with the minimum amount of redundant computation.
  5028. _vab.subVectors( b, a );
  5029. _vac.subVectors( c, a );
  5030. _vap.subVectors( p, a );
  5031. const d1 = _vab.dot( _vap );
  5032. const d2 = _vac.dot( _vap );
  5033. if ( d1 <= 0 && d2 <= 0 ) {
  5034. // vertex region of A; barycentric coords (1, 0, 0)
  5035. return target.copy( a );
  5036. }
  5037. _vbp.subVectors( p, b );
  5038. const d3 = _vab.dot( _vbp );
  5039. const d4 = _vac.dot( _vbp );
  5040. if ( d3 >= 0 && d4 <= d3 ) {
  5041. // vertex region of B; barycentric coords (0, 1, 0)
  5042. return target.copy( b );
  5043. }
  5044. const vc = d1 * d4 - d3 * d2;
  5045. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5046. v = d1 / ( d1 - d3 );
  5047. // edge region of AB; barycentric coords (1-v, v, 0)
  5048. return target.copy( a ).addScaledVector( _vab, v );
  5049. }
  5050. _vcp.subVectors( p, c );
  5051. const d5 = _vab.dot( _vcp );
  5052. const d6 = _vac.dot( _vcp );
  5053. if ( d6 >= 0 && d5 <= d6 ) {
  5054. // vertex region of C; barycentric coords (0, 0, 1)
  5055. return target.copy( c );
  5056. }
  5057. const vb = d5 * d2 - d1 * d6;
  5058. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5059. w = d2 / ( d2 - d6 );
  5060. // edge region of AC; barycentric coords (1-w, 0, w)
  5061. return target.copy( a ).addScaledVector( _vac, w );
  5062. }
  5063. const va = d3 * d6 - d5 * d4;
  5064. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5065. _vbc.subVectors( c, b );
  5066. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5067. // edge region of BC; barycentric coords (0, 1-w, w)
  5068. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5069. }
  5070. // face region
  5071. const denom = 1 / ( va + vb + vc );
  5072. // u = va * denom
  5073. v = vb * denom;
  5074. w = vc * denom;
  5075. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5076. }
  5077. equals( triangle ) {
  5078. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5079. }
  5080. }
  5081. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5082. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5083. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5084. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5085. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5086. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5087. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5088. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5089. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5090. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5091. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5092. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5093. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5094. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5095. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5096. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5097. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5098. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5099. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5100. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5101. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5102. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5103. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5104. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5105. const _hslA = { h: 0, s: 0, l: 0 };
  5106. const _hslB = { h: 0, s: 0, l: 0 };
  5107. function hue2rgb( p, q, t ) {
  5108. if ( t < 0 ) t += 1;
  5109. if ( t > 1 ) t -= 1;
  5110. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5111. if ( t < 1 / 2 ) return q;
  5112. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5113. return p;
  5114. }
  5115. class Color {
  5116. constructor( r, g, b ) {
  5117. this.isColor = true;
  5118. this.r = 1;
  5119. this.g = 1;
  5120. this.b = 1;
  5121. return this.set( r, g, b );
  5122. }
  5123. set( r, g, b ) {
  5124. if ( g === undefined && b === undefined ) {
  5125. // r is THREE.Color, hex or string
  5126. const value = r;
  5127. if ( value && value.isColor ) {
  5128. this.copy( value );
  5129. } else if ( typeof value === 'number' ) {
  5130. this.setHex( value );
  5131. } else if ( typeof value === 'string' ) {
  5132. this.setStyle( value );
  5133. }
  5134. } else {
  5135. this.setRGB( r, g, b );
  5136. }
  5137. return this;
  5138. }
  5139. setScalar( scalar ) {
  5140. this.r = scalar;
  5141. this.g = scalar;
  5142. this.b = scalar;
  5143. return this;
  5144. }
  5145. setHex( hex, colorSpace = SRGBColorSpace ) {
  5146. hex = Math.floor( hex );
  5147. this.r = ( hex >> 16 & 255 ) / 255;
  5148. this.g = ( hex >> 8 & 255 ) / 255;
  5149. this.b = ( hex & 255 ) / 255;
  5150. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5151. return this;
  5152. }
  5153. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5154. this.r = r;
  5155. this.g = g;
  5156. this.b = b;
  5157. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5158. return this;
  5159. }
  5160. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5161. // h,s,l ranges are in 0.0 - 1.0
  5162. h = euclideanModulo( h, 1 );
  5163. s = clamp$1( s, 0, 1 );
  5164. l = clamp$1( l, 0, 1 );
  5165. if ( s === 0 ) {
  5166. this.r = this.g = this.b = l;
  5167. } else {
  5168. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5169. const q = ( 2 * l ) - p;
  5170. this.r = hue2rgb( q, p, h + 1 / 3 );
  5171. this.g = hue2rgb( q, p, h );
  5172. this.b = hue2rgb( q, p, h - 1 / 3 );
  5173. }
  5174. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5175. return this;
  5176. }
  5177. setStyle( style, colorSpace = SRGBColorSpace ) {
  5178. function handleAlpha( string ) {
  5179. if ( string === undefined ) return;
  5180. if ( parseFloat( string ) < 1 ) {
  5181. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5182. }
  5183. }
  5184. let m;
  5185. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5186. // rgb / hsl
  5187. let color;
  5188. const name = m[ 1 ];
  5189. const components = m[ 2 ];
  5190. switch ( name ) {
  5191. case 'rgb':
  5192. case 'rgba':
  5193. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5194. // rgb(255,0,0) rgba(255,0,0,0.5)
  5195. handleAlpha( color[ 4 ] );
  5196. return this.setRGB(
  5197. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5198. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5199. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5200. colorSpace
  5201. );
  5202. }
  5203. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5204. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5205. handleAlpha( color[ 4 ] );
  5206. return this.setRGB(
  5207. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5208. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5209. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5210. colorSpace
  5211. );
  5212. }
  5213. break;
  5214. case 'hsl':
  5215. case 'hsla':
  5216. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5217. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5218. handleAlpha( color[ 4 ] );
  5219. return this.setHSL(
  5220. parseFloat( color[ 1 ] ) / 360,
  5221. parseFloat( color[ 2 ] ) / 100,
  5222. parseFloat( color[ 3 ] ) / 100,
  5223. colorSpace
  5224. );
  5225. }
  5226. break;
  5227. default:
  5228. console.warn( 'THREE.Color: Unknown color model ' + style );
  5229. }
  5230. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5231. // hex color
  5232. const hex = m[ 1 ];
  5233. const size = hex.length;
  5234. if ( size === 3 ) {
  5235. // #ff0
  5236. return this.setRGB(
  5237. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5238. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5239. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5240. colorSpace
  5241. );
  5242. } else if ( size === 6 ) {
  5243. // #ff0000
  5244. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5245. } else {
  5246. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5247. }
  5248. } else if ( style && style.length > 0 ) {
  5249. return this.setColorName( style, colorSpace );
  5250. }
  5251. return this;
  5252. }
  5253. setColorName( style, colorSpace = SRGBColorSpace ) {
  5254. // color keywords
  5255. const hex = _colorKeywords[ style.toLowerCase() ];
  5256. if ( hex !== undefined ) {
  5257. // red
  5258. this.setHex( hex, colorSpace );
  5259. } else {
  5260. // unknown color
  5261. console.warn( 'THREE.Color: Unknown color ' + style );
  5262. }
  5263. return this;
  5264. }
  5265. clone() {
  5266. return new this.constructor( this.r, this.g, this.b );
  5267. }
  5268. copy( color ) {
  5269. this.r = color.r;
  5270. this.g = color.g;
  5271. this.b = color.b;
  5272. return this;
  5273. }
  5274. copySRGBToLinear( color ) {
  5275. this.r = SRGBToLinear( color.r );
  5276. this.g = SRGBToLinear( color.g );
  5277. this.b = SRGBToLinear( color.b );
  5278. return this;
  5279. }
  5280. copyLinearToSRGB( color ) {
  5281. this.r = LinearToSRGB( color.r );
  5282. this.g = LinearToSRGB( color.g );
  5283. this.b = LinearToSRGB( color.b );
  5284. return this;
  5285. }
  5286. convertSRGBToLinear() {
  5287. this.copySRGBToLinear( this );
  5288. return this;
  5289. }
  5290. convertLinearToSRGB() {
  5291. this.copyLinearToSRGB( this );
  5292. return this;
  5293. }
  5294. getHex( colorSpace = SRGBColorSpace ) {
  5295. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5296. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5297. }
  5298. getHexString( colorSpace = SRGBColorSpace ) {
  5299. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5300. }
  5301. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5302. // h,s,l ranges are in 0.0 - 1.0
  5303. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5304. const r = _color.r, g = _color.g, b = _color.b;
  5305. const max = Math.max( r, g, b );
  5306. const min = Math.min( r, g, b );
  5307. let hue, saturation;
  5308. const lightness = ( min + max ) / 2.0;
  5309. if ( min === max ) {
  5310. hue = 0;
  5311. saturation = 0;
  5312. } else {
  5313. const delta = max - min;
  5314. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5315. switch ( max ) {
  5316. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5317. case g: hue = ( b - r ) / delta + 2; break;
  5318. case b: hue = ( r - g ) / delta + 4; break;
  5319. }
  5320. hue /= 6;
  5321. }
  5322. target.h = hue;
  5323. target.s = saturation;
  5324. target.l = lightness;
  5325. return target;
  5326. }
  5327. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5328. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5329. target.r = _color.r;
  5330. target.g = _color.g;
  5331. target.b = _color.b;
  5332. return target;
  5333. }
  5334. getStyle( colorSpace = SRGBColorSpace ) {
  5335. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5336. const r = _color.r, g = _color.g, b = _color.b;
  5337. if ( colorSpace !== SRGBColorSpace ) {
  5338. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5339. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5340. }
  5341. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5342. }
  5343. offsetHSL( h, s, l ) {
  5344. this.getHSL( _hslA );
  5345. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5346. }
  5347. add( color ) {
  5348. this.r += color.r;
  5349. this.g += color.g;
  5350. this.b += color.b;
  5351. return this;
  5352. }
  5353. addColors( color1, color2 ) {
  5354. this.r = color1.r + color2.r;
  5355. this.g = color1.g + color2.g;
  5356. this.b = color1.b + color2.b;
  5357. return this;
  5358. }
  5359. addScalar( s ) {
  5360. this.r += s;
  5361. this.g += s;
  5362. this.b += s;
  5363. return this;
  5364. }
  5365. sub( color ) {
  5366. this.r = Math.max( 0, this.r - color.r );
  5367. this.g = Math.max( 0, this.g - color.g );
  5368. this.b = Math.max( 0, this.b - color.b );
  5369. return this;
  5370. }
  5371. multiply( color ) {
  5372. this.r *= color.r;
  5373. this.g *= color.g;
  5374. this.b *= color.b;
  5375. return this;
  5376. }
  5377. multiplyScalar( s ) {
  5378. this.r *= s;
  5379. this.g *= s;
  5380. this.b *= s;
  5381. return this;
  5382. }
  5383. lerp( color, alpha ) {
  5384. this.r += ( color.r - this.r ) * alpha;
  5385. this.g += ( color.g - this.g ) * alpha;
  5386. this.b += ( color.b - this.b ) * alpha;
  5387. return this;
  5388. }
  5389. lerpColors( color1, color2, alpha ) {
  5390. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5391. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5392. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5393. return this;
  5394. }
  5395. lerpHSL( color, alpha ) {
  5396. this.getHSL( _hslA );
  5397. color.getHSL( _hslB );
  5398. const h = lerp( _hslA.h, _hslB.h, alpha );
  5399. const s = lerp( _hslA.s, _hslB.s, alpha );
  5400. const l = lerp( _hslA.l, _hslB.l, alpha );
  5401. this.setHSL( h, s, l );
  5402. return this;
  5403. }
  5404. setFromVector3( v ) {
  5405. this.r = v.x;
  5406. this.g = v.y;
  5407. this.b = v.z;
  5408. return this;
  5409. }
  5410. applyMatrix3( m ) {
  5411. const r = this.r, g = this.g, b = this.b;
  5412. const e = m.elements;
  5413. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5414. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5415. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5416. return this;
  5417. }
  5418. equals( c ) {
  5419. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5420. }
  5421. fromArray( array, offset = 0 ) {
  5422. this.r = array[ offset ];
  5423. this.g = array[ offset + 1 ];
  5424. this.b = array[ offset + 2 ];
  5425. return this;
  5426. }
  5427. toArray( array = [], offset = 0 ) {
  5428. array[ offset ] = this.r;
  5429. array[ offset + 1 ] = this.g;
  5430. array[ offset + 2 ] = this.b;
  5431. return array;
  5432. }
  5433. fromBufferAttribute( attribute, index ) {
  5434. this.r = attribute.getX( index );
  5435. this.g = attribute.getY( index );
  5436. this.b = attribute.getZ( index );
  5437. return this;
  5438. }
  5439. toJSON() {
  5440. return this.getHex();
  5441. }
  5442. *[ Symbol.iterator ]() {
  5443. yield this.r;
  5444. yield this.g;
  5445. yield this.b;
  5446. }
  5447. }
  5448. const _color = /*@__PURE__*/ new Color();
  5449. Color.NAMES = _colorKeywords;
  5450. let _materialId = 0;
  5451. class Material extends EventDispatcher {
  5452. constructor() {
  5453. super();
  5454. this.isMaterial = true;
  5455. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5456. this.uuid = generateUUID();
  5457. this.name = '';
  5458. this.type = 'Material';
  5459. this.blending = NormalBlending;
  5460. this.side = FrontSide;
  5461. this.vertexColors = false;
  5462. this.opacity = 1;
  5463. this.transparent = false;
  5464. this.alphaHash = false;
  5465. this.blendSrc = SrcAlphaFactor;
  5466. this.blendDst = OneMinusSrcAlphaFactor;
  5467. this.blendEquation = AddEquation;
  5468. this.blendSrcAlpha = null;
  5469. this.blendDstAlpha = null;
  5470. this.blendEquationAlpha = null;
  5471. this.blendColor = new Color( 0, 0, 0 );
  5472. this.blendAlpha = 0;
  5473. this.depthFunc = LessEqualDepth;
  5474. this.depthTest = true;
  5475. this.depthWrite = true;
  5476. this.stencilWriteMask = 0xff;
  5477. this.stencilFunc = AlwaysStencilFunc;
  5478. this.stencilRef = 0;
  5479. this.stencilFuncMask = 0xff;
  5480. this.stencilFail = KeepStencilOp;
  5481. this.stencilZFail = KeepStencilOp;
  5482. this.stencilZPass = KeepStencilOp;
  5483. this.stencilWrite = false;
  5484. this.clippingPlanes = null;
  5485. this.clipIntersection = false;
  5486. this.clipShadows = false;
  5487. this.shadowSide = null;
  5488. this.colorWrite = true;
  5489. this.precision = null; // override the renderer's default precision for this material
  5490. this.polygonOffset = false;
  5491. this.polygonOffsetFactor = 0;
  5492. this.polygonOffsetUnits = 0;
  5493. this.dithering = false;
  5494. this.alphaToCoverage = false;
  5495. this.premultipliedAlpha = false;
  5496. this.forceSinglePass = false;
  5497. this.visible = true;
  5498. this.toneMapped = true;
  5499. this.userData = {};
  5500. this.version = 0;
  5501. this._alphaTest = 0;
  5502. }
  5503. get alphaTest() {
  5504. return this._alphaTest;
  5505. }
  5506. set alphaTest( value ) {
  5507. if ( this._alphaTest > 0 !== value > 0 ) {
  5508. this.version ++;
  5509. }
  5510. this._alphaTest = value;
  5511. }
  5512. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5513. customProgramCacheKey() {
  5514. return this.onBeforeCompile.toString();
  5515. }
  5516. setValues( values ) {
  5517. if ( values === undefined ) return;
  5518. for ( const key in values ) {
  5519. const newValue = values[ key ];
  5520. if ( newValue === undefined ) {
  5521. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5522. continue;
  5523. }
  5524. const currentValue = this[ key ];
  5525. if ( currentValue === undefined ) {
  5526. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5527. continue;
  5528. }
  5529. if ( currentValue && currentValue.isColor ) {
  5530. currentValue.set( newValue );
  5531. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5532. currentValue.copy( newValue );
  5533. } else {
  5534. this[ key ] = newValue;
  5535. }
  5536. }
  5537. }
  5538. toJSON( meta ) {
  5539. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5540. if ( isRootObject ) {
  5541. meta = {
  5542. textures: {},
  5543. images: {}
  5544. };
  5545. }
  5546. const data = {
  5547. metadata: {
  5548. version: 4.6,
  5549. type: 'Material',
  5550. generator: 'Material.toJSON'
  5551. }
  5552. };
  5553. // standard Material serialization
  5554. data.uuid = this.uuid;
  5555. data.type = this.type;
  5556. if ( this.name !== '' ) data.name = this.name;
  5557. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5558. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5559. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5560. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5561. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5562. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5563. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5564. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5565. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5566. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5567. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5568. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5569. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5570. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5571. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5572. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5573. }
  5574. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5575. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5576. }
  5577. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5578. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5579. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5580. }
  5581. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5582. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5583. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5584. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5585. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5586. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5587. }
  5588. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5589. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5590. }
  5591. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5592. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5593. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5594. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5595. }
  5596. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5597. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5598. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5599. if ( this.lightMap && this.lightMap.isTexture ) {
  5600. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5601. data.lightMapIntensity = this.lightMapIntensity;
  5602. }
  5603. if ( this.aoMap && this.aoMap.isTexture ) {
  5604. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5605. data.aoMapIntensity = this.aoMapIntensity;
  5606. }
  5607. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5608. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5609. data.bumpScale = this.bumpScale;
  5610. }
  5611. if ( this.normalMap && this.normalMap.isTexture ) {
  5612. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5613. data.normalMapType = this.normalMapType;
  5614. data.normalScale = this.normalScale.toArray();
  5615. }
  5616. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5617. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5618. data.displacementScale = this.displacementScale;
  5619. data.displacementBias = this.displacementBias;
  5620. }
  5621. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5622. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5623. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5624. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5625. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5626. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5627. if ( this.envMap && this.envMap.isTexture ) {
  5628. data.envMap = this.envMap.toJSON( meta ).uuid;
  5629. if ( this.combine !== undefined ) data.combine = this.combine;
  5630. }
  5631. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5632. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5633. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5634. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5635. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5636. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5637. }
  5638. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5639. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5640. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5641. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5642. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5643. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5644. if ( this.size !== undefined ) data.size = this.size;
  5645. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5646. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5647. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5648. if ( this.side !== FrontSide ) data.side = this.side;
  5649. if ( this.vertexColors === true ) data.vertexColors = true;
  5650. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5651. if ( this.transparent === true ) data.transparent = true;
  5652. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5653. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5654. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5655. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5656. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5657. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5658. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5659. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5660. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5661. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5662. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5663. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5664. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5665. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5666. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5667. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5668. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5669. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5670. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5671. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5672. // rotation (SpriteMaterial)
  5673. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5674. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5675. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5676. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5677. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5678. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5679. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5680. if ( this.scale !== undefined ) data.scale = this.scale;
  5681. if ( this.dithering === true ) data.dithering = true;
  5682. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5683. if ( this.alphaHash === true ) data.alphaHash = true;
  5684. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5685. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5686. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5687. if ( this.wireframe === true ) data.wireframe = true;
  5688. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5689. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5690. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5691. if ( this.flatShading === true ) data.flatShading = true;
  5692. if ( this.visible === false ) data.visible = false;
  5693. if ( this.toneMapped === false ) data.toneMapped = false;
  5694. if ( this.fog === false ) data.fog = false;
  5695. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5696. // TODO: Copied from Object3D.toJSON
  5697. function extractFromCache( cache ) {
  5698. const values = [];
  5699. for ( const key in cache ) {
  5700. const data = cache[ key ];
  5701. delete data.metadata;
  5702. values.push( data );
  5703. }
  5704. return values;
  5705. }
  5706. if ( isRootObject ) {
  5707. const textures = extractFromCache( meta.textures );
  5708. const images = extractFromCache( meta.images );
  5709. if ( textures.length > 0 ) data.textures = textures;
  5710. if ( images.length > 0 ) data.images = images;
  5711. }
  5712. return data;
  5713. }
  5714. clone() {
  5715. return new this.constructor().copy( this );
  5716. }
  5717. copy( source ) {
  5718. this.name = source.name;
  5719. this.blending = source.blending;
  5720. this.side = source.side;
  5721. this.vertexColors = source.vertexColors;
  5722. this.opacity = source.opacity;
  5723. this.transparent = source.transparent;
  5724. this.blendSrc = source.blendSrc;
  5725. this.blendDst = source.blendDst;
  5726. this.blendEquation = source.blendEquation;
  5727. this.blendSrcAlpha = source.blendSrcAlpha;
  5728. this.blendDstAlpha = source.blendDstAlpha;
  5729. this.blendEquationAlpha = source.blendEquationAlpha;
  5730. this.blendColor.copy( source.blendColor );
  5731. this.blendAlpha = source.blendAlpha;
  5732. this.depthFunc = source.depthFunc;
  5733. this.depthTest = source.depthTest;
  5734. this.depthWrite = source.depthWrite;
  5735. this.stencilWriteMask = source.stencilWriteMask;
  5736. this.stencilFunc = source.stencilFunc;
  5737. this.stencilRef = source.stencilRef;
  5738. this.stencilFuncMask = source.stencilFuncMask;
  5739. this.stencilFail = source.stencilFail;
  5740. this.stencilZFail = source.stencilZFail;
  5741. this.stencilZPass = source.stencilZPass;
  5742. this.stencilWrite = source.stencilWrite;
  5743. const srcPlanes = source.clippingPlanes;
  5744. let dstPlanes = null;
  5745. if ( srcPlanes !== null ) {
  5746. const n = srcPlanes.length;
  5747. dstPlanes = new Array( n );
  5748. for ( let i = 0; i !== n; ++ i ) {
  5749. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5750. }
  5751. }
  5752. this.clippingPlanes = dstPlanes;
  5753. this.clipIntersection = source.clipIntersection;
  5754. this.clipShadows = source.clipShadows;
  5755. this.shadowSide = source.shadowSide;
  5756. this.colorWrite = source.colorWrite;
  5757. this.precision = source.precision;
  5758. this.polygonOffset = source.polygonOffset;
  5759. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5760. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5761. this.dithering = source.dithering;
  5762. this.alphaTest = source.alphaTest;
  5763. this.alphaHash = source.alphaHash;
  5764. this.alphaToCoverage = source.alphaToCoverage;
  5765. this.premultipliedAlpha = source.premultipliedAlpha;
  5766. this.forceSinglePass = source.forceSinglePass;
  5767. this.visible = source.visible;
  5768. this.toneMapped = source.toneMapped;
  5769. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5770. return this;
  5771. }
  5772. dispose() {
  5773. this.dispatchEvent( { type: 'dispose' } );
  5774. }
  5775. set needsUpdate( value ) {
  5776. if ( value === true ) this.version ++;
  5777. }
  5778. onBuild( /* shaderobject, renderer */ ) {
  5779. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5780. }
  5781. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {
  5782. console.warn( 'Material: onBeforeRender() has been removed.' ); // @deprecated, r166
  5783. }
  5784. }
  5785. class MeshBasicMaterial extends Material {
  5786. constructor( parameters ) {
  5787. super();
  5788. this.isMeshBasicMaterial = true;
  5789. this.type = 'MeshBasicMaterial';
  5790. this.color = new Color( 0xffffff ); // emissive
  5791. this.map = null;
  5792. this.lightMap = null;
  5793. this.lightMapIntensity = 1.0;
  5794. this.aoMap = null;
  5795. this.aoMapIntensity = 1.0;
  5796. this.specularMap = null;
  5797. this.alphaMap = null;
  5798. this.envMap = null;
  5799. this.envMapRotation = new Euler();
  5800. this.combine = MultiplyOperation;
  5801. this.reflectivity = 1;
  5802. this.refractionRatio = 0.98;
  5803. this.wireframe = false;
  5804. this.wireframeLinewidth = 1;
  5805. this.wireframeLinecap = 'round';
  5806. this.wireframeLinejoin = 'round';
  5807. this.fog = true;
  5808. this.setValues( parameters );
  5809. }
  5810. copy( source ) {
  5811. super.copy( source );
  5812. this.color.copy( source.color );
  5813. this.map = source.map;
  5814. this.lightMap = source.lightMap;
  5815. this.lightMapIntensity = source.lightMapIntensity;
  5816. this.aoMap = source.aoMap;
  5817. this.aoMapIntensity = source.aoMapIntensity;
  5818. this.specularMap = source.specularMap;
  5819. this.alphaMap = source.alphaMap;
  5820. this.envMap = source.envMap;
  5821. this.envMapRotation.copy( source.envMapRotation );
  5822. this.combine = source.combine;
  5823. this.reflectivity = source.reflectivity;
  5824. this.refractionRatio = source.refractionRatio;
  5825. this.wireframe = source.wireframe;
  5826. this.wireframeLinewidth = source.wireframeLinewidth;
  5827. this.wireframeLinecap = source.wireframeLinecap;
  5828. this.wireframeLinejoin = source.wireframeLinejoin;
  5829. this.fog = source.fog;
  5830. return this;
  5831. }
  5832. }
  5833. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5834. const _tables = /*@__PURE__*/ _generateTables();
  5835. function _generateTables() {
  5836. // float32 to float16 helpers
  5837. const buffer = new ArrayBuffer( 4 );
  5838. const floatView = new Float32Array( buffer );
  5839. const uint32View = new Uint32Array( buffer );
  5840. const baseTable = new Uint32Array( 512 );
  5841. const shiftTable = new Uint32Array( 512 );
  5842. for ( let i = 0; i < 256; ++ i ) {
  5843. const e = i - 127;
  5844. // very small number (0, -0)
  5845. if ( e < - 27 ) {
  5846. baseTable[ i ] = 0x0000;
  5847. baseTable[ i | 0x100 ] = 0x8000;
  5848. shiftTable[ i ] = 24;
  5849. shiftTable[ i | 0x100 ] = 24;
  5850. // small number (denorm)
  5851. } else if ( e < - 14 ) {
  5852. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5853. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5854. shiftTable[ i ] = - e - 1;
  5855. shiftTable[ i | 0x100 ] = - e - 1;
  5856. // normal number
  5857. } else if ( e <= 15 ) {
  5858. baseTable[ i ] = ( e + 15 ) << 10;
  5859. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5860. shiftTable[ i ] = 13;
  5861. shiftTable[ i | 0x100 ] = 13;
  5862. // large number (Infinity, -Infinity)
  5863. } else if ( e < 128 ) {
  5864. baseTable[ i ] = 0x7c00;
  5865. baseTable[ i | 0x100 ] = 0xfc00;
  5866. shiftTable[ i ] = 24;
  5867. shiftTable[ i | 0x100 ] = 24;
  5868. // stay (NaN, Infinity, -Infinity)
  5869. } else {
  5870. baseTable[ i ] = 0x7c00;
  5871. baseTable[ i | 0x100 ] = 0xfc00;
  5872. shiftTable[ i ] = 13;
  5873. shiftTable[ i | 0x100 ] = 13;
  5874. }
  5875. }
  5876. // float16 to float32 helpers
  5877. const mantissaTable = new Uint32Array( 2048 );
  5878. const exponentTable = new Uint32Array( 64 );
  5879. const offsetTable = new Uint32Array( 64 );
  5880. for ( let i = 1; i < 1024; ++ i ) {
  5881. let m = i << 13; // zero pad mantissa bits
  5882. let e = 0; // zero exponent
  5883. // normalized
  5884. while ( ( m & 0x00800000 ) === 0 ) {
  5885. m <<= 1;
  5886. e -= 0x00800000; // decrement exponent
  5887. }
  5888. m &= ~ 0x00800000; // clear leading 1 bit
  5889. e += 0x38800000; // adjust bias
  5890. mantissaTable[ i ] = m | e;
  5891. }
  5892. for ( let i = 1024; i < 2048; ++ i ) {
  5893. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5894. }
  5895. for ( let i = 1; i < 31; ++ i ) {
  5896. exponentTable[ i ] = i << 23;
  5897. }
  5898. exponentTable[ 31 ] = 0x47800000;
  5899. exponentTable[ 32 ] = 0x80000000;
  5900. for ( let i = 33; i < 63; ++ i ) {
  5901. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5902. }
  5903. exponentTable[ 63 ] = 0xc7800000;
  5904. for ( let i = 1; i < 64; ++ i ) {
  5905. if ( i !== 32 ) {
  5906. offsetTable[ i ] = 1024;
  5907. }
  5908. }
  5909. return {
  5910. floatView: floatView,
  5911. uint32View: uint32View,
  5912. baseTable: baseTable,
  5913. shiftTable: shiftTable,
  5914. mantissaTable: mantissaTable,
  5915. exponentTable: exponentTable,
  5916. offsetTable: offsetTable
  5917. };
  5918. }
  5919. // float32 to float16
  5920. function toHalfFloat( val ) {
  5921. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5922. val = clamp$1( val, - 65504, 65504 );
  5923. _tables.floatView[ 0 ] = val;
  5924. const f = _tables.uint32View[ 0 ];
  5925. const e = ( f >> 23 ) & 0x1ff;
  5926. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5927. }
  5928. // float16 to float32
  5929. function fromHalfFloat( val ) {
  5930. const m = val >> 10;
  5931. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5932. return _tables.floatView[ 0 ];
  5933. }
  5934. const DataUtils = {
  5935. toHalfFloat: toHalfFloat,
  5936. fromHalfFloat: fromHalfFloat,
  5937. };
  5938. const _vector$9 = /*@__PURE__*/ new Vector3();
  5939. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5940. class BufferAttribute {
  5941. constructor( array, itemSize, normalized = false ) {
  5942. if ( Array.isArray( array ) ) {
  5943. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5944. }
  5945. this.isBufferAttribute = true;
  5946. this.name = '';
  5947. this.array = array;
  5948. this.itemSize = itemSize;
  5949. this.count = array !== undefined ? array.length / itemSize : 0;
  5950. this.normalized = normalized;
  5951. this.usage = StaticDrawUsage;
  5952. this._updateRange = { offset: 0, count: - 1 };
  5953. this.updateRanges = [];
  5954. this.gpuType = FloatType;
  5955. this.version = 0;
  5956. }
  5957. onUploadCallback() {}
  5958. set needsUpdate( value ) {
  5959. if ( value === true ) this.version ++;
  5960. }
  5961. get updateRange() {
  5962. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5963. return this._updateRange;
  5964. }
  5965. setUsage( value ) {
  5966. this.usage = value;
  5967. return this;
  5968. }
  5969. addUpdateRange( start, count ) {
  5970. this.updateRanges.push( { start, count } );
  5971. }
  5972. clearUpdateRanges() {
  5973. this.updateRanges.length = 0;
  5974. }
  5975. copy( source ) {
  5976. this.name = source.name;
  5977. this.array = new source.array.constructor( source.array );
  5978. this.itemSize = source.itemSize;
  5979. this.count = source.count;
  5980. this.normalized = source.normalized;
  5981. this.usage = source.usage;
  5982. this.gpuType = source.gpuType;
  5983. return this;
  5984. }
  5985. copyAt( index1, attribute, index2 ) {
  5986. index1 *= this.itemSize;
  5987. index2 *= attribute.itemSize;
  5988. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5989. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5990. }
  5991. return this;
  5992. }
  5993. copyArray( array ) {
  5994. this.array.set( array );
  5995. return this;
  5996. }
  5997. applyMatrix3( m ) {
  5998. if ( this.itemSize === 2 ) {
  5999. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6000. _vector2$1.fromBufferAttribute( this, i );
  6001. _vector2$1.applyMatrix3( m );
  6002. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6003. }
  6004. } else if ( this.itemSize === 3 ) {
  6005. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6006. _vector$9.fromBufferAttribute( this, i );
  6007. _vector$9.applyMatrix3( m );
  6008. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6009. }
  6010. }
  6011. return this;
  6012. }
  6013. applyMatrix4( m ) {
  6014. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6015. _vector$9.fromBufferAttribute( this, i );
  6016. _vector$9.applyMatrix4( m );
  6017. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6018. }
  6019. return this;
  6020. }
  6021. applyNormalMatrix( m ) {
  6022. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6023. _vector$9.fromBufferAttribute( this, i );
  6024. _vector$9.applyNormalMatrix( m );
  6025. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6026. }
  6027. return this;
  6028. }
  6029. transformDirection( m ) {
  6030. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6031. _vector$9.fromBufferAttribute( this, i );
  6032. _vector$9.transformDirection( m );
  6033. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6034. }
  6035. return this;
  6036. }
  6037. set( value, offset = 0 ) {
  6038. // Matching BufferAttribute constructor, do not normalize the array.
  6039. this.array.set( value, offset );
  6040. return this;
  6041. }
  6042. getComponent( index, component ) {
  6043. let value = this.array[ index * this.itemSize + component ];
  6044. if ( this.normalized ) value = denormalize( value, this.array );
  6045. return value;
  6046. }
  6047. setComponent( index, component, value ) {
  6048. if ( this.normalized ) value = normalize$1( value, this.array );
  6049. this.array[ index * this.itemSize + component ] = value;
  6050. return this;
  6051. }
  6052. getX( index ) {
  6053. let x = this.array[ index * this.itemSize ];
  6054. if ( this.normalized ) x = denormalize( x, this.array );
  6055. return x;
  6056. }
  6057. setX( index, x ) {
  6058. if ( this.normalized ) x = normalize$1( x, this.array );
  6059. this.array[ index * this.itemSize ] = x;
  6060. return this;
  6061. }
  6062. getY( index ) {
  6063. let y = this.array[ index * this.itemSize + 1 ];
  6064. if ( this.normalized ) y = denormalize( y, this.array );
  6065. return y;
  6066. }
  6067. setY( index, y ) {
  6068. if ( this.normalized ) y = normalize$1( y, this.array );
  6069. this.array[ index * this.itemSize + 1 ] = y;
  6070. return this;
  6071. }
  6072. getZ( index ) {
  6073. let z = this.array[ index * this.itemSize + 2 ];
  6074. if ( this.normalized ) z = denormalize( z, this.array );
  6075. return z;
  6076. }
  6077. setZ( index, z ) {
  6078. if ( this.normalized ) z = normalize$1( z, this.array );
  6079. this.array[ index * this.itemSize + 2 ] = z;
  6080. return this;
  6081. }
  6082. getW( index ) {
  6083. let w = this.array[ index * this.itemSize + 3 ];
  6084. if ( this.normalized ) w = denormalize( w, this.array );
  6085. return w;
  6086. }
  6087. setW( index, w ) {
  6088. if ( this.normalized ) w = normalize$1( w, this.array );
  6089. this.array[ index * this.itemSize + 3 ] = w;
  6090. return this;
  6091. }
  6092. setXY( index, x, y ) {
  6093. index *= this.itemSize;
  6094. if ( this.normalized ) {
  6095. x = normalize$1( x, this.array );
  6096. y = normalize$1( y, this.array );
  6097. }
  6098. this.array[ index + 0 ] = x;
  6099. this.array[ index + 1 ] = y;
  6100. return this;
  6101. }
  6102. setXYZ( index, x, y, z ) {
  6103. index *= this.itemSize;
  6104. if ( this.normalized ) {
  6105. x = normalize$1( x, this.array );
  6106. y = normalize$1( y, this.array );
  6107. z = normalize$1( z, this.array );
  6108. }
  6109. this.array[ index + 0 ] = x;
  6110. this.array[ index + 1 ] = y;
  6111. this.array[ index + 2 ] = z;
  6112. return this;
  6113. }
  6114. setXYZW( index, x, y, z, w ) {
  6115. index *= this.itemSize;
  6116. if ( this.normalized ) {
  6117. x = normalize$1( x, this.array );
  6118. y = normalize$1( y, this.array );
  6119. z = normalize$1( z, this.array );
  6120. w = normalize$1( w, this.array );
  6121. }
  6122. this.array[ index + 0 ] = x;
  6123. this.array[ index + 1 ] = y;
  6124. this.array[ index + 2 ] = z;
  6125. this.array[ index + 3 ] = w;
  6126. return this;
  6127. }
  6128. onUpload( callback ) {
  6129. this.onUploadCallback = callback;
  6130. return this;
  6131. }
  6132. clone() {
  6133. return new this.constructor( this.array, this.itemSize ).copy( this );
  6134. }
  6135. toJSON() {
  6136. const data = {
  6137. itemSize: this.itemSize,
  6138. type: this.array.constructor.name,
  6139. array: Array.from( this.array ),
  6140. normalized: this.normalized
  6141. };
  6142. if ( this.name !== '' ) data.name = this.name;
  6143. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6144. return data;
  6145. }
  6146. }
  6147. //
  6148. class Int8BufferAttribute extends BufferAttribute {
  6149. constructor( array, itemSize, normalized ) {
  6150. super( new Int8Array( array ), itemSize, normalized );
  6151. }
  6152. }
  6153. class Uint8BufferAttribute extends BufferAttribute {
  6154. constructor( array, itemSize, normalized ) {
  6155. super( new Uint8Array( array ), itemSize, normalized );
  6156. }
  6157. }
  6158. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Int16BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Int16Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Uint16BufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Uint16Array( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Int32BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Int32Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Uint32BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Uint32Array( array ), itemSize, normalized );
  6181. }
  6182. }
  6183. class Float16BufferAttribute extends BufferAttribute {
  6184. constructor( array, itemSize, normalized ) {
  6185. super( new Uint16Array( array ), itemSize, normalized );
  6186. this.isFloat16BufferAttribute = true;
  6187. }
  6188. getX( index ) {
  6189. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6190. if ( this.normalized ) x = denormalize( x, this.array );
  6191. return x;
  6192. }
  6193. setX( index, x ) {
  6194. if ( this.normalized ) x = normalize$1( x, this.array );
  6195. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6196. return this;
  6197. }
  6198. getY( index ) {
  6199. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6200. if ( this.normalized ) y = denormalize( y, this.array );
  6201. return y;
  6202. }
  6203. setY( index, y ) {
  6204. if ( this.normalized ) y = normalize$1( y, this.array );
  6205. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6206. return this;
  6207. }
  6208. getZ( index ) {
  6209. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6210. if ( this.normalized ) z = denormalize( z, this.array );
  6211. return z;
  6212. }
  6213. setZ( index, z ) {
  6214. if ( this.normalized ) z = normalize$1( z, this.array );
  6215. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6216. return this;
  6217. }
  6218. getW( index ) {
  6219. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6220. if ( this.normalized ) w = denormalize( w, this.array );
  6221. return w;
  6222. }
  6223. setW( index, w ) {
  6224. if ( this.normalized ) w = normalize$1( w, this.array );
  6225. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6226. return this;
  6227. }
  6228. setXY( index, x, y ) {
  6229. index *= this.itemSize;
  6230. if ( this.normalized ) {
  6231. x = normalize$1( x, this.array );
  6232. y = normalize$1( y, this.array );
  6233. }
  6234. this.array[ index + 0 ] = toHalfFloat( x );
  6235. this.array[ index + 1 ] = toHalfFloat( y );
  6236. return this;
  6237. }
  6238. setXYZ( index, x, y, z ) {
  6239. index *= this.itemSize;
  6240. if ( this.normalized ) {
  6241. x = normalize$1( x, this.array );
  6242. y = normalize$1( y, this.array );
  6243. z = normalize$1( z, this.array );
  6244. }
  6245. this.array[ index + 0 ] = toHalfFloat( x );
  6246. this.array[ index + 1 ] = toHalfFloat( y );
  6247. this.array[ index + 2 ] = toHalfFloat( z );
  6248. return this;
  6249. }
  6250. setXYZW( index, x, y, z, w ) {
  6251. index *= this.itemSize;
  6252. if ( this.normalized ) {
  6253. x = normalize$1( x, this.array );
  6254. y = normalize$1( y, this.array );
  6255. z = normalize$1( z, this.array );
  6256. w = normalize$1( w, this.array );
  6257. }
  6258. this.array[ index + 0 ] = toHalfFloat( x );
  6259. this.array[ index + 1 ] = toHalfFloat( y );
  6260. this.array[ index + 2 ] = toHalfFloat( z );
  6261. this.array[ index + 3 ] = toHalfFloat( w );
  6262. return this;
  6263. }
  6264. }
  6265. class Float32BufferAttribute extends BufferAttribute {
  6266. constructor( array, itemSize, normalized ) {
  6267. super( new Float32Array( array ), itemSize, normalized );
  6268. }
  6269. }
  6270. let _id$9 = 0;
  6271. const _m1 = /*@__PURE__*/ new Matrix4();
  6272. const _obj = /*@__PURE__*/ new Object3D();
  6273. const _offset = /*@__PURE__*/ new Vector3();
  6274. const _box$2 = /*@__PURE__*/ new Box3();
  6275. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6276. const _vector$8 = /*@__PURE__*/ new Vector3();
  6277. class BufferGeometry extends EventDispatcher {
  6278. constructor() {
  6279. super();
  6280. this.isBufferGeometry = true;
  6281. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6282. this.uuid = generateUUID();
  6283. this.name = '';
  6284. this.type = 'BufferGeometry';
  6285. this.index = null;
  6286. this.attributes = {};
  6287. this.morphAttributes = {};
  6288. this.morphTargetsRelative = false;
  6289. this.groups = [];
  6290. this.boundingBox = null;
  6291. this.boundingSphere = null;
  6292. this.drawRange = { start: 0, count: Infinity };
  6293. this.userData = {};
  6294. }
  6295. getIndex() {
  6296. return this.index;
  6297. }
  6298. setIndex( index ) {
  6299. if ( Array.isArray( index ) ) {
  6300. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6301. } else {
  6302. this.index = index;
  6303. }
  6304. return this;
  6305. }
  6306. getAttribute( name ) {
  6307. return this.attributes[ name ];
  6308. }
  6309. setAttribute( name, attribute ) {
  6310. this.attributes[ name ] = attribute;
  6311. return this;
  6312. }
  6313. deleteAttribute( name ) {
  6314. delete this.attributes[ name ];
  6315. return this;
  6316. }
  6317. hasAttribute( name ) {
  6318. return this.attributes[ name ] !== undefined;
  6319. }
  6320. addGroup( start, count, materialIndex = 0 ) {
  6321. this.groups.push( {
  6322. start: start,
  6323. count: count,
  6324. materialIndex: materialIndex
  6325. } );
  6326. }
  6327. clearGroups() {
  6328. this.groups = [];
  6329. }
  6330. setDrawRange( start, count ) {
  6331. this.drawRange.start = start;
  6332. this.drawRange.count = count;
  6333. }
  6334. applyMatrix4( matrix ) {
  6335. const position = this.attributes.position;
  6336. if ( position !== undefined ) {
  6337. position.applyMatrix4( matrix );
  6338. position.needsUpdate = true;
  6339. }
  6340. const normal = this.attributes.normal;
  6341. if ( normal !== undefined ) {
  6342. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6343. normal.applyNormalMatrix( normalMatrix );
  6344. normal.needsUpdate = true;
  6345. }
  6346. const tangent = this.attributes.tangent;
  6347. if ( tangent !== undefined ) {
  6348. tangent.transformDirection( matrix );
  6349. tangent.needsUpdate = true;
  6350. }
  6351. if ( this.boundingBox !== null ) {
  6352. this.computeBoundingBox();
  6353. }
  6354. if ( this.boundingSphere !== null ) {
  6355. this.computeBoundingSphere();
  6356. }
  6357. return this;
  6358. }
  6359. applyQuaternion( q ) {
  6360. _m1.makeRotationFromQuaternion( q );
  6361. this.applyMatrix4( _m1 );
  6362. return this;
  6363. }
  6364. rotateX( angle ) {
  6365. // rotate geometry around world x-axis
  6366. _m1.makeRotationX( angle );
  6367. this.applyMatrix4( _m1 );
  6368. return this;
  6369. }
  6370. rotateY( angle ) {
  6371. // rotate geometry around world y-axis
  6372. _m1.makeRotationY( angle );
  6373. this.applyMatrix4( _m1 );
  6374. return this;
  6375. }
  6376. rotateZ( angle ) {
  6377. // rotate geometry around world z-axis
  6378. _m1.makeRotationZ( angle );
  6379. this.applyMatrix4( _m1 );
  6380. return this;
  6381. }
  6382. translate( x, y, z ) {
  6383. // translate geometry
  6384. _m1.makeTranslation( x, y, z );
  6385. this.applyMatrix4( _m1 );
  6386. return this;
  6387. }
  6388. scale( x, y, z ) {
  6389. // scale geometry
  6390. _m1.makeScale( x, y, z );
  6391. this.applyMatrix4( _m1 );
  6392. return this;
  6393. }
  6394. lookAt( vector ) {
  6395. _obj.lookAt( vector );
  6396. _obj.updateMatrix();
  6397. this.applyMatrix4( _obj.matrix );
  6398. return this;
  6399. }
  6400. center() {
  6401. this.computeBoundingBox();
  6402. this.boundingBox.getCenter( _offset ).negate();
  6403. this.translate( _offset.x, _offset.y, _offset.z );
  6404. return this;
  6405. }
  6406. setFromPoints( points ) {
  6407. const position = [];
  6408. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6409. const point = points[ i ];
  6410. position.push( point.x, point.y, point.z || 0 );
  6411. }
  6412. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6413. return this;
  6414. }
  6415. computeBoundingBox() {
  6416. if ( this.boundingBox === null ) {
  6417. this.boundingBox = new Box3();
  6418. }
  6419. const position = this.attributes.position;
  6420. const morphAttributesPosition = this.morphAttributes.position;
  6421. if ( position && position.isGLBufferAttribute ) {
  6422. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6423. this.boundingBox.set(
  6424. new Vector3( - Infinity, - Infinity, - Infinity ),
  6425. new Vector3( + Infinity, + Infinity, + Infinity )
  6426. );
  6427. return;
  6428. }
  6429. if ( position !== undefined ) {
  6430. this.boundingBox.setFromBufferAttribute( position );
  6431. // process morph attributes if present
  6432. if ( morphAttributesPosition ) {
  6433. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6434. const morphAttribute = morphAttributesPosition[ i ];
  6435. _box$2.setFromBufferAttribute( morphAttribute );
  6436. if ( this.morphTargetsRelative ) {
  6437. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6438. this.boundingBox.expandByPoint( _vector$8 );
  6439. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6440. this.boundingBox.expandByPoint( _vector$8 );
  6441. } else {
  6442. this.boundingBox.expandByPoint( _box$2.min );
  6443. this.boundingBox.expandByPoint( _box$2.max );
  6444. }
  6445. }
  6446. }
  6447. } else {
  6448. this.boundingBox.makeEmpty();
  6449. }
  6450. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6451. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6452. }
  6453. }
  6454. computeBoundingSphere() {
  6455. if ( this.boundingSphere === null ) {
  6456. this.boundingSphere = new Sphere();
  6457. }
  6458. const position = this.attributes.position;
  6459. const morphAttributesPosition = this.morphAttributes.position;
  6460. if ( position && position.isGLBufferAttribute ) {
  6461. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6462. this.boundingSphere.set( new Vector3(), Infinity );
  6463. return;
  6464. }
  6465. if ( position ) {
  6466. // first, find the center of the bounding sphere
  6467. const center = this.boundingSphere.center;
  6468. _box$2.setFromBufferAttribute( position );
  6469. // process morph attributes if present
  6470. if ( morphAttributesPosition ) {
  6471. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6472. const morphAttribute = morphAttributesPosition[ i ];
  6473. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6474. if ( this.morphTargetsRelative ) {
  6475. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6476. _box$2.expandByPoint( _vector$8 );
  6477. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6478. _box$2.expandByPoint( _vector$8 );
  6479. } else {
  6480. _box$2.expandByPoint( _boxMorphTargets.min );
  6481. _box$2.expandByPoint( _boxMorphTargets.max );
  6482. }
  6483. }
  6484. }
  6485. _box$2.getCenter( center );
  6486. // second, try to find a boundingSphere with a radius smaller than the
  6487. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6488. let maxRadiusSq = 0;
  6489. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6490. _vector$8.fromBufferAttribute( position, i );
  6491. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6492. }
  6493. // process morph attributes if present
  6494. if ( morphAttributesPosition ) {
  6495. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6496. const morphAttribute = morphAttributesPosition[ i ];
  6497. const morphTargetsRelative = this.morphTargetsRelative;
  6498. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6499. _vector$8.fromBufferAttribute( morphAttribute, j );
  6500. if ( morphTargetsRelative ) {
  6501. _offset.fromBufferAttribute( position, j );
  6502. _vector$8.add( _offset );
  6503. }
  6504. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6505. }
  6506. }
  6507. }
  6508. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6509. if ( isNaN( this.boundingSphere.radius ) ) {
  6510. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6511. }
  6512. }
  6513. }
  6514. computeTangents() {
  6515. const index = this.index;
  6516. const attributes = this.attributes;
  6517. // based on http://www.terathon.com/code/tangent.html
  6518. // (per vertex tangents)
  6519. if ( index === null ||
  6520. attributes.position === undefined ||
  6521. attributes.normal === undefined ||
  6522. attributes.uv === undefined ) {
  6523. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6524. return;
  6525. }
  6526. const positionAttribute = attributes.position;
  6527. const normalAttribute = attributes.normal;
  6528. const uvAttribute = attributes.uv;
  6529. if ( this.hasAttribute( 'tangent' ) === false ) {
  6530. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6531. }
  6532. const tangentAttribute = this.getAttribute( 'tangent' );
  6533. const tan1 = [], tan2 = [];
  6534. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6535. tan1[ i ] = new Vector3();
  6536. tan2[ i ] = new Vector3();
  6537. }
  6538. const vA = new Vector3(),
  6539. vB = new Vector3(),
  6540. vC = new Vector3(),
  6541. uvA = new Vector2(),
  6542. uvB = new Vector2(),
  6543. uvC = new Vector2(),
  6544. sdir = new Vector3(),
  6545. tdir = new Vector3();
  6546. function handleTriangle( a, b, c ) {
  6547. vA.fromBufferAttribute( positionAttribute, a );
  6548. vB.fromBufferAttribute( positionAttribute, b );
  6549. vC.fromBufferAttribute( positionAttribute, c );
  6550. uvA.fromBufferAttribute( uvAttribute, a );
  6551. uvB.fromBufferAttribute( uvAttribute, b );
  6552. uvC.fromBufferAttribute( uvAttribute, c );
  6553. vB.sub( vA );
  6554. vC.sub( vA );
  6555. uvB.sub( uvA );
  6556. uvC.sub( uvA );
  6557. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6558. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6559. if ( ! isFinite( r ) ) return;
  6560. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6561. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6562. tan1[ a ].add( sdir );
  6563. tan1[ b ].add( sdir );
  6564. tan1[ c ].add( sdir );
  6565. tan2[ a ].add( tdir );
  6566. tan2[ b ].add( tdir );
  6567. tan2[ c ].add( tdir );
  6568. }
  6569. let groups = this.groups;
  6570. if ( groups.length === 0 ) {
  6571. groups = [ {
  6572. start: 0,
  6573. count: index.count
  6574. } ];
  6575. }
  6576. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6577. const group = groups[ i ];
  6578. const start = group.start;
  6579. const count = group.count;
  6580. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6581. handleTriangle(
  6582. index.getX( j + 0 ),
  6583. index.getX( j + 1 ),
  6584. index.getX( j + 2 )
  6585. );
  6586. }
  6587. }
  6588. const tmp = new Vector3(), tmp2 = new Vector3();
  6589. const n = new Vector3(), n2 = new Vector3();
  6590. function handleVertex( v ) {
  6591. n.fromBufferAttribute( normalAttribute, v );
  6592. n2.copy( n );
  6593. const t = tan1[ v ];
  6594. // Gram-Schmidt orthogonalize
  6595. tmp.copy( t );
  6596. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6597. // Calculate handedness
  6598. tmp2.crossVectors( n2, t );
  6599. const test = tmp2.dot( tan2[ v ] );
  6600. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6601. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6602. }
  6603. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6604. const group = groups[ i ];
  6605. const start = group.start;
  6606. const count = group.count;
  6607. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6608. handleVertex( index.getX( j + 0 ) );
  6609. handleVertex( index.getX( j + 1 ) );
  6610. handleVertex( index.getX( j + 2 ) );
  6611. }
  6612. }
  6613. }
  6614. computeVertexNormals() {
  6615. const index = this.index;
  6616. const positionAttribute = this.getAttribute( 'position' );
  6617. if ( positionAttribute !== undefined ) {
  6618. let normalAttribute = this.getAttribute( 'normal' );
  6619. if ( normalAttribute === undefined ) {
  6620. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6621. this.setAttribute( 'normal', normalAttribute );
  6622. } else {
  6623. // reset existing normals to zero
  6624. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6625. normalAttribute.setXYZ( i, 0, 0, 0 );
  6626. }
  6627. }
  6628. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6629. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6630. const cb = new Vector3(), ab = new Vector3();
  6631. // indexed elements
  6632. if ( index ) {
  6633. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6634. const vA = index.getX( i + 0 );
  6635. const vB = index.getX( i + 1 );
  6636. const vC = index.getX( i + 2 );
  6637. pA.fromBufferAttribute( positionAttribute, vA );
  6638. pB.fromBufferAttribute( positionAttribute, vB );
  6639. pC.fromBufferAttribute( positionAttribute, vC );
  6640. cb.subVectors( pC, pB );
  6641. ab.subVectors( pA, pB );
  6642. cb.cross( ab );
  6643. nA.fromBufferAttribute( normalAttribute, vA );
  6644. nB.fromBufferAttribute( normalAttribute, vB );
  6645. nC.fromBufferAttribute( normalAttribute, vC );
  6646. nA.add( cb );
  6647. nB.add( cb );
  6648. nC.add( cb );
  6649. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6650. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6651. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6652. }
  6653. } else {
  6654. // non-indexed elements (unconnected triangle soup)
  6655. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6656. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6657. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6658. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6659. cb.subVectors( pC, pB );
  6660. ab.subVectors( pA, pB );
  6661. cb.cross( ab );
  6662. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6663. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6664. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6665. }
  6666. }
  6667. this.normalizeNormals();
  6668. normalAttribute.needsUpdate = true;
  6669. }
  6670. }
  6671. normalizeNormals() {
  6672. const normals = this.attributes.normal;
  6673. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6674. _vector$8.fromBufferAttribute( normals, i );
  6675. _vector$8.normalize();
  6676. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6677. }
  6678. }
  6679. toNonIndexed() {
  6680. function convertBufferAttribute( attribute, indices ) {
  6681. const array = attribute.array;
  6682. const itemSize = attribute.itemSize;
  6683. const normalized = attribute.normalized;
  6684. const array2 = new array.constructor( indices.length * itemSize );
  6685. let index = 0, index2 = 0;
  6686. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6687. if ( attribute.isInterleavedBufferAttribute ) {
  6688. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6689. } else {
  6690. index = indices[ i ] * itemSize;
  6691. }
  6692. for ( let j = 0; j < itemSize; j ++ ) {
  6693. array2[ index2 ++ ] = array[ index ++ ];
  6694. }
  6695. }
  6696. return new BufferAttribute( array2, itemSize, normalized );
  6697. }
  6698. //
  6699. if ( this.index === null ) {
  6700. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6701. return this;
  6702. }
  6703. const geometry2 = new BufferGeometry();
  6704. const indices = this.index.array;
  6705. const attributes = this.attributes;
  6706. // attributes
  6707. for ( const name in attributes ) {
  6708. const attribute = attributes[ name ];
  6709. const newAttribute = convertBufferAttribute( attribute, indices );
  6710. geometry2.setAttribute( name, newAttribute );
  6711. }
  6712. // morph attributes
  6713. const morphAttributes = this.morphAttributes;
  6714. for ( const name in morphAttributes ) {
  6715. const morphArray = [];
  6716. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6717. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6718. const attribute = morphAttribute[ i ];
  6719. const newAttribute = convertBufferAttribute( attribute, indices );
  6720. morphArray.push( newAttribute );
  6721. }
  6722. geometry2.morphAttributes[ name ] = morphArray;
  6723. }
  6724. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6725. // groups
  6726. const groups = this.groups;
  6727. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6728. const group = groups[ i ];
  6729. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6730. }
  6731. return geometry2;
  6732. }
  6733. toJSON() {
  6734. const data = {
  6735. metadata: {
  6736. version: 4.6,
  6737. type: 'BufferGeometry',
  6738. generator: 'BufferGeometry.toJSON'
  6739. }
  6740. };
  6741. // standard BufferGeometry serialization
  6742. data.uuid = this.uuid;
  6743. data.type = this.type;
  6744. if ( this.name !== '' ) data.name = this.name;
  6745. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6746. if ( this.parameters !== undefined ) {
  6747. const parameters = this.parameters;
  6748. for ( const key in parameters ) {
  6749. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6750. }
  6751. return data;
  6752. }
  6753. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6754. data.data = { attributes: {} };
  6755. const index = this.index;
  6756. if ( index !== null ) {
  6757. data.data.index = {
  6758. type: index.array.constructor.name,
  6759. array: Array.prototype.slice.call( index.array )
  6760. };
  6761. }
  6762. const attributes = this.attributes;
  6763. for ( const key in attributes ) {
  6764. const attribute = attributes[ key ];
  6765. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6766. }
  6767. const morphAttributes = {};
  6768. let hasMorphAttributes = false;
  6769. for ( const key in this.morphAttributes ) {
  6770. const attributeArray = this.morphAttributes[ key ];
  6771. const array = [];
  6772. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6773. const attribute = attributeArray[ i ];
  6774. array.push( attribute.toJSON( data.data ) );
  6775. }
  6776. if ( array.length > 0 ) {
  6777. morphAttributes[ key ] = array;
  6778. hasMorphAttributes = true;
  6779. }
  6780. }
  6781. if ( hasMorphAttributes ) {
  6782. data.data.morphAttributes = morphAttributes;
  6783. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6784. }
  6785. const groups = this.groups;
  6786. if ( groups.length > 0 ) {
  6787. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6788. }
  6789. const boundingSphere = this.boundingSphere;
  6790. if ( boundingSphere !== null ) {
  6791. data.data.boundingSphere = {
  6792. center: boundingSphere.center.toArray(),
  6793. radius: boundingSphere.radius
  6794. };
  6795. }
  6796. return data;
  6797. }
  6798. clone() {
  6799. return new this.constructor().copy( this );
  6800. }
  6801. copy( source ) {
  6802. // reset
  6803. this.index = null;
  6804. this.attributes = {};
  6805. this.morphAttributes = {};
  6806. this.groups = [];
  6807. this.boundingBox = null;
  6808. this.boundingSphere = null;
  6809. // used for storing cloned, shared data
  6810. const data = {};
  6811. // name
  6812. this.name = source.name;
  6813. // index
  6814. const index = source.index;
  6815. if ( index !== null ) {
  6816. this.setIndex( index.clone( data ) );
  6817. }
  6818. // attributes
  6819. const attributes = source.attributes;
  6820. for ( const name in attributes ) {
  6821. const attribute = attributes[ name ];
  6822. this.setAttribute( name, attribute.clone( data ) );
  6823. }
  6824. // morph attributes
  6825. const morphAttributes = source.morphAttributes;
  6826. for ( const name in morphAttributes ) {
  6827. const array = [];
  6828. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6829. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6830. array.push( morphAttribute[ i ].clone( data ) );
  6831. }
  6832. this.morphAttributes[ name ] = array;
  6833. }
  6834. this.morphTargetsRelative = source.morphTargetsRelative;
  6835. // groups
  6836. const groups = source.groups;
  6837. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6838. const group = groups[ i ];
  6839. this.addGroup( group.start, group.count, group.materialIndex );
  6840. }
  6841. // bounding box
  6842. const boundingBox = source.boundingBox;
  6843. if ( boundingBox !== null ) {
  6844. this.boundingBox = boundingBox.clone();
  6845. }
  6846. // bounding sphere
  6847. const boundingSphere = source.boundingSphere;
  6848. if ( boundingSphere !== null ) {
  6849. this.boundingSphere = boundingSphere.clone();
  6850. }
  6851. // draw range
  6852. this.drawRange.start = source.drawRange.start;
  6853. this.drawRange.count = source.drawRange.count;
  6854. // user data
  6855. this.userData = source.userData;
  6856. return this;
  6857. }
  6858. dispose() {
  6859. this.dispatchEvent( { type: 'dispose' } );
  6860. }
  6861. }
  6862. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6863. const _ray$3 = /*@__PURE__*/ new Ray();
  6864. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6865. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6866. const _vA$1 = /*@__PURE__*/ new Vector3();
  6867. const _vB$1 = /*@__PURE__*/ new Vector3();
  6868. const _vC$1 = /*@__PURE__*/ new Vector3();
  6869. const _tempA = /*@__PURE__*/ new Vector3();
  6870. const _morphA = /*@__PURE__*/ new Vector3();
  6871. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6872. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6873. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6874. const _normalA = /*@__PURE__*/ new Vector3();
  6875. const _normalB = /*@__PURE__*/ new Vector3();
  6876. const _normalC = /*@__PURE__*/ new Vector3();
  6877. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6878. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6879. class Mesh extends Object3D {
  6880. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6881. super();
  6882. this.isMesh = true;
  6883. this.type = 'Mesh';
  6884. this.geometry = geometry;
  6885. this.material = material;
  6886. this.updateMorphTargets();
  6887. }
  6888. copy( source, recursive ) {
  6889. super.copy( source, recursive );
  6890. if ( source.morphTargetInfluences !== undefined ) {
  6891. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6892. }
  6893. if ( source.morphTargetDictionary !== undefined ) {
  6894. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6895. }
  6896. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6897. this.geometry = source.geometry;
  6898. return this;
  6899. }
  6900. updateMorphTargets() {
  6901. const geometry = this.geometry;
  6902. const morphAttributes = geometry.morphAttributes;
  6903. const keys = Object.keys( morphAttributes );
  6904. if ( keys.length > 0 ) {
  6905. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6906. if ( morphAttribute !== undefined ) {
  6907. this.morphTargetInfluences = [];
  6908. this.morphTargetDictionary = {};
  6909. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6910. const name = morphAttribute[ m ].name || String( m );
  6911. this.morphTargetInfluences.push( 0 );
  6912. this.morphTargetDictionary[ name ] = m;
  6913. }
  6914. }
  6915. }
  6916. }
  6917. getVertexPosition( index, target ) {
  6918. const geometry = this.geometry;
  6919. const position = geometry.attributes.position;
  6920. const morphPosition = geometry.morphAttributes.position;
  6921. const morphTargetsRelative = geometry.morphTargetsRelative;
  6922. target.fromBufferAttribute( position, index );
  6923. const morphInfluences = this.morphTargetInfluences;
  6924. if ( morphPosition && morphInfluences ) {
  6925. _morphA.set( 0, 0, 0 );
  6926. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6927. const influence = morphInfluences[ i ];
  6928. const morphAttribute = morphPosition[ i ];
  6929. if ( influence === 0 ) continue;
  6930. _tempA.fromBufferAttribute( morphAttribute, index );
  6931. if ( morphTargetsRelative ) {
  6932. _morphA.addScaledVector( _tempA, influence );
  6933. } else {
  6934. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6935. }
  6936. }
  6937. target.add( _morphA );
  6938. }
  6939. return target;
  6940. }
  6941. raycast( raycaster, intersects ) {
  6942. const geometry = this.geometry;
  6943. const material = this.material;
  6944. const matrixWorld = this.matrixWorld;
  6945. if ( material === undefined ) return;
  6946. // test with bounding sphere in world space
  6947. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6948. _sphere$6.copy( geometry.boundingSphere );
  6949. _sphere$6.applyMatrix4( matrixWorld );
  6950. // check distance from ray origin to bounding sphere
  6951. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6952. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6953. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6954. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6955. }
  6956. // convert ray to local space of mesh
  6957. _inverseMatrix$3.copy( matrixWorld ).invert();
  6958. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6959. // test with bounding box in local space
  6960. if ( geometry.boundingBox !== null ) {
  6961. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6962. }
  6963. // test for intersections with geometry
  6964. this._computeIntersections( raycaster, intersects, _ray$3 );
  6965. }
  6966. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6967. let intersection;
  6968. const geometry = this.geometry;
  6969. const material = this.material;
  6970. const index = geometry.index;
  6971. const position = geometry.attributes.position;
  6972. const uv = geometry.attributes.uv;
  6973. const uv1 = geometry.attributes.uv1;
  6974. const normal = geometry.attributes.normal;
  6975. const groups = geometry.groups;
  6976. const drawRange = geometry.drawRange;
  6977. if ( index !== null ) {
  6978. // indexed buffer geometry
  6979. if ( Array.isArray( material ) ) {
  6980. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6981. const group = groups[ i ];
  6982. const groupMaterial = material[ group.materialIndex ];
  6983. const start = Math.max( group.start, drawRange.start );
  6984. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6985. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6986. const a = index.getX( j );
  6987. const b = index.getX( j + 1 );
  6988. const c = index.getX( j + 2 );
  6989. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6990. if ( intersection ) {
  6991. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6992. intersection.face.materialIndex = group.materialIndex;
  6993. intersects.push( intersection );
  6994. }
  6995. }
  6996. }
  6997. } else {
  6998. const start = Math.max( 0, drawRange.start );
  6999. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7000. for ( let i = start, il = end; i < il; i += 3 ) {
  7001. const a = index.getX( i );
  7002. const b = index.getX( i + 1 );
  7003. const c = index.getX( i + 2 );
  7004. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7005. if ( intersection ) {
  7006. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7007. intersects.push( intersection );
  7008. }
  7009. }
  7010. }
  7011. } else if ( position !== undefined ) {
  7012. // non-indexed buffer geometry
  7013. if ( Array.isArray( material ) ) {
  7014. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7015. const group = groups[ i ];
  7016. const groupMaterial = material[ group.materialIndex ];
  7017. const start = Math.max( group.start, drawRange.start );
  7018. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7019. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7020. const a = j;
  7021. const b = j + 1;
  7022. const c = j + 2;
  7023. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7024. if ( intersection ) {
  7025. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7026. intersection.face.materialIndex = group.materialIndex;
  7027. intersects.push( intersection );
  7028. }
  7029. }
  7030. }
  7031. } else {
  7032. const start = Math.max( 0, drawRange.start );
  7033. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7034. for ( let i = start, il = end; i < il; i += 3 ) {
  7035. const a = i;
  7036. const b = i + 1;
  7037. const c = i + 2;
  7038. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7039. if ( intersection ) {
  7040. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7041. intersects.push( intersection );
  7042. }
  7043. }
  7044. }
  7045. }
  7046. }
  7047. }
  7048. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7049. let intersect;
  7050. if ( material.side === BackSide ) {
  7051. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7052. } else {
  7053. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7054. }
  7055. if ( intersect === null ) return null;
  7056. _intersectionPointWorld.copy( point );
  7057. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7058. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7059. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7060. return {
  7061. distance: distance,
  7062. point: _intersectionPointWorld.clone(),
  7063. object: object
  7064. };
  7065. }
  7066. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7067. object.getVertexPosition( a, _vA$1 );
  7068. object.getVertexPosition( b, _vB$1 );
  7069. object.getVertexPosition( c, _vC$1 );
  7070. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7071. if ( intersection ) {
  7072. if ( uv ) {
  7073. _uvA$1.fromBufferAttribute( uv, a );
  7074. _uvB$1.fromBufferAttribute( uv, b );
  7075. _uvC$1.fromBufferAttribute( uv, c );
  7076. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7077. }
  7078. if ( uv1 ) {
  7079. _uvA$1.fromBufferAttribute( uv1, a );
  7080. _uvB$1.fromBufferAttribute( uv1, b );
  7081. _uvC$1.fromBufferAttribute( uv1, c );
  7082. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7083. }
  7084. if ( normal ) {
  7085. _normalA.fromBufferAttribute( normal, a );
  7086. _normalB.fromBufferAttribute( normal, b );
  7087. _normalC.fromBufferAttribute( normal, c );
  7088. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7089. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7090. intersection.normal.multiplyScalar( - 1 );
  7091. }
  7092. }
  7093. const face = {
  7094. a: a,
  7095. b: b,
  7096. c: c,
  7097. normal: new Vector3(),
  7098. materialIndex: 0
  7099. };
  7100. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7101. intersection.face = face;
  7102. }
  7103. return intersection;
  7104. }
  7105. class BoxGeometry extends BufferGeometry {
  7106. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7107. super();
  7108. this.type = 'BoxGeometry';
  7109. this.parameters = {
  7110. width: width,
  7111. height: height,
  7112. depth: depth,
  7113. widthSegments: widthSegments,
  7114. heightSegments: heightSegments,
  7115. depthSegments: depthSegments
  7116. };
  7117. const scope = this;
  7118. // segments
  7119. widthSegments = Math.floor( widthSegments );
  7120. heightSegments = Math.floor( heightSegments );
  7121. depthSegments = Math.floor( depthSegments );
  7122. // buffers
  7123. const indices = [];
  7124. const vertices = [];
  7125. const normals = [];
  7126. const uvs = [];
  7127. // helper variables
  7128. let numberOfVertices = 0;
  7129. let groupStart = 0;
  7130. // build each side of the box geometry
  7131. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7132. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7133. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7134. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7135. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7136. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7137. // build geometry
  7138. this.setIndex( indices );
  7139. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7140. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7141. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7142. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7143. const segmentWidth = width / gridX;
  7144. const segmentHeight = height / gridY;
  7145. const widthHalf = width / 2;
  7146. const heightHalf = height / 2;
  7147. const depthHalf = depth / 2;
  7148. const gridX1 = gridX + 1;
  7149. const gridY1 = gridY + 1;
  7150. let vertexCounter = 0;
  7151. let groupCount = 0;
  7152. const vector = new Vector3();
  7153. // generate vertices, normals and uvs
  7154. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7155. const y = iy * segmentHeight - heightHalf;
  7156. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7157. const x = ix * segmentWidth - widthHalf;
  7158. // set values to correct vector component
  7159. vector[ u ] = x * udir;
  7160. vector[ v ] = y * vdir;
  7161. vector[ w ] = depthHalf;
  7162. // now apply vector to vertex buffer
  7163. vertices.push( vector.x, vector.y, vector.z );
  7164. // set values to correct vector component
  7165. vector[ u ] = 0;
  7166. vector[ v ] = 0;
  7167. vector[ w ] = depth > 0 ? 1 : - 1;
  7168. // now apply vector to normal buffer
  7169. normals.push( vector.x, vector.y, vector.z );
  7170. // uvs
  7171. uvs.push( ix / gridX );
  7172. uvs.push( 1 - ( iy / gridY ) );
  7173. // counters
  7174. vertexCounter += 1;
  7175. }
  7176. }
  7177. // indices
  7178. // 1. you need three indices to draw a single face
  7179. // 2. a single segment consists of two faces
  7180. // 3. so we need to generate six (2*3) indices per segment
  7181. for ( let iy = 0; iy < gridY; iy ++ ) {
  7182. for ( let ix = 0; ix < gridX; ix ++ ) {
  7183. const a = numberOfVertices + ix + gridX1 * iy;
  7184. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7185. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7186. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7187. // faces
  7188. indices.push( a, b, d );
  7189. indices.push( b, c, d );
  7190. // increase counter
  7191. groupCount += 6;
  7192. }
  7193. }
  7194. // add a group to the geometry. this will ensure multi material support
  7195. scope.addGroup( groupStart, groupCount, materialIndex );
  7196. // calculate new start value for groups
  7197. groupStart += groupCount;
  7198. // update total number of vertices
  7199. numberOfVertices += vertexCounter;
  7200. }
  7201. }
  7202. copy( source ) {
  7203. super.copy( source );
  7204. this.parameters = Object.assign( {}, source.parameters );
  7205. return this;
  7206. }
  7207. static fromJSON( data ) {
  7208. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7209. }
  7210. }
  7211. /**
  7212. * Uniform Utilities
  7213. */
  7214. function cloneUniforms( src ) {
  7215. const dst = {};
  7216. for ( const u in src ) {
  7217. dst[ u ] = {};
  7218. for ( const p in src[ u ] ) {
  7219. const property = src[ u ][ p ];
  7220. if ( property && ( property.isColor ||
  7221. property.isMatrix3 || property.isMatrix4 ||
  7222. property.isVector2 || property.isVector3 || property.isVector4 ||
  7223. property.isTexture || property.isQuaternion ) ) {
  7224. if ( property.isRenderTargetTexture ) {
  7225. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7226. dst[ u ][ p ] = null;
  7227. } else {
  7228. dst[ u ][ p ] = property.clone();
  7229. }
  7230. } else if ( Array.isArray( property ) ) {
  7231. dst[ u ][ p ] = property.slice();
  7232. } else {
  7233. dst[ u ][ p ] = property;
  7234. }
  7235. }
  7236. }
  7237. return dst;
  7238. }
  7239. function cloneUniformsGroups( src ) {
  7240. const dst = [];
  7241. for ( let u = 0; u < src.length; u ++ ) {
  7242. dst.push( src[ u ].clone() );
  7243. }
  7244. return dst;
  7245. }
  7246. var default_vertex = /* glsl */`
  7247. void main() {
  7248. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7249. }
  7250. `;
  7251. var default_fragment = /* glsl */`
  7252. void main() {
  7253. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7254. }
  7255. `;
  7256. class ShaderMaterial extends Material {
  7257. constructor( parameters ) {
  7258. super();
  7259. this.isShaderMaterial = true;
  7260. this.type = 'ShaderMaterial';
  7261. this.defines = {};
  7262. this.uniforms = {};
  7263. this.uniformsGroups = [];
  7264. this.vertexShader = default_vertex;
  7265. this.fragmentShader = default_fragment;
  7266. this.linewidth = 1;
  7267. this.wireframe = false;
  7268. this.wireframeLinewidth = 1;
  7269. this.fog = false; // set to use scene fog
  7270. this.lights = false; // set to use scene lights
  7271. this.clipping = false; // set to use user-defined clipping planes
  7272. this.forceSinglePass = true;
  7273. this.extensions = {
  7274. clipCullDistance: false, // set to use vertex shader clipping
  7275. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7276. };
  7277. // When rendered geometry doesn't include these attributes but the material does,
  7278. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7279. this.defaultAttributeValues = {
  7280. 'color': [ 1, 1, 1 ],
  7281. 'uv': [ 0, 0 ],
  7282. 'uv1': [ 0, 0 ]
  7283. };
  7284. this.index0AttributeName = undefined;
  7285. this.uniformsNeedUpdate = false;
  7286. this.glslVersion = null;
  7287. if ( parameters !== undefined ) {
  7288. this.setValues( parameters );
  7289. }
  7290. }
  7291. copy( source ) {
  7292. super.copy( source );
  7293. this.fragmentShader = source.fragmentShader;
  7294. this.vertexShader = source.vertexShader;
  7295. this.uniforms = cloneUniforms( source.uniforms );
  7296. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7297. this.defines = Object.assign( {}, source.defines );
  7298. this.wireframe = source.wireframe;
  7299. this.wireframeLinewidth = source.wireframeLinewidth;
  7300. this.fog = source.fog;
  7301. this.lights = source.lights;
  7302. this.clipping = source.clipping;
  7303. this.extensions = Object.assign( {}, source.extensions );
  7304. this.glslVersion = source.glslVersion;
  7305. return this;
  7306. }
  7307. toJSON( meta ) {
  7308. const data = super.toJSON( meta );
  7309. data.glslVersion = this.glslVersion;
  7310. data.uniforms = {};
  7311. for ( const name in this.uniforms ) {
  7312. const uniform = this.uniforms[ name ];
  7313. const value = uniform.value;
  7314. if ( value && value.isTexture ) {
  7315. data.uniforms[ name ] = {
  7316. type: 't',
  7317. value: value.toJSON( meta ).uuid
  7318. };
  7319. } else if ( value && value.isColor ) {
  7320. data.uniforms[ name ] = {
  7321. type: 'c',
  7322. value: value.getHex()
  7323. };
  7324. } else if ( value && value.isVector2 ) {
  7325. data.uniforms[ name ] = {
  7326. type: 'v2',
  7327. value: value.toArray()
  7328. };
  7329. } else if ( value && value.isVector3 ) {
  7330. data.uniforms[ name ] = {
  7331. type: 'v3',
  7332. value: value.toArray()
  7333. };
  7334. } else if ( value && value.isVector4 ) {
  7335. data.uniforms[ name ] = {
  7336. type: 'v4',
  7337. value: value.toArray()
  7338. };
  7339. } else if ( value && value.isMatrix3 ) {
  7340. data.uniforms[ name ] = {
  7341. type: 'm3',
  7342. value: value.toArray()
  7343. };
  7344. } else if ( value && value.isMatrix4 ) {
  7345. data.uniforms[ name ] = {
  7346. type: 'm4',
  7347. value: value.toArray()
  7348. };
  7349. } else {
  7350. data.uniforms[ name ] = {
  7351. value: value
  7352. };
  7353. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7354. }
  7355. }
  7356. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7357. data.vertexShader = this.vertexShader;
  7358. data.fragmentShader = this.fragmentShader;
  7359. data.lights = this.lights;
  7360. data.clipping = this.clipping;
  7361. const extensions = {};
  7362. for ( const key in this.extensions ) {
  7363. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7364. }
  7365. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7366. return data;
  7367. }
  7368. }
  7369. class Camera extends Object3D {
  7370. constructor() {
  7371. super();
  7372. this.isCamera = true;
  7373. this.type = 'Camera';
  7374. this.matrixWorldInverse = new Matrix4();
  7375. this.projectionMatrix = new Matrix4();
  7376. this.projectionMatrixInverse = new Matrix4();
  7377. this.coordinateSystem = WebGLCoordinateSystem;
  7378. }
  7379. copy( source, recursive ) {
  7380. super.copy( source, recursive );
  7381. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7382. this.projectionMatrix.copy( source.projectionMatrix );
  7383. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7384. this.coordinateSystem = source.coordinateSystem;
  7385. return this;
  7386. }
  7387. getWorldDirection( target ) {
  7388. return super.getWorldDirection( target ).negate();
  7389. }
  7390. updateMatrixWorld( force ) {
  7391. super.updateMatrixWorld( force );
  7392. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7393. }
  7394. updateWorldMatrix( updateParents, updateChildren ) {
  7395. super.updateWorldMatrix( updateParents, updateChildren );
  7396. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7397. }
  7398. clone() {
  7399. return new this.constructor().copy( this );
  7400. }
  7401. }
  7402. const _v3$1 = /*@__PURE__*/ new Vector3();
  7403. const _minTarget = /*@__PURE__*/ new Vector2();
  7404. const _maxTarget = /*@__PURE__*/ new Vector2();
  7405. class PerspectiveCamera extends Camera {
  7406. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7407. super();
  7408. this.isPerspectiveCamera = true;
  7409. this.type = 'PerspectiveCamera';
  7410. this.fov = fov;
  7411. this.zoom = 1;
  7412. this.near = near;
  7413. this.far = far;
  7414. this.focus = 10;
  7415. this.aspect = aspect;
  7416. this.view = null;
  7417. this.filmGauge = 35; // width of the film (default in millimeters)
  7418. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7419. this.updateProjectionMatrix();
  7420. }
  7421. copy( source, recursive ) {
  7422. super.copy( source, recursive );
  7423. this.fov = source.fov;
  7424. this.zoom = source.zoom;
  7425. this.near = source.near;
  7426. this.far = source.far;
  7427. this.focus = source.focus;
  7428. this.aspect = source.aspect;
  7429. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7430. this.filmGauge = source.filmGauge;
  7431. this.filmOffset = source.filmOffset;
  7432. return this;
  7433. }
  7434. /**
  7435. * Sets the FOV by focal length in respect to the current .filmGauge.
  7436. *
  7437. * The default film gauge is 35, so that the focal length can be specified for
  7438. * a 35mm (full frame) camera.
  7439. *
  7440. * Values for focal length and film gauge must have the same unit.
  7441. */
  7442. setFocalLength( focalLength ) {
  7443. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7444. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7445. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7446. this.updateProjectionMatrix();
  7447. }
  7448. /**
  7449. * Calculates the focal length from the current .fov and .filmGauge.
  7450. */
  7451. getFocalLength() {
  7452. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7453. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7454. }
  7455. getEffectiveFOV() {
  7456. return RAD2DEG * 2 * Math.atan(
  7457. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7458. }
  7459. getFilmWidth() {
  7460. // film not completely covered in portrait format (aspect < 1)
  7461. return this.filmGauge * Math.min( this.aspect, 1 );
  7462. }
  7463. getFilmHeight() {
  7464. // film not completely covered in landscape format (aspect > 1)
  7465. return this.filmGauge / Math.max( this.aspect, 1 );
  7466. }
  7467. /**
  7468. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7469. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7470. */
  7471. getViewBounds( distance, minTarget, maxTarget ) {
  7472. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7473. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7474. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7475. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7476. }
  7477. /**
  7478. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7479. * Copies the result into the target Vector2, where x is width and y is height.
  7480. */
  7481. getViewSize( distance, target ) {
  7482. this.getViewBounds( distance, _minTarget, _maxTarget );
  7483. return target.subVectors( _maxTarget, _minTarget );
  7484. }
  7485. /**
  7486. * Sets an offset in a larger frustum. This is useful for multi-window or
  7487. * multi-monitor/multi-machine setups.
  7488. *
  7489. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7490. * the monitors are in grid like this
  7491. *
  7492. * +---+---+---+
  7493. * | A | B | C |
  7494. * +---+---+---+
  7495. * | D | E | F |
  7496. * +---+---+---+
  7497. *
  7498. * then for each monitor you would call it like this
  7499. *
  7500. * const w = 1920;
  7501. * const h = 1080;
  7502. * const fullWidth = w * 3;
  7503. * const fullHeight = h * 2;
  7504. *
  7505. * --A--
  7506. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7507. * --B--
  7508. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7509. * --C--
  7510. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7511. * --D--
  7512. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7513. * --E--
  7514. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7515. * --F--
  7516. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7517. *
  7518. * Note there is no reason monitors have to be the same size or in a grid.
  7519. */
  7520. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7521. this.aspect = fullWidth / fullHeight;
  7522. if ( this.view === null ) {
  7523. this.view = {
  7524. enabled: true,
  7525. fullWidth: 1,
  7526. fullHeight: 1,
  7527. offsetX: 0,
  7528. offsetY: 0,
  7529. width: 1,
  7530. height: 1
  7531. };
  7532. }
  7533. this.view.enabled = true;
  7534. this.view.fullWidth = fullWidth;
  7535. this.view.fullHeight = fullHeight;
  7536. this.view.offsetX = x;
  7537. this.view.offsetY = y;
  7538. this.view.width = width;
  7539. this.view.height = height;
  7540. this.updateProjectionMatrix();
  7541. }
  7542. clearViewOffset() {
  7543. if ( this.view !== null ) {
  7544. this.view.enabled = false;
  7545. }
  7546. this.updateProjectionMatrix();
  7547. }
  7548. updateProjectionMatrix() {
  7549. const near = this.near;
  7550. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7551. let height = 2 * top;
  7552. let width = this.aspect * height;
  7553. let left = - 0.5 * width;
  7554. const view = this.view;
  7555. if ( this.view !== null && this.view.enabled ) {
  7556. const fullWidth = view.fullWidth,
  7557. fullHeight = view.fullHeight;
  7558. left += view.offsetX * width / fullWidth;
  7559. top -= view.offsetY * height / fullHeight;
  7560. width *= view.width / fullWidth;
  7561. height *= view.height / fullHeight;
  7562. }
  7563. const skew = this.filmOffset;
  7564. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7565. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7566. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7567. }
  7568. toJSON( meta ) {
  7569. const data = super.toJSON( meta );
  7570. data.object.fov = this.fov;
  7571. data.object.zoom = this.zoom;
  7572. data.object.near = this.near;
  7573. data.object.far = this.far;
  7574. data.object.focus = this.focus;
  7575. data.object.aspect = this.aspect;
  7576. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7577. data.object.filmGauge = this.filmGauge;
  7578. data.object.filmOffset = this.filmOffset;
  7579. return data;
  7580. }
  7581. }
  7582. const fov = - 90; // negative fov is not an error
  7583. const aspect = 1;
  7584. class CubeCamera extends Object3D {
  7585. constructor( near, far, renderTarget ) {
  7586. super();
  7587. this.type = 'CubeCamera';
  7588. this.renderTarget = renderTarget;
  7589. this.coordinateSystem = null;
  7590. this.activeMipmapLevel = 0;
  7591. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7592. cameraPX.layers = this.layers;
  7593. this.add( cameraPX );
  7594. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7595. cameraNX.layers = this.layers;
  7596. this.add( cameraNX );
  7597. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7598. cameraPY.layers = this.layers;
  7599. this.add( cameraPY );
  7600. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7601. cameraNY.layers = this.layers;
  7602. this.add( cameraNY );
  7603. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7604. cameraPZ.layers = this.layers;
  7605. this.add( cameraPZ );
  7606. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7607. cameraNZ.layers = this.layers;
  7608. this.add( cameraNZ );
  7609. }
  7610. updateCoordinateSystem() {
  7611. const coordinateSystem = this.coordinateSystem;
  7612. const cameras = this.children.concat();
  7613. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7614. for ( const camera of cameras ) this.remove( camera );
  7615. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7616. cameraPX.up.set( 0, 1, 0 );
  7617. cameraPX.lookAt( 1, 0, 0 );
  7618. cameraNX.up.set( 0, 1, 0 );
  7619. cameraNX.lookAt( - 1, 0, 0 );
  7620. cameraPY.up.set( 0, 0, - 1 );
  7621. cameraPY.lookAt( 0, 1, 0 );
  7622. cameraNY.up.set( 0, 0, 1 );
  7623. cameraNY.lookAt( 0, - 1, 0 );
  7624. cameraPZ.up.set( 0, 1, 0 );
  7625. cameraPZ.lookAt( 0, 0, 1 );
  7626. cameraNZ.up.set( 0, 1, 0 );
  7627. cameraNZ.lookAt( 0, 0, - 1 );
  7628. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7629. cameraPX.up.set( 0, - 1, 0 );
  7630. cameraPX.lookAt( - 1, 0, 0 );
  7631. cameraNX.up.set( 0, - 1, 0 );
  7632. cameraNX.lookAt( 1, 0, 0 );
  7633. cameraPY.up.set( 0, 0, 1 );
  7634. cameraPY.lookAt( 0, 1, 0 );
  7635. cameraNY.up.set( 0, 0, - 1 );
  7636. cameraNY.lookAt( 0, - 1, 0 );
  7637. cameraPZ.up.set( 0, - 1, 0 );
  7638. cameraPZ.lookAt( 0, 0, 1 );
  7639. cameraNZ.up.set( 0, - 1, 0 );
  7640. cameraNZ.lookAt( 0, 0, - 1 );
  7641. } else {
  7642. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7643. }
  7644. for ( const camera of cameras ) {
  7645. this.add( camera );
  7646. camera.updateMatrixWorld();
  7647. }
  7648. }
  7649. update( renderer, scene ) {
  7650. if ( this.parent === null ) this.updateMatrixWorld();
  7651. const { renderTarget, activeMipmapLevel } = this;
  7652. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7653. this.coordinateSystem = renderer.coordinateSystem;
  7654. this.updateCoordinateSystem();
  7655. }
  7656. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7657. const currentRenderTarget = renderer.getRenderTarget();
  7658. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7659. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7660. const currentXrEnabled = renderer.xr.enabled;
  7661. renderer.xr.enabled = false;
  7662. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7663. renderTarget.texture.generateMipmaps = false;
  7664. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7665. renderer.render( scene, cameraPX );
  7666. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7667. renderer.render( scene, cameraNX );
  7668. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7669. renderer.render( scene, cameraPY );
  7670. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7671. renderer.render( scene, cameraNY );
  7672. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7673. renderer.render( scene, cameraPZ );
  7674. // mipmaps are generated during the last call of render()
  7675. // at this point, all sides of the cube render target are defined
  7676. renderTarget.texture.generateMipmaps = generateMipmaps;
  7677. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7678. renderer.render( scene, cameraNZ );
  7679. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7680. renderer.xr.enabled = currentXrEnabled;
  7681. renderTarget.texture.needsPMREMUpdate = true;
  7682. }
  7683. }
  7684. class CubeTexture extends Texture {
  7685. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7686. images = images !== undefined ? images : [];
  7687. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7688. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7689. this.isCubeTexture = true;
  7690. this.flipY = false;
  7691. }
  7692. get images() {
  7693. return this.image;
  7694. }
  7695. set images( value ) {
  7696. this.image = value;
  7697. }
  7698. }
  7699. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7700. constructor( size = 1, options = {} ) {
  7701. super( size, size, options );
  7702. this.isWebGLCubeRenderTarget = true;
  7703. const image = { width: size, height: size, depth: 1 };
  7704. const images = [ image, image, image, image, image, image ];
  7705. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7706. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7707. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7708. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7709. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7710. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7711. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7712. this.texture.isRenderTargetTexture = true;
  7713. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7714. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7715. }
  7716. fromEquirectangularTexture( renderer, texture ) {
  7717. this.texture.type = texture.type;
  7718. this.texture.colorSpace = texture.colorSpace;
  7719. this.texture.generateMipmaps = texture.generateMipmaps;
  7720. this.texture.minFilter = texture.minFilter;
  7721. this.texture.magFilter = texture.magFilter;
  7722. const shader = {
  7723. uniforms: {
  7724. tEquirect: { value: null },
  7725. },
  7726. vertexShader: /* glsl */`
  7727. varying vec3 vWorldDirection;
  7728. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7729. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7730. }
  7731. void main() {
  7732. vWorldDirection = transformDirection( position, modelMatrix );
  7733. #include <begin_vertex>
  7734. #include <project_vertex>
  7735. }
  7736. `,
  7737. fragmentShader: /* glsl */`
  7738. uniform sampler2D tEquirect;
  7739. varying vec3 vWorldDirection;
  7740. #include <common>
  7741. void main() {
  7742. vec3 direction = normalize( vWorldDirection );
  7743. vec2 sampleUV = equirectUv( direction );
  7744. gl_FragColor = texture2D( tEquirect, sampleUV );
  7745. }
  7746. `
  7747. };
  7748. const geometry = new BoxGeometry( 5, 5, 5 );
  7749. const material = new ShaderMaterial( {
  7750. name: 'CubemapFromEquirect',
  7751. uniforms: cloneUniforms( shader.uniforms ),
  7752. vertexShader: shader.vertexShader,
  7753. fragmentShader: shader.fragmentShader,
  7754. side: BackSide,
  7755. blending: NoBlending
  7756. } );
  7757. material.uniforms.tEquirect.value = texture;
  7758. const mesh = new Mesh( geometry, material );
  7759. const currentMinFilter = texture.minFilter;
  7760. // Avoid blurred poles
  7761. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7762. const camera = new CubeCamera( 1, 10, this );
  7763. camera.update( renderer, mesh );
  7764. texture.minFilter = currentMinFilter;
  7765. mesh.geometry.dispose();
  7766. mesh.material.dispose();
  7767. return this;
  7768. }
  7769. clear( renderer, color, depth, stencil ) {
  7770. const currentRenderTarget = renderer.getRenderTarget();
  7771. for ( let i = 0; i < 6; i ++ ) {
  7772. renderer.setRenderTarget( this, i );
  7773. renderer.clear( color, depth, stencil );
  7774. }
  7775. renderer.setRenderTarget( currentRenderTarget );
  7776. }
  7777. }
  7778. class FogExp2 {
  7779. constructor( color, density = 0.00025 ) {
  7780. this.isFogExp2 = true;
  7781. this.name = '';
  7782. this.color = new Color( color );
  7783. this.density = density;
  7784. }
  7785. clone() {
  7786. return new FogExp2( this.color, this.density );
  7787. }
  7788. toJSON( /* meta */ ) {
  7789. return {
  7790. type: 'FogExp2',
  7791. name: this.name,
  7792. color: this.color.getHex(),
  7793. density: this.density
  7794. };
  7795. }
  7796. }
  7797. class Fog {
  7798. constructor( color, near = 1, far = 1000 ) {
  7799. this.isFog = true;
  7800. this.name = '';
  7801. this.color = new Color( color );
  7802. this.near = near;
  7803. this.far = far;
  7804. }
  7805. clone() {
  7806. return new Fog( this.color, this.near, this.far );
  7807. }
  7808. toJSON( /* meta */ ) {
  7809. return {
  7810. type: 'Fog',
  7811. name: this.name,
  7812. color: this.color.getHex(),
  7813. near: this.near,
  7814. far: this.far
  7815. };
  7816. }
  7817. }
  7818. class Scene extends Object3D {
  7819. constructor() {
  7820. super();
  7821. this.isScene = true;
  7822. this.type = 'Scene';
  7823. this.background = null;
  7824. this.environment = null;
  7825. this.fog = null;
  7826. this.backgroundBlurriness = 0;
  7827. this.backgroundIntensity = 1;
  7828. this.backgroundRotation = new Euler();
  7829. this.environmentIntensity = 1;
  7830. this.environmentRotation = new Euler();
  7831. this.overrideMaterial = null;
  7832. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7833. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7834. }
  7835. }
  7836. copy( source, recursive ) {
  7837. super.copy( source, recursive );
  7838. if ( source.background !== null ) this.background = source.background.clone();
  7839. if ( source.environment !== null ) this.environment = source.environment.clone();
  7840. if ( source.fog !== null ) this.fog = source.fog.clone();
  7841. this.backgroundBlurriness = source.backgroundBlurriness;
  7842. this.backgroundIntensity = source.backgroundIntensity;
  7843. this.backgroundRotation.copy( source.backgroundRotation );
  7844. this.environmentIntensity = source.environmentIntensity;
  7845. this.environmentRotation.copy( source.environmentRotation );
  7846. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7847. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7848. return this;
  7849. }
  7850. toJSON( meta ) {
  7851. const data = super.toJSON( meta );
  7852. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7853. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7854. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7855. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7856. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7857. data.object.environmentRotation = this.environmentRotation.toArray();
  7858. return data;
  7859. }
  7860. }
  7861. class InterleavedBuffer {
  7862. constructor( array, stride ) {
  7863. this.isInterleavedBuffer = true;
  7864. this.array = array;
  7865. this.stride = stride;
  7866. this.count = array !== undefined ? array.length / stride : 0;
  7867. this.usage = StaticDrawUsage;
  7868. this._updateRange = { offset: 0, count: - 1 };
  7869. this.updateRanges = [];
  7870. this.version = 0;
  7871. this.uuid = generateUUID();
  7872. }
  7873. onUploadCallback() {}
  7874. set needsUpdate( value ) {
  7875. if ( value === true ) this.version ++;
  7876. }
  7877. get updateRange() {
  7878. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  7879. return this._updateRange;
  7880. }
  7881. setUsage( value ) {
  7882. this.usage = value;
  7883. return this;
  7884. }
  7885. addUpdateRange( start, count ) {
  7886. this.updateRanges.push( { start, count } );
  7887. }
  7888. clearUpdateRanges() {
  7889. this.updateRanges.length = 0;
  7890. }
  7891. copy( source ) {
  7892. this.array = new source.array.constructor( source.array );
  7893. this.count = source.count;
  7894. this.stride = source.stride;
  7895. this.usage = source.usage;
  7896. return this;
  7897. }
  7898. copyAt( index1, attribute, index2 ) {
  7899. index1 *= this.stride;
  7900. index2 *= attribute.stride;
  7901. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7902. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7903. }
  7904. return this;
  7905. }
  7906. set( value, offset = 0 ) {
  7907. this.array.set( value, offset );
  7908. return this;
  7909. }
  7910. clone( data ) {
  7911. if ( data.arrayBuffers === undefined ) {
  7912. data.arrayBuffers = {};
  7913. }
  7914. if ( this.array.buffer._uuid === undefined ) {
  7915. this.array.buffer._uuid = generateUUID();
  7916. }
  7917. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7918. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7919. }
  7920. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7921. const ib = new this.constructor( array, this.stride );
  7922. ib.setUsage( this.usage );
  7923. return ib;
  7924. }
  7925. onUpload( callback ) {
  7926. this.onUploadCallback = callback;
  7927. return this;
  7928. }
  7929. toJSON( data ) {
  7930. if ( data.arrayBuffers === undefined ) {
  7931. data.arrayBuffers = {};
  7932. }
  7933. // generate UUID for array buffer if necessary
  7934. if ( this.array.buffer._uuid === undefined ) {
  7935. this.array.buffer._uuid = generateUUID();
  7936. }
  7937. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7938. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7939. }
  7940. //
  7941. return {
  7942. uuid: this.uuid,
  7943. buffer: this.array.buffer._uuid,
  7944. type: this.array.constructor.name,
  7945. stride: this.stride
  7946. };
  7947. }
  7948. }
  7949. const _vector$7 = /*@__PURE__*/ new Vector3();
  7950. class InterleavedBufferAttribute {
  7951. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7952. this.isInterleavedBufferAttribute = true;
  7953. this.name = '';
  7954. this.data = interleavedBuffer;
  7955. this.itemSize = itemSize;
  7956. this.offset = offset;
  7957. this.normalized = normalized;
  7958. }
  7959. get count() {
  7960. return this.data.count;
  7961. }
  7962. get array() {
  7963. return this.data.array;
  7964. }
  7965. set needsUpdate( value ) {
  7966. this.data.needsUpdate = value;
  7967. }
  7968. applyMatrix4( m ) {
  7969. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7970. _vector$7.fromBufferAttribute( this, i );
  7971. _vector$7.applyMatrix4( m );
  7972. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7973. }
  7974. return this;
  7975. }
  7976. applyNormalMatrix( m ) {
  7977. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7978. _vector$7.fromBufferAttribute( this, i );
  7979. _vector$7.applyNormalMatrix( m );
  7980. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7981. }
  7982. return this;
  7983. }
  7984. transformDirection( m ) {
  7985. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7986. _vector$7.fromBufferAttribute( this, i );
  7987. _vector$7.transformDirection( m );
  7988. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7989. }
  7990. return this;
  7991. }
  7992. getComponent( index, component ) {
  7993. let value = this.array[ index * this.data.stride + this.offset + component ];
  7994. if ( this.normalized ) value = denormalize( value, this.array );
  7995. return value;
  7996. }
  7997. setComponent( index, component, value ) {
  7998. if ( this.normalized ) value = normalize$1( value, this.array );
  7999. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8000. return this;
  8001. }
  8002. setX( index, x ) {
  8003. if ( this.normalized ) x = normalize$1( x, this.array );
  8004. this.data.array[ index * this.data.stride + this.offset ] = x;
  8005. return this;
  8006. }
  8007. setY( index, y ) {
  8008. if ( this.normalized ) y = normalize$1( y, this.array );
  8009. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8010. return this;
  8011. }
  8012. setZ( index, z ) {
  8013. if ( this.normalized ) z = normalize$1( z, this.array );
  8014. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8015. return this;
  8016. }
  8017. setW( index, w ) {
  8018. if ( this.normalized ) w = normalize$1( w, this.array );
  8019. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8020. return this;
  8021. }
  8022. getX( index ) {
  8023. let x = this.data.array[ index * this.data.stride + this.offset ];
  8024. if ( this.normalized ) x = denormalize( x, this.array );
  8025. return x;
  8026. }
  8027. getY( index ) {
  8028. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8029. if ( this.normalized ) y = denormalize( y, this.array );
  8030. return y;
  8031. }
  8032. getZ( index ) {
  8033. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8034. if ( this.normalized ) z = denormalize( z, this.array );
  8035. return z;
  8036. }
  8037. getW( index ) {
  8038. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8039. if ( this.normalized ) w = denormalize( w, this.array );
  8040. return w;
  8041. }
  8042. setXY( index, x, y ) {
  8043. index = index * this.data.stride + this.offset;
  8044. if ( this.normalized ) {
  8045. x = normalize$1( x, this.array );
  8046. y = normalize$1( y, this.array );
  8047. }
  8048. this.data.array[ index + 0 ] = x;
  8049. this.data.array[ index + 1 ] = y;
  8050. return this;
  8051. }
  8052. setXYZ( index, x, y, z ) {
  8053. index = index * this.data.stride + this.offset;
  8054. if ( this.normalized ) {
  8055. x = normalize$1( x, this.array );
  8056. y = normalize$1( y, this.array );
  8057. z = normalize$1( z, this.array );
  8058. }
  8059. this.data.array[ index + 0 ] = x;
  8060. this.data.array[ index + 1 ] = y;
  8061. this.data.array[ index + 2 ] = z;
  8062. return this;
  8063. }
  8064. setXYZW( index, x, y, z, w ) {
  8065. index = index * this.data.stride + this.offset;
  8066. if ( this.normalized ) {
  8067. x = normalize$1( x, this.array );
  8068. y = normalize$1( y, this.array );
  8069. z = normalize$1( z, this.array );
  8070. w = normalize$1( w, this.array );
  8071. }
  8072. this.data.array[ index + 0 ] = x;
  8073. this.data.array[ index + 1 ] = y;
  8074. this.data.array[ index + 2 ] = z;
  8075. this.data.array[ index + 3 ] = w;
  8076. return this;
  8077. }
  8078. clone( data ) {
  8079. if ( data === undefined ) {
  8080. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8081. const array = [];
  8082. for ( let i = 0; i < this.count; i ++ ) {
  8083. const index = i * this.data.stride + this.offset;
  8084. for ( let j = 0; j < this.itemSize; j ++ ) {
  8085. array.push( this.data.array[ index + j ] );
  8086. }
  8087. }
  8088. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8089. } else {
  8090. if ( data.interleavedBuffers === undefined ) {
  8091. data.interleavedBuffers = {};
  8092. }
  8093. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8094. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8095. }
  8096. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8097. }
  8098. }
  8099. toJSON( data ) {
  8100. if ( data === undefined ) {
  8101. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8102. const array = [];
  8103. for ( let i = 0; i < this.count; i ++ ) {
  8104. const index = i * this.data.stride + this.offset;
  8105. for ( let j = 0; j < this.itemSize; j ++ ) {
  8106. array.push( this.data.array[ index + j ] );
  8107. }
  8108. }
  8109. // de-interleave data and save it as an ordinary buffer attribute for now
  8110. return {
  8111. itemSize: this.itemSize,
  8112. type: this.array.constructor.name,
  8113. array: array,
  8114. normalized: this.normalized
  8115. };
  8116. } else {
  8117. // save as true interleaved attribute
  8118. if ( data.interleavedBuffers === undefined ) {
  8119. data.interleavedBuffers = {};
  8120. }
  8121. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8122. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8123. }
  8124. return {
  8125. isInterleavedBufferAttribute: true,
  8126. itemSize: this.itemSize,
  8127. data: this.data.uuid,
  8128. offset: this.offset,
  8129. normalized: this.normalized
  8130. };
  8131. }
  8132. }
  8133. }
  8134. class SpriteMaterial extends Material {
  8135. constructor( parameters ) {
  8136. super();
  8137. this.isSpriteMaterial = true;
  8138. this.type = 'SpriteMaterial';
  8139. this.color = new Color( 0xffffff );
  8140. this.map = null;
  8141. this.alphaMap = null;
  8142. this.rotation = 0;
  8143. this.sizeAttenuation = true;
  8144. this.transparent = true;
  8145. this.fog = true;
  8146. this.setValues( parameters );
  8147. }
  8148. copy( source ) {
  8149. super.copy( source );
  8150. this.color.copy( source.color );
  8151. this.map = source.map;
  8152. this.alphaMap = source.alphaMap;
  8153. this.rotation = source.rotation;
  8154. this.sizeAttenuation = source.sizeAttenuation;
  8155. this.fog = source.fog;
  8156. return this;
  8157. }
  8158. }
  8159. let _geometry$1;
  8160. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8161. const _worldScale = /*@__PURE__*/ new Vector3();
  8162. const _mvPosition = /*@__PURE__*/ new Vector3();
  8163. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8164. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8165. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8166. const _vA = /*@__PURE__*/ new Vector3();
  8167. const _vB = /*@__PURE__*/ new Vector3();
  8168. const _vC = /*@__PURE__*/ new Vector3();
  8169. const _uvA = /*@__PURE__*/ new Vector2();
  8170. const _uvB = /*@__PURE__*/ new Vector2();
  8171. const _uvC = /*@__PURE__*/ new Vector2();
  8172. class Sprite extends Object3D {
  8173. constructor( material = new SpriteMaterial() ) {
  8174. super();
  8175. this.isSprite = true;
  8176. this.type = 'Sprite';
  8177. if ( _geometry$1 === undefined ) {
  8178. _geometry$1 = new BufferGeometry();
  8179. const float32Array = new Float32Array( [
  8180. - 0.5, - 0.5, 0, 0, 0,
  8181. 0.5, - 0.5, 0, 1, 0,
  8182. 0.5, 0.5, 0, 1, 1,
  8183. - 0.5, 0.5, 0, 0, 1
  8184. ] );
  8185. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8186. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8187. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8188. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8189. }
  8190. this.geometry = _geometry$1;
  8191. this.material = material;
  8192. this.center = new Vector2( 0.5, 0.5 );
  8193. }
  8194. raycast( raycaster, intersects ) {
  8195. if ( raycaster.camera === null ) {
  8196. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8197. }
  8198. _worldScale.setFromMatrixScale( this.matrixWorld );
  8199. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8200. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8201. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8202. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8203. _worldScale.multiplyScalar( - _mvPosition.z );
  8204. }
  8205. const rotation = this.material.rotation;
  8206. let sin, cos;
  8207. if ( rotation !== 0 ) {
  8208. cos = Math.cos( rotation );
  8209. sin = Math.sin( rotation );
  8210. }
  8211. const center = this.center;
  8212. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8213. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8214. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8215. _uvA.set( 0, 0 );
  8216. _uvB.set( 1, 0 );
  8217. _uvC.set( 1, 1 );
  8218. // check first triangle
  8219. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8220. if ( intersect === null ) {
  8221. // check second triangle
  8222. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8223. _uvB.set( 0, 1 );
  8224. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8225. if ( intersect === null ) {
  8226. return;
  8227. }
  8228. }
  8229. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8230. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8231. intersects.push( {
  8232. distance: distance,
  8233. point: _intersectPoint.clone(),
  8234. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8235. face: null,
  8236. object: this
  8237. } );
  8238. }
  8239. copy( source, recursive ) {
  8240. super.copy( source, recursive );
  8241. if ( source.center !== undefined ) this.center.copy( source.center );
  8242. this.material = source.material;
  8243. return this;
  8244. }
  8245. }
  8246. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8247. // compute position in camera space
  8248. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8249. // to check if rotation is not zero
  8250. if ( sin !== undefined ) {
  8251. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8252. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8253. } else {
  8254. _rotatedPosition.copy( _alignedPosition );
  8255. }
  8256. vertexPosition.copy( mvPosition );
  8257. vertexPosition.x += _rotatedPosition.x;
  8258. vertexPosition.y += _rotatedPosition.y;
  8259. // transform to world space
  8260. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8261. }
  8262. const _v1$2 = /*@__PURE__*/ new Vector3();
  8263. const _v2$1 = /*@__PURE__*/ new Vector3();
  8264. class LOD extends Object3D {
  8265. constructor() {
  8266. super();
  8267. this._currentLevel = 0;
  8268. this.type = 'LOD';
  8269. Object.defineProperties( this, {
  8270. levels: {
  8271. enumerable: true,
  8272. value: []
  8273. },
  8274. isLOD: {
  8275. value: true,
  8276. }
  8277. } );
  8278. this.autoUpdate = true;
  8279. }
  8280. copy( source ) {
  8281. super.copy( source, false );
  8282. const levels = source.levels;
  8283. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8284. const level = levels[ i ];
  8285. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8286. }
  8287. this.autoUpdate = source.autoUpdate;
  8288. return this;
  8289. }
  8290. addLevel( object, distance = 0, hysteresis = 0 ) {
  8291. distance = Math.abs( distance );
  8292. const levels = this.levels;
  8293. let l;
  8294. for ( l = 0; l < levels.length; l ++ ) {
  8295. if ( distance < levels[ l ].distance ) {
  8296. break;
  8297. }
  8298. }
  8299. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8300. this.add( object );
  8301. return this;
  8302. }
  8303. getCurrentLevel() {
  8304. return this._currentLevel;
  8305. }
  8306. getObjectForDistance( distance ) {
  8307. const levels = this.levels;
  8308. if ( levels.length > 0 ) {
  8309. let i, l;
  8310. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8311. let levelDistance = levels[ i ].distance;
  8312. if ( levels[ i ].object.visible ) {
  8313. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8314. }
  8315. if ( distance < levelDistance ) {
  8316. break;
  8317. }
  8318. }
  8319. return levels[ i - 1 ].object;
  8320. }
  8321. return null;
  8322. }
  8323. raycast( raycaster, intersects ) {
  8324. const levels = this.levels;
  8325. if ( levels.length > 0 ) {
  8326. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8327. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8328. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8329. }
  8330. }
  8331. update( camera ) {
  8332. const levels = this.levels;
  8333. if ( levels.length > 1 ) {
  8334. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8335. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8336. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8337. levels[ 0 ].object.visible = true;
  8338. let i, l;
  8339. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8340. let levelDistance = levels[ i ].distance;
  8341. if ( levels[ i ].object.visible ) {
  8342. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8343. }
  8344. if ( distance >= levelDistance ) {
  8345. levels[ i - 1 ].object.visible = false;
  8346. levels[ i ].object.visible = true;
  8347. } else {
  8348. break;
  8349. }
  8350. }
  8351. this._currentLevel = i - 1;
  8352. for ( ; i < l; i ++ ) {
  8353. levels[ i ].object.visible = false;
  8354. }
  8355. }
  8356. }
  8357. toJSON( meta ) {
  8358. const data = super.toJSON( meta );
  8359. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8360. data.object.levels = [];
  8361. const levels = this.levels;
  8362. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8363. const level = levels[ i ];
  8364. data.object.levels.push( {
  8365. object: level.object.uuid,
  8366. distance: level.distance,
  8367. hysteresis: level.hysteresis
  8368. } );
  8369. }
  8370. return data;
  8371. }
  8372. }
  8373. const _basePosition = /*@__PURE__*/ new Vector3();
  8374. const _skinIndex = /*@__PURE__*/ new Vector4();
  8375. const _skinWeight = /*@__PURE__*/ new Vector4();
  8376. const _vector3$1 = /*@__PURE__*/ new Vector3();
  8377. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8378. const _vertex = /*@__PURE__*/ new Vector3();
  8379. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8380. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8381. const _ray$2 = /*@__PURE__*/ new Ray();
  8382. class SkinnedMesh extends Mesh {
  8383. constructor( geometry, material ) {
  8384. super( geometry, material );
  8385. this.isSkinnedMesh = true;
  8386. this.type = 'SkinnedMesh';
  8387. this.bindMode = AttachedBindMode;
  8388. this.bindMatrix = new Matrix4();
  8389. this.bindMatrixInverse = new Matrix4();
  8390. this.boundingBox = null;
  8391. this.boundingSphere = null;
  8392. }
  8393. computeBoundingBox() {
  8394. const geometry = this.geometry;
  8395. if ( this.boundingBox === null ) {
  8396. this.boundingBox = new Box3();
  8397. }
  8398. this.boundingBox.makeEmpty();
  8399. const positionAttribute = geometry.getAttribute( 'position' );
  8400. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8401. this.getVertexPosition( i, _vertex );
  8402. this.boundingBox.expandByPoint( _vertex );
  8403. }
  8404. }
  8405. computeBoundingSphere() {
  8406. const geometry = this.geometry;
  8407. if ( this.boundingSphere === null ) {
  8408. this.boundingSphere = new Sphere();
  8409. }
  8410. this.boundingSphere.makeEmpty();
  8411. const positionAttribute = geometry.getAttribute( 'position' );
  8412. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8413. this.getVertexPosition( i, _vertex );
  8414. this.boundingSphere.expandByPoint( _vertex );
  8415. }
  8416. }
  8417. copy( source, recursive ) {
  8418. super.copy( source, recursive );
  8419. this.bindMode = source.bindMode;
  8420. this.bindMatrix.copy( source.bindMatrix );
  8421. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8422. this.skeleton = source.skeleton;
  8423. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8424. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8425. return this;
  8426. }
  8427. raycast( raycaster, intersects ) {
  8428. const material = this.material;
  8429. const matrixWorld = this.matrixWorld;
  8430. if ( material === undefined ) return;
  8431. // test with bounding sphere in world space
  8432. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8433. _sphere$5.copy( this.boundingSphere );
  8434. _sphere$5.applyMatrix4( matrixWorld );
  8435. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8436. // convert ray to local space of skinned mesh
  8437. _inverseMatrix$2.copy( matrixWorld ).invert();
  8438. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8439. // test with bounding box in local space
  8440. if ( this.boundingBox !== null ) {
  8441. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8442. }
  8443. // test for intersections with geometry
  8444. this._computeIntersections( raycaster, intersects, _ray$2 );
  8445. }
  8446. getVertexPosition( index, target ) {
  8447. super.getVertexPosition( index, target );
  8448. this.applyBoneTransform( index, target );
  8449. return target;
  8450. }
  8451. bind( skeleton, bindMatrix ) {
  8452. this.skeleton = skeleton;
  8453. if ( bindMatrix === undefined ) {
  8454. this.updateMatrixWorld( true );
  8455. this.skeleton.calculateInverses();
  8456. bindMatrix = this.matrixWorld;
  8457. }
  8458. this.bindMatrix.copy( bindMatrix );
  8459. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8460. }
  8461. pose() {
  8462. this.skeleton.pose();
  8463. }
  8464. normalizeSkinWeights() {
  8465. const vector = new Vector4();
  8466. const skinWeight = this.geometry.attributes.skinWeight;
  8467. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8468. vector.fromBufferAttribute( skinWeight, i );
  8469. const scale = 1.0 / vector.manhattanLength();
  8470. if ( scale !== Infinity ) {
  8471. vector.multiplyScalar( scale );
  8472. } else {
  8473. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8474. }
  8475. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8476. }
  8477. }
  8478. updateMatrixWorld( force ) {
  8479. super.updateMatrixWorld( force );
  8480. if ( this.bindMode === AttachedBindMode ) {
  8481. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8482. } else if ( this.bindMode === DetachedBindMode ) {
  8483. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8484. } else {
  8485. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8486. }
  8487. }
  8488. applyBoneTransform( index, vector ) {
  8489. const skeleton = this.skeleton;
  8490. const geometry = this.geometry;
  8491. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8492. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8493. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8494. vector.set( 0, 0, 0 );
  8495. for ( let i = 0; i < 4; i ++ ) {
  8496. const weight = _skinWeight.getComponent( i );
  8497. if ( weight !== 0 ) {
  8498. const boneIndex = _skinIndex.getComponent( i );
  8499. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8500. vector.addScaledVector( _vector3$1.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8501. }
  8502. }
  8503. return vector.applyMatrix4( this.bindMatrixInverse );
  8504. }
  8505. }
  8506. class Bone extends Object3D {
  8507. constructor() {
  8508. super();
  8509. this.isBone = true;
  8510. this.type = 'Bone';
  8511. }
  8512. }
  8513. class DataTexture extends Texture {
  8514. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8515. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8516. this.isDataTexture = true;
  8517. this.image = { data: data, width: width, height: height };
  8518. this.generateMipmaps = false;
  8519. this.flipY = false;
  8520. this.unpackAlignment = 1;
  8521. }
  8522. }
  8523. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8524. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8525. class Skeleton {
  8526. constructor( bones = [], boneInverses = [] ) {
  8527. this.uuid = generateUUID();
  8528. this.bones = bones.slice( 0 );
  8529. this.boneInverses = boneInverses;
  8530. this.boneMatrices = null;
  8531. this.boneTexture = null;
  8532. this.init();
  8533. }
  8534. init() {
  8535. const bones = this.bones;
  8536. const boneInverses = this.boneInverses;
  8537. this.boneMatrices = new Float32Array( bones.length * 16 );
  8538. // calculate inverse bone matrices if necessary
  8539. if ( boneInverses.length === 0 ) {
  8540. this.calculateInverses();
  8541. } else {
  8542. // handle special case
  8543. if ( bones.length !== boneInverses.length ) {
  8544. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8545. this.boneInverses = [];
  8546. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8547. this.boneInverses.push( new Matrix4() );
  8548. }
  8549. }
  8550. }
  8551. }
  8552. calculateInverses() {
  8553. this.boneInverses.length = 0;
  8554. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8555. const inverse = new Matrix4();
  8556. if ( this.bones[ i ] ) {
  8557. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8558. }
  8559. this.boneInverses.push( inverse );
  8560. }
  8561. }
  8562. pose() {
  8563. // recover the bind-time world matrices
  8564. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8565. const bone = this.bones[ i ];
  8566. if ( bone ) {
  8567. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8568. }
  8569. }
  8570. // compute the local matrices, positions, rotations and scales
  8571. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8572. const bone = this.bones[ i ];
  8573. if ( bone ) {
  8574. if ( bone.parent && bone.parent.isBone ) {
  8575. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8576. bone.matrix.multiply( bone.matrixWorld );
  8577. } else {
  8578. bone.matrix.copy( bone.matrixWorld );
  8579. }
  8580. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8581. }
  8582. }
  8583. }
  8584. update() {
  8585. const bones = this.bones;
  8586. const boneInverses = this.boneInverses;
  8587. const boneMatrices = this.boneMatrices;
  8588. const boneTexture = this.boneTexture;
  8589. // flatten bone matrices to array
  8590. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8591. // compute the offset between the current and the original transform
  8592. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8593. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8594. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8595. }
  8596. if ( boneTexture !== null ) {
  8597. boneTexture.needsUpdate = true;
  8598. }
  8599. }
  8600. clone() {
  8601. return new Skeleton( this.bones, this.boneInverses );
  8602. }
  8603. computeBoneTexture() {
  8604. // layout (1 matrix = 4 pixels)
  8605. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8606. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8607. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8608. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8609. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8610. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8611. size = Math.ceil( size / 4 ) * 4;
  8612. size = Math.max( size, 4 );
  8613. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8614. boneMatrices.set( this.boneMatrices ); // copy current values
  8615. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8616. boneTexture.needsUpdate = true;
  8617. this.boneMatrices = boneMatrices;
  8618. this.boneTexture = boneTexture;
  8619. return this;
  8620. }
  8621. getBoneByName( name ) {
  8622. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8623. const bone = this.bones[ i ];
  8624. if ( bone.name === name ) {
  8625. return bone;
  8626. }
  8627. }
  8628. return undefined;
  8629. }
  8630. dispose( ) {
  8631. if ( this.boneTexture !== null ) {
  8632. this.boneTexture.dispose();
  8633. this.boneTexture = null;
  8634. }
  8635. }
  8636. fromJSON( json, bones ) {
  8637. this.uuid = json.uuid;
  8638. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8639. const uuid = json.bones[ i ];
  8640. let bone = bones[ uuid ];
  8641. if ( bone === undefined ) {
  8642. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8643. bone = new Bone();
  8644. }
  8645. this.bones.push( bone );
  8646. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8647. }
  8648. this.init();
  8649. return this;
  8650. }
  8651. toJSON() {
  8652. const data = {
  8653. metadata: {
  8654. version: 4.6,
  8655. type: 'Skeleton',
  8656. generator: 'Skeleton.toJSON'
  8657. },
  8658. bones: [],
  8659. boneInverses: []
  8660. };
  8661. data.uuid = this.uuid;
  8662. const bones = this.bones;
  8663. const boneInverses = this.boneInverses;
  8664. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8665. const bone = bones[ i ];
  8666. data.bones.push( bone.uuid );
  8667. const boneInverse = boneInverses[ i ];
  8668. data.boneInverses.push( boneInverse.toArray() );
  8669. }
  8670. return data;
  8671. }
  8672. }
  8673. class InstancedBufferAttribute extends BufferAttribute {
  8674. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8675. super( array, itemSize, normalized );
  8676. this.isInstancedBufferAttribute = true;
  8677. this.meshPerAttribute = meshPerAttribute;
  8678. }
  8679. copy( source ) {
  8680. super.copy( source );
  8681. this.meshPerAttribute = source.meshPerAttribute;
  8682. return this;
  8683. }
  8684. toJSON() {
  8685. const data = super.toJSON();
  8686. data.meshPerAttribute = this.meshPerAttribute;
  8687. data.isInstancedBufferAttribute = true;
  8688. return data;
  8689. }
  8690. }
  8691. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8692. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8693. const _instanceIntersects = [];
  8694. const _box3 = /*@__PURE__*/ new Box3();
  8695. const _identity = /*@__PURE__*/ new Matrix4();
  8696. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8697. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8698. class InstancedMesh extends Mesh {
  8699. constructor( geometry, material, count ) {
  8700. super( geometry, material );
  8701. this.isInstancedMesh = true;
  8702. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8703. this.instanceColor = null;
  8704. this.morphTexture = null;
  8705. this.count = count;
  8706. this.boundingBox = null;
  8707. this.boundingSphere = null;
  8708. for ( let i = 0; i < count; i ++ ) {
  8709. this.setMatrixAt( i, _identity );
  8710. }
  8711. }
  8712. computeBoundingBox() {
  8713. const geometry = this.geometry;
  8714. const count = this.count;
  8715. if ( this.boundingBox === null ) {
  8716. this.boundingBox = new Box3();
  8717. }
  8718. if ( geometry.boundingBox === null ) {
  8719. geometry.computeBoundingBox();
  8720. }
  8721. this.boundingBox.makeEmpty();
  8722. for ( let i = 0; i < count; i ++ ) {
  8723. this.getMatrixAt( i, _instanceLocalMatrix );
  8724. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8725. this.boundingBox.union( _box3 );
  8726. }
  8727. }
  8728. computeBoundingSphere() {
  8729. const geometry = this.geometry;
  8730. const count = this.count;
  8731. if ( this.boundingSphere === null ) {
  8732. this.boundingSphere = new Sphere();
  8733. }
  8734. if ( geometry.boundingSphere === null ) {
  8735. geometry.computeBoundingSphere();
  8736. }
  8737. this.boundingSphere.makeEmpty();
  8738. for ( let i = 0; i < count; i ++ ) {
  8739. this.getMatrixAt( i, _instanceLocalMatrix );
  8740. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8741. this.boundingSphere.union( _sphere$4 );
  8742. }
  8743. }
  8744. copy( source, recursive ) {
  8745. super.copy( source, recursive );
  8746. this.instanceMatrix.copy( source.instanceMatrix );
  8747. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8748. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8749. this.count = source.count;
  8750. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8751. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8752. return this;
  8753. }
  8754. getColorAt( index, color ) {
  8755. color.fromArray( this.instanceColor.array, index * 3 );
  8756. }
  8757. getMatrixAt( index, matrix ) {
  8758. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8759. }
  8760. getMorphAt( index, object ) {
  8761. const objectInfluences = object.morphTargetInfluences;
  8762. const array = this.morphTexture.source.data.data;
  8763. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8764. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8765. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8766. objectInfluences[ i ] = array[ dataIndex + i ];
  8767. }
  8768. }
  8769. raycast( raycaster, intersects ) {
  8770. const matrixWorld = this.matrixWorld;
  8771. const raycastTimes = this.count;
  8772. _mesh$1.geometry = this.geometry;
  8773. _mesh$1.material = this.material;
  8774. if ( _mesh$1.material === undefined ) return;
  8775. // test with bounding sphere first
  8776. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8777. _sphere$4.copy( this.boundingSphere );
  8778. _sphere$4.applyMatrix4( matrixWorld );
  8779. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8780. // now test each instance
  8781. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8782. // calculate the world matrix for each instance
  8783. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8784. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8785. // the mesh represents this single instance
  8786. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8787. _mesh$1.raycast( raycaster, _instanceIntersects );
  8788. // process the result of raycast
  8789. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8790. const intersect = _instanceIntersects[ i ];
  8791. intersect.instanceId = instanceId;
  8792. intersect.object = this;
  8793. intersects.push( intersect );
  8794. }
  8795. _instanceIntersects.length = 0;
  8796. }
  8797. }
  8798. setColorAt( index, color ) {
  8799. if ( this.instanceColor === null ) {
  8800. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8801. }
  8802. color.toArray( this.instanceColor.array, index * 3 );
  8803. }
  8804. setMatrixAt( index, matrix ) {
  8805. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8806. }
  8807. setMorphAt( index, object ) {
  8808. const objectInfluences = object.morphTargetInfluences;
  8809. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8810. if ( this.morphTexture === null ) {
  8811. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8812. }
  8813. const array = this.morphTexture.source.data.data;
  8814. let morphInfluencesSum = 0;
  8815. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8816. morphInfluencesSum += objectInfluences[ i ];
  8817. }
  8818. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8819. const dataIndex = len * index;
  8820. array[ dataIndex ] = morphBaseInfluence;
  8821. array.set( objectInfluences, dataIndex + 1 );
  8822. }
  8823. updateMorphTargets() {
  8824. }
  8825. dispose() {
  8826. this.dispatchEvent( { type: 'dispose' } );
  8827. if ( this.morphTexture !== null ) {
  8828. this.morphTexture.dispose();
  8829. this.morphTexture = null;
  8830. }
  8831. return this;
  8832. }
  8833. }
  8834. const _vector1 = /*@__PURE__*/ new Vector3();
  8835. const _vector2 = /*@__PURE__*/ new Vector3();
  8836. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8837. class Plane {
  8838. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8839. this.isPlane = true;
  8840. // normal is assumed to be normalized
  8841. this.normal = normal;
  8842. this.constant = constant;
  8843. }
  8844. set( normal, constant ) {
  8845. this.normal.copy( normal );
  8846. this.constant = constant;
  8847. return this;
  8848. }
  8849. setComponents( x, y, z, w ) {
  8850. this.normal.set( x, y, z );
  8851. this.constant = w;
  8852. return this;
  8853. }
  8854. setFromNormalAndCoplanarPoint( normal, point ) {
  8855. this.normal.copy( normal );
  8856. this.constant = - point.dot( this.normal );
  8857. return this;
  8858. }
  8859. setFromCoplanarPoints( a, b, c ) {
  8860. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8861. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8862. this.setFromNormalAndCoplanarPoint( normal, a );
  8863. return this;
  8864. }
  8865. copy( plane ) {
  8866. this.normal.copy( plane.normal );
  8867. this.constant = plane.constant;
  8868. return this;
  8869. }
  8870. normalize() {
  8871. // Note: will lead to a divide by zero if the plane is invalid.
  8872. const inverseNormalLength = 1.0 / this.normal.length();
  8873. this.normal.multiplyScalar( inverseNormalLength );
  8874. this.constant *= inverseNormalLength;
  8875. return this;
  8876. }
  8877. negate() {
  8878. this.constant *= - 1;
  8879. this.normal.negate();
  8880. return this;
  8881. }
  8882. distanceToPoint( point ) {
  8883. return this.normal.dot( point ) + this.constant;
  8884. }
  8885. distanceToSphere( sphere ) {
  8886. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8887. }
  8888. projectPoint( point, target ) {
  8889. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8890. }
  8891. intersectLine( line, target ) {
  8892. const direction = line.delta( _vector1 );
  8893. const denominator = this.normal.dot( direction );
  8894. if ( denominator === 0 ) {
  8895. // line is coplanar, return origin
  8896. if ( this.distanceToPoint( line.start ) === 0 ) {
  8897. return target.copy( line.start );
  8898. }
  8899. // Unsure if this is the correct method to handle this case.
  8900. return null;
  8901. }
  8902. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8903. if ( t < 0 || t > 1 ) {
  8904. return null;
  8905. }
  8906. return target.copy( line.start ).addScaledVector( direction, t );
  8907. }
  8908. intersectsLine( line ) {
  8909. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8910. const startSign = this.distanceToPoint( line.start );
  8911. const endSign = this.distanceToPoint( line.end );
  8912. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8913. }
  8914. intersectsBox( box ) {
  8915. return box.intersectsPlane( this );
  8916. }
  8917. intersectsSphere( sphere ) {
  8918. return sphere.intersectsPlane( this );
  8919. }
  8920. coplanarPoint( target ) {
  8921. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8922. }
  8923. applyMatrix4( matrix, optionalNormalMatrix ) {
  8924. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8925. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8926. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8927. this.constant = - referencePoint.dot( normal );
  8928. return this;
  8929. }
  8930. translate( offset ) {
  8931. this.constant -= offset.dot( this.normal );
  8932. return this;
  8933. }
  8934. equals( plane ) {
  8935. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8936. }
  8937. clone() {
  8938. return new this.constructor().copy( this );
  8939. }
  8940. }
  8941. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8942. const _vector$6 = /*@__PURE__*/ new Vector3();
  8943. class Frustum {
  8944. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8945. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8946. }
  8947. set( p0, p1, p2, p3, p4, p5 ) {
  8948. const planes = this.planes;
  8949. planes[ 0 ].copy( p0 );
  8950. planes[ 1 ].copy( p1 );
  8951. planes[ 2 ].copy( p2 );
  8952. planes[ 3 ].copy( p3 );
  8953. planes[ 4 ].copy( p4 );
  8954. planes[ 5 ].copy( p5 );
  8955. return this;
  8956. }
  8957. copy( frustum ) {
  8958. const planes = this.planes;
  8959. for ( let i = 0; i < 6; i ++ ) {
  8960. planes[ i ].copy( frustum.planes[ i ] );
  8961. }
  8962. return this;
  8963. }
  8964. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8965. const planes = this.planes;
  8966. const me = m.elements;
  8967. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8968. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8969. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8970. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8971. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8972. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8973. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8974. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8975. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8976. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8977. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8978. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8979. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8980. } else {
  8981. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8982. }
  8983. return this;
  8984. }
  8985. intersectsObject( object ) {
  8986. if ( object.boundingSphere !== undefined ) {
  8987. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8988. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8989. } else {
  8990. const geometry = object.geometry;
  8991. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8992. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8993. }
  8994. return this.intersectsSphere( _sphere$3 );
  8995. }
  8996. intersectsSprite( sprite ) {
  8997. _sphere$3.center.set( 0, 0, 0 );
  8998. _sphere$3.radius = 0.7071067811865476;
  8999. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9000. return this.intersectsSphere( _sphere$3 );
  9001. }
  9002. intersectsSphere( sphere ) {
  9003. const planes = this.planes;
  9004. const center = sphere.center;
  9005. const negRadius = - sphere.radius;
  9006. for ( let i = 0; i < 6; i ++ ) {
  9007. const distance = planes[ i ].distanceToPoint( center );
  9008. if ( distance < negRadius ) {
  9009. return false;
  9010. }
  9011. }
  9012. return true;
  9013. }
  9014. intersectsBox( box ) {
  9015. const planes = this.planes;
  9016. for ( let i = 0; i < 6; i ++ ) {
  9017. const plane = planes[ i ];
  9018. // corner at max distance
  9019. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9020. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9021. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9022. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9023. return false;
  9024. }
  9025. }
  9026. return true;
  9027. }
  9028. containsPoint( point ) {
  9029. const planes = this.planes;
  9030. for ( let i = 0; i < 6; i ++ ) {
  9031. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9032. return false;
  9033. }
  9034. }
  9035. return true;
  9036. }
  9037. clone() {
  9038. return new this.constructor().copy( this );
  9039. }
  9040. }
  9041. function sortOpaque( a, b ) {
  9042. return a.z - b.z;
  9043. }
  9044. function sortTransparent( a, b ) {
  9045. return b.z - a.z;
  9046. }
  9047. class MultiDrawRenderList {
  9048. constructor() {
  9049. this.index = 0;
  9050. this.pool = [];
  9051. this.list = [];
  9052. }
  9053. push( drawRange, z, index ) {
  9054. const pool = this.pool;
  9055. const list = this.list;
  9056. if ( this.index >= pool.length ) {
  9057. pool.push( {
  9058. start: - 1,
  9059. count: - 1,
  9060. z: - 1,
  9061. index: - 1,
  9062. } );
  9063. }
  9064. const item = pool[ this.index ];
  9065. list.push( item );
  9066. this.index ++;
  9067. item.start = drawRange.start;
  9068. item.count = drawRange.count;
  9069. item.z = z;
  9070. item.index = index;
  9071. }
  9072. reset() {
  9073. this.list.length = 0;
  9074. this.index = 0;
  9075. }
  9076. }
  9077. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9078. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9079. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9080. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9081. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9082. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9083. const _box$1 = /*@__PURE__*/ new Box3();
  9084. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9085. const _vector$5 = /*@__PURE__*/ new Vector3();
  9086. const _forward = /*@__PURE__*/ new Vector3();
  9087. const _temp = /*@__PURE__*/ new Vector3();
  9088. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9089. const _mesh = /*@__PURE__*/ new Mesh();
  9090. const _batchIntersects = [];
  9091. // @TODO: SkinnedMesh support?
  9092. // @TODO: geometry.groups support?
  9093. // @TODO: geometry.drawRange support?
  9094. // @TODO: geometry.morphAttributes support?
  9095. // @TODO: Support uniform parameter per geometry
  9096. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9097. // copies data from attribute "src" into "target" starting at "targetOffset"
  9098. function copyAttributeData( src, target, targetOffset = 0 ) {
  9099. const itemSize = target.itemSize;
  9100. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9101. // use the component getters and setters if the array data cannot
  9102. // be copied directly
  9103. const vertexCount = src.count;
  9104. for ( let i = 0; i < vertexCount; i ++ ) {
  9105. for ( let c = 0; c < itemSize; c ++ ) {
  9106. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9107. }
  9108. }
  9109. } else {
  9110. // faster copy approach using typed array set function
  9111. target.array.set( src.array, targetOffset * itemSize );
  9112. }
  9113. target.needsUpdate = true;
  9114. }
  9115. class BatchedMesh extends Mesh {
  9116. get maxInstanceCount() {
  9117. return this._maxInstanceCount;
  9118. }
  9119. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9120. super( new BufferGeometry(), material );
  9121. this.isBatchedMesh = true;
  9122. this.perObjectFrustumCulled = true;
  9123. this.sortObjects = true;
  9124. this.boundingBox = null;
  9125. this.boundingSphere = null;
  9126. this.customSort = null;
  9127. // stores visible, active, and geometry id per object
  9128. this._drawInfo = [];
  9129. // geometry information
  9130. this._drawRanges = [];
  9131. this._reservedRanges = [];
  9132. this._bounds = [];
  9133. this._maxInstanceCount = maxInstanceCount;
  9134. this._maxVertexCount = maxVertexCount;
  9135. this._maxIndexCount = maxIndexCount;
  9136. this._geometryInitialized = false;
  9137. this._geometryCount = 0;
  9138. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9139. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9140. this._multiDrawCount = 0;
  9141. this._multiDrawInstances = null;
  9142. this._visibilityChanged = true;
  9143. // Local matrix per geometry by using data texture
  9144. this._matricesTexture = null;
  9145. this._indirectTexture = null;
  9146. this._colorsTexture = null;
  9147. this._initMatricesTexture();
  9148. this._initIndirectTexture();
  9149. }
  9150. _initMatricesTexture() {
  9151. // layout (1 matrix = 4 pixels)
  9152. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9153. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9154. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9155. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9156. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9157. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9158. size = Math.ceil( size / 4 ) * 4;
  9159. size = Math.max( size, 4 );
  9160. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9161. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9162. this._matricesTexture = matricesTexture;
  9163. }
  9164. _initIndirectTexture() {
  9165. let size = Math.sqrt( this._maxInstanceCount );
  9166. size = Math.ceil( size );
  9167. const indirectArray = new Uint32Array( size * size );
  9168. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9169. this._indirectTexture = indirectTexture;
  9170. }
  9171. _initColorsTexture() {
  9172. let size = Math.sqrt( this._maxIndexCount );
  9173. size = Math.ceil( size );
  9174. // 4 floats per RGBA pixel initialized to white
  9175. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9176. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9177. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9178. this._colorsTexture = colorsTexture;
  9179. }
  9180. _initializeGeometry( reference ) {
  9181. const geometry = this.geometry;
  9182. const maxVertexCount = this._maxVertexCount;
  9183. const maxIndexCount = this._maxIndexCount;
  9184. if ( this._geometryInitialized === false ) {
  9185. for ( const attributeName in reference.attributes ) {
  9186. const srcAttribute = reference.getAttribute( attributeName );
  9187. const { array, itemSize, normalized } = srcAttribute;
  9188. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9189. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9190. geometry.setAttribute( attributeName, dstAttribute );
  9191. }
  9192. if ( reference.getIndex() !== null ) {
  9193. // Reserve last u16 index for primitive restart.
  9194. const indexArray = maxVertexCount > 65535
  9195. ? new Uint32Array( maxIndexCount )
  9196. : new Uint16Array( maxIndexCount );
  9197. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9198. }
  9199. this._geometryInitialized = true;
  9200. }
  9201. }
  9202. // Make sure the geometry is compatible with the existing combined geometry attributes
  9203. _validateGeometry( geometry ) {
  9204. // check to ensure the geometries are using consistent attributes and indices
  9205. const batchGeometry = this.geometry;
  9206. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9207. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9208. }
  9209. for ( const attributeName in batchGeometry.attributes ) {
  9210. if ( ! geometry.hasAttribute( attributeName ) ) {
  9211. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9212. }
  9213. const srcAttribute = geometry.getAttribute( attributeName );
  9214. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9215. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9216. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9217. }
  9218. }
  9219. }
  9220. setCustomSort( func ) {
  9221. this.customSort = func;
  9222. return this;
  9223. }
  9224. computeBoundingBox() {
  9225. if ( this.boundingBox === null ) {
  9226. this.boundingBox = new Box3();
  9227. }
  9228. const geometryCount = this._geometryCount;
  9229. const boundingBox = this.boundingBox;
  9230. const drawInfo = this._drawInfo;
  9231. boundingBox.makeEmpty();
  9232. for ( let i = 0; i < geometryCount; i ++ ) {
  9233. if ( drawInfo[ i ].active === false ) continue;
  9234. const geometryId = drawInfo[ i ].geometryIndex;
  9235. this.getMatrixAt( i, _matrix$1 );
  9236. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9237. boundingBox.union( _box$1 );
  9238. }
  9239. }
  9240. computeBoundingSphere() {
  9241. if ( this.boundingSphere === null ) {
  9242. this.boundingSphere = new Sphere();
  9243. }
  9244. const boundingSphere = this.boundingSphere;
  9245. const drawInfo = this._drawInfo;
  9246. boundingSphere.makeEmpty();
  9247. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9248. if ( drawInfo[ i ].active === false ) continue;
  9249. const geometryId = drawInfo[ i ].geometryIndex;
  9250. this.getMatrixAt( i, _matrix$1 );
  9251. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9252. boundingSphere.union( _sphere$2 );
  9253. }
  9254. }
  9255. addInstance( geometryId ) {
  9256. // ensure we're not over geometry
  9257. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9258. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9259. }
  9260. this._drawInfo.push( {
  9261. visible: true,
  9262. active: true,
  9263. geometryIndex: geometryId,
  9264. } );
  9265. // initialize the matrix
  9266. const drawId = this._drawInfo.length - 1;
  9267. const matricesTexture = this._matricesTexture;
  9268. const matricesArray = matricesTexture.image.data;
  9269. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9270. matricesTexture.needsUpdate = true;
  9271. const colorsTexture = this._colorsTexture;
  9272. if ( colorsTexture ) {
  9273. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9274. colorsTexture.needsUpdate = true;
  9275. }
  9276. return drawId;
  9277. }
  9278. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9279. this._initializeGeometry( geometry );
  9280. this._validateGeometry( geometry );
  9281. // ensure we're not over geometry
  9282. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9283. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9284. }
  9285. // get the necessary range fo the geometry
  9286. const reservedRange = {
  9287. vertexStart: - 1,
  9288. vertexCount: - 1,
  9289. indexStart: - 1,
  9290. indexCount: - 1,
  9291. };
  9292. let lastRange = null;
  9293. const reservedRanges = this._reservedRanges;
  9294. const drawRanges = this._drawRanges;
  9295. const bounds = this._bounds;
  9296. if ( this._geometryCount !== 0 ) {
  9297. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9298. }
  9299. if ( vertexCount === - 1 ) {
  9300. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9301. } else {
  9302. reservedRange.vertexCount = vertexCount;
  9303. }
  9304. if ( lastRange === null ) {
  9305. reservedRange.vertexStart = 0;
  9306. } else {
  9307. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9308. }
  9309. const index = geometry.getIndex();
  9310. const hasIndex = index !== null;
  9311. if ( hasIndex ) {
  9312. if ( indexCount === - 1 ) {
  9313. reservedRange.indexCount = index.count;
  9314. } else {
  9315. reservedRange.indexCount = indexCount;
  9316. }
  9317. if ( lastRange === null ) {
  9318. reservedRange.indexStart = 0;
  9319. } else {
  9320. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9321. }
  9322. }
  9323. if (
  9324. reservedRange.indexStart !== - 1 &&
  9325. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9326. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9327. ) {
  9328. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9329. }
  9330. // update id
  9331. const geometryId = this._geometryCount;
  9332. this._geometryCount ++;
  9333. // add the reserved range and draw range objects
  9334. reservedRanges.push( reservedRange );
  9335. drawRanges.push( {
  9336. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9337. count: - 1
  9338. } );
  9339. bounds.push( {
  9340. boxInitialized: false,
  9341. box: new Box3(),
  9342. sphereInitialized: false,
  9343. sphere: new Sphere()
  9344. } );
  9345. // update the geometry
  9346. this.setGeometryAt( geometryId, geometry );
  9347. return geometryId;
  9348. }
  9349. setGeometryAt( geometryId, geometry ) {
  9350. if ( geometryId >= this._geometryCount ) {
  9351. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9352. }
  9353. this._validateGeometry( geometry );
  9354. const batchGeometry = this.geometry;
  9355. const hasIndex = batchGeometry.getIndex() !== null;
  9356. const dstIndex = batchGeometry.getIndex();
  9357. const srcIndex = geometry.getIndex();
  9358. const reservedRange = this._reservedRanges[ geometryId ];
  9359. if (
  9360. hasIndex &&
  9361. srcIndex.count > reservedRange.indexCount ||
  9362. geometry.attributes.position.count > reservedRange.vertexCount
  9363. ) {
  9364. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9365. }
  9366. // copy geometry over
  9367. const vertexStart = reservedRange.vertexStart;
  9368. const vertexCount = reservedRange.vertexCount;
  9369. for ( const attributeName in batchGeometry.attributes ) {
  9370. // copy attribute data
  9371. const srcAttribute = geometry.getAttribute( attributeName );
  9372. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9373. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9374. // fill the rest in with zeroes
  9375. const itemSize = srcAttribute.itemSize;
  9376. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9377. const index = vertexStart + i;
  9378. for ( let c = 0; c < itemSize; c ++ ) {
  9379. dstAttribute.setComponent( index, c, 0 );
  9380. }
  9381. }
  9382. dstAttribute.needsUpdate = true;
  9383. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9384. }
  9385. // copy index
  9386. if ( hasIndex ) {
  9387. const indexStart = reservedRange.indexStart;
  9388. // copy index data over
  9389. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9390. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9391. }
  9392. // fill the rest in with zeroes
  9393. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9394. dstIndex.setX( indexStart + i, vertexStart );
  9395. }
  9396. dstIndex.needsUpdate = true;
  9397. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9398. }
  9399. // store the bounding boxes
  9400. const bound = this._bounds[ geometryId ];
  9401. if ( geometry.boundingBox !== null ) {
  9402. bound.box.copy( geometry.boundingBox );
  9403. bound.boxInitialized = true;
  9404. } else {
  9405. bound.boxInitialized = false;
  9406. }
  9407. if ( geometry.boundingSphere !== null ) {
  9408. bound.sphere.copy( geometry.boundingSphere );
  9409. bound.sphereInitialized = true;
  9410. } else {
  9411. bound.sphereInitialized = false;
  9412. }
  9413. // set drawRange count
  9414. const drawRange = this._drawRanges[ geometryId ];
  9415. const posAttr = geometry.getAttribute( 'position' );
  9416. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9417. this._visibilityChanged = true;
  9418. return geometryId;
  9419. }
  9420. /*
  9421. deleteGeometry( geometryId ) {
  9422. // TODO: delete geometry and associated instances
  9423. }
  9424. */
  9425. /*
  9426. deleteInstance( instanceId ) {
  9427. // Note: User needs to call optimize() afterward to pack the data.
  9428. const drawInfo = this._drawInfo;
  9429. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9430. return this;
  9431. }
  9432. drawInfo[ instanceId ].active = false;
  9433. this._visibilityChanged = true;
  9434. return this;
  9435. }
  9436. */
  9437. // get bounding box and compute it if it doesn't exist
  9438. getBoundingBoxAt( geometryId, target ) {
  9439. if ( geometryId >= this._geometryCount ) {
  9440. return null;
  9441. }
  9442. // compute bounding box
  9443. const bound = this._bounds[ geometryId ];
  9444. const box = bound.box;
  9445. const geometry = this.geometry;
  9446. if ( bound.boxInitialized === false ) {
  9447. box.makeEmpty();
  9448. const index = geometry.index;
  9449. const position = geometry.attributes.position;
  9450. const drawRange = this._drawRanges[ geometryId ];
  9451. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9452. let iv = i;
  9453. if ( index ) {
  9454. iv = index.getX( iv );
  9455. }
  9456. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9457. }
  9458. bound.boxInitialized = true;
  9459. }
  9460. target.copy( box );
  9461. return target;
  9462. }
  9463. // get bounding sphere and compute it if it doesn't exist
  9464. getBoundingSphereAt( geometryId, target ) {
  9465. if ( geometryId >= this._geometryCount ) {
  9466. return null;
  9467. }
  9468. // compute bounding sphere
  9469. const bound = this._bounds[ geometryId ];
  9470. const sphere = bound.sphere;
  9471. const geometry = this.geometry;
  9472. if ( bound.sphereInitialized === false ) {
  9473. sphere.makeEmpty();
  9474. this.getBoundingBoxAt( geometryId, _box$1 );
  9475. _box$1.getCenter( sphere.center );
  9476. const index = geometry.index;
  9477. const position = geometry.attributes.position;
  9478. const drawRange = this._drawRanges[ geometryId ];
  9479. let maxRadiusSq = 0;
  9480. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9481. let iv = i;
  9482. if ( index ) {
  9483. iv = index.getX( iv );
  9484. }
  9485. _vector$5.fromBufferAttribute( position, iv );
  9486. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9487. }
  9488. sphere.radius = Math.sqrt( maxRadiusSq );
  9489. bound.sphereInitialized = true;
  9490. }
  9491. target.copy( sphere );
  9492. return target;
  9493. }
  9494. setMatrixAt( instanceId, matrix ) {
  9495. // @TODO: Map geometryId to index of the arrays because
  9496. // optimize() can make geometryId mismatch the index
  9497. const drawInfo = this._drawInfo;
  9498. const matricesTexture = this._matricesTexture;
  9499. const matricesArray = this._matricesTexture.image.data;
  9500. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9501. return this;
  9502. }
  9503. matrix.toArray( matricesArray, instanceId * 16 );
  9504. matricesTexture.needsUpdate = true;
  9505. return this;
  9506. }
  9507. getMatrixAt( instanceId, matrix ) {
  9508. const drawInfo = this._drawInfo;
  9509. const matricesArray = this._matricesTexture.image.data;
  9510. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9511. return null;
  9512. }
  9513. return matrix.fromArray( matricesArray, instanceId * 16 );
  9514. }
  9515. setColorAt( instanceId, color ) {
  9516. if ( this._colorsTexture === null ) {
  9517. this._initColorsTexture();
  9518. }
  9519. // @TODO: Map id to index of the arrays because
  9520. // optimize() can make id mismatch the index
  9521. const colorsTexture = this._colorsTexture;
  9522. const colorsArray = this._colorsTexture.image.data;
  9523. const drawInfo = this._drawInfo;
  9524. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9525. return this;
  9526. }
  9527. color.toArray( colorsArray, instanceId * 4 );
  9528. colorsTexture.needsUpdate = true;
  9529. return this;
  9530. }
  9531. getColorAt( instanceId, color ) {
  9532. const colorsArray = this._colorsTexture.image.data;
  9533. const drawInfo = this._drawInfo;
  9534. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9535. return null;
  9536. }
  9537. return color.fromArray( colorsArray, instanceId * 4 );
  9538. }
  9539. setVisibleAt( instanceId, value ) {
  9540. // if the geometry is out of range, not active, or visibility state
  9541. // does not change then return early
  9542. const drawInfo = this._drawInfo;
  9543. if (
  9544. instanceId >= drawInfo.length ||
  9545. drawInfo[ instanceId ].active === false ||
  9546. drawInfo[ instanceId ].visible === value
  9547. ) {
  9548. return this;
  9549. }
  9550. drawInfo[ instanceId ].visible = value;
  9551. this._visibilityChanged = true;
  9552. return this;
  9553. }
  9554. getVisibleAt( instanceId ) {
  9555. // return early if the geometry is out of range or not active
  9556. const drawInfo = this._drawInfo;
  9557. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9558. return false;
  9559. }
  9560. return drawInfo[ instanceId ].visible;
  9561. }
  9562. raycast( raycaster, intersects ) {
  9563. const drawInfo = this._drawInfo;
  9564. const drawRanges = this._drawRanges;
  9565. const matrixWorld = this.matrixWorld;
  9566. const batchGeometry = this.geometry;
  9567. // iterate over each geometry
  9568. _mesh.material = this.material;
  9569. _mesh.geometry.index = batchGeometry.index;
  9570. _mesh.geometry.attributes = batchGeometry.attributes;
  9571. if ( _mesh.geometry.boundingBox === null ) {
  9572. _mesh.geometry.boundingBox = new Box3();
  9573. }
  9574. if ( _mesh.geometry.boundingSphere === null ) {
  9575. _mesh.geometry.boundingSphere = new Sphere();
  9576. }
  9577. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9578. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9579. continue;
  9580. }
  9581. const geometryId = drawInfo[ i ].geometryIndex;
  9582. const drawRange = drawRanges[ geometryId ];
  9583. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9584. // ge the intersects
  9585. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9586. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9587. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9588. _mesh.raycast( raycaster, _batchIntersects );
  9589. // add batch id to the intersects
  9590. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9591. const intersect = _batchIntersects[ j ];
  9592. intersect.object = this;
  9593. intersect.batchId = i;
  9594. intersects.push( intersect );
  9595. }
  9596. _batchIntersects.length = 0;
  9597. }
  9598. _mesh.material = null;
  9599. _mesh.geometry.index = null;
  9600. _mesh.geometry.attributes = {};
  9601. _mesh.geometry.setDrawRange( 0, Infinity );
  9602. }
  9603. copy( source ) {
  9604. super.copy( source );
  9605. this.geometry = source.geometry.clone();
  9606. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9607. this.sortObjects = source.sortObjects;
  9608. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9609. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9610. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9611. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9612. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9613. this._bounds = source._bounds.map( bound => ( {
  9614. boxInitialized: bound.boxInitialized,
  9615. box: bound.box.clone(),
  9616. sphereInitialized: bound.sphereInitialized,
  9617. sphere: bound.sphere.clone()
  9618. } ) );
  9619. this._maxInstanceCount = source._maxInstanceCount;
  9620. this._maxVertexCount = source._maxVertexCount;
  9621. this._maxIndexCount = source._maxIndexCount;
  9622. this._geometryInitialized = source._geometryInitialized;
  9623. this._geometryCount = source._geometryCount;
  9624. this._multiDrawCounts = source._multiDrawCounts.slice();
  9625. this._multiDrawStarts = source._multiDrawStarts.slice();
  9626. this._matricesTexture = source._matricesTexture.clone();
  9627. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9628. if ( this._colorsTexture !== null ) {
  9629. this._colorsTexture = source._colorsTexture.clone();
  9630. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9631. }
  9632. return this;
  9633. }
  9634. dispose() {
  9635. // Assuming the geometry is not shared with other meshes
  9636. this.geometry.dispose();
  9637. this._matricesTexture.dispose();
  9638. this._matricesTexture = null;
  9639. this._indirectTexture.dispose();
  9640. this._indirectTexture = null;
  9641. if ( this._colorsTexture !== null ) {
  9642. this._colorsTexture.dispose();
  9643. this._colorsTexture = null;
  9644. }
  9645. return this;
  9646. }
  9647. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9648. // if visibility has not changed and frustum culling and object sorting is not required
  9649. // then skip iterating over all items
  9650. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9651. return;
  9652. }
  9653. // the indexed version of the multi draw function requires specifying the start
  9654. // offset in bytes.
  9655. const index = geometry.getIndex();
  9656. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9657. const drawInfo = this._drawInfo;
  9658. const multiDrawStarts = this._multiDrawStarts;
  9659. const multiDrawCounts = this._multiDrawCounts;
  9660. const drawRanges = this._drawRanges;
  9661. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9662. const indirectTexture = this._indirectTexture;
  9663. const indirectArray = indirectTexture.image.data;
  9664. // prepare the frustum in the local frame
  9665. if ( perObjectFrustumCulled ) {
  9666. _projScreenMatrix$3
  9667. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9668. .multiply( this.matrixWorld );
  9669. _frustum$1.setFromProjectionMatrix(
  9670. _projScreenMatrix$3,
  9671. renderer.coordinateSystem
  9672. );
  9673. }
  9674. let count = 0;
  9675. if ( this.sortObjects ) {
  9676. // get the camera position in the local frame
  9677. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9678. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9679. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9680. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9681. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9682. const geometryId = drawInfo[ i ].geometryIndex;
  9683. // get the bounds in world space
  9684. this.getMatrixAt( i, _matrix$1 );
  9685. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9686. // determine whether the batched geometry is within the frustum
  9687. let culled = false;
  9688. if ( perObjectFrustumCulled ) {
  9689. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9690. }
  9691. if ( ! culled ) {
  9692. // get the distance from camera used for sorting
  9693. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9694. _renderList.push( drawRanges[ geometryId ], z, i );
  9695. }
  9696. }
  9697. }
  9698. // Sort the draw ranges and prep for rendering
  9699. const list = _renderList.list;
  9700. const customSort = this.customSort;
  9701. if ( customSort === null ) {
  9702. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9703. } else {
  9704. customSort.call( this, list, camera );
  9705. }
  9706. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9707. const item = list[ i ];
  9708. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9709. multiDrawCounts[ count ] = item.count;
  9710. indirectArray[ count ] = item.index;
  9711. count ++;
  9712. }
  9713. _renderList.reset();
  9714. } else {
  9715. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9716. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9717. const geometryId = drawInfo[ i ].geometryIndex;
  9718. // determine whether the batched geometry is within the frustum
  9719. let culled = false;
  9720. if ( perObjectFrustumCulled ) {
  9721. // get the bounds in world space
  9722. this.getMatrixAt( i, _matrix$1 );
  9723. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9724. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9725. }
  9726. if ( ! culled ) {
  9727. const range = drawRanges[ geometryId ];
  9728. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9729. multiDrawCounts[ count ] = range.count;
  9730. indirectArray[ count ] = i;
  9731. count ++;
  9732. }
  9733. }
  9734. }
  9735. }
  9736. indirectTexture.needsUpdate = true;
  9737. this._multiDrawCount = count;
  9738. this._visibilityChanged = false;
  9739. }
  9740. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9741. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9742. }
  9743. }
  9744. class LineBasicMaterial extends Material {
  9745. constructor( parameters ) {
  9746. super();
  9747. this.isLineBasicMaterial = true;
  9748. this.type = 'LineBasicMaterial';
  9749. this.color = new Color( 0xffffff );
  9750. this.map = null;
  9751. this.linewidth = 1;
  9752. this.linecap = 'round';
  9753. this.linejoin = 'round';
  9754. this.fog = true;
  9755. this.setValues( parameters );
  9756. }
  9757. copy( source ) {
  9758. super.copy( source );
  9759. this.color.copy( source.color );
  9760. this.map = source.map;
  9761. this.linewidth = source.linewidth;
  9762. this.linecap = source.linecap;
  9763. this.linejoin = source.linejoin;
  9764. this.fog = source.fog;
  9765. return this;
  9766. }
  9767. }
  9768. const _vStart = /*@__PURE__*/ new Vector3();
  9769. const _vEnd = /*@__PURE__*/ new Vector3();
  9770. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9771. const _ray$1 = /*@__PURE__*/ new Ray();
  9772. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9773. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9774. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9775. class Line extends Object3D {
  9776. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9777. super();
  9778. this.isLine = true;
  9779. this.type = 'Line';
  9780. this.geometry = geometry;
  9781. this.material = material;
  9782. this.updateMorphTargets();
  9783. }
  9784. copy( source, recursive ) {
  9785. super.copy( source, recursive );
  9786. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9787. this.geometry = source.geometry;
  9788. return this;
  9789. }
  9790. computeLineDistances() {
  9791. const geometry = this.geometry;
  9792. // we assume non-indexed geometry
  9793. if ( geometry.index === null ) {
  9794. const positionAttribute = geometry.attributes.position;
  9795. const lineDistances = [ 0 ];
  9796. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9797. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9798. _vEnd.fromBufferAttribute( positionAttribute, i );
  9799. lineDistances[ i ] = lineDistances[ i - 1 ];
  9800. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9801. }
  9802. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9803. } else {
  9804. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9805. }
  9806. return this;
  9807. }
  9808. raycast( raycaster, intersects ) {
  9809. const geometry = this.geometry;
  9810. const matrixWorld = this.matrixWorld;
  9811. const threshold = raycaster.params.Line.threshold;
  9812. const drawRange = geometry.drawRange;
  9813. // Checking boundingSphere distance to ray
  9814. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9815. _sphere$1.copy( geometry.boundingSphere );
  9816. _sphere$1.applyMatrix4( matrixWorld );
  9817. _sphere$1.radius += threshold;
  9818. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9819. //
  9820. _inverseMatrix$1.copy( matrixWorld ).invert();
  9821. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9822. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9823. const localThresholdSq = localThreshold * localThreshold;
  9824. const step = this.isLineSegments ? 2 : 1;
  9825. const index = geometry.index;
  9826. const attributes = geometry.attributes;
  9827. const positionAttribute = attributes.position;
  9828. if ( index !== null ) {
  9829. const start = Math.max( 0, drawRange.start );
  9830. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9831. for ( let i = start, l = end - 1; i < l; i += step ) {
  9832. const a = index.getX( i );
  9833. const b = index.getX( i + 1 );
  9834. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9835. if ( intersect ) {
  9836. intersects.push( intersect );
  9837. }
  9838. }
  9839. if ( this.isLineLoop ) {
  9840. const a = index.getX( end - 1 );
  9841. const b = index.getX( start );
  9842. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9843. if ( intersect ) {
  9844. intersects.push( intersect );
  9845. }
  9846. }
  9847. } else {
  9848. const start = Math.max( 0, drawRange.start );
  9849. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9850. for ( let i = start, l = end - 1; i < l; i += step ) {
  9851. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9852. if ( intersect ) {
  9853. intersects.push( intersect );
  9854. }
  9855. }
  9856. if ( this.isLineLoop ) {
  9857. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9858. if ( intersect ) {
  9859. intersects.push( intersect );
  9860. }
  9861. }
  9862. }
  9863. }
  9864. updateMorphTargets() {
  9865. const geometry = this.geometry;
  9866. const morphAttributes = geometry.morphAttributes;
  9867. const keys = Object.keys( morphAttributes );
  9868. if ( keys.length > 0 ) {
  9869. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9870. if ( morphAttribute !== undefined ) {
  9871. this.morphTargetInfluences = [];
  9872. this.morphTargetDictionary = {};
  9873. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9874. const name = morphAttribute[ m ].name || String( m );
  9875. this.morphTargetInfluences.push( 0 );
  9876. this.morphTargetDictionary[ name ] = m;
  9877. }
  9878. }
  9879. }
  9880. }
  9881. }
  9882. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9883. const positionAttribute = object.geometry.attributes.position;
  9884. _vStart.fromBufferAttribute( positionAttribute, a );
  9885. _vEnd.fromBufferAttribute( positionAttribute, b );
  9886. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9887. if ( distSq > thresholdSq ) return;
  9888. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9889. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9890. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9891. return {
  9892. distance: distance,
  9893. // What do we want? intersection point on the ray or on the segment??
  9894. // point: raycaster.ray.at( distance ),
  9895. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9896. index: a,
  9897. face: null,
  9898. faceIndex: null,
  9899. object: object
  9900. };
  9901. }
  9902. const _start = /*@__PURE__*/ new Vector3();
  9903. const _end = /*@__PURE__*/ new Vector3();
  9904. class LineSegments extends Line {
  9905. constructor( geometry, material ) {
  9906. super( geometry, material );
  9907. this.isLineSegments = true;
  9908. this.type = 'LineSegments';
  9909. }
  9910. computeLineDistances() {
  9911. const geometry = this.geometry;
  9912. // we assume non-indexed geometry
  9913. if ( geometry.index === null ) {
  9914. const positionAttribute = geometry.attributes.position;
  9915. const lineDistances = [];
  9916. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9917. _start.fromBufferAttribute( positionAttribute, i );
  9918. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9919. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9920. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9921. }
  9922. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9923. } else {
  9924. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9925. }
  9926. return this;
  9927. }
  9928. }
  9929. class LineLoop extends Line {
  9930. constructor( geometry, material ) {
  9931. super( geometry, material );
  9932. this.isLineLoop = true;
  9933. this.type = 'LineLoop';
  9934. }
  9935. }
  9936. class PointsMaterial extends Material {
  9937. constructor( parameters ) {
  9938. super();
  9939. this.isPointsMaterial = true;
  9940. this.type = 'PointsMaterial';
  9941. this.color = new Color( 0xffffff );
  9942. this.map = null;
  9943. this.alphaMap = null;
  9944. this.size = 1;
  9945. this.sizeAttenuation = true;
  9946. this.fog = true;
  9947. this.setValues( parameters );
  9948. }
  9949. copy( source ) {
  9950. super.copy( source );
  9951. this.color.copy( source.color );
  9952. this.map = source.map;
  9953. this.alphaMap = source.alphaMap;
  9954. this.size = source.size;
  9955. this.sizeAttenuation = source.sizeAttenuation;
  9956. this.fog = source.fog;
  9957. return this;
  9958. }
  9959. }
  9960. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9961. const _ray = /*@__PURE__*/ new Ray();
  9962. const _sphere = /*@__PURE__*/ new Sphere();
  9963. const _position$2 = /*@__PURE__*/ new Vector3();
  9964. class Points extends Object3D {
  9965. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9966. super();
  9967. this.isPoints = true;
  9968. this.type = 'Points';
  9969. this.geometry = geometry;
  9970. this.material = material;
  9971. this.updateMorphTargets();
  9972. }
  9973. copy( source, recursive ) {
  9974. super.copy( source, recursive );
  9975. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9976. this.geometry = source.geometry;
  9977. return this;
  9978. }
  9979. raycast( raycaster, intersects ) {
  9980. const geometry = this.geometry;
  9981. const matrixWorld = this.matrixWorld;
  9982. const threshold = raycaster.params.Points.threshold;
  9983. const drawRange = geometry.drawRange;
  9984. // Checking boundingSphere distance to ray
  9985. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9986. _sphere.copy( geometry.boundingSphere );
  9987. _sphere.applyMatrix4( matrixWorld );
  9988. _sphere.radius += threshold;
  9989. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  9990. //
  9991. _inverseMatrix.copy( matrixWorld ).invert();
  9992. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  9993. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9994. const localThresholdSq = localThreshold * localThreshold;
  9995. const index = geometry.index;
  9996. const attributes = geometry.attributes;
  9997. const positionAttribute = attributes.position;
  9998. if ( index !== null ) {
  9999. const start = Math.max( 0, drawRange.start );
  10000. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10001. for ( let i = start, il = end; i < il; i ++ ) {
  10002. const a = index.getX( i );
  10003. _position$2.fromBufferAttribute( positionAttribute, a );
  10004. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10005. }
  10006. } else {
  10007. const start = Math.max( 0, drawRange.start );
  10008. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10009. for ( let i = start, l = end; i < l; i ++ ) {
  10010. _position$2.fromBufferAttribute( positionAttribute, i );
  10011. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10012. }
  10013. }
  10014. }
  10015. updateMorphTargets() {
  10016. const geometry = this.geometry;
  10017. const morphAttributes = geometry.morphAttributes;
  10018. const keys = Object.keys( morphAttributes );
  10019. if ( keys.length > 0 ) {
  10020. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10021. if ( morphAttribute !== undefined ) {
  10022. this.morphTargetInfluences = [];
  10023. this.morphTargetDictionary = {};
  10024. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10025. const name = morphAttribute[ m ].name || String( m );
  10026. this.morphTargetInfluences.push( 0 );
  10027. this.morphTargetDictionary[ name ] = m;
  10028. }
  10029. }
  10030. }
  10031. }
  10032. }
  10033. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10034. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10035. if ( rayPointDistanceSq < localThresholdSq ) {
  10036. const intersectPoint = new Vector3();
  10037. _ray.closestPointToPoint( point, intersectPoint );
  10038. intersectPoint.applyMatrix4( matrixWorld );
  10039. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10040. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10041. intersects.push( {
  10042. distance: distance,
  10043. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10044. point: intersectPoint,
  10045. index: index,
  10046. face: null,
  10047. object: object
  10048. } );
  10049. }
  10050. }
  10051. class Group extends Object3D {
  10052. constructor() {
  10053. super();
  10054. this.isGroup = true;
  10055. this.type = 'Group';
  10056. }
  10057. }
  10058. class VideoTexture extends Texture {
  10059. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10060. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10061. this.isVideoTexture = true;
  10062. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10063. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10064. this.generateMipmaps = false;
  10065. const scope = this;
  10066. function updateVideo() {
  10067. scope.needsUpdate = true;
  10068. video.requestVideoFrameCallback( updateVideo );
  10069. }
  10070. if ( 'requestVideoFrameCallback' in video ) {
  10071. video.requestVideoFrameCallback( updateVideo );
  10072. }
  10073. }
  10074. clone() {
  10075. return new this.constructor( this.image ).copy( this );
  10076. }
  10077. update() {
  10078. const video = this.image;
  10079. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10080. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10081. this.needsUpdate = true;
  10082. }
  10083. }
  10084. }
  10085. class FramebufferTexture extends Texture {
  10086. constructor( width, height ) {
  10087. super( { width, height } );
  10088. this.isFramebufferTexture = true;
  10089. this.magFilter = NearestFilter;
  10090. this.minFilter = NearestFilter;
  10091. this.generateMipmaps = false;
  10092. this.needsUpdate = true;
  10093. }
  10094. }
  10095. class CompressedTexture extends Texture {
  10096. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10097. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10098. this.isCompressedTexture = true;
  10099. this.image = { width: width, height: height };
  10100. this.mipmaps = mipmaps;
  10101. // no flipping for cube textures
  10102. // (also flipping doesn't work for compressed textures )
  10103. this.flipY = false;
  10104. // can't generate mipmaps for compressed textures
  10105. // mips must be embedded in DDS files
  10106. this.generateMipmaps = false;
  10107. }
  10108. }
  10109. class CompressedArrayTexture extends CompressedTexture {
  10110. constructor( mipmaps, width, height, depth, format, type ) {
  10111. super( mipmaps, width, height, format, type );
  10112. this.isCompressedArrayTexture = true;
  10113. this.image.depth = depth;
  10114. this.wrapR = ClampToEdgeWrapping;
  10115. this.layerUpdates = new Set();
  10116. }
  10117. addLayerUpdate( layerIndex ) {
  10118. this.layerUpdates.add( layerIndex );
  10119. }
  10120. clearLayerUpdates() {
  10121. this.layerUpdates.clear();
  10122. }
  10123. }
  10124. class CompressedCubeTexture extends CompressedTexture {
  10125. constructor( images, format, type ) {
  10126. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10127. this.isCompressedCubeTexture = true;
  10128. this.isCubeTexture = true;
  10129. this.image = images;
  10130. }
  10131. }
  10132. class CanvasTexture extends Texture {
  10133. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10134. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10135. this.isCanvasTexture = true;
  10136. this.needsUpdate = true;
  10137. }
  10138. }
  10139. class DepthTexture extends Texture {
  10140. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10141. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10142. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10143. }
  10144. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10145. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10146. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10147. this.isDepthTexture = true;
  10148. this.image = { width: width, height: height };
  10149. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10150. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10151. this.flipY = false;
  10152. this.generateMipmaps = false;
  10153. this.compareFunction = null;
  10154. }
  10155. copy( source ) {
  10156. super.copy( source );
  10157. this.compareFunction = source.compareFunction;
  10158. return this;
  10159. }
  10160. toJSON( meta ) {
  10161. const data = super.toJSON( meta );
  10162. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10163. return data;
  10164. }
  10165. }
  10166. /**
  10167. * Extensible curve object.
  10168. *
  10169. * Some common of curve methods:
  10170. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10171. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10172. * .getPoints(), .getSpacedPoints()
  10173. * .getLength()
  10174. * .updateArcLengths()
  10175. *
  10176. * This following curves inherit from THREE.Curve:
  10177. *
  10178. * -- 2D curves --
  10179. * THREE.ArcCurve
  10180. * THREE.CubicBezierCurve
  10181. * THREE.EllipseCurve
  10182. * THREE.LineCurve
  10183. * THREE.QuadraticBezierCurve
  10184. * THREE.SplineCurve
  10185. *
  10186. * -- 3D curves --
  10187. * THREE.CatmullRomCurve3
  10188. * THREE.CubicBezierCurve3
  10189. * THREE.LineCurve3
  10190. * THREE.QuadraticBezierCurve3
  10191. *
  10192. * A series of curves can be represented as a THREE.CurvePath.
  10193. *
  10194. **/
  10195. class Curve {
  10196. constructor() {
  10197. this.type = 'Curve';
  10198. this.arcLengthDivisions = 200;
  10199. }
  10200. // Virtual base class method to overwrite and implement in subclasses
  10201. // - t [0 .. 1]
  10202. getPoint( /* t, optionalTarget */ ) {
  10203. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10204. return null;
  10205. }
  10206. // Get point at relative position in curve according to arc length
  10207. // - u [0 .. 1]
  10208. getPointAt( u, optionalTarget ) {
  10209. const t = this.getUtoTmapping( u );
  10210. return this.getPoint( t, optionalTarget );
  10211. }
  10212. // Get sequence of points using getPoint( t )
  10213. getPoints( divisions = 5 ) {
  10214. const points = [];
  10215. for ( let d = 0; d <= divisions; d ++ ) {
  10216. points.push( this.getPoint( d / divisions ) );
  10217. }
  10218. return points;
  10219. }
  10220. // Get sequence of points using getPointAt( u )
  10221. getSpacedPoints( divisions = 5 ) {
  10222. const points = [];
  10223. for ( let d = 0; d <= divisions; d ++ ) {
  10224. points.push( this.getPointAt( d / divisions ) );
  10225. }
  10226. return points;
  10227. }
  10228. // Get total curve arc length
  10229. getLength() {
  10230. const lengths = this.getLengths();
  10231. return lengths[ lengths.length - 1 ];
  10232. }
  10233. // Get list of cumulative segment lengths
  10234. getLengths( divisions = this.arcLengthDivisions ) {
  10235. if ( this.cacheArcLengths &&
  10236. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10237. ! this.needsUpdate ) {
  10238. return this.cacheArcLengths;
  10239. }
  10240. this.needsUpdate = false;
  10241. const cache = [];
  10242. let current, last = this.getPoint( 0 );
  10243. let sum = 0;
  10244. cache.push( 0 );
  10245. for ( let p = 1; p <= divisions; p ++ ) {
  10246. current = this.getPoint( p / divisions );
  10247. sum += current.distanceTo( last );
  10248. cache.push( sum );
  10249. last = current;
  10250. }
  10251. this.cacheArcLengths = cache;
  10252. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10253. }
  10254. updateArcLengths() {
  10255. this.needsUpdate = true;
  10256. this.getLengths();
  10257. }
  10258. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10259. getUtoTmapping( u, distance ) {
  10260. const arcLengths = this.getLengths();
  10261. let i = 0;
  10262. const il = arcLengths.length;
  10263. let targetArcLength; // The targeted u distance value to get
  10264. if ( distance ) {
  10265. targetArcLength = distance;
  10266. } else {
  10267. targetArcLength = u * arcLengths[ il - 1 ];
  10268. }
  10269. // binary search for the index with largest value smaller than target u distance
  10270. let low = 0, high = il - 1, comparison;
  10271. while ( low <= high ) {
  10272. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  10273. comparison = arcLengths[ i ] - targetArcLength;
  10274. if ( comparison < 0 ) {
  10275. low = i + 1;
  10276. } else if ( comparison > 0 ) {
  10277. high = i - 1;
  10278. } else {
  10279. high = i;
  10280. break;
  10281. // DONE
  10282. }
  10283. }
  10284. i = high;
  10285. if ( arcLengths[ i ] === targetArcLength ) {
  10286. return i / ( il - 1 );
  10287. }
  10288. // we could get finer grain at lengths, or use simple interpolation between two points
  10289. const lengthBefore = arcLengths[ i ];
  10290. const lengthAfter = arcLengths[ i + 1 ];
  10291. const segmentLength = lengthAfter - lengthBefore;
  10292. // determine where we are between the 'before' and 'after' points
  10293. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10294. // add that fractional amount to t
  10295. const t = ( i + segmentFraction ) / ( il - 1 );
  10296. return t;
  10297. }
  10298. // Returns a unit vector tangent at t
  10299. // In case any sub curve does not implement its tangent derivation,
  10300. // 2 points a small delta apart will be used to find its gradient
  10301. // which seems to give a reasonable approximation
  10302. getTangent( t, optionalTarget ) {
  10303. const delta = 0.0001;
  10304. let t1 = t - delta;
  10305. let t2 = t + delta;
  10306. // Capping in case of danger
  10307. if ( t1 < 0 ) t1 = 0;
  10308. if ( t2 > 1 ) t2 = 1;
  10309. const pt1 = this.getPoint( t1 );
  10310. const pt2 = this.getPoint( t2 );
  10311. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10312. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10313. return tangent;
  10314. }
  10315. getTangentAt( u, optionalTarget ) {
  10316. const t = this.getUtoTmapping( u );
  10317. return this.getTangent( t, optionalTarget );
  10318. }
  10319. computeFrenetFrames( segments, closed ) {
  10320. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10321. const normal = new Vector3();
  10322. const tangents = [];
  10323. const normals = [];
  10324. const binormals = [];
  10325. const vec = new Vector3();
  10326. const mat = new Matrix4();
  10327. // compute the tangent vectors for each segment on the curve
  10328. for ( let i = 0; i <= segments; i ++ ) {
  10329. const u = i / segments;
  10330. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10331. }
  10332. // select an initial normal vector perpendicular to the first tangent vector,
  10333. // and in the direction of the minimum tangent xyz component
  10334. normals[ 0 ] = new Vector3();
  10335. binormals[ 0 ] = new Vector3();
  10336. let min = Number.MAX_VALUE;
  10337. const tx = Math.abs( tangents[ 0 ].x );
  10338. const ty = Math.abs( tangents[ 0 ].y );
  10339. const tz = Math.abs( tangents[ 0 ].z );
  10340. if ( tx <= min ) {
  10341. min = tx;
  10342. normal.set( 1, 0, 0 );
  10343. }
  10344. if ( ty <= min ) {
  10345. min = ty;
  10346. normal.set( 0, 1, 0 );
  10347. }
  10348. if ( tz <= min ) {
  10349. normal.set( 0, 0, 1 );
  10350. }
  10351. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10352. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10353. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10354. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10355. for ( let i = 1; i <= segments; i ++ ) {
  10356. normals[ i ] = normals[ i - 1 ].clone();
  10357. binormals[ i ] = binormals[ i - 1 ].clone();
  10358. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10359. if ( vec.length() > Number.EPSILON ) {
  10360. vec.normalize();
  10361. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10362. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10363. }
  10364. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10365. }
  10366. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10367. if ( closed === true ) {
  10368. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10369. theta /= segments;
  10370. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10371. theta = - theta;
  10372. }
  10373. for ( let i = 1; i <= segments; i ++ ) {
  10374. // twist a little...
  10375. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10376. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10377. }
  10378. }
  10379. return {
  10380. tangents: tangents,
  10381. normals: normals,
  10382. binormals: binormals
  10383. };
  10384. }
  10385. clone() {
  10386. return new this.constructor().copy( this );
  10387. }
  10388. copy( source ) {
  10389. this.arcLengthDivisions = source.arcLengthDivisions;
  10390. return this;
  10391. }
  10392. toJSON() {
  10393. const data = {
  10394. metadata: {
  10395. version: 4.6,
  10396. type: 'Curve',
  10397. generator: 'Curve.toJSON'
  10398. }
  10399. };
  10400. data.arcLengthDivisions = this.arcLengthDivisions;
  10401. data.type = this.type;
  10402. return data;
  10403. }
  10404. fromJSON( json ) {
  10405. this.arcLengthDivisions = json.arcLengthDivisions;
  10406. return this;
  10407. }
  10408. }
  10409. class EllipseCurve extends Curve {
  10410. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10411. super();
  10412. this.isEllipseCurve = true;
  10413. this.type = 'EllipseCurve';
  10414. this.aX = aX;
  10415. this.aY = aY;
  10416. this.xRadius = xRadius;
  10417. this.yRadius = yRadius;
  10418. this.aStartAngle = aStartAngle;
  10419. this.aEndAngle = aEndAngle;
  10420. this.aClockwise = aClockwise;
  10421. this.aRotation = aRotation;
  10422. }
  10423. getPoint( t, optionalTarget = new Vector2() ) {
  10424. const point = optionalTarget;
  10425. const twoPi = Math.PI * 2;
  10426. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10427. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10428. // ensures that deltaAngle is 0 .. 2 PI
  10429. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10430. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10431. if ( deltaAngle < Number.EPSILON ) {
  10432. if ( samePoints ) {
  10433. deltaAngle = 0;
  10434. } else {
  10435. deltaAngle = twoPi;
  10436. }
  10437. }
  10438. if ( this.aClockwise === true && ! samePoints ) {
  10439. if ( deltaAngle === twoPi ) {
  10440. deltaAngle = - twoPi;
  10441. } else {
  10442. deltaAngle = deltaAngle - twoPi;
  10443. }
  10444. }
  10445. const angle = this.aStartAngle + t * deltaAngle;
  10446. let x = this.aX + this.xRadius * Math.cos( angle );
  10447. let y = this.aY + this.yRadius * Math.sin( angle );
  10448. if ( this.aRotation !== 0 ) {
  10449. const cos = Math.cos( this.aRotation );
  10450. const sin = Math.sin( this.aRotation );
  10451. const tx = x - this.aX;
  10452. const ty = y - this.aY;
  10453. // Rotate the point about the center of the ellipse.
  10454. x = tx * cos - ty * sin + this.aX;
  10455. y = tx * sin + ty * cos + this.aY;
  10456. }
  10457. return point.set( x, y );
  10458. }
  10459. copy( source ) {
  10460. super.copy( source );
  10461. this.aX = source.aX;
  10462. this.aY = source.aY;
  10463. this.xRadius = source.xRadius;
  10464. this.yRadius = source.yRadius;
  10465. this.aStartAngle = source.aStartAngle;
  10466. this.aEndAngle = source.aEndAngle;
  10467. this.aClockwise = source.aClockwise;
  10468. this.aRotation = source.aRotation;
  10469. return this;
  10470. }
  10471. toJSON() {
  10472. const data = super.toJSON();
  10473. data.aX = this.aX;
  10474. data.aY = this.aY;
  10475. data.xRadius = this.xRadius;
  10476. data.yRadius = this.yRadius;
  10477. data.aStartAngle = this.aStartAngle;
  10478. data.aEndAngle = this.aEndAngle;
  10479. data.aClockwise = this.aClockwise;
  10480. data.aRotation = this.aRotation;
  10481. return data;
  10482. }
  10483. fromJSON( json ) {
  10484. super.fromJSON( json );
  10485. this.aX = json.aX;
  10486. this.aY = json.aY;
  10487. this.xRadius = json.xRadius;
  10488. this.yRadius = json.yRadius;
  10489. this.aStartAngle = json.aStartAngle;
  10490. this.aEndAngle = json.aEndAngle;
  10491. this.aClockwise = json.aClockwise;
  10492. this.aRotation = json.aRotation;
  10493. return this;
  10494. }
  10495. }
  10496. class ArcCurve extends EllipseCurve {
  10497. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10498. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10499. this.isArcCurve = true;
  10500. this.type = 'ArcCurve';
  10501. }
  10502. }
  10503. /**
  10504. * Centripetal CatmullRom Curve - which is useful for avoiding
  10505. * cusps and self-intersections in non-uniform catmull rom curves.
  10506. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10507. *
  10508. * curve.type accepts centripetal(default), chordal and catmullrom
  10509. * curve.tension is used for catmullrom which defaults to 0.5
  10510. */
  10511. /*
  10512. Based on an optimized c++ solution in
  10513. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10514. - http://ideone.com/NoEbVM
  10515. This CubicPoly class could be used for reusing some variables and calculations,
  10516. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10517. which can be placed in CurveUtils.
  10518. */
  10519. function CubicPoly() {
  10520. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10521. /*
  10522. * Compute coefficients for a cubic polynomial
  10523. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10524. * such that
  10525. * p(0) = x0, p(1) = x1
  10526. * and
  10527. * p'(0) = t0, p'(1) = t1.
  10528. */
  10529. function init( x0, x1, t0, t1 ) {
  10530. c0 = x0;
  10531. c1 = t0;
  10532. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10533. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10534. }
  10535. return {
  10536. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10537. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10538. },
  10539. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10540. // compute tangents when parameterized in [t1,t2]
  10541. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10542. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10543. // rescale tangents for parametrization in [0,1]
  10544. t1 *= dt1;
  10545. t2 *= dt1;
  10546. init( x1, x2, t1, t2 );
  10547. },
  10548. calc: function ( t ) {
  10549. const t2 = t * t;
  10550. const t3 = t2 * t;
  10551. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10552. }
  10553. };
  10554. }
  10555. //
  10556. const tmp = /*@__PURE__*/ new Vector3();
  10557. const px = /*@__PURE__*/ new CubicPoly();
  10558. const py = /*@__PURE__*/ new CubicPoly();
  10559. const pz = /*@__PURE__*/ new CubicPoly();
  10560. class CatmullRomCurve3 extends Curve {
  10561. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10562. super();
  10563. this.isCatmullRomCurve3 = true;
  10564. this.type = 'CatmullRomCurve3';
  10565. this.points = points;
  10566. this.closed = closed;
  10567. this.curveType = curveType;
  10568. this.tension = tension;
  10569. }
  10570. getPoint( t, optionalTarget = new Vector3() ) {
  10571. const point = optionalTarget;
  10572. const points = this.points;
  10573. const l = points.length;
  10574. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10575. let intPoint = Math.floor( p );
  10576. let weight = p - intPoint;
  10577. if ( this.closed ) {
  10578. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10579. } else if ( weight === 0 && intPoint === l - 1 ) {
  10580. intPoint = l - 2;
  10581. weight = 1;
  10582. }
  10583. let p0, p3; // 4 points (p1 & p2 defined below)
  10584. if ( this.closed || intPoint > 0 ) {
  10585. p0 = points[ ( intPoint - 1 ) % l ];
  10586. } else {
  10587. // extrapolate first point
  10588. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10589. p0 = tmp;
  10590. }
  10591. const p1 = points[ intPoint % l ];
  10592. const p2 = points[ ( intPoint + 1 ) % l ];
  10593. if ( this.closed || intPoint + 2 < l ) {
  10594. p3 = points[ ( intPoint + 2 ) % l ];
  10595. } else {
  10596. // extrapolate last point
  10597. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10598. p3 = tmp;
  10599. }
  10600. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10601. // init Centripetal / Chordal Catmull-Rom
  10602. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10603. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10604. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10605. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10606. // safety check for repeated points
  10607. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10608. if ( dt0 < 1e-4 ) dt0 = dt1;
  10609. if ( dt2 < 1e-4 ) dt2 = dt1;
  10610. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10611. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10612. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10613. } else if ( this.curveType === 'catmullrom' ) {
  10614. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10615. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10616. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10617. }
  10618. point.set(
  10619. px.calc( weight ),
  10620. py.calc( weight ),
  10621. pz.calc( weight )
  10622. );
  10623. return point;
  10624. }
  10625. copy( source ) {
  10626. super.copy( source );
  10627. this.points = [];
  10628. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10629. const point = source.points[ i ];
  10630. this.points.push( point.clone() );
  10631. }
  10632. this.closed = source.closed;
  10633. this.curveType = source.curveType;
  10634. this.tension = source.tension;
  10635. return this;
  10636. }
  10637. toJSON() {
  10638. const data = super.toJSON();
  10639. data.points = [];
  10640. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10641. const point = this.points[ i ];
  10642. data.points.push( point.toArray() );
  10643. }
  10644. data.closed = this.closed;
  10645. data.curveType = this.curveType;
  10646. data.tension = this.tension;
  10647. return data;
  10648. }
  10649. fromJSON( json ) {
  10650. super.fromJSON( json );
  10651. this.points = [];
  10652. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10653. const point = json.points[ i ];
  10654. this.points.push( new Vector3().fromArray( point ) );
  10655. }
  10656. this.closed = json.closed;
  10657. this.curveType = json.curveType;
  10658. this.tension = json.tension;
  10659. return this;
  10660. }
  10661. }
  10662. /**
  10663. * Bezier Curves formulas obtained from
  10664. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10665. */
  10666. function CatmullRom( t, p0, p1, p2, p3 ) {
  10667. const v0 = ( p2 - p0 ) * 0.5;
  10668. const v1 = ( p3 - p1 ) * 0.5;
  10669. const t2 = t * t;
  10670. const t3 = t * t2;
  10671. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10672. }
  10673. //
  10674. function QuadraticBezierP0( t, p ) {
  10675. const k = 1 - t;
  10676. return k * k * p;
  10677. }
  10678. function QuadraticBezierP1( t, p ) {
  10679. return 2 * ( 1 - t ) * t * p;
  10680. }
  10681. function QuadraticBezierP2( t, p ) {
  10682. return t * t * p;
  10683. }
  10684. function QuadraticBezier( t, p0, p1, p2 ) {
  10685. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10686. QuadraticBezierP2( t, p2 );
  10687. }
  10688. //
  10689. function CubicBezierP0( t, p ) {
  10690. const k = 1 - t;
  10691. return k * k * k * p;
  10692. }
  10693. function CubicBezierP1( t, p ) {
  10694. const k = 1 - t;
  10695. return 3 * k * k * t * p;
  10696. }
  10697. function CubicBezierP2( t, p ) {
  10698. return 3 * ( 1 - t ) * t * t * p;
  10699. }
  10700. function CubicBezierP3( t, p ) {
  10701. return t * t * t * p;
  10702. }
  10703. function CubicBezier( t, p0, p1, p2, p3 ) {
  10704. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10705. CubicBezierP3( t, p3 );
  10706. }
  10707. class CubicBezierCurve extends Curve {
  10708. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10709. super();
  10710. this.isCubicBezierCurve = true;
  10711. this.type = 'CubicBezierCurve';
  10712. this.v0 = v0;
  10713. this.v1 = v1;
  10714. this.v2 = v2;
  10715. this.v3 = v3;
  10716. }
  10717. getPoint( t, optionalTarget = new Vector2() ) {
  10718. const point = optionalTarget;
  10719. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10720. point.set(
  10721. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10722. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10723. );
  10724. return point;
  10725. }
  10726. copy( source ) {
  10727. super.copy( source );
  10728. this.v0.copy( source.v0 );
  10729. this.v1.copy( source.v1 );
  10730. this.v2.copy( source.v2 );
  10731. this.v3.copy( source.v3 );
  10732. return this;
  10733. }
  10734. toJSON() {
  10735. const data = super.toJSON();
  10736. data.v0 = this.v0.toArray();
  10737. data.v1 = this.v1.toArray();
  10738. data.v2 = this.v2.toArray();
  10739. data.v3 = this.v3.toArray();
  10740. return data;
  10741. }
  10742. fromJSON( json ) {
  10743. super.fromJSON( json );
  10744. this.v0.fromArray( json.v0 );
  10745. this.v1.fromArray( json.v1 );
  10746. this.v2.fromArray( json.v2 );
  10747. this.v3.fromArray( json.v3 );
  10748. return this;
  10749. }
  10750. }
  10751. class CubicBezierCurve3 extends Curve {
  10752. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10753. super();
  10754. this.isCubicBezierCurve3 = true;
  10755. this.type = 'CubicBezierCurve3';
  10756. this.v0 = v0;
  10757. this.v1 = v1;
  10758. this.v2 = v2;
  10759. this.v3 = v3;
  10760. }
  10761. getPoint( t, optionalTarget = new Vector3() ) {
  10762. const point = optionalTarget;
  10763. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10764. point.set(
  10765. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10766. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10767. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10768. );
  10769. return point;
  10770. }
  10771. copy( source ) {
  10772. super.copy( source );
  10773. this.v0.copy( source.v0 );
  10774. this.v1.copy( source.v1 );
  10775. this.v2.copy( source.v2 );
  10776. this.v3.copy( source.v3 );
  10777. return this;
  10778. }
  10779. toJSON() {
  10780. const data = super.toJSON();
  10781. data.v0 = this.v0.toArray();
  10782. data.v1 = this.v1.toArray();
  10783. data.v2 = this.v2.toArray();
  10784. data.v3 = this.v3.toArray();
  10785. return data;
  10786. }
  10787. fromJSON( json ) {
  10788. super.fromJSON( json );
  10789. this.v0.fromArray( json.v0 );
  10790. this.v1.fromArray( json.v1 );
  10791. this.v2.fromArray( json.v2 );
  10792. this.v3.fromArray( json.v3 );
  10793. return this;
  10794. }
  10795. }
  10796. class LineCurve extends Curve {
  10797. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10798. super();
  10799. this.isLineCurve = true;
  10800. this.type = 'LineCurve';
  10801. this.v1 = v1;
  10802. this.v2 = v2;
  10803. }
  10804. getPoint( t, optionalTarget = new Vector2() ) {
  10805. const point = optionalTarget;
  10806. if ( t === 1 ) {
  10807. point.copy( this.v2 );
  10808. } else {
  10809. point.copy( this.v2 ).sub( this.v1 );
  10810. point.multiplyScalar( t ).add( this.v1 );
  10811. }
  10812. return point;
  10813. }
  10814. // Line curve is linear, so we can overwrite default getPointAt
  10815. getPointAt( u, optionalTarget ) {
  10816. return this.getPoint( u, optionalTarget );
  10817. }
  10818. getTangent( t, optionalTarget = new Vector2() ) {
  10819. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10820. }
  10821. getTangentAt( u, optionalTarget ) {
  10822. return this.getTangent( u, optionalTarget );
  10823. }
  10824. copy( source ) {
  10825. super.copy( source );
  10826. this.v1.copy( source.v1 );
  10827. this.v2.copy( source.v2 );
  10828. return this;
  10829. }
  10830. toJSON() {
  10831. const data = super.toJSON();
  10832. data.v1 = this.v1.toArray();
  10833. data.v2 = this.v2.toArray();
  10834. return data;
  10835. }
  10836. fromJSON( json ) {
  10837. super.fromJSON( json );
  10838. this.v1.fromArray( json.v1 );
  10839. this.v2.fromArray( json.v2 );
  10840. return this;
  10841. }
  10842. }
  10843. class LineCurve3 extends Curve {
  10844. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10845. super();
  10846. this.isLineCurve3 = true;
  10847. this.type = 'LineCurve3';
  10848. this.v1 = v1;
  10849. this.v2 = v2;
  10850. }
  10851. getPoint( t, optionalTarget = new Vector3() ) {
  10852. const point = optionalTarget;
  10853. if ( t === 1 ) {
  10854. point.copy( this.v2 );
  10855. } else {
  10856. point.copy( this.v2 ).sub( this.v1 );
  10857. point.multiplyScalar( t ).add( this.v1 );
  10858. }
  10859. return point;
  10860. }
  10861. // Line curve is linear, so we can overwrite default getPointAt
  10862. getPointAt( u, optionalTarget ) {
  10863. return this.getPoint( u, optionalTarget );
  10864. }
  10865. getTangent( t, optionalTarget = new Vector3() ) {
  10866. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10867. }
  10868. getTangentAt( u, optionalTarget ) {
  10869. return this.getTangent( u, optionalTarget );
  10870. }
  10871. copy( source ) {
  10872. super.copy( source );
  10873. this.v1.copy( source.v1 );
  10874. this.v2.copy( source.v2 );
  10875. return this;
  10876. }
  10877. toJSON() {
  10878. const data = super.toJSON();
  10879. data.v1 = this.v1.toArray();
  10880. data.v2 = this.v2.toArray();
  10881. return data;
  10882. }
  10883. fromJSON( json ) {
  10884. super.fromJSON( json );
  10885. this.v1.fromArray( json.v1 );
  10886. this.v2.fromArray( json.v2 );
  10887. return this;
  10888. }
  10889. }
  10890. class QuadraticBezierCurve extends Curve {
  10891. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10892. super();
  10893. this.isQuadraticBezierCurve = true;
  10894. this.type = 'QuadraticBezierCurve';
  10895. this.v0 = v0;
  10896. this.v1 = v1;
  10897. this.v2 = v2;
  10898. }
  10899. getPoint( t, optionalTarget = new Vector2() ) {
  10900. const point = optionalTarget;
  10901. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10902. point.set(
  10903. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10904. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10905. );
  10906. return point;
  10907. }
  10908. copy( source ) {
  10909. super.copy( source );
  10910. this.v0.copy( source.v0 );
  10911. this.v1.copy( source.v1 );
  10912. this.v2.copy( source.v2 );
  10913. return this;
  10914. }
  10915. toJSON() {
  10916. const data = super.toJSON();
  10917. data.v0 = this.v0.toArray();
  10918. data.v1 = this.v1.toArray();
  10919. data.v2 = this.v2.toArray();
  10920. return data;
  10921. }
  10922. fromJSON( json ) {
  10923. super.fromJSON( json );
  10924. this.v0.fromArray( json.v0 );
  10925. this.v1.fromArray( json.v1 );
  10926. this.v2.fromArray( json.v2 );
  10927. return this;
  10928. }
  10929. }
  10930. class QuadraticBezierCurve3 extends Curve {
  10931. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10932. super();
  10933. this.isQuadraticBezierCurve3 = true;
  10934. this.type = 'QuadraticBezierCurve3';
  10935. this.v0 = v0;
  10936. this.v1 = v1;
  10937. this.v2 = v2;
  10938. }
  10939. getPoint( t, optionalTarget = new Vector3() ) {
  10940. const point = optionalTarget;
  10941. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10942. point.set(
  10943. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10944. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10945. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10946. );
  10947. return point;
  10948. }
  10949. copy( source ) {
  10950. super.copy( source );
  10951. this.v0.copy( source.v0 );
  10952. this.v1.copy( source.v1 );
  10953. this.v2.copy( source.v2 );
  10954. return this;
  10955. }
  10956. toJSON() {
  10957. const data = super.toJSON();
  10958. data.v0 = this.v0.toArray();
  10959. data.v1 = this.v1.toArray();
  10960. data.v2 = this.v2.toArray();
  10961. return data;
  10962. }
  10963. fromJSON( json ) {
  10964. super.fromJSON( json );
  10965. this.v0.fromArray( json.v0 );
  10966. this.v1.fromArray( json.v1 );
  10967. this.v2.fromArray( json.v2 );
  10968. return this;
  10969. }
  10970. }
  10971. class SplineCurve extends Curve {
  10972. constructor( points = [] ) {
  10973. super();
  10974. this.isSplineCurve = true;
  10975. this.type = 'SplineCurve';
  10976. this.points = points;
  10977. }
  10978. getPoint( t, optionalTarget = new Vector2() ) {
  10979. const point = optionalTarget;
  10980. const points = this.points;
  10981. const p = ( points.length - 1 ) * t;
  10982. const intPoint = Math.floor( p );
  10983. const weight = p - intPoint;
  10984. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  10985. const p1 = points[ intPoint ];
  10986. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  10987. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  10988. point.set(
  10989. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  10990. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  10991. );
  10992. return point;
  10993. }
  10994. copy( source ) {
  10995. super.copy( source );
  10996. this.points = [];
  10997. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10998. const point = source.points[ i ];
  10999. this.points.push( point.clone() );
  11000. }
  11001. return this;
  11002. }
  11003. toJSON() {
  11004. const data = super.toJSON();
  11005. data.points = [];
  11006. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11007. const point = this.points[ i ];
  11008. data.points.push( point.toArray() );
  11009. }
  11010. return data;
  11011. }
  11012. fromJSON( json ) {
  11013. super.fromJSON( json );
  11014. this.points = [];
  11015. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11016. const point = json.points[ i ];
  11017. this.points.push( new Vector2().fromArray( point ) );
  11018. }
  11019. return this;
  11020. }
  11021. }
  11022. var Curves = /*#__PURE__*/Object.freeze({
  11023. __proto__: null,
  11024. ArcCurve: ArcCurve,
  11025. CatmullRomCurve3: CatmullRomCurve3,
  11026. CubicBezierCurve: CubicBezierCurve,
  11027. CubicBezierCurve3: CubicBezierCurve3,
  11028. EllipseCurve: EllipseCurve,
  11029. LineCurve: LineCurve,
  11030. LineCurve3: LineCurve3,
  11031. QuadraticBezierCurve: QuadraticBezierCurve,
  11032. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11033. SplineCurve: SplineCurve
  11034. });
  11035. /**************************************************************
  11036. * Curved Path - a curve path is simply a array of connected
  11037. * curves, but retains the api of a curve
  11038. **************************************************************/
  11039. class CurvePath extends Curve {
  11040. constructor() {
  11041. super();
  11042. this.type = 'CurvePath';
  11043. this.curves = [];
  11044. this.autoClose = false; // Automatically closes the path
  11045. }
  11046. add( curve ) {
  11047. this.curves.push( curve );
  11048. }
  11049. closePath() {
  11050. // Add a line curve if start and end of lines are not connected
  11051. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11052. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11053. if ( ! startPoint.equals( endPoint ) ) {
  11054. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11055. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11056. }
  11057. return this;
  11058. }
  11059. // To get accurate point with reference to
  11060. // entire path distance at time t,
  11061. // following has to be done:
  11062. // 1. Length of each sub path have to be known
  11063. // 2. Locate and identify type of curve
  11064. // 3. Get t for the curve
  11065. // 4. Return curve.getPointAt(t')
  11066. getPoint( t, optionalTarget ) {
  11067. const d = t * this.getLength();
  11068. const curveLengths = this.getCurveLengths();
  11069. let i = 0;
  11070. // To think about boundaries points.
  11071. while ( i < curveLengths.length ) {
  11072. if ( curveLengths[ i ] >= d ) {
  11073. const diff = curveLengths[ i ] - d;
  11074. const curve = this.curves[ i ];
  11075. const segmentLength = curve.getLength();
  11076. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11077. return curve.getPointAt( u, optionalTarget );
  11078. }
  11079. i ++;
  11080. }
  11081. return null;
  11082. // loop where sum != 0, sum > d , sum+1 <d
  11083. }
  11084. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11085. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11086. // getPoint() depends on getLength
  11087. getLength() {
  11088. const lens = this.getCurveLengths();
  11089. return lens[ lens.length - 1 ];
  11090. }
  11091. // cacheLengths must be recalculated.
  11092. updateArcLengths() {
  11093. this.needsUpdate = true;
  11094. this.cacheLengths = null;
  11095. this.getCurveLengths();
  11096. }
  11097. // Compute lengths and cache them
  11098. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11099. getCurveLengths() {
  11100. // We use cache values if curves and cache array are same length
  11101. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11102. return this.cacheLengths;
  11103. }
  11104. // Get length of sub-curve
  11105. // Push sums into cached array
  11106. const lengths = [];
  11107. let sums = 0;
  11108. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11109. sums += this.curves[ i ].getLength();
  11110. lengths.push( sums );
  11111. }
  11112. this.cacheLengths = lengths;
  11113. return lengths;
  11114. }
  11115. getSpacedPoints( divisions = 40 ) {
  11116. const points = [];
  11117. for ( let i = 0; i <= divisions; i ++ ) {
  11118. points.push( this.getPoint( i / divisions ) );
  11119. }
  11120. if ( this.autoClose ) {
  11121. points.push( points[ 0 ] );
  11122. }
  11123. return points;
  11124. }
  11125. getPoints( divisions = 12 ) {
  11126. const points = [];
  11127. let last;
  11128. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11129. const curve = curves[ i ];
  11130. const resolution = curve.isEllipseCurve ? divisions * 2
  11131. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11132. : curve.isSplineCurve ? divisions * curve.points.length
  11133. : divisions;
  11134. const pts = curve.getPoints( resolution );
  11135. for ( let j = 0; j < pts.length; j ++ ) {
  11136. const point = pts[ j ];
  11137. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11138. points.push( point );
  11139. last = point;
  11140. }
  11141. }
  11142. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11143. points.push( points[ 0 ] );
  11144. }
  11145. return points;
  11146. }
  11147. copy( source ) {
  11148. super.copy( source );
  11149. this.curves = [];
  11150. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11151. const curve = source.curves[ i ];
  11152. this.curves.push( curve.clone() );
  11153. }
  11154. this.autoClose = source.autoClose;
  11155. return this;
  11156. }
  11157. toJSON() {
  11158. const data = super.toJSON();
  11159. data.autoClose = this.autoClose;
  11160. data.curves = [];
  11161. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11162. const curve = this.curves[ i ];
  11163. data.curves.push( curve.toJSON() );
  11164. }
  11165. return data;
  11166. }
  11167. fromJSON( json ) {
  11168. super.fromJSON( json );
  11169. this.autoClose = json.autoClose;
  11170. this.curves = [];
  11171. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11172. const curve = json.curves[ i ];
  11173. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11174. }
  11175. return this;
  11176. }
  11177. }
  11178. class Path extends CurvePath {
  11179. constructor( points ) {
  11180. super();
  11181. this.type = 'Path';
  11182. this.currentPoint = new Vector2();
  11183. if ( points ) {
  11184. this.setFromPoints( points );
  11185. }
  11186. }
  11187. setFromPoints( points ) {
  11188. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11189. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11190. this.lineTo( points[ i ].x, points[ i ].y );
  11191. }
  11192. return this;
  11193. }
  11194. moveTo( x, y ) {
  11195. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11196. return this;
  11197. }
  11198. lineTo( x, y ) {
  11199. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11200. this.curves.push( curve );
  11201. this.currentPoint.set( x, y );
  11202. return this;
  11203. }
  11204. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11205. const curve = new QuadraticBezierCurve(
  11206. this.currentPoint.clone(),
  11207. new Vector2( aCPx, aCPy ),
  11208. new Vector2( aX, aY )
  11209. );
  11210. this.curves.push( curve );
  11211. this.currentPoint.set( aX, aY );
  11212. return this;
  11213. }
  11214. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11215. const curve = new CubicBezierCurve(
  11216. this.currentPoint.clone(),
  11217. new Vector2( aCP1x, aCP1y ),
  11218. new Vector2( aCP2x, aCP2y ),
  11219. new Vector2( aX, aY )
  11220. );
  11221. this.curves.push( curve );
  11222. this.currentPoint.set( aX, aY );
  11223. return this;
  11224. }
  11225. splineThru( pts /*Array of Vector*/ ) {
  11226. const npts = [ this.currentPoint.clone() ].concat( pts );
  11227. const curve = new SplineCurve( npts );
  11228. this.curves.push( curve );
  11229. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11230. return this;
  11231. }
  11232. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11233. const x0 = this.currentPoint.x;
  11234. const y0 = this.currentPoint.y;
  11235. this.absarc( aX + x0, aY + y0, aRadius,
  11236. aStartAngle, aEndAngle, aClockwise );
  11237. return this;
  11238. }
  11239. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11240. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11241. return this;
  11242. }
  11243. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11244. const x0 = this.currentPoint.x;
  11245. const y0 = this.currentPoint.y;
  11246. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11247. return this;
  11248. }
  11249. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11250. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11251. if ( this.curves.length > 0 ) {
  11252. // if a previous curve is present, attempt to join
  11253. const firstPoint = curve.getPoint( 0 );
  11254. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11255. this.lineTo( firstPoint.x, firstPoint.y );
  11256. }
  11257. }
  11258. this.curves.push( curve );
  11259. const lastPoint = curve.getPoint( 1 );
  11260. this.currentPoint.copy( lastPoint );
  11261. return this;
  11262. }
  11263. copy( source ) {
  11264. super.copy( source );
  11265. this.currentPoint.copy( source.currentPoint );
  11266. return this;
  11267. }
  11268. toJSON() {
  11269. const data = super.toJSON();
  11270. data.currentPoint = this.currentPoint.toArray();
  11271. return data;
  11272. }
  11273. fromJSON( json ) {
  11274. super.fromJSON( json );
  11275. this.currentPoint.fromArray( json.currentPoint );
  11276. return this;
  11277. }
  11278. }
  11279. class LatheGeometry extends BufferGeometry {
  11280. constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  11281. super();
  11282. this.type = 'LatheGeometry';
  11283. this.parameters = {
  11284. points: points,
  11285. segments: segments,
  11286. phiStart: phiStart,
  11287. phiLength: phiLength
  11288. };
  11289. segments = Math.floor( segments );
  11290. // clamp phiLength so it's in range of [ 0, 2PI ]
  11291. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11292. // buffers
  11293. const indices = [];
  11294. const vertices = [];
  11295. const uvs = [];
  11296. const initNormals = [];
  11297. const normals = [];
  11298. // helper variables
  11299. const inverseSegments = 1.0 / segments;
  11300. const vertex = new Vector3();
  11301. const uv = new Vector2();
  11302. const normal = new Vector3();
  11303. const curNormal = new Vector3();
  11304. const prevNormal = new Vector3();
  11305. let dx = 0;
  11306. let dy = 0;
  11307. // pre-compute normals for initial "meridian"
  11308. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11309. switch ( j ) {
  11310. case 0: // special handling for 1st vertex on path
  11311. dx = points[ j + 1 ].x - points[ j ].x;
  11312. dy = points[ j + 1 ].y - points[ j ].y;
  11313. normal.x = dy * 1.0;
  11314. normal.y = - dx;
  11315. normal.z = dy * 0.0;
  11316. prevNormal.copy( normal );
  11317. normal.normalize();
  11318. initNormals.push( normal.x, normal.y, normal.z );
  11319. break;
  11320. case ( points.length - 1 ): // special handling for last Vertex on path
  11321. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11322. break;
  11323. default: // default handling for all vertices in between
  11324. dx = points[ j + 1 ].x - points[ j ].x;
  11325. dy = points[ j + 1 ].y - points[ j ].y;
  11326. normal.x = dy * 1.0;
  11327. normal.y = - dx;
  11328. normal.z = dy * 0.0;
  11329. curNormal.copy( normal );
  11330. normal.x += prevNormal.x;
  11331. normal.y += prevNormal.y;
  11332. normal.z += prevNormal.z;
  11333. normal.normalize();
  11334. initNormals.push( normal.x, normal.y, normal.z );
  11335. prevNormal.copy( curNormal );
  11336. }
  11337. }
  11338. // generate vertices, uvs and normals
  11339. for ( let i = 0; i <= segments; i ++ ) {
  11340. const phi = phiStart + i * inverseSegments * phiLength;
  11341. const sin = Math.sin( phi );
  11342. const cos = Math.cos( phi );
  11343. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11344. // vertex
  11345. vertex.x = points[ j ].x * sin;
  11346. vertex.y = points[ j ].y;
  11347. vertex.z = points[ j ].x * cos;
  11348. vertices.push( vertex.x, vertex.y, vertex.z );
  11349. // uv
  11350. uv.x = i / segments;
  11351. uv.y = j / ( points.length - 1 );
  11352. uvs.push( uv.x, uv.y );
  11353. // normal
  11354. const x = initNormals[ 3 * j + 0 ] * sin;
  11355. const y = initNormals[ 3 * j + 1 ];
  11356. const z = initNormals[ 3 * j + 0 ] * cos;
  11357. normals.push( x, y, z );
  11358. }
  11359. }
  11360. // indices
  11361. for ( let i = 0; i < segments; i ++ ) {
  11362. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11363. const base = j + i * points.length;
  11364. const a = base;
  11365. const b = base + points.length;
  11366. const c = base + points.length + 1;
  11367. const d = base + 1;
  11368. // faces
  11369. indices.push( a, b, d );
  11370. indices.push( c, d, b );
  11371. }
  11372. }
  11373. // build geometry
  11374. this.setIndex( indices );
  11375. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11376. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11377. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11378. }
  11379. copy( source ) {
  11380. super.copy( source );
  11381. this.parameters = Object.assign( {}, source.parameters );
  11382. return this;
  11383. }
  11384. static fromJSON( data ) {
  11385. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11386. }
  11387. }
  11388. class CapsuleGeometry extends LatheGeometry {
  11389. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11390. const path = new Path();
  11391. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11392. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11393. super( path.getPoints( capSegments ), radialSegments );
  11394. this.type = 'CapsuleGeometry';
  11395. this.parameters = {
  11396. radius: radius,
  11397. length: length,
  11398. capSegments: capSegments,
  11399. radialSegments: radialSegments,
  11400. };
  11401. }
  11402. static fromJSON( data ) {
  11403. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11404. }
  11405. }
  11406. class CircleGeometry extends BufferGeometry {
  11407. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11408. super();
  11409. this.type = 'CircleGeometry';
  11410. this.parameters = {
  11411. radius: radius,
  11412. segments: segments,
  11413. thetaStart: thetaStart,
  11414. thetaLength: thetaLength
  11415. };
  11416. segments = Math.max( 3, segments );
  11417. // buffers
  11418. const indices = [];
  11419. const vertices = [];
  11420. const normals = [];
  11421. const uvs = [];
  11422. // helper variables
  11423. const vertex = new Vector3();
  11424. const uv = new Vector2();
  11425. // center point
  11426. vertices.push( 0, 0, 0 );
  11427. normals.push( 0, 0, 1 );
  11428. uvs.push( 0.5, 0.5 );
  11429. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11430. const segment = thetaStart + s / segments * thetaLength;
  11431. // vertex
  11432. vertex.x = radius * Math.cos( segment );
  11433. vertex.y = radius * Math.sin( segment );
  11434. vertices.push( vertex.x, vertex.y, vertex.z );
  11435. // normal
  11436. normals.push( 0, 0, 1 );
  11437. // uvs
  11438. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11439. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11440. uvs.push( uv.x, uv.y );
  11441. }
  11442. // indices
  11443. for ( let i = 1; i <= segments; i ++ ) {
  11444. indices.push( i, i + 1, 0 );
  11445. }
  11446. // build geometry
  11447. this.setIndex( indices );
  11448. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11449. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11450. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11451. }
  11452. copy( source ) {
  11453. super.copy( source );
  11454. this.parameters = Object.assign( {}, source.parameters );
  11455. return this;
  11456. }
  11457. static fromJSON( data ) {
  11458. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11459. }
  11460. }
  11461. class CylinderGeometry extends BufferGeometry {
  11462. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11463. super();
  11464. this.type = 'CylinderGeometry';
  11465. this.parameters = {
  11466. radiusTop: radiusTop,
  11467. radiusBottom: radiusBottom,
  11468. height: height,
  11469. radialSegments: radialSegments,
  11470. heightSegments: heightSegments,
  11471. openEnded: openEnded,
  11472. thetaStart: thetaStart,
  11473. thetaLength: thetaLength
  11474. };
  11475. const scope = this;
  11476. radialSegments = Math.floor( radialSegments );
  11477. heightSegments = Math.floor( heightSegments );
  11478. // buffers
  11479. const indices = [];
  11480. const vertices = [];
  11481. const normals = [];
  11482. const uvs = [];
  11483. // helper variables
  11484. let index = 0;
  11485. const indexArray = [];
  11486. const halfHeight = height / 2;
  11487. let groupStart = 0;
  11488. // generate geometry
  11489. generateTorso();
  11490. if ( openEnded === false ) {
  11491. if ( radiusTop > 0 ) generateCap( true );
  11492. if ( radiusBottom > 0 ) generateCap( false );
  11493. }
  11494. // build geometry
  11495. this.setIndex( indices );
  11496. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11497. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11498. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11499. function generateTorso() {
  11500. const normal = new Vector3();
  11501. const vertex = new Vector3();
  11502. let groupCount = 0;
  11503. // this will be used to calculate the normal
  11504. const slope = ( radiusBottom - radiusTop ) / height;
  11505. // generate vertices, normals and uvs
  11506. for ( let y = 0; y <= heightSegments; y ++ ) {
  11507. const indexRow = [];
  11508. const v = y / heightSegments;
  11509. // calculate the radius of the current row
  11510. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11511. for ( let x = 0; x <= radialSegments; x ++ ) {
  11512. const u = x / radialSegments;
  11513. const theta = u * thetaLength + thetaStart;
  11514. const sinTheta = Math.sin( theta );
  11515. const cosTheta = Math.cos( theta );
  11516. // vertex
  11517. vertex.x = radius * sinTheta;
  11518. vertex.y = - v * height + halfHeight;
  11519. vertex.z = radius * cosTheta;
  11520. vertices.push( vertex.x, vertex.y, vertex.z );
  11521. // normal
  11522. normal.set( sinTheta, slope, cosTheta ).normalize();
  11523. normals.push( normal.x, normal.y, normal.z );
  11524. // uv
  11525. uvs.push( u, 1 - v );
  11526. // save index of vertex in respective row
  11527. indexRow.push( index ++ );
  11528. }
  11529. // now save vertices of the row in our index array
  11530. indexArray.push( indexRow );
  11531. }
  11532. // generate indices
  11533. for ( let x = 0; x < radialSegments; x ++ ) {
  11534. for ( let y = 0; y < heightSegments; y ++ ) {
  11535. // we use the index array to access the correct indices
  11536. const a = indexArray[ y ][ x ];
  11537. const b = indexArray[ y + 1 ][ x ];
  11538. const c = indexArray[ y + 1 ][ x + 1 ];
  11539. const d = indexArray[ y ][ x + 1 ];
  11540. // faces
  11541. indices.push( a, b, d );
  11542. indices.push( b, c, d );
  11543. // update group counter
  11544. groupCount += 6;
  11545. }
  11546. }
  11547. // add a group to the geometry. this will ensure multi material support
  11548. scope.addGroup( groupStart, groupCount, 0 );
  11549. // calculate new start value for groups
  11550. groupStart += groupCount;
  11551. }
  11552. function generateCap( top ) {
  11553. // save the index of the first center vertex
  11554. const centerIndexStart = index;
  11555. const uv = new Vector2();
  11556. const vertex = new Vector3();
  11557. let groupCount = 0;
  11558. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11559. const sign = ( top === true ) ? 1 : - 1;
  11560. // first we generate the center vertex data of the cap.
  11561. // because the geometry needs one set of uvs per face,
  11562. // we must generate a center vertex per face/segment
  11563. for ( let x = 1; x <= radialSegments; x ++ ) {
  11564. // vertex
  11565. vertices.push( 0, halfHeight * sign, 0 );
  11566. // normal
  11567. normals.push( 0, sign, 0 );
  11568. // uv
  11569. uvs.push( 0.5, 0.5 );
  11570. // increase index
  11571. index ++;
  11572. }
  11573. // save the index of the last center vertex
  11574. const centerIndexEnd = index;
  11575. // now we generate the surrounding vertices, normals and uvs
  11576. for ( let x = 0; x <= radialSegments; x ++ ) {
  11577. const u = x / radialSegments;
  11578. const theta = u * thetaLength + thetaStart;
  11579. const cosTheta = Math.cos( theta );
  11580. const sinTheta = Math.sin( theta );
  11581. // vertex
  11582. vertex.x = radius * sinTheta;
  11583. vertex.y = halfHeight * sign;
  11584. vertex.z = radius * cosTheta;
  11585. vertices.push( vertex.x, vertex.y, vertex.z );
  11586. // normal
  11587. normals.push( 0, sign, 0 );
  11588. // uv
  11589. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11590. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11591. uvs.push( uv.x, uv.y );
  11592. // increase index
  11593. index ++;
  11594. }
  11595. // generate indices
  11596. for ( let x = 0; x < radialSegments; x ++ ) {
  11597. const c = centerIndexStart + x;
  11598. const i = centerIndexEnd + x;
  11599. if ( top === true ) {
  11600. // face top
  11601. indices.push( i, i + 1, c );
  11602. } else {
  11603. // face bottom
  11604. indices.push( i + 1, i, c );
  11605. }
  11606. groupCount += 3;
  11607. }
  11608. // add a group to the geometry. this will ensure multi material support
  11609. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11610. // calculate new start value for groups
  11611. groupStart += groupCount;
  11612. }
  11613. }
  11614. copy( source ) {
  11615. super.copy( source );
  11616. this.parameters = Object.assign( {}, source.parameters );
  11617. return this;
  11618. }
  11619. static fromJSON( data ) {
  11620. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11621. }
  11622. }
  11623. class ConeGeometry extends CylinderGeometry {
  11624. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11625. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11626. this.type = 'ConeGeometry';
  11627. this.parameters = {
  11628. radius: radius,
  11629. height: height,
  11630. radialSegments: radialSegments,
  11631. heightSegments: heightSegments,
  11632. openEnded: openEnded,
  11633. thetaStart: thetaStart,
  11634. thetaLength: thetaLength
  11635. };
  11636. }
  11637. static fromJSON( data ) {
  11638. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11639. }
  11640. }
  11641. class PolyhedronGeometry extends BufferGeometry {
  11642. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11643. super();
  11644. this.type = 'PolyhedronGeometry';
  11645. this.parameters = {
  11646. vertices: vertices,
  11647. indices: indices,
  11648. radius: radius,
  11649. detail: detail
  11650. };
  11651. // default buffer data
  11652. const vertexBuffer = [];
  11653. const uvBuffer = [];
  11654. // the subdivision creates the vertex buffer data
  11655. subdivide( detail );
  11656. // all vertices should lie on a conceptual sphere with a given radius
  11657. applyRadius( radius );
  11658. // finally, create the uv data
  11659. generateUVs();
  11660. // build non-indexed geometry
  11661. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11662. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11663. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11664. if ( detail === 0 ) {
  11665. this.computeVertexNormals(); // flat normals
  11666. } else {
  11667. this.normalizeNormals(); // smooth normals
  11668. }
  11669. // helper functions
  11670. function subdivide( detail ) {
  11671. const a = new Vector3();
  11672. const b = new Vector3();
  11673. const c = new Vector3();
  11674. // iterate over all faces and apply a subdivision with the given detail value
  11675. for ( let i = 0; i < indices.length; i += 3 ) {
  11676. // get the vertices of the face
  11677. getVertexByIndex( indices[ i + 0 ], a );
  11678. getVertexByIndex( indices[ i + 1 ], b );
  11679. getVertexByIndex( indices[ i + 2 ], c );
  11680. // perform subdivision
  11681. subdivideFace( a, b, c, detail );
  11682. }
  11683. }
  11684. function subdivideFace( a, b, c, detail ) {
  11685. const cols = detail + 1;
  11686. // we use this multidimensional array as a data structure for creating the subdivision
  11687. const v = [];
  11688. // construct all of the vertices for this subdivision
  11689. for ( let i = 0; i <= cols; i ++ ) {
  11690. v[ i ] = [];
  11691. const aj = a.clone().lerp( c, i / cols );
  11692. const bj = b.clone().lerp( c, i / cols );
  11693. const rows = cols - i;
  11694. for ( let j = 0; j <= rows; j ++ ) {
  11695. if ( j === 0 && i === cols ) {
  11696. v[ i ][ j ] = aj;
  11697. } else {
  11698. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11699. }
  11700. }
  11701. }
  11702. // construct all of the faces
  11703. for ( let i = 0; i < cols; i ++ ) {
  11704. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11705. const k = Math.floor( j / 2 );
  11706. if ( j % 2 === 0 ) {
  11707. pushVertex( v[ i ][ k + 1 ] );
  11708. pushVertex( v[ i + 1 ][ k ] );
  11709. pushVertex( v[ i ][ k ] );
  11710. } else {
  11711. pushVertex( v[ i ][ k + 1 ] );
  11712. pushVertex( v[ i + 1 ][ k + 1 ] );
  11713. pushVertex( v[ i + 1 ][ k ] );
  11714. }
  11715. }
  11716. }
  11717. }
  11718. function applyRadius( radius ) {
  11719. const vertex = new Vector3();
  11720. // iterate over the entire buffer and apply the radius to each vertex
  11721. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11722. vertex.x = vertexBuffer[ i + 0 ];
  11723. vertex.y = vertexBuffer[ i + 1 ];
  11724. vertex.z = vertexBuffer[ i + 2 ];
  11725. vertex.normalize().multiplyScalar( radius );
  11726. vertexBuffer[ i + 0 ] = vertex.x;
  11727. vertexBuffer[ i + 1 ] = vertex.y;
  11728. vertexBuffer[ i + 2 ] = vertex.z;
  11729. }
  11730. }
  11731. function generateUVs() {
  11732. const vertex = new Vector3();
  11733. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11734. vertex.x = vertexBuffer[ i + 0 ];
  11735. vertex.y = vertexBuffer[ i + 1 ];
  11736. vertex.z = vertexBuffer[ i + 2 ];
  11737. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11738. const v = inclination( vertex ) / Math.PI + 0.5;
  11739. uvBuffer.push( u, 1 - v );
  11740. }
  11741. correctUVs();
  11742. correctSeam();
  11743. }
  11744. function correctSeam() {
  11745. // handle case when face straddles the seam, see #3269
  11746. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11747. // uv data of a single face
  11748. const x0 = uvBuffer[ i + 0 ];
  11749. const x1 = uvBuffer[ i + 2 ];
  11750. const x2 = uvBuffer[ i + 4 ];
  11751. const max = Math.max( x0, x1, x2 );
  11752. const min = Math.min( x0, x1, x2 );
  11753. // 0.9 is somewhat arbitrary
  11754. if ( max > 0.9 && min < 0.1 ) {
  11755. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11756. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11757. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11758. }
  11759. }
  11760. }
  11761. function pushVertex( vertex ) {
  11762. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11763. }
  11764. function getVertexByIndex( index, vertex ) {
  11765. const stride = index * 3;
  11766. vertex.x = vertices[ stride + 0 ];
  11767. vertex.y = vertices[ stride + 1 ];
  11768. vertex.z = vertices[ stride + 2 ];
  11769. }
  11770. function correctUVs() {
  11771. const a = new Vector3();
  11772. const b = new Vector3();
  11773. const c = new Vector3();
  11774. const centroid = new Vector3();
  11775. const uvA = new Vector2();
  11776. const uvB = new Vector2();
  11777. const uvC = new Vector2();
  11778. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11779. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11780. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11781. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11782. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11783. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11784. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11785. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11786. const azi = azimuth( centroid );
  11787. correctUV( uvA, j + 0, a, azi );
  11788. correctUV( uvB, j + 2, b, azi );
  11789. correctUV( uvC, j + 4, c, azi );
  11790. }
  11791. }
  11792. function correctUV( uv, stride, vector, azimuth ) {
  11793. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11794. uvBuffer[ stride ] = uv.x - 1;
  11795. }
  11796. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11797. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11798. }
  11799. }
  11800. // Angle around the Y axis, counter-clockwise when looking from above.
  11801. function azimuth( vector ) {
  11802. return Math.atan2( vector.z, - vector.x );
  11803. }
  11804. // Angle above the XZ plane.
  11805. function inclination( vector ) {
  11806. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11807. }
  11808. }
  11809. copy( source ) {
  11810. super.copy( source );
  11811. this.parameters = Object.assign( {}, source.parameters );
  11812. return this;
  11813. }
  11814. static fromJSON( data ) {
  11815. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11816. }
  11817. }
  11818. class DodecahedronGeometry extends PolyhedronGeometry {
  11819. constructor( radius = 1, detail = 0 ) {
  11820. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11821. const r = 1 / t;
  11822. const vertices = [
  11823. // (±1, ±1, ±1)
  11824. - 1, - 1, - 1, - 1, - 1, 1,
  11825. - 1, 1, - 1, - 1, 1, 1,
  11826. 1, - 1, - 1, 1, - 1, 1,
  11827. 1, 1, - 1, 1, 1, 1,
  11828. // (0, ±1/φ, ±φ)
  11829. 0, - r, - t, 0, - r, t,
  11830. 0, r, - t, 0, r, t,
  11831. // (±1/φ, ±φ, 0)
  11832. - r, - t, 0, - r, t, 0,
  11833. r, - t, 0, r, t, 0,
  11834. // (±φ, 0, ±1/φ)
  11835. - t, 0, - r, t, 0, - r,
  11836. - t, 0, r, t, 0, r
  11837. ];
  11838. const indices = [
  11839. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11840. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11841. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11842. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11843. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11844. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11845. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11846. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11847. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11848. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11849. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11850. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11851. ];
  11852. super( vertices, indices, radius, detail );
  11853. this.type = 'DodecahedronGeometry';
  11854. this.parameters = {
  11855. radius: radius,
  11856. detail: detail
  11857. };
  11858. }
  11859. static fromJSON( data ) {
  11860. return new DodecahedronGeometry( data.radius, data.detail );
  11861. }
  11862. }
  11863. const _v0 = /*@__PURE__*/ new Vector3();
  11864. const _v1$1 = /*@__PURE__*/ new Vector3();
  11865. const _normal$1 = /*@__PURE__*/ new Vector3();
  11866. const _triangle = /*@__PURE__*/ new Triangle();
  11867. class EdgesGeometry extends BufferGeometry {
  11868. constructor( geometry = null, thresholdAngle = 1 ) {
  11869. super();
  11870. this.type = 'EdgesGeometry';
  11871. this.parameters = {
  11872. geometry: geometry,
  11873. thresholdAngle: thresholdAngle
  11874. };
  11875. if ( geometry !== null ) {
  11876. const precisionPoints = 4;
  11877. const precision = Math.pow( 10, precisionPoints );
  11878. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11879. const indexAttr = geometry.getIndex();
  11880. const positionAttr = geometry.getAttribute( 'position' );
  11881. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11882. const indexArr = [ 0, 0, 0 ];
  11883. const vertKeys = [ 'a', 'b', 'c' ];
  11884. const hashes = new Array( 3 );
  11885. const edgeData = {};
  11886. const vertices = [];
  11887. for ( let i = 0; i < indexCount; i += 3 ) {
  11888. if ( indexAttr ) {
  11889. indexArr[ 0 ] = indexAttr.getX( i );
  11890. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11891. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11892. } else {
  11893. indexArr[ 0 ] = i;
  11894. indexArr[ 1 ] = i + 1;
  11895. indexArr[ 2 ] = i + 2;
  11896. }
  11897. const { a, b, c } = _triangle;
  11898. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11899. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11900. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11901. _triangle.getNormal( _normal$1 );
  11902. // create hashes for the edge from the vertices
  11903. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11904. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11905. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11906. // skip degenerate triangles
  11907. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11908. continue;
  11909. }
  11910. // iterate over every edge
  11911. for ( let j = 0; j < 3; j ++ ) {
  11912. // get the first and next vertex making up the edge
  11913. const jNext = ( j + 1 ) % 3;
  11914. const vecHash0 = hashes[ j ];
  11915. const vecHash1 = hashes[ jNext ];
  11916. const v0 = _triangle[ vertKeys[ j ] ];
  11917. const v1 = _triangle[ vertKeys[ jNext ] ];
  11918. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11919. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11920. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11921. // if we found a sibling edge add it into the vertex array if
  11922. // it meets the angle threshold and delete the edge from the map.
  11923. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11924. vertices.push( v0.x, v0.y, v0.z );
  11925. vertices.push( v1.x, v1.y, v1.z );
  11926. }
  11927. edgeData[ reverseHash ] = null;
  11928. } else if ( ! ( hash in edgeData ) ) {
  11929. // if we've already got an edge here then skip adding a new one
  11930. edgeData[ hash ] = {
  11931. index0: indexArr[ j ],
  11932. index1: indexArr[ jNext ],
  11933. normal: _normal$1.clone(),
  11934. };
  11935. }
  11936. }
  11937. }
  11938. // iterate over all remaining, unmatched edges and add them to the vertex array
  11939. for ( const key in edgeData ) {
  11940. if ( edgeData[ key ] ) {
  11941. const { index0, index1 } = edgeData[ key ];
  11942. _v0.fromBufferAttribute( positionAttr, index0 );
  11943. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11944. vertices.push( _v0.x, _v0.y, _v0.z );
  11945. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11946. }
  11947. }
  11948. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11949. }
  11950. }
  11951. copy( source ) {
  11952. super.copy( source );
  11953. this.parameters = Object.assign( {}, source.parameters );
  11954. return this;
  11955. }
  11956. }
  11957. class Shape extends Path {
  11958. constructor( points ) {
  11959. super( points );
  11960. this.uuid = generateUUID();
  11961. this.type = 'Shape';
  11962. this.holes = [];
  11963. }
  11964. getPointsHoles( divisions ) {
  11965. const holesPts = [];
  11966. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11967. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  11968. }
  11969. return holesPts;
  11970. }
  11971. // get points of shape and holes (keypoints based on segments parameter)
  11972. extractPoints( divisions ) {
  11973. return {
  11974. shape: this.getPoints( divisions ),
  11975. holes: this.getPointsHoles( divisions )
  11976. };
  11977. }
  11978. copy( source ) {
  11979. super.copy( source );
  11980. this.holes = [];
  11981. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  11982. const hole = source.holes[ i ];
  11983. this.holes.push( hole.clone() );
  11984. }
  11985. return this;
  11986. }
  11987. toJSON() {
  11988. const data = super.toJSON();
  11989. data.uuid = this.uuid;
  11990. data.holes = [];
  11991. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  11992. const hole = this.holes[ i ];
  11993. data.holes.push( hole.toJSON() );
  11994. }
  11995. return data;
  11996. }
  11997. fromJSON( json ) {
  11998. super.fromJSON( json );
  11999. this.uuid = json.uuid;
  12000. this.holes = [];
  12001. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12002. const hole = json.holes[ i ];
  12003. this.holes.push( new Path().fromJSON( hole ) );
  12004. }
  12005. return this;
  12006. }
  12007. }
  12008. /**
  12009. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12010. */
  12011. const Earcut = {
  12012. triangulate: function ( data, holeIndices, dim = 2 ) {
  12013. const hasHoles = holeIndices && holeIndices.length;
  12014. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12015. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12016. const triangles = [];
  12017. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12018. let minX, minY, maxX, maxY, x, y, invSize;
  12019. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12020. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12021. if ( data.length > 80 * dim ) {
  12022. minX = maxX = data[ 0 ];
  12023. minY = maxY = data[ 1 ];
  12024. for ( let i = dim; i < outerLen; i += dim ) {
  12025. x = data[ i ];
  12026. y = data[ i + 1 ];
  12027. if ( x < minX ) minX = x;
  12028. if ( y < minY ) minY = y;
  12029. if ( x > maxX ) maxX = x;
  12030. if ( y > maxY ) maxY = y;
  12031. }
  12032. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12033. invSize = Math.max( maxX - minX, maxY - minY );
  12034. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12035. }
  12036. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12037. return triangles;
  12038. }
  12039. };
  12040. // create a circular doubly linked list from polygon points in the specified winding order
  12041. function linkedList( data, start, end, dim, clockwise ) {
  12042. let i, last;
  12043. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12044. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12045. } else {
  12046. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12047. }
  12048. if ( last && equals$1( last, last.next ) ) {
  12049. removeNode( last );
  12050. last = last.next;
  12051. }
  12052. return last;
  12053. }
  12054. // eliminate colinear or duplicate points
  12055. function filterPoints( start, end ) {
  12056. if ( ! start ) return start;
  12057. if ( ! end ) end = start;
  12058. let p = start,
  12059. again;
  12060. do {
  12061. again = false;
  12062. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12063. removeNode( p );
  12064. p = end = p.prev;
  12065. if ( p === p.next ) break;
  12066. again = true;
  12067. } else {
  12068. p = p.next;
  12069. }
  12070. } while ( again || p !== end );
  12071. return end;
  12072. }
  12073. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12074. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12075. if ( ! ear ) return;
  12076. // interlink polygon nodes in z-order
  12077. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12078. let stop = ear,
  12079. prev, next;
  12080. // iterate through ears, slicing them one by one
  12081. while ( ear.prev !== ear.next ) {
  12082. prev = ear.prev;
  12083. next = ear.next;
  12084. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12085. // cut off the triangle
  12086. triangles.push( prev.i / dim | 0 );
  12087. triangles.push( ear.i / dim | 0 );
  12088. triangles.push( next.i / dim | 0 );
  12089. removeNode( ear );
  12090. // skipping the next vertex leads to less sliver triangles
  12091. ear = next.next;
  12092. stop = next.next;
  12093. continue;
  12094. }
  12095. ear = next;
  12096. // if we looped through the whole remaining polygon and can't find any more ears
  12097. if ( ear === stop ) {
  12098. // try filtering points and slicing again
  12099. if ( ! pass ) {
  12100. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12101. // if this didn't work, try curing all small self-intersections locally
  12102. } else if ( pass === 1 ) {
  12103. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12104. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12105. // as a last resort, try splitting the remaining polygon into two
  12106. } else if ( pass === 2 ) {
  12107. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12108. }
  12109. break;
  12110. }
  12111. }
  12112. }
  12113. // check whether a polygon node forms a valid ear with adjacent nodes
  12114. function isEar( ear ) {
  12115. const a = ear.prev,
  12116. b = ear,
  12117. c = ear.next;
  12118. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12119. // now make sure we don't have other points inside the potential ear
  12120. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12121. // triangle bbox; min & max are calculated like this for speed
  12122. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12123. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12124. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12125. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12126. let p = c.next;
  12127. while ( p !== a ) {
  12128. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12129. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12130. area( p.prev, p, p.next ) >= 0 ) return false;
  12131. p = p.next;
  12132. }
  12133. return true;
  12134. }
  12135. function isEarHashed( ear, minX, minY, invSize ) {
  12136. const a = ear.prev,
  12137. b = ear,
  12138. c = ear.next;
  12139. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12140. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12141. // triangle bbox; min & max are calculated like this for speed
  12142. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12143. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12144. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12145. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12146. // z-order range for the current triangle bbox;
  12147. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12148. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12149. let p = ear.prevZ,
  12150. n = ear.nextZ;
  12151. // look for points inside the triangle in both directions
  12152. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12153. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12154. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12155. p = p.prevZ;
  12156. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12157. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12158. n = n.nextZ;
  12159. }
  12160. // look for remaining points in decreasing z-order
  12161. while ( p && p.z >= minZ ) {
  12162. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12163. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12164. p = p.prevZ;
  12165. }
  12166. // look for remaining points in increasing z-order
  12167. while ( n && n.z <= maxZ ) {
  12168. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12169. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12170. n = n.nextZ;
  12171. }
  12172. return true;
  12173. }
  12174. // go through all polygon nodes and cure small local self-intersections
  12175. function cureLocalIntersections( start, triangles, dim ) {
  12176. let p = start;
  12177. do {
  12178. const a = p.prev,
  12179. b = p.next.next;
  12180. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12181. triangles.push( a.i / dim | 0 );
  12182. triangles.push( p.i / dim | 0 );
  12183. triangles.push( b.i / dim | 0 );
  12184. // remove two nodes involved
  12185. removeNode( p );
  12186. removeNode( p.next );
  12187. p = start = b;
  12188. }
  12189. p = p.next;
  12190. } while ( p !== start );
  12191. return filterPoints( p );
  12192. }
  12193. // try splitting polygon into two and triangulate them independently
  12194. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12195. // look for a valid diagonal that divides the polygon into two
  12196. let a = start;
  12197. do {
  12198. let b = a.next.next;
  12199. while ( b !== a.prev ) {
  12200. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12201. // split the polygon in two by the diagonal
  12202. let c = splitPolygon( a, b );
  12203. // filter colinear points around the cuts
  12204. a = filterPoints( a, a.next );
  12205. c = filterPoints( c, c.next );
  12206. // run earcut on each half
  12207. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12208. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12209. return;
  12210. }
  12211. b = b.next;
  12212. }
  12213. a = a.next;
  12214. } while ( a !== start );
  12215. }
  12216. // link every hole into the outer loop, producing a single-ring polygon without holes
  12217. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12218. const queue = [];
  12219. let i, len, start, end, list;
  12220. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12221. start = holeIndices[ i ] * dim;
  12222. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12223. list = linkedList( data, start, end, dim, false );
  12224. if ( list === list.next ) list.steiner = true;
  12225. queue.push( getLeftmost( list ) );
  12226. }
  12227. queue.sort( compareX );
  12228. // process holes from left to right
  12229. for ( i = 0; i < queue.length; i ++ ) {
  12230. outerNode = eliminateHole( queue[ i ], outerNode );
  12231. }
  12232. return outerNode;
  12233. }
  12234. function compareX( a, b ) {
  12235. return a.x - b.x;
  12236. }
  12237. // find a bridge between vertices that connects hole with an outer ring and link it
  12238. function eliminateHole( hole, outerNode ) {
  12239. const bridge = findHoleBridge( hole, outerNode );
  12240. if ( ! bridge ) {
  12241. return outerNode;
  12242. }
  12243. const bridgeReverse = splitPolygon( bridge, hole );
  12244. // filter collinear points around the cuts
  12245. filterPoints( bridgeReverse, bridgeReverse.next );
  12246. return filterPoints( bridge, bridge.next );
  12247. }
  12248. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12249. function findHoleBridge( hole, outerNode ) {
  12250. let p = outerNode,
  12251. qx = - Infinity,
  12252. m;
  12253. const hx = hole.x, hy = hole.y;
  12254. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12255. // segment's endpoint with lesser x will be potential connection point
  12256. do {
  12257. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12258. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12259. if ( x <= hx && x > qx ) {
  12260. qx = x;
  12261. m = p.x < p.next.x ? p : p.next;
  12262. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12263. }
  12264. }
  12265. p = p.next;
  12266. } while ( p !== outerNode );
  12267. if ( ! m ) return null;
  12268. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12269. // if there are no points found, we have a valid connection;
  12270. // otherwise choose the point of the minimum angle with the ray as connection point
  12271. const stop = m,
  12272. mx = m.x,
  12273. my = m.y;
  12274. let tanMin = Infinity, tan;
  12275. p = m;
  12276. do {
  12277. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12278. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12279. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12280. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12281. m = p;
  12282. tanMin = tan;
  12283. }
  12284. }
  12285. p = p.next;
  12286. } while ( p !== stop );
  12287. return m;
  12288. }
  12289. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12290. function sectorContainsSector( m, p ) {
  12291. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12292. }
  12293. // interlink polygon nodes in z-order
  12294. function indexCurve( start, minX, minY, invSize ) {
  12295. let p = start;
  12296. do {
  12297. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12298. p.prevZ = p.prev;
  12299. p.nextZ = p.next;
  12300. p = p.next;
  12301. } while ( p !== start );
  12302. p.prevZ.nextZ = null;
  12303. p.prevZ = null;
  12304. sortLinked( p );
  12305. }
  12306. // Simon Tatham's linked list merge sort algorithm
  12307. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12308. function sortLinked( list ) {
  12309. let i, p, q, e, tail, numMerges, pSize, qSize,
  12310. inSize = 1;
  12311. do {
  12312. p = list;
  12313. list = null;
  12314. tail = null;
  12315. numMerges = 0;
  12316. while ( p ) {
  12317. numMerges ++;
  12318. q = p;
  12319. pSize = 0;
  12320. for ( i = 0; i < inSize; i ++ ) {
  12321. pSize ++;
  12322. q = q.nextZ;
  12323. if ( ! q ) break;
  12324. }
  12325. qSize = inSize;
  12326. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12327. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12328. e = p;
  12329. p = p.nextZ;
  12330. pSize --;
  12331. } else {
  12332. e = q;
  12333. q = q.nextZ;
  12334. qSize --;
  12335. }
  12336. if ( tail ) tail.nextZ = e;
  12337. else list = e;
  12338. e.prevZ = tail;
  12339. tail = e;
  12340. }
  12341. p = q;
  12342. }
  12343. tail.nextZ = null;
  12344. inSize *= 2;
  12345. } while ( numMerges > 1 );
  12346. return list;
  12347. }
  12348. // z-order of a point given coords and inverse of the longer side of data bbox
  12349. function zOrder( x, y, minX, minY, invSize ) {
  12350. // coords are transformed into non-negative 15-bit integer range
  12351. x = ( x - minX ) * invSize | 0;
  12352. y = ( y - minY ) * invSize | 0;
  12353. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12354. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12355. x = ( x | ( x << 2 ) ) & 0x33333333;
  12356. x = ( x | ( x << 1 ) ) & 0x55555555;
  12357. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12358. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12359. y = ( y | ( y << 2 ) ) & 0x33333333;
  12360. y = ( y | ( y << 1 ) ) & 0x55555555;
  12361. return x | ( y << 1 );
  12362. }
  12363. // find the leftmost node of a polygon ring
  12364. function getLeftmost( start ) {
  12365. let p = start,
  12366. leftmost = start;
  12367. do {
  12368. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12369. p = p.next;
  12370. } while ( p !== start );
  12371. return leftmost;
  12372. }
  12373. // check if a point lies within a convex triangle
  12374. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12375. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12376. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12377. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12378. }
  12379. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12380. function isValidDiagonal( a, b ) {
  12381. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12382. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12383. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12384. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12385. }
  12386. // signed area of a triangle
  12387. function area( p, q, r ) {
  12388. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12389. }
  12390. // check if two points are equal
  12391. function equals$1( p1, p2 ) {
  12392. return p1.x === p2.x && p1.y === p2.y;
  12393. }
  12394. // check if two segments intersect
  12395. function intersects( p1, q1, p2, q2 ) {
  12396. const o1 = sign$1( area( p1, q1, p2 ) );
  12397. const o2 = sign$1( area( p1, q1, q2 ) );
  12398. const o3 = sign$1( area( p2, q2, p1 ) );
  12399. const o4 = sign$1( area( p2, q2, q1 ) );
  12400. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12401. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12402. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12403. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12404. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12405. return false;
  12406. }
  12407. // for collinear points p, q, r, check if point q lies on segment pr
  12408. function onSegment( p, q, r ) {
  12409. return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
  12410. }
  12411. function sign$1( num ) {
  12412. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12413. }
  12414. // check if a polygon diagonal intersects any polygon segments
  12415. function intersectsPolygon( a, b ) {
  12416. let p = a;
  12417. do {
  12418. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12419. intersects( p, p.next, a, b ) ) return true;
  12420. p = p.next;
  12421. } while ( p !== a );
  12422. return false;
  12423. }
  12424. // check if a polygon diagonal is locally inside the polygon
  12425. function locallyInside( a, b ) {
  12426. return area( a.prev, a, a.next ) < 0 ?
  12427. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12428. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12429. }
  12430. // check if the middle point of a polygon diagonal is inside the polygon
  12431. function middleInside( a, b ) {
  12432. let p = a,
  12433. inside = false;
  12434. const px = ( a.x + b.x ) / 2,
  12435. py = ( a.y + b.y ) / 2;
  12436. do {
  12437. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12438. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12439. inside = ! inside;
  12440. p = p.next;
  12441. } while ( p !== a );
  12442. return inside;
  12443. }
  12444. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12445. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12446. function splitPolygon( a, b ) {
  12447. const a2 = new Node$1( a.i, a.x, a.y ),
  12448. b2 = new Node$1( b.i, b.x, b.y ),
  12449. an = a.next,
  12450. bp = b.prev;
  12451. a.next = b;
  12452. b.prev = a;
  12453. a2.next = an;
  12454. an.prev = a2;
  12455. b2.next = a2;
  12456. a2.prev = b2;
  12457. bp.next = b2;
  12458. b2.prev = bp;
  12459. return b2;
  12460. }
  12461. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12462. function insertNode( i, x, y, last ) {
  12463. const p = new Node$1( i, x, y );
  12464. if ( ! last ) {
  12465. p.prev = p;
  12466. p.next = p;
  12467. } else {
  12468. p.next = last.next;
  12469. p.prev = last;
  12470. last.next.prev = p;
  12471. last.next = p;
  12472. }
  12473. return p;
  12474. }
  12475. function removeNode( p ) {
  12476. p.next.prev = p.prev;
  12477. p.prev.next = p.next;
  12478. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12479. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12480. }
  12481. function Node$1( i, x, y ) {
  12482. // vertex index in coordinates array
  12483. this.i = i;
  12484. // vertex coordinates
  12485. this.x = x;
  12486. this.y = y;
  12487. // previous and next vertex nodes in a polygon ring
  12488. this.prev = null;
  12489. this.next = null;
  12490. // z-order curve value
  12491. this.z = 0;
  12492. // previous and next nodes in z-order
  12493. this.prevZ = null;
  12494. this.nextZ = null;
  12495. // indicates whether this is a steiner point
  12496. this.steiner = false;
  12497. }
  12498. function signedArea( data, start, end, dim ) {
  12499. let sum = 0;
  12500. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12501. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12502. j = i;
  12503. }
  12504. return sum;
  12505. }
  12506. class ShapeUtils {
  12507. // calculate area of the contour polygon
  12508. static area( contour ) {
  12509. const n = contour.length;
  12510. let a = 0.0;
  12511. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12512. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12513. }
  12514. return a * 0.5;
  12515. }
  12516. static isClockWise( pts ) {
  12517. return ShapeUtils.area( pts ) < 0;
  12518. }
  12519. static triangulateShape( contour, holes ) {
  12520. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12521. const holeIndices = []; // array of hole indices
  12522. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12523. removeDupEndPts( contour );
  12524. addContour( vertices, contour );
  12525. //
  12526. let holeIndex = contour.length;
  12527. holes.forEach( removeDupEndPts );
  12528. for ( let i = 0; i < holes.length; i ++ ) {
  12529. holeIndices.push( holeIndex );
  12530. holeIndex += holes[ i ].length;
  12531. addContour( vertices, holes[ i ] );
  12532. }
  12533. //
  12534. const triangles = Earcut.triangulate( vertices, holeIndices );
  12535. //
  12536. for ( let i = 0; i < triangles.length; i += 3 ) {
  12537. faces.push( triangles.slice( i, i + 3 ) );
  12538. }
  12539. return faces;
  12540. }
  12541. }
  12542. function removeDupEndPts( points ) {
  12543. const l = points.length;
  12544. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12545. points.pop();
  12546. }
  12547. }
  12548. function addContour( vertices, contour ) {
  12549. for ( let i = 0; i < contour.length; i ++ ) {
  12550. vertices.push( contour[ i ].x );
  12551. vertices.push( contour[ i ].y );
  12552. }
  12553. }
  12554. /**
  12555. * Creates extruded geometry from a path shape.
  12556. *
  12557. * parameters = {
  12558. *
  12559. * curveSegments: <int>, // number of points on the curves
  12560. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12561. * depth: <float>, // Depth to extrude the shape
  12562. *
  12563. * bevelEnabled: <bool>, // turn on bevel
  12564. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12565. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12566. * bevelOffset: <float>, // how far from shape outline does bevel start
  12567. * bevelSegments: <int>, // number of bevel layers
  12568. *
  12569. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12570. *
  12571. * UVGenerator: <Object> // object that provides UV generator functions
  12572. *
  12573. * }
  12574. */
  12575. class ExtrudeGeometry extends BufferGeometry {
  12576. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  12577. super();
  12578. this.type = 'ExtrudeGeometry';
  12579. this.parameters = {
  12580. shapes: shapes,
  12581. options: options
  12582. };
  12583. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12584. const scope = this;
  12585. const verticesArray = [];
  12586. const uvArray = [];
  12587. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12588. const shape = shapes[ i ];
  12589. addShape( shape );
  12590. }
  12591. // build geometry
  12592. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12593. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12594. this.computeVertexNormals();
  12595. // functions
  12596. function addShape( shape ) {
  12597. const placeholder = [];
  12598. // options
  12599. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12600. const steps = options.steps !== undefined ? options.steps : 1;
  12601. const depth = options.depth !== undefined ? options.depth : 1;
  12602. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12603. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12604. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12605. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12606. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12607. const extrudePath = options.extrudePath;
  12608. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12609. //
  12610. let extrudePts, extrudeByPath = false;
  12611. let splineTube, binormal, normal, position2;
  12612. if ( extrudePath ) {
  12613. extrudePts = extrudePath.getSpacedPoints( steps );
  12614. extrudeByPath = true;
  12615. bevelEnabled = false; // bevels not supported for path extrusion
  12616. // SETUP TNB variables
  12617. // TODO1 - have a .isClosed in spline?
  12618. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12619. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12620. binormal = new Vector3();
  12621. normal = new Vector3();
  12622. position2 = new Vector3();
  12623. }
  12624. // Safeguards if bevels are not enabled
  12625. if ( ! bevelEnabled ) {
  12626. bevelSegments = 0;
  12627. bevelThickness = 0;
  12628. bevelSize = 0;
  12629. bevelOffset = 0;
  12630. }
  12631. // Variables initialization
  12632. const shapePoints = shape.extractPoints( curveSegments );
  12633. let vertices = shapePoints.shape;
  12634. const holes = shapePoints.holes;
  12635. const reverse = ! ShapeUtils.isClockWise( vertices );
  12636. if ( reverse ) {
  12637. vertices = vertices.reverse();
  12638. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12639. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12640. const ahole = holes[ h ];
  12641. if ( ShapeUtils.isClockWise( ahole ) ) {
  12642. holes[ h ] = ahole.reverse();
  12643. }
  12644. }
  12645. }
  12646. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12647. /* Vertices */
  12648. const contour = vertices; // vertices has all points but contour has only points of circumference
  12649. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12650. const ahole = holes[ h ];
  12651. vertices = vertices.concat( ahole );
  12652. }
  12653. function scalePt2( pt, vec, size ) {
  12654. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12655. return pt.clone().addScaledVector( vec, size );
  12656. }
  12657. const vlen = vertices.length, flen = faces.length;
  12658. // Find directions for point movement
  12659. function getBevelVec( inPt, inPrev, inNext ) {
  12660. // computes for inPt the corresponding point inPt' on a new contour
  12661. // shifted by 1 unit (length of normalized vector) to the left
  12662. // if we walk along contour clockwise, this new contour is outside the old one
  12663. //
  12664. // inPt' is the intersection of the two lines parallel to the two
  12665. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12666. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12667. // good reading for geometry algorithms (here: line-line intersection)
  12668. // http://geomalgorithms.com/a05-_intersect-1.html
  12669. const v_prev_x = inPt.x - inPrev.x,
  12670. v_prev_y = inPt.y - inPrev.y;
  12671. const v_next_x = inNext.x - inPt.x,
  12672. v_next_y = inNext.y - inPt.y;
  12673. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12674. // check for collinear edges
  12675. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12676. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12677. // not collinear
  12678. // length of vectors for normalizing
  12679. const v_prev_len = Math.sqrt( v_prev_lensq );
  12680. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12681. // shift adjacent points by unit vectors to the left
  12682. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12683. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12684. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12685. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12686. // scaling factor for v_prev to intersection point
  12687. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12688. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12689. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12690. // vector from inPt to intersection point
  12691. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12692. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12693. // Don't normalize!, otherwise sharp corners become ugly
  12694. // but prevent crazy spikes
  12695. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12696. if ( v_trans_lensq <= 2 ) {
  12697. return new Vector2( v_trans_x, v_trans_y );
  12698. } else {
  12699. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12700. }
  12701. } else {
  12702. // handle special case of collinear edges
  12703. let direction_eq = false; // assumes: opposite
  12704. if ( v_prev_x > Number.EPSILON ) {
  12705. if ( v_next_x > Number.EPSILON ) {
  12706. direction_eq = true;
  12707. }
  12708. } else {
  12709. if ( v_prev_x < - Number.EPSILON ) {
  12710. if ( v_next_x < - Number.EPSILON ) {
  12711. direction_eq = true;
  12712. }
  12713. } else {
  12714. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12715. direction_eq = true;
  12716. }
  12717. }
  12718. }
  12719. if ( direction_eq ) {
  12720. // console.log("Warning: lines are a straight sequence");
  12721. v_trans_x = - v_prev_y;
  12722. v_trans_y = v_prev_x;
  12723. shrink_by = Math.sqrt( v_prev_lensq );
  12724. } else {
  12725. // console.log("Warning: lines are a straight spike");
  12726. v_trans_x = v_prev_x;
  12727. v_trans_y = v_prev_y;
  12728. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12729. }
  12730. }
  12731. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12732. }
  12733. const contourMovements = [];
  12734. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12735. if ( j === il ) j = 0;
  12736. if ( k === il ) k = 0;
  12737. // (j)---(i)---(k)
  12738. // console.log('i,j,k', i, j , k)
  12739. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12740. }
  12741. const holesMovements = [];
  12742. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12743. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12744. const ahole = holes[ h ];
  12745. oneHoleMovements = [];
  12746. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12747. if ( j === il ) j = 0;
  12748. if ( k === il ) k = 0;
  12749. // (j)---(i)---(k)
  12750. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12751. }
  12752. holesMovements.push( oneHoleMovements );
  12753. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12754. }
  12755. // Loop bevelSegments, 1 for the front, 1 for the back
  12756. for ( let b = 0; b < bevelSegments; b ++ ) {
  12757. //for ( b = bevelSegments; b > 0; b -- ) {
  12758. const t = b / bevelSegments;
  12759. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12760. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12761. // contract shape
  12762. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12763. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12764. v( vert.x, vert.y, - z );
  12765. }
  12766. // expand holes
  12767. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12768. const ahole = holes[ h ];
  12769. oneHoleMovements = holesMovements[ h ];
  12770. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12771. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12772. v( vert.x, vert.y, - z );
  12773. }
  12774. }
  12775. }
  12776. const bs = bevelSize + bevelOffset;
  12777. // Back facing vertices
  12778. for ( let i = 0; i < vlen; i ++ ) {
  12779. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12780. if ( ! extrudeByPath ) {
  12781. v( vert.x, vert.y, 0 );
  12782. } else {
  12783. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12784. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12785. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12786. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12787. v( position2.x, position2.y, position2.z );
  12788. }
  12789. }
  12790. // Add stepped vertices...
  12791. // Including front facing vertices
  12792. for ( let s = 1; s <= steps; s ++ ) {
  12793. for ( let i = 0; i < vlen; i ++ ) {
  12794. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12795. if ( ! extrudeByPath ) {
  12796. v( vert.x, vert.y, depth / steps * s );
  12797. } else {
  12798. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12799. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12800. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12801. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12802. v( position2.x, position2.y, position2.z );
  12803. }
  12804. }
  12805. }
  12806. // Add bevel segments planes
  12807. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12808. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12809. const t = b / bevelSegments;
  12810. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12811. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12812. // contract shape
  12813. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12814. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12815. v( vert.x, vert.y, depth + z );
  12816. }
  12817. // expand holes
  12818. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12819. const ahole = holes[ h ];
  12820. oneHoleMovements = holesMovements[ h ];
  12821. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12822. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12823. if ( ! extrudeByPath ) {
  12824. v( vert.x, vert.y, depth + z );
  12825. } else {
  12826. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12827. }
  12828. }
  12829. }
  12830. }
  12831. /* Faces */
  12832. // Top and bottom faces
  12833. buildLidFaces();
  12834. // Sides faces
  12835. buildSideFaces();
  12836. ///// Internal functions
  12837. function buildLidFaces() {
  12838. const start = verticesArray.length / 3;
  12839. if ( bevelEnabled ) {
  12840. let layer = 0; // steps + 1
  12841. let offset = vlen * layer;
  12842. // Bottom faces
  12843. for ( let i = 0; i < flen; i ++ ) {
  12844. const face = faces[ i ];
  12845. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12846. }
  12847. layer = steps + bevelSegments * 2;
  12848. offset = vlen * layer;
  12849. // Top faces
  12850. for ( let i = 0; i < flen; i ++ ) {
  12851. const face = faces[ i ];
  12852. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12853. }
  12854. } else {
  12855. // Bottom faces
  12856. for ( let i = 0; i < flen; i ++ ) {
  12857. const face = faces[ i ];
  12858. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12859. }
  12860. // Top faces
  12861. for ( let i = 0; i < flen; i ++ ) {
  12862. const face = faces[ i ];
  12863. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12864. }
  12865. }
  12866. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12867. }
  12868. // Create faces for the z-sides of the shape
  12869. function buildSideFaces() {
  12870. const start = verticesArray.length / 3;
  12871. let layeroffset = 0;
  12872. sidewalls( contour, layeroffset );
  12873. layeroffset += contour.length;
  12874. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12875. const ahole = holes[ h ];
  12876. sidewalls( ahole, layeroffset );
  12877. //, true
  12878. layeroffset += ahole.length;
  12879. }
  12880. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12881. }
  12882. function sidewalls( contour, layeroffset ) {
  12883. let i = contour.length;
  12884. while ( -- i >= 0 ) {
  12885. const j = i;
  12886. let k = i - 1;
  12887. if ( k < 0 ) k = contour.length - 1;
  12888. //console.log('b', i,j, i-1, k,vertices.length);
  12889. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12890. const slen1 = vlen * s;
  12891. const slen2 = vlen * ( s + 1 );
  12892. const a = layeroffset + j + slen1,
  12893. b = layeroffset + k + slen1,
  12894. c = layeroffset + k + slen2,
  12895. d = layeroffset + j + slen2;
  12896. f4( a, b, c, d );
  12897. }
  12898. }
  12899. }
  12900. function v( x, y, z ) {
  12901. placeholder.push( x );
  12902. placeholder.push( y );
  12903. placeholder.push( z );
  12904. }
  12905. function f3( a, b, c ) {
  12906. addVertex( a );
  12907. addVertex( b );
  12908. addVertex( c );
  12909. const nextIndex = verticesArray.length / 3;
  12910. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12911. addUV( uvs[ 0 ] );
  12912. addUV( uvs[ 1 ] );
  12913. addUV( uvs[ 2 ] );
  12914. }
  12915. function f4( a, b, c, d ) {
  12916. addVertex( a );
  12917. addVertex( b );
  12918. addVertex( d );
  12919. addVertex( b );
  12920. addVertex( c );
  12921. addVertex( d );
  12922. const nextIndex = verticesArray.length / 3;
  12923. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12924. addUV( uvs[ 0 ] );
  12925. addUV( uvs[ 1 ] );
  12926. addUV( uvs[ 3 ] );
  12927. addUV( uvs[ 1 ] );
  12928. addUV( uvs[ 2 ] );
  12929. addUV( uvs[ 3 ] );
  12930. }
  12931. function addVertex( index ) {
  12932. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12933. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12934. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12935. }
  12936. function addUV( vector2 ) {
  12937. uvArray.push( vector2.x );
  12938. uvArray.push( vector2.y );
  12939. }
  12940. }
  12941. }
  12942. copy( source ) {
  12943. super.copy( source );
  12944. this.parameters = Object.assign( {}, source.parameters );
  12945. return this;
  12946. }
  12947. toJSON() {
  12948. const data = super.toJSON();
  12949. const shapes = this.parameters.shapes;
  12950. const options = this.parameters.options;
  12951. return toJSON$1( shapes, options, data );
  12952. }
  12953. static fromJSON( data, shapes ) {
  12954. const geometryShapes = [];
  12955. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12956. const shape = shapes[ data.shapes[ j ] ];
  12957. geometryShapes.push( shape );
  12958. }
  12959. const extrudePath = data.options.extrudePath;
  12960. if ( extrudePath !== undefined ) {
  12961. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  12962. }
  12963. return new ExtrudeGeometry( geometryShapes, data.options );
  12964. }
  12965. }
  12966. const WorldUVGenerator = {
  12967. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  12968. const a_x = vertices[ indexA * 3 ];
  12969. const a_y = vertices[ indexA * 3 + 1 ];
  12970. const b_x = vertices[ indexB * 3 ];
  12971. const b_y = vertices[ indexB * 3 + 1 ];
  12972. const c_x = vertices[ indexC * 3 ];
  12973. const c_y = vertices[ indexC * 3 + 1 ];
  12974. return [
  12975. new Vector2( a_x, a_y ),
  12976. new Vector2( b_x, b_y ),
  12977. new Vector2( c_x, c_y )
  12978. ];
  12979. },
  12980. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  12981. const a_x = vertices[ indexA * 3 ];
  12982. const a_y = vertices[ indexA * 3 + 1 ];
  12983. const a_z = vertices[ indexA * 3 + 2 ];
  12984. const b_x = vertices[ indexB * 3 ];
  12985. const b_y = vertices[ indexB * 3 + 1 ];
  12986. const b_z = vertices[ indexB * 3 + 2 ];
  12987. const c_x = vertices[ indexC * 3 ];
  12988. const c_y = vertices[ indexC * 3 + 1 ];
  12989. const c_z = vertices[ indexC * 3 + 2 ];
  12990. const d_x = vertices[ indexD * 3 ];
  12991. const d_y = vertices[ indexD * 3 + 1 ];
  12992. const d_z = vertices[ indexD * 3 + 2 ];
  12993. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  12994. return [
  12995. new Vector2( a_x, 1 - a_z ),
  12996. new Vector2( b_x, 1 - b_z ),
  12997. new Vector2( c_x, 1 - c_z ),
  12998. new Vector2( d_x, 1 - d_z )
  12999. ];
  13000. } else {
  13001. return [
  13002. new Vector2( a_y, 1 - a_z ),
  13003. new Vector2( b_y, 1 - b_z ),
  13004. new Vector2( c_y, 1 - c_z ),
  13005. new Vector2( d_y, 1 - d_z )
  13006. ];
  13007. }
  13008. }
  13009. };
  13010. function toJSON$1( shapes, options, data ) {
  13011. data.shapes = [];
  13012. if ( Array.isArray( shapes ) ) {
  13013. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13014. const shape = shapes[ i ];
  13015. data.shapes.push( shape.uuid );
  13016. }
  13017. } else {
  13018. data.shapes.push( shapes.uuid );
  13019. }
  13020. data.options = Object.assign( {}, options );
  13021. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13022. return data;
  13023. }
  13024. class IcosahedronGeometry extends PolyhedronGeometry {
  13025. constructor( radius = 1, detail = 0 ) {
  13026. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13027. const vertices = [
  13028. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13029. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13030. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13031. ];
  13032. const indices = [
  13033. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13034. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13035. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13036. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13037. ];
  13038. super( vertices, indices, radius, detail );
  13039. this.type = 'IcosahedronGeometry';
  13040. this.parameters = {
  13041. radius: radius,
  13042. detail: detail
  13043. };
  13044. }
  13045. static fromJSON( data ) {
  13046. return new IcosahedronGeometry( data.radius, data.detail );
  13047. }
  13048. }
  13049. class OctahedronGeometry extends PolyhedronGeometry {
  13050. constructor( radius = 1, detail = 0 ) {
  13051. const vertices = [
  13052. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13053. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13054. ];
  13055. const indices = [
  13056. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13057. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13058. 1, 3, 4, 1, 4, 2
  13059. ];
  13060. super( vertices, indices, radius, detail );
  13061. this.type = 'OctahedronGeometry';
  13062. this.parameters = {
  13063. radius: radius,
  13064. detail: detail
  13065. };
  13066. }
  13067. static fromJSON( data ) {
  13068. return new OctahedronGeometry( data.radius, data.detail );
  13069. }
  13070. }
  13071. class PlaneGeometry extends BufferGeometry {
  13072. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13073. super();
  13074. this.type = 'PlaneGeometry';
  13075. this.parameters = {
  13076. width: width,
  13077. height: height,
  13078. widthSegments: widthSegments,
  13079. heightSegments: heightSegments
  13080. };
  13081. const width_half = width / 2;
  13082. const height_half = height / 2;
  13083. const gridX = Math.floor( widthSegments );
  13084. const gridY = Math.floor( heightSegments );
  13085. const gridX1 = gridX + 1;
  13086. const gridY1 = gridY + 1;
  13087. const segment_width = width / gridX;
  13088. const segment_height = height / gridY;
  13089. //
  13090. const indices = [];
  13091. const vertices = [];
  13092. const normals = [];
  13093. const uvs = [];
  13094. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13095. const y = iy * segment_height - height_half;
  13096. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13097. const x = ix * segment_width - width_half;
  13098. vertices.push( x, - y, 0 );
  13099. normals.push( 0, 0, 1 );
  13100. uvs.push( ix / gridX );
  13101. uvs.push( 1 - ( iy / gridY ) );
  13102. }
  13103. }
  13104. for ( let iy = 0; iy < gridY; iy ++ ) {
  13105. for ( let ix = 0; ix < gridX; ix ++ ) {
  13106. const a = ix + gridX1 * iy;
  13107. const b = ix + gridX1 * ( iy + 1 );
  13108. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13109. const d = ( ix + 1 ) + gridX1 * iy;
  13110. indices.push( a, b, d );
  13111. indices.push( b, c, d );
  13112. }
  13113. }
  13114. this.setIndex( indices );
  13115. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13116. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13117. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13118. }
  13119. copy( source ) {
  13120. super.copy( source );
  13121. this.parameters = Object.assign( {}, source.parameters );
  13122. return this;
  13123. }
  13124. static fromJSON( data ) {
  13125. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13126. }
  13127. }
  13128. class RingGeometry extends BufferGeometry {
  13129. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13130. super();
  13131. this.type = 'RingGeometry';
  13132. this.parameters = {
  13133. innerRadius: innerRadius,
  13134. outerRadius: outerRadius,
  13135. thetaSegments: thetaSegments,
  13136. phiSegments: phiSegments,
  13137. thetaStart: thetaStart,
  13138. thetaLength: thetaLength
  13139. };
  13140. thetaSegments = Math.max( 3, thetaSegments );
  13141. phiSegments = Math.max( 1, phiSegments );
  13142. // buffers
  13143. const indices = [];
  13144. const vertices = [];
  13145. const normals = [];
  13146. const uvs = [];
  13147. // some helper variables
  13148. let radius = innerRadius;
  13149. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13150. const vertex = new Vector3();
  13151. const uv = new Vector2();
  13152. // generate vertices, normals and uvs
  13153. for ( let j = 0; j <= phiSegments; j ++ ) {
  13154. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13155. // values are generate from the inside of the ring to the outside
  13156. const segment = thetaStart + i / thetaSegments * thetaLength;
  13157. // vertex
  13158. vertex.x = radius * Math.cos( segment );
  13159. vertex.y = radius * Math.sin( segment );
  13160. vertices.push( vertex.x, vertex.y, vertex.z );
  13161. // normal
  13162. normals.push( 0, 0, 1 );
  13163. // uv
  13164. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13165. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13166. uvs.push( uv.x, uv.y );
  13167. }
  13168. // increase the radius for next row of vertices
  13169. radius += radiusStep;
  13170. }
  13171. // indices
  13172. for ( let j = 0; j < phiSegments; j ++ ) {
  13173. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13174. for ( let i = 0; i < thetaSegments; i ++ ) {
  13175. const segment = i + thetaSegmentLevel;
  13176. const a = segment;
  13177. const b = segment + thetaSegments + 1;
  13178. const c = segment + thetaSegments + 2;
  13179. const d = segment + 1;
  13180. // faces
  13181. indices.push( a, b, d );
  13182. indices.push( b, c, d );
  13183. }
  13184. }
  13185. // build geometry
  13186. this.setIndex( indices );
  13187. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13188. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13189. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13190. }
  13191. copy( source ) {
  13192. super.copy( source );
  13193. this.parameters = Object.assign( {}, source.parameters );
  13194. return this;
  13195. }
  13196. static fromJSON( data ) {
  13197. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13198. }
  13199. }
  13200. class ShapeGeometry extends BufferGeometry {
  13201. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13202. super();
  13203. this.type = 'ShapeGeometry';
  13204. this.parameters = {
  13205. shapes: shapes,
  13206. curveSegments: curveSegments
  13207. };
  13208. // buffers
  13209. const indices = [];
  13210. const vertices = [];
  13211. const normals = [];
  13212. const uvs = [];
  13213. // helper variables
  13214. let groupStart = 0;
  13215. let groupCount = 0;
  13216. // allow single and array values for "shapes" parameter
  13217. if ( Array.isArray( shapes ) === false ) {
  13218. addShape( shapes );
  13219. } else {
  13220. for ( let i = 0; i < shapes.length; i ++ ) {
  13221. addShape( shapes[ i ] );
  13222. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13223. groupStart += groupCount;
  13224. groupCount = 0;
  13225. }
  13226. }
  13227. // build geometry
  13228. this.setIndex( indices );
  13229. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13230. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13231. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13232. // helper functions
  13233. function addShape( shape ) {
  13234. const indexOffset = vertices.length / 3;
  13235. const points = shape.extractPoints( curveSegments );
  13236. let shapeVertices = points.shape;
  13237. const shapeHoles = points.holes;
  13238. // check direction of vertices
  13239. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13240. shapeVertices = shapeVertices.reverse();
  13241. }
  13242. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13243. const shapeHole = shapeHoles[ i ];
  13244. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13245. shapeHoles[ i ] = shapeHole.reverse();
  13246. }
  13247. }
  13248. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13249. // join vertices of inner and outer paths to a single array
  13250. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13251. const shapeHole = shapeHoles[ i ];
  13252. shapeVertices = shapeVertices.concat( shapeHole );
  13253. }
  13254. // vertices, normals, uvs
  13255. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13256. const vertex = shapeVertices[ i ];
  13257. vertices.push( vertex.x, vertex.y, 0 );
  13258. normals.push( 0, 0, 1 );
  13259. uvs.push( vertex.x, vertex.y ); // world uvs
  13260. }
  13261. // indices
  13262. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13263. const face = faces[ i ];
  13264. const a = face[ 0 ] + indexOffset;
  13265. const b = face[ 1 ] + indexOffset;
  13266. const c = face[ 2 ] + indexOffset;
  13267. indices.push( a, b, c );
  13268. groupCount += 3;
  13269. }
  13270. }
  13271. }
  13272. copy( source ) {
  13273. super.copy( source );
  13274. this.parameters = Object.assign( {}, source.parameters );
  13275. return this;
  13276. }
  13277. toJSON() {
  13278. const data = super.toJSON();
  13279. const shapes = this.parameters.shapes;
  13280. return toJSON( shapes, data );
  13281. }
  13282. static fromJSON( data, shapes ) {
  13283. const geometryShapes = [];
  13284. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13285. const shape = shapes[ data.shapes[ j ] ];
  13286. geometryShapes.push( shape );
  13287. }
  13288. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13289. }
  13290. }
  13291. function toJSON( shapes, data ) {
  13292. data.shapes = [];
  13293. if ( Array.isArray( shapes ) ) {
  13294. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13295. const shape = shapes[ i ];
  13296. data.shapes.push( shape.uuid );
  13297. }
  13298. } else {
  13299. data.shapes.push( shapes.uuid );
  13300. }
  13301. return data;
  13302. }
  13303. class SphereGeometry extends BufferGeometry {
  13304. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13305. super();
  13306. this.type = 'SphereGeometry';
  13307. this.parameters = {
  13308. radius: radius,
  13309. widthSegments: widthSegments,
  13310. heightSegments: heightSegments,
  13311. phiStart: phiStart,
  13312. phiLength: phiLength,
  13313. thetaStart: thetaStart,
  13314. thetaLength: thetaLength
  13315. };
  13316. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13317. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13318. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13319. let index = 0;
  13320. const grid = [];
  13321. const vertex = new Vector3();
  13322. const normal = new Vector3();
  13323. // buffers
  13324. const indices = [];
  13325. const vertices = [];
  13326. const normals = [];
  13327. const uvs = [];
  13328. // generate vertices, normals and uvs
  13329. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13330. const verticesRow = [];
  13331. const v = iy / heightSegments;
  13332. // special case for the poles
  13333. let uOffset = 0;
  13334. if ( iy === 0 && thetaStart === 0 ) {
  13335. uOffset = 0.5 / widthSegments;
  13336. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13337. uOffset = - 0.5 / widthSegments;
  13338. }
  13339. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13340. const u = ix / widthSegments;
  13341. // vertex
  13342. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13343. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13344. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13345. vertices.push( vertex.x, vertex.y, vertex.z );
  13346. // normal
  13347. normal.copy( vertex ).normalize();
  13348. normals.push( normal.x, normal.y, normal.z );
  13349. // uv
  13350. uvs.push( u + uOffset, 1 - v );
  13351. verticesRow.push( index ++ );
  13352. }
  13353. grid.push( verticesRow );
  13354. }
  13355. // indices
  13356. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13357. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13358. const a = grid[ iy ][ ix + 1 ];
  13359. const b = grid[ iy ][ ix ];
  13360. const c = grid[ iy + 1 ][ ix ];
  13361. const d = grid[ iy + 1 ][ ix + 1 ];
  13362. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13363. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13364. }
  13365. }
  13366. // build geometry
  13367. this.setIndex( indices );
  13368. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13369. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13370. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13371. }
  13372. copy( source ) {
  13373. super.copy( source );
  13374. this.parameters = Object.assign( {}, source.parameters );
  13375. return this;
  13376. }
  13377. static fromJSON( data ) {
  13378. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13379. }
  13380. }
  13381. class TetrahedronGeometry extends PolyhedronGeometry {
  13382. constructor( radius = 1, detail = 0 ) {
  13383. const vertices = [
  13384. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13385. ];
  13386. const indices = [
  13387. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13388. ];
  13389. super( vertices, indices, radius, detail );
  13390. this.type = 'TetrahedronGeometry';
  13391. this.parameters = {
  13392. radius: radius,
  13393. detail: detail
  13394. };
  13395. }
  13396. static fromJSON( data ) {
  13397. return new TetrahedronGeometry( data.radius, data.detail );
  13398. }
  13399. }
  13400. class TorusGeometry extends BufferGeometry {
  13401. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13402. super();
  13403. this.type = 'TorusGeometry';
  13404. this.parameters = {
  13405. radius: radius,
  13406. tube: tube,
  13407. radialSegments: radialSegments,
  13408. tubularSegments: tubularSegments,
  13409. arc: arc
  13410. };
  13411. radialSegments = Math.floor( radialSegments );
  13412. tubularSegments = Math.floor( tubularSegments );
  13413. // buffers
  13414. const indices = [];
  13415. const vertices = [];
  13416. const normals = [];
  13417. const uvs = [];
  13418. // helper variables
  13419. const center = new Vector3();
  13420. const vertex = new Vector3();
  13421. const normal = new Vector3();
  13422. // generate vertices, normals and uvs
  13423. for ( let j = 0; j <= radialSegments; j ++ ) {
  13424. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13425. const u = i / tubularSegments * arc;
  13426. const v = j / radialSegments * Math.PI * 2;
  13427. // vertex
  13428. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13429. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13430. vertex.z = tube * Math.sin( v );
  13431. vertices.push( vertex.x, vertex.y, vertex.z );
  13432. // normal
  13433. center.x = radius * Math.cos( u );
  13434. center.y = radius * Math.sin( u );
  13435. normal.subVectors( vertex, center ).normalize();
  13436. normals.push( normal.x, normal.y, normal.z );
  13437. // uv
  13438. uvs.push( i / tubularSegments );
  13439. uvs.push( j / radialSegments );
  13440. }
  13441. }
  13442. // generate indices
  13443. for ( let j = 1; j <= radialSegments; j ++ ) {
  13444. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13445. // indices
  13446. const a = ( tubularSegments + 1 ) * j + i - 1;
  13447. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13448. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13449. const d = ( tubularSegments + 1 ) * j + i;
  13450. // faces
  13451. indices.push( a, b, d );
  13452. indices.push( b, c, d );
  13453. }
  13454. }
  13455. // build geometry
  13456. this.setIndex( indices );
  13457. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13458. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13459. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13460. }
  13461. copy( source ) {
  13462. super.copy( source );
  13463. this.parameters = Object.assign( {}, source.parameters );
  13464. return this;
  13465. }
  13466. static fromJSON( data ) {
  13467. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13468. }
  13469. }
  13470. class TorusKnotGeometry extends BufferGeometry {
  13471. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13472. super();
  13473. this.type = 'TorusKnotGeometry';
  13474. this.parameters = {
  13475. radius: radius,
  13476. tube: tube,
  13477. tubularSegments: tubularSegments,
  13478. radialSegments: radialSegments,
  13479. p: p,
  13480. q: q
  13481. };
  13482. tubularSegments = Math.floor( tubularSegments );
  13483. radialSegments = Math.floor( radialSegments );
  13484. // buffers
  13485. const indices = [];
  13486. const vertices = [];
  13487. const normals = [];
  13488. const uvs = [];
  13489. // helper variables
  13490. const vertex = new Vector3();
  13491. const normal = new Vector3();
  13492. const P1 = new Vector3();
  13493. const P2 = new Vector3();
  13494. const B = new Vector3();
  13495. const T = new Vector3();
  13496. const N = new Vector3();
  13497. // generate vertices, normals and uvs
  13498. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13499. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13500. const u = i / tubularSegments * p * Math.PI * 2;
  13501. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13502. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13503. calculatePositionOnCurve( u, p, q, radius, P1 );
  13504. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13505. // calculate orthonormal basis
  13506. T.subVectors( P2, P1 );
  13507. N.addVectors( P2, P1 );
  13508. B.crossVectors( T, N );
  13509. N.crossVectors( B, T );
  13510. // normalize B, N. T can be ignored, we don't use it
  13511. B.normalize();
  13512. N.normalize();
  13513. for ( let j = 0; j <= radialSegments; ++ j ) {
  13514. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13515. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13516. const v = j / radialSegments * Math.PI * 2;
  13517. const cx = - tube * Math.cos( v );
  13518. const cy = tube * Math.sin( v );
  13519. // now calculate the final vertex position.
  13520. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13521. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13522. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13523. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13524. vertices.push( vertex.x, vertex.y, vertex.z );
  13525. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13526. normal.subVectors( vertex, P1 ).normalize();
  13527. normals.push( normal.x, normal.y, normal.z );
  13528. // uv
  13529. uvs.push( i / tubularSegments );
  13530. uvs.push( j / radialSegments );
  13531. }
  13532. }
  13533. // generate indices
  13534. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13535. for ( let i = 1; i <= radialSegments; i ++ ) {
  13536. // indices
  13537. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13538. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13539. const c = ( radialSegments + 1 ) * j + i;
  13540. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13541. // faces
  13542. indices.push( a, b, d );
  13543. indices.push( b, c, d );
  13544. }
  13545. }
  13546. // build geometry
  13547. this.setIndex( indices );
  13548. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13549. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13550. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13551. // this function calculates the current position on the torus curve
  13552. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13553. const cu = Math.cos( u );
  13554. const su = Math.sin( u );
  13555. const quOverP = q / p * u;
  13556. const cs = Math.cos( quOverP );
  13557. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13558. position.y = radius * ( 2 + cs ) * su * 0.5;
  13559. position.z = radius * Math.sin( quOverP ) * 0.5;
  13560. }
  13561. }
  13562. copy( source ) {
  13563. super.copy( source );
  13564. this.parameters = Object.assign( {}, source.parameters );
  13565. return this;
  13566. }
  13567. static fromJSON( data ) {
  13568. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13569. }
  13570. }
  13571. class TubeGeometry extends BufferGeometry {
  13572. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  13573. super();
  13574. this.type = 'TubeGeometry';
  13575. this.parameters = {
  13576. path: path,
  13577. tubularSegments: tubularSegments,
  13578. radius: radius,
  13579. radialSegments: radialSegments,
  13580. closed: closed
  13581. };
  13582. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13583. // expose internals
  13584. this.tangents = frames.tangents;
  13585. this.normals = frames.normals;
  13586. this.binormals = frames.binormals;
  13587. // helper variables
  13588. const vertex = new Vector3();
  13589. const normal = new Vector3();
  13590. const uv = new Vector2();
  13591. let P = new Vector3();
  13592. // buffer
  13593. const vertices = [];
  13594. const normals = [];
  13595. const uvs = [];
  13596. const indices = [];
  13597. // create buffer data
  13598. generateBufferData();
  13599. // build geometry
  13600. this.setIndex( indices );
  13601. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13602. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13603. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13604. // functions
  13605. function generateBufferData() {
  13606. for ( let i = 0; i < tubularSegments; i ++ ) {
  13607. generateSegment( i );
  13608. }
  13609. // if the geometry is not closed, generate the last row of vertices and normals
  13610. // at the regular position on the given path
  13611. //
  13612. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13613. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13614. // uvs are generated in a separate function.
  13615. // this makes it easy compute correct values for closed geometries
  13616. generateUVs();
  13617. // finally create faces
  13618. generateIndices();
  13619. }
  13620. function generateSegment( i ) {
  13621. // we use getPointAt to sample evenly distributed points from the given path
  13622. P = path.getPointAt( i / tubularSegments, P );
  13623. // retrieve corresponding normal and binormal
  13624. const N = frames.normals[ i ];
  13625. const B = frames.binormals[ i ];
  13626. // generate normals and vertices for the current segment
  13627. for ( let j = 0; j <= radialSegments; j ++ ) {
  13628. const v = j / radialSegments * Math.PI * 2;
  13629. const sin = Math.sin( v );
  13630. const cos = - Math.cos( v );
  13631. // normal
  13632. normal.x = ( cos * N.x + sin * B.x );
  13633. normal.y = ( cos * N.y + sin * B.y );
  13634. normal.z = ( cos * N.z + sin * B.z );
  13635. normal.normalize();
  13636. normals.push( normal.x, normal.y, normal.z );
  13637. // vertex
  13638. vertex.x = P.x + radius * normal.x;
  13639. vertex.y = P.y + radius * normal.y;
  13640. vertex.z = P.z + radius * normal.z;
  13641. vertices.push( vertex.x, vertex.y, vertex.z );
  13642. }
  13643. }
  13644. function generateIndices() {
  13645. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13646. for ( let i = 1; i <= radialSegments; i ++ ) {
  13647. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13648. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13649. const c = ( radialSegments + 1 ) * j + i;
  13650. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13651. // faces
  13652. indices.push( a, b, d );
  13653. indices.push( b, c, d );
  13654. }
  13655. }
  13656. }
  13657. function generateUVs() {
  13658. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13659. for ( let j = 0; j <= radialSegments; j ++ ) {
  13660. uv.x = i / tubularSegments;
  13661. uv.y = j / radialSegments;
  13662. uvs.push( uv.x, uv.y );
  13663. }
  13664. }
  13665. }
  13666. }
  13667. copy( source ) {
  13668. super.copy( source );
  13669. this.parameters = Object.assign( {}, source.parameters );
  13670. return this;
  13671. }
  13672. toJSON() {
  13673. const data = super.toJSON();
  13674. data.path = this.parameters.path.toJSON();
  13675. return data;
  13676. }
  13677. static fromJSON( data ) {
  13678. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13679. // User defined curves or instances of CurvePath will not be deserialized.
  13680. return new TubeGeometry(
  13681. new Curves[ data.path.type ]().fromJSON( data.path ),
  13682. data.tubularSegments,
  13683. data.radius,
  13684. data.radialSegments,
  13685. data.closed
  13686. );
  13687. }
  13688. }
  13689. class WireframeGeometry extends BufferGeometry {
  13690. constructor( geometry = null ) {
  13691. super();
  13692. this.type = 'WireframeGeometry';
  13693. this.parameters = {
  13694. geometry: geometry
  13695. };
  13696. if ( geometry !== null ) {
  13697. // buffer
  13698. const vertices = [];
  13699. const edges = new Set();
  13700. // helper variables
  13701. const start = new Vector3();
  13702. const end = new Vector3();
  13703. if ( geometry.index !== null ) {
  13704. // indexed BufferGeometry
  13705. const position = geometry.attributes.position;
  13706. const indices = geometry.index;
  13707. let groups = geometry.groups;
  13708. if ( groups.length === 0 ) {
  13709. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13710. }
  13711. // create a data structure that contains all edges without duplicates
  13712. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13713. const group = groups[ o ];
  13714. const groupStart = group.start;
  13715. const groupCount = group.count;
  13716. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13717. for ( let j = 0; j < 3; j ++ ) {
  13718. const index1 = indices.getX( i + j );
  13719. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13720. start.fromBufferAttribute( position, index1 );
  13721. end.fromBufferAttribute( position, index2 );
  13722. if ( isUniqueEdge( start, end, edges ) === true ) {
  13723. vertices.push( start.x, start.y, start.z );
  13724. vertices.push( end.x, end.y, end.z );
  13725. }
  13726. }
  13727. }
  13728. }
  13729. } else {
  13730. // non-indexed BufferGeometry
  13731. const position = geometry.attributes.position;
  13732. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13733. for ( let j = 0; j < 3; j ++ ) {
  13734. // three edges per triangle, an edge is represented as (index1, index2)
  13735. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13736. const index1 = 3 * i + j;
  13737. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13738. start.fromBufferAttribute( position, index1 );
  13739. end.fromBufferAttribute( position, index2 );
  13740. if ( isUniqueEdge( start, end, edges ) === true ) {
  13741. vertices.push( start.x, start.y, start.z );
  13742. vertices.push( end.x, end.y, end.z );
  13743. }
  13744. }
  13745. }
  13746. }
  13747. // build geometry
  13748. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13749. }
  13750. }
  13751. copy( source ) {
  13752. super.copy( source );
  13753. this.parameters = Object.assign( {}, source.parameters );
  13754. return this;
  13755. }
  13756. }
  13757. function isUniqueEdge( start, end, edges ) {
  13758. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13759. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13760. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13761. return false;
  13762. } else {
  13763. edges.add( hash1 );
  13764. edges.add( hash2 );
  13765. return true;
  13766. }
  13767. }
  13768. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13769. __proto__: null,
  13770. BoxGeometry: BoxGeometry,
  13771. CapsuleGeometry: CapsuleGeometry,
  13772. CircleGeometry: CircleGeometry,
  13773. ConeGeometry: ConeGeometry,
  13774. CylinderGeometry: CylinderGeometry,
  13775. DodecahedronGeometry: DodecahedronGeometry,
  13776. EdgesGeometry: EdgesGeometry,
  13777. ExtrudeGeometry: ExtrudeGeometry,
  13778. IcosahedronGeometry: IcosahedronGeometry,
  13779. LatheGeometry: LatheGeometry,
  13780. OctahedronGeometry: OctahedronGeometry,
  13781. PlaneGeometry: PlaneGeometry,
  13782. PolyhedronGeometry: PolyhedronGeometry,
  13783. RingGeometry: RingGeometry,
  13784. ShapeGeometry: ShapeGeometry,
  13785. SphereGeometry: SphereGeometry,
  13786. TetrahedronGeometry: TetrahedronGeometry,
  13787. TorusGeometry: TorusGeometry,
  13788. TorusKnotGeometry: TorusKnotGeometry,
  13789. TubeGeometry: TubeGeometry,
  13790. WireframeGeometry: WireframeGeometry
  13791. });
  13792. class ShadowMaterial extends Material {
  13793. constructor( parameters ) {
  13794. super();
  13795. this.isShadowMaterial = true;
  13796. this.type = 'ShadowMaterial';
  13797. this.color = new Color( 0x000000 );
  13798. this.transparent = true;
  13799. this.fog = true;
  13800. this.setValues( parameters );
  13801. }
  13802. copy( source ) {
  13803. super.copy( source );
  13804. this.color.copy( source.color );
  13805. this.fog = source.fog;
  13806. return this;
  13807. }
  13808. }
  13809. class RawShaderMaterial extends ShaderMaterial {
  13810. constructor( parameters ) {
  13811. super( parameters );
  13812. this.isRawShaderMaterial = true;
  13813. this.type = 'RawShaderMaterial';
  13814. }
  13815. }
  13816. class MeshStandardMaterial extends Material {
  13817. constructor( parameters ) {
  13818. super();
  13819. this.isMeshStandardMaterial = true;
  13820. this.defines = { 'STANDARD': '' };
  13821. this.type = 'MeshStandardMaterial';
  13822. this.color = new Color( 0xffffff ); // diffuse
  13823. this.roughness = 1.0;
  13824. this.metalness = 0.0;
  13825. this.map = null;
  13826. this.lightMap = null;
  13827. this.lightMapIntensity = 1.0;
  13828. this.aoMap = null;
  13829. this.aoMapIntensity = 1.0;
  13830. this.emissive = new Color( 0x000000 );
  13831. this.emissiveIntensity = 1.0;
  13832. this.emissiveMap = null;
  13833. this.bumpMap = null;
  13834. this.bumpScale = 1;
  13835. this.normalMap = null;
  13836. this.normalMapType = TangentSpaceNormalMap;
  13837. this.normalScale = new Vector2( 1, 1 );
  13838. this.displacementMap = null;
  13839. this.displacementScale = 1;
  13840. this.displacementBias = 0;
  13841. this.roughnessMap = null;
  13842. this.metalnessMap = null;
  13843. this.alphaMap = null;
  13844. this.envMap = null;
  13845. this.envMapRotation = new Euler();
  13846. this.envMapIntensity = 1.0;
  13847. this.wireframe = false;
  13848. this.wireframeLinewidth = 1;
  13849. this.wireframeLinecap = 'round';
  13850. this.wireframeLinejoin = 'round';
  13851. this.flatShading = false;
  13852. this.fog = true;
  13853. this.setValues( parameters );
  13854. }
  13855. copy( source ) {
  13856. super.copy( source );
  13857. this.defines = { 'STANDARD': '' };
  13858. this.color.copy( source.color );
  13859. this.roughness = source.roughness;
  13860. this.metalness = source.metalness;
  13861. this.map = source.map;
  13862. this.lightMap = source.lightMap;
  13863. this.lightMapIntensity = source.lightMapIntensity;
  13864. this.aoMap = source.aoMap;
  13865. this.aoMapIntensity = source.aoMapIntensity;
  13866. this.emissive.copy( source.emissive );
  13867. this.emissiveMap = source.emissiveMap;
  13868. this.emissiveIntensity = source.emissiveIntensity;
  13869. this.bumpMap = source.bumpMap;
  13870. this.bumpScale = source.bumpScale;
  13871. this.normalMap = source.normalMap;
  13872. this.normalMapType = source.normalMapType;
  13873. this.normalScale.copy( source.normalScale );
  13874. this.displacementMap = source.displacementMap;
  13875. this.displacementScale = source.displacementScale;
  13876. this.displacementBias = source.displacementBias;
  13877. this.roughnessMap = source.roughnessMap;
  13878. this.metalnessMap = source.metalnessMap;
  13879. this.alphaMap = source.alphaMap;
  13880. this.envMap = source.envMap;
  13881. this.envMapRotation.copy( source.envMapRotation );
  13882. this.envMapIntensity = source.envMapIntensity;
  13883. this.wireframe = source.wireframe;
  13884. this.wireframeLinewidth = source.wireframeLinewidth;
  13885. this.wireframeLinecap = source.wireframeLinecap;
  13886. this.wireframeLinejoin = source.wireframeLinejoin;
  13887. this.flatShading = source.flatShading;
  13888. this.fog = source.fog;
  13889. return this;
  13890. }
  13891. }
  13892. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13893. constructor( parameters ) {
  13894. super();
  13895. this.isMeshPhysicalMaterial = true;
  13896. this.defines = {
  13897. 'STANDARD': '',
  13898. 'PHYSICAL': ''
  13899. };
  13900. this.type = 'MeshPhysicalMaterial';
  13901. this.anisotropyRotation = 0;
  13902. this.anisotropyMap = null;
  13903. this.clearcoatMap = null;
  13904. this.clearcoatRoughness = 0.0;
  13905. this.clearcoatRoughnessMap = null;
  13906. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13907. this.clearcoatNormalMap = null;
  13908. this.ior = 1.5;
  13909. Object.defineProperty( this, 'reflectivity', {
  13910. get: function () {
  13911. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13912. },
  13913. set: function ( reflectivity ) {
  13914. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13915. }
  13916. } );
  13917. this.iridescenceMap = null;
  13918. this.iridescenceIOR = 1.3;
  13919. this.iridescenceThicknessRange = [ 100, 400 ];
  13920. this.iridescenceThicknessMap = null;
  13921. this.sheenColor = new Color( 0x000000 );
  13922. this.sheenColorMap = null;
  13923. this.sheenRoughness = 1.0;
  13924. this.sheenRoughnessMap = null;
  13925. this.transmissionMap = null;
  13926. this.thickness = 0;
  13927. this.thicknessMap = null;
  13928. this.attenuationDistance = Infinity;
  13929. this.attenuationColor = new Color( 1, 1, 1 );
  13930. this.specularIntensity = 1.0;
  13931. this.specularIntensityMap = null;
  13932. this.specularColor = new Color( 1, 1, 1 );
  13933. this.specularColorMap = null;
  13934. this._anisotropy = 0;
  13935. this._clearcoat = 0;
  13936. this._dispersion = 0;
  13937. this._iridescence = 0;
  13938. this._sheen = 0.0;
  13939. this._transmission = 0;
  13940. this.setValues( parameters );
  13941. }
  13942. get anisotropy() {
  13943. return this._anisotropy;
  13944. }
  13945. set anisotropy( value ) {
  13946. if ( this._anisotropy > 0 !== value > 0 ) {
  13947. this.version ++;
  13948. }
  13949. this._anisotropy = value;
  13950. }
  13951. get clearcoat() {
  13952. return this._clearcoat;
  13953. }
  13954. set clearcoat( value ) {
  13955. if ( this._clearcoat > 0 !== value > 0 ) {
  13956. this.version ++;
  13957. }
  13958. this._clearcoat = value;
  13959. }
  13960. get iridescence() {
  13961. return this._iridescence;
  13962. }
  13963. set iridescence( value ) {
  13964. if ( this._iridescence > 0 !== value > 0 ) {
  13965. this.version ++;
  13966. }
  13967. this._iridescence = value;
  13968. }
  13969. get dispersion() {
  13970. return this._dispersion;
  13971. }
  13972. set dispersion( value ) {
  13973. if ( this._dispersion > 0 !== value > 0 ) {
  13974. this.version ++;
  13975. }
  13976. this._dispersion = value;
  13977. }
  13978. get sheen() {
  13979. return this._sheen;
  13980. }
  13981. set sheen( value ) {
  13982. if ( this._sheen > 0 !== value > 0 ) {
  13983. this.version ++;
  13984. }
  13985. this._sheen = value;
  13986. }
  13987. get transmission() {
  13988. return this._transmission;
  13989. }
  13990. set transmission( value ) {
  13991. if ( this._transmission > 0 !== value > 0 ) {
  13992. this.version ++;
  13993. }
  13994. this._transmission = value;
  13995. }
  13996. copy( source ) {
  13997. super.copy( source );
  13998. this.defines = {
  13999. 'STANDARD': '',
  14000. 'PHYSICAL': ''
  14001. };
  14002. this.anisotropy = source.anisotropy;
  14003. this.anisotropyRotation = source.anisotropyRotation;
  14004. this.anisotropyMap = source.anisotropyMap;
  14005. this.clearcoat = source.clearcoat;
  14006. this.clearcoatMap = source.clearcoatMap;
  14007. this.clearcoatRoughness = source.clearcoatRoughness;
  14008. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14009. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14010. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14011. this.dispersion = source.dispersion;
  14012. this.ior = source.ior;
  14013. this.iridescence = source.iridescence;
  14014. this.iridescenceMap = source.iridescenceMap;
  14015. this.iridescenceIOR = source.iridescenceIOR;
  14016. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14017. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14018. this.sheen = source.sheen;
  14019. this.sheenColor.copy( source.sheenColor );
  14020. this.sheenColorMap = source.sheenColorMap;
  14021. this.sheenRoughness = source.sheenRoughness;
  14022. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14023. this.transmission = source.transmission;
  14024. this.transmissionMap = source.transmissionMap;
  14025. this.thickness = source.thickness;
  14026. this.thicknessMap = source.thicknessMap;
  14027. this.attenuationDistance = source.attenuationDistance;
  14028. this.attenuationColor.copy( source.attenuationColor );
  14029. this.specularIntensity = source.specularIntensity;
  14030. this.specularIntensityMap = source.specularIntensityMap;
  14031. this.specularColor.copy( source.specularColor );
  14032. this.specularColorMap = source.specularColorMap;
  14033. return this;
  14034. }
  14035. }
  14036. class MeshPhongMaterial extends Material {
  14037. constructor( parameters ) {
  14038. super();
  14039. this.isMeshPhongMaterial = true;
  14040. this.type = 'MeshPhongMaterial';
  14041. this.color = new Color( 0xffffff ); // diffuse
  14042. this.specular = new Color( 0x111111 );
  14043. this.shininess = 30;
  14044. this.map = null;
  14045. this.lightMap = null;
  14046. this.lightMapIntensity = 1.0;
  14047. this.aoMap = null;
  14048. this.aoMapIntensity = 1.0;
  14049. this.emissive = new Color( 0x000000 );
  14050. this.emissiveIntensity = 1.0;
  14051. this.emissiveMap = null;
  14052. this.bumpMap = null;
  14053. this.bumpScale = 1;
  14054. this.normalMap = null;
  14055. this.normalMapType = TangentSpaceNormalMap;
  14056. this.normalScale = new Vector2( 1, 1 );
  14057. this.displacementMap = null;
  14058. this.displacementScale = 1;
  14059. this.displacementBias = 0;
  14060. this.specularMap = null;
  14061. this.alphaMap = null;
  14062. this.envMap = null;
  14063. this.envMapRotation = new Euler();
  14064. this.combine = MultiplyOperation;
  14065. this.reflectivity = 1;
  14066. this.refractionRatio = 0.98;
  14067. this.wireframe = false;
  14068. this.wireframeLinewidth = 1;
  14069. this.wireframeLinecap = 'round';
  14070. this.wireframeLinejoin = 'round';
  14071. this.flatShading = false;
  14072. this.fog = true;
  14073. this.setValues( parameters );
  14074. }
  14075. copy( source ) {
  14076. super.copy( source );
  14077. this.color.copy( source.color );
  14078. this.specular.copy( source.specular );
  14079. this.shininess = source.shininess;
  14080. this.map = source.map;
  14081. this.lightMap = source.lightMap;
  14082. this.lightMapIntensity = source.lightMapIntensity;
  14083. this.aoMap = source.aoMap;
  14084. this.aoMapIntensity = source.aoMapIntensity;
  14085. this.emissive.copy( source.emissive );
  14086. this.emissiveMap = source.emissiveMap;
  14087. this.emissiveIntensity = source.emissiveIntensity;
  14088. this.bumpMap = source.bumpMap;
  14089. this.bumpScale = source.bumpScale;
  14090. this.normalMap = source.normalMap;
  14091. this.normalMapType = source.normalMapType;
  14092. this.normalScale.copy( source.normalScale );
  14093. this.displacementMap = source.displacementMap;
  14094. this.displacementScale = source.displacementScale;
  14095. this.displacementBias = source.displacementBias;
  14096. this.specularMap = source.specularMap;
  14097. this.alphaMap = source.alphaMap;
  14098. this.envMap = source.envMap;
  14099. this.envMapRotation.copy( source.envMapRotation );
  14100. this.combine = source.combine;
  14101. this.reflectivity = source.reflectivity;
  14102. this.refractionRatio = source.refractionRatio;
  14103. this.wireframe = source.wireframe;
  14104. this.wireframeLinewidth = source.wireframeLinewidth;
  14105. this.wireframeLinecap = source.wireframeLinecap;
  14106. this.wireframeLinejoin = source.wireframeLinejoin;
  14107. this.flatShading = source.flatShading;
  14108. this.fog = source.fog;
  14109. return this;
  14110. }
  14111. }
  14112. class MeshToonMaterial extends Material {
  14113. constructor( parameters ) {
  14114. super();
  14115. this.isMeshToonMaterial = true;
  14116. this.defines = { 'TOON': '' };
  14117. this.type = 'MeshToonMaterial';
  14118. this.color = new Color( 0xffffff );
  14119. this.map = null;
  14120. this.gradientMap = null;
  14121. this.lightMap = null;
  14122. this.lightMapIntensity = 1.0;
  14123. this.aoMap = null;
  14124. this.aoMapIntensity = 1.0;
  14125. this.emissive = new Color( 0x000000 );
  14126. this.emissiveIntensity = 1.0;
  14127. this.emissiveMap = null;
  14128. this.bumpMap = null;
  14129. this.bumpScale = 1;
  14130. this.normalMap = null;
  14131. this.normalMapType = TangentSpaceNormalMap;
  14132. this.normalScale = new Vector2( 1, 1 );
  14133. this.displacementMap = null;
  14134. this.displacementScale = 1;
  14135. this.displacementBias = 0;
  14136. this.alphaMap = null;
  14137. this.wireframe = false;
  14138. this.wireframeLinewidth = 1;
  14139. this.wireframeLinecap = 'round';
  14140. this.wireframeLinejoin = 'round';
  14141. this.fog = true;
  14142. this.setValues( parameters );
  14143. }
  14144. copy( source ) {
  14145. super.copy( source );
  14146. this.color.copy( source.color );
  14147. this.map = source.map;
  14148. this.gradientMap = source.gradientMap;
  14149. this.lightMap = source.lightMap;
  14150. this.lightMapIntensity = source.lightMapIntensity;
  14151. this.aoMap = source.aoMap;
  14152. this.aoMapIntensity = source.aoMapIntensity;
  14153. this.emissive.copy( source.emissive );
  14154. this.emissiveMap = source.emissiveMap;
  14155. this.emissiveIntensity = source.emissiveIntensity;
  14156. this.bumpMap = source.bumpMap;
  14157. this.bumpScale = source.bumpScale;
  14158. this.normalMap = source.normalMap;
  14159. this.normalMapType = source.normalMapType;
  14160. this.normalScale.copy( source.normalScale );
  14161. this.displacementMap = source.displacementMap;
  14162. this.displacementScale = source.displacementScale;
  14163. this.displacementBias = source.displacementBias;
  14164. this.alphaMap = source.alphaMap;
  14165. this.wireframe = source.wireframe;
  14166. this.wireframeLinewidth = source.wireframeLinewidth;
  14167. this.wireframeLinecap = source.wireframeLinecap;
  14168. this.wireframeLinejoin = source.wireframeLinejoin;
  14169. this.fog = source.fog;
  14170. return this;
  14171. }
  14172. }
  14173. class MeshNormalMaterial extends Material {
  14174. constructor( parameters ) {
  14175. super();
  14176. this.isMeshNormalMaterial = true;
  14177. this.type = 'MeshNormalMaterial';
  14178. this.bumpMap = null;
  14179. this.bumpScale = 1;
  14180. this.normalMap = null;
  14181. this.normalMapType = TangentSpaceNormalMap;
  14182. this.normalScale = new Vector2( 1, 1 );
  14183. this.displacementMap = null;
  14184. this.displacementScale = 1;
  14185. this.displacementBias = 0;
  14186. this.wireframe = false;
  14187. this.wireframeLinewidth = 1;
  14188. this.flatShading = false;
  14189. this.setValues( parameters );
  14190. }
  14191. copy( source ) {
  14192. super.copy( source );
  14193. this.bumpMap = source.bumpMap;
  14194. this.bumpScale = source.bumpScale;
  14195. this.normalMap = source.normalMap;
  14196. this.normalMapType = source.normalMapType;
  14197. this.normalScale.copy( source.normalScale );
  14198. this.displacementMap = source.displacementMap;
  14199. this.displacementScale = source.displacementScale;
  14200. this.displacementBias = source.displacementBias;
  14201. this.wireframe = source.wireframe;
  14202. this.wireframeLinewidth = source.wireframeLinewidth;
  14203. this.flatShading = source.flatShading;
  14204. return this;
  14205. }
  14206. }
  14207. class MeshLambertMaterial extends Material {
  14208. constructor( parameters ) {
  14209. super();
  14210. this.isMeshLambertMaterial = true;
  14211. this.type = 'MeshLambertMaterial';
  14212. this.color = new Color( 0xffffff ); // diffuse
  14213. this.map = null;
  14214. this.lightMap = null;
  14215. this.lightMapIntensity = 1.0;
  14216. this.aoMap = null;
  14217. this.aoMapIntensity = 1.0;
  14218. this.emissive = new Color( 0x000000 );
  14219. this.emissiveIntensity = 1.0;
  14220. this.emissiveMap = null;
  14221. this.bumpMap = null;
  14222. this.bumpScale = 1;
  14223. this.normalMap = null;
  14224. this.normalMapType = TangentSpaceNormalMap;
  14225. this.normalScale = new Vector2( 1, 1 );
  14226. this.displacementMap = null;
  14227. this.displacementScale = 1;
  14228. this.displacementBias = 0;
  14229. this.specularMap = null;
  14230. this.alphaMap = null;
  14231. this.envMap = null;
  14232. this.envMapRotation = new Euler();
  14233. this.combine = MultiplyOperation;
  14234. this.reflectivity = 1;
  14235. this.refractionRatio = 0.98;
  14236. this.wireframe = false;
  14237. this.wireframeLinewidth = 1;
  14238. this.wireframeLinecap = 'round';
  14239. this.wireframeLinejoin = 'round';
  14240. this.flatShading = false;
  14241. this.fog = true;
  14242. this.setValues( parameters );
  14243. }
  14244. copy( source ) {
  14245. super.copy( source );
  14246. this.color.copy( source.color );
  14247. this.map = source.map;
  14248. this.lightMap = source.lightMap;
  14249. this.lightMapIntensity = source.lightMapIntensity;
  14250. this.aoMap = source.aoMap;
  14251. this.aoMapIntensity = source.aoMapIntensity;
  14252. this.emissive.copy( source.emissive );
  14253. this.emissiveMap = source.emissiveMap;
  14254. this.emissiveIntensity = source.emissiveIntensity;
  14255. this.bumpMap = source.bumpMap;
  14256. this.bumpScale = source.bumpScale;
  14257. this.normalMap = source.normalMap;
  14258. this.normalMapType = source.normalMapType;
  14259. this.normalScale.copy( source.normalScale );
  14260. this.displacementMap = source.displacementMap;
  14261. this.displacementScale = source.displacementScale;
  14262. this.displacementBias = source.displacementBias;
  14263. this.specularMap = source.specularMap;
  14264. this.alphaMap = source.alphaMap;
  14265. this.envMap = source.envMap;
  14266. this.envMapRotation.copy( source.envMapRotation );
  14267. this.combine = source.combine;
  14268. this.reflectivity = source.reflectivity;
  14269. this.refractionRatio = source.refractionRatio;
  14270. this.wireframe = source.wireframe;
  14271. this.wireframeLinewidth = source.wireframeLinewidth;
  14272. this.wireframeLinecap = source.wireframeLinecap;
  14273. this.wireframeLinejoin = source.wireframeLinejoin;
  14274. this.flatShading = source.flatShading;
  14275. this.fog = source.fog;
  14276. return this;
  14277. }
  14278. }
  14279. class MeshDepthMaterial extends Material {
  14280. constructor( parameters ) {
  14281. super();
  14282. this.isMeshDepthMaterial = true;
  14283. this.type = 'MeshDepthMaterial';
  14284. this.depthPacking = BasicDepthPacking;
  14285. this.map = null;
  14286. this.alphaMap = null;
  14287. this.displacementMap = null;
  14288. this.displacementScale = 1;
  14289. this.displacementBias = 0;
  14290. this.wireframe = false;
  14291. this.wireframeLinewidth = 1;
  14292. this.setValues( parameters );
  14293. }
  14294. copy( source ) {
  14295. super.copy( source );
  14296. this.depthPacking = source.depthPacking;
  14297. this.map = source.map;
  14298. this.alphaMap = source.alphaMap;
  14299. this.displacementMap = source.displacementMap;
  14300. this.displacementScale = source.displacementScale;
  14301. this.displacementBias = source.displacementBias;
  14302. this.wireframe = source.wireframe;
  14303. this.wireframeLinewidth = source.wireframeLinewidth;
  14304. return this;
  14305. }
  14306. }
  14307. class MeshDistanceMaterial extends Material {
  14308. constructor( parameters ) {
  14309. super();
  14310. this.isMeshDistanceMaterial = true;
  14311. this.type = 'MeshDistanceMaterial';
  14312. this.map = null;
  14313. this.alphaMap = null;
  14314. this.displacementMap = null;
  14315. this.displacementScale = 1;
  14316. this.displacementBias = 0;
  14317. this.setValues( parameters );
  14318. }
  14319. copy( source ) {
  14320. super.copy( source );
  14321. this.map = source.map;
  14322. this.alphaMap = source.alphaMap;
  14323. this.displacementMap = source.displacementMap;
  14324. this.displacementScale = source.displacementScale;
  14325. this.displacementBias = source.displacementBias;
  14326. return this;
  14327. }
  14328. }
  14329. class MeshMatcapMaterial extends Material {
  14330. constructor( parameters ) {
  14331. super();
  14332. this.isMeshMatcapMaterial = true;
  14333. this.defines = { 'MATCAP': '' };
  14334. this.type = 'MeshMatcapMaterial';
  14335. this.color = new Color( 0xffffff ); // diffuse
  14336. this.matcap = null;
  14337. this.map = null;
  14338. this.bumpMap = null;
  14339. this.bumpScale = 1;
  14340. this.normalMap = null;
  14341. this.normalMapType = TangentSpaceNormalMap;
  14342. this.normalScale = new Vector2( 1, 1 );
  14343. this.displacementMap = null;
  14344. this.displacementScale = 1;
  14345. this.displacementBias = 0;
  14346. this.alphaMap = null;
  14347. this.flatShading = false;
  14348. this.fog = true;
  14349. this.setValues( parameters );
  14350. }
  14351. copy( source ) {
  14352. super.copy( source );
  14353. this.defines = { 'MATCAP': '' };
  14354. this.color.copy( source.color );
  14355. this.matcap = source.matcap;
  14356. this.map = source.map;
  14357. this.bumpMap = source.bumpMap;
  14358. this.bumpScale = source.bumpScale;
  14359. this.normalMap = source.normalMap;
  14360. this.normalMapType = source.normalMapType;
  14361. this.normalScale.copy( source.normalScale );
  14362. this.displacementMap = source.displacementMap;
  14363. this.displacementScale = source.displacementScale;
  14364. this.displacementBias = source.displacementBias;
  14365. this.alphaMap = source.alphaMap;
  14366. this.flatShading = source.flatShading;
  14367. this.fog = source.fog;
  14368. return this;
  14369. }
  14370. }
  14371. class LineDashedMaterial extends LineBasicMaterial {
  14372. constructor( parameters ) {
  14373. super();
  14374. this.isLineDashedMaterial = true;
  14375. this.type = 'LineDashedMaterial';
  14376. this.scale = 1;
  14377. this.dashSize = 3;
  14378. this.gapSize = 1;
  14379. this.setValues( parameters );
  14380. }
  14381. copy( source ) {
  14382. super.copy( source );
  14383. this.scale = source.scale;
  14384. this.dashSize = source.dashSize;
  14385. this.gapSize = source.gapSize;
  14386. return this;
  14387. }
  14388. }
  14389. // converts an array to a specific type
  14390. function convertArray( array, type, forceClone ) {
  14391. if ( ! array || // let 'undefined' and 'null' pass
  14392. ! forceClone && array.constructor === type ) return array;
  14393. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14394. return new type( array ); // create typed array
  14395. }
  14396. return Array.prototype.slice.call( array ); // create Array
  14397. }
  14398. function isTypedArray( object ) {
  14399. return ArrayBuffer.isView( object ) &&
  14400. ! ( object instanceof DataView );
  14401. }
  14402. // returns an array by which times and values can be sorted
  14403. function getKeyframeOrder( times ) {
  14404. function compareTime( i, j ) {
  14405. return times[ i ] - times[ j ];
  14406. }
  14407. const n = times.length;
  14408. const result = new Array( n );
  14409. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14410. result.sort( compareTime );
  14411. return result;
  14412. }
  14413. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14414. function sortedArray( values, stride, order ) {
  14415. const nValues = values.length;
  14416. const result = new values.constructor( nValues );
  14417. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14418. const srcOffset = order[ i ] * stride;
  14419. for ( let j = 0; j !== stride; ++ j ) {
  14420. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14421. }
  14422. }
  14423. return result;
  14424. }
  14425. // function for parsing AOS keyframe formats
  14426. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14427. let i = 1, key = jsonKeys[ 0 ];
  14428. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14429. key = jsonKeys[ i ++ ];
  14430. }
  14431. if ( key === undefined ) return; // no data
  14432. let value = key[ valuePropertyName ];
  14433. if ( value === undefined ) return; // no data
  14434. if ( Array.isArray( value ) ) {
  14435. do {
  14436. value = key[ valuePropertyName ];
  14437. if ( value !== undefined ) {
  14438. times.push( key.time );
  14439. values.push.apply( values, value ); // push all elements
  14440. }
  14441. key = jsonKeys[ i ++ ];
  14442. } while ( key !== undefined );
  14443. } else if ( value.toArray !== undefined ) {
  14444. // ...assume THREE.Math-ish
  14445. do {
  14446. value = key[ valuePropertyName ];
  14447. if ( value !== undefined ) {
  14448. times.push( key.time );
  14449. value.toArray( values, values.length );
  14450. }
  14451. key = jsonKeys[ i ++ ];
  14452. } while ( key !== undefined );
  14453. } else {
  14454. // otherwise push as-is
  14455. do {
  14456. value = key[ valuePropertyName ];
  14457. if ( value !== undefined ) {
  14458. times.push( key.time );
  14459. values.push( value );
  14460. }
  14461. key = jsonKeys[ i ++ ];
  14462. } while ( key !== undefined );
  14463. }
  14464. }
  14465. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14466. const clip = sourceClip.clone();
  14467. clip.name = name;
  14468. const tracks = [];
  14469. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14470. const track = clip.tracks[ i ];
  14471. const valueSize = track.getValueSize();
  14472. const times = [];
  14473. const values = [];
  14474. for ( let j = 0; j < track.times.length; ++ j ) {
  14475. const frame = track.times[ j ] * fps;
  14476. if ( frame < startFrame || frame >= endFrame ) continue;
  14477. times.push( track.times[ j ] );
  14478. for ( let k = 0; k < valueSize; ++ k ) {
  14479. values.push( track.values[ j * valueSize + k ] );
  14480. }
  14481. }
  14482. if ( times.length === 0 ) continue;
  14483. track.times = convertArray( times, track.times.constructor );
  14484. track.values = convertArray( values, track.values.constructor );
  14485. tracks.push( track );
  14486. }
  14487. clip.tracks = tracks;
  14488. // find minimum .times value across all tracks in the trimmed clip
  14489. let minStartTime = Infinity;
  14490. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14491. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14492. minStartTime = clip.tracks[ i ].times[ 0 ];
  14493. }
  14494. }
  14495. // shift all tracks such that clip begins at t=0
  14496. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14497. clip.tracks[ i ].shift( - 1 * minStartTime );
  14498. }
  14499. clip.resetDuration();
  14500. return clip;
  14501. }
  14502. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14503. if ( fps <= 0 ) fps = 30;
  14504. const numTracks = referenceClip.tracks.length;
  14505. const referenceTime = referenceFrame / fps;
  14506. // Make each track's values relative to the values at the reference frame
  14507. for ( let i = 0; i < numTracks; ++ i ) {
  14508. const referenceTrack = referenceClip.tracks[ i ];
  14509. const referenceTrackType = referenceTrack.ValueTypeName;
  14510. // Skip this track if it's non-numeric
  14511. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14512. // Find the track in the target clip whose name and type matches the reference track
  14513. const targetTrack = targetClip.tracks.find( function ( track ) {
  14514. return track.name === referenceTrack.name
  14515. && track.ValueTypeName === referenceTrackType;
  14516. } );
  14517. if ( targetTrack === undefined ) continue;
  14518. let referenceOffset = 0;
  14519. const referenceValueSize = referenceTrack.getValueSize();
  14520. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14521. referenceOffset = referenceValueSize / 3;
  14522. }
  14523. let targetOffset = 0;
  14524. const targetValueSize = targetTrack.getValueSize();
  14525. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14526. targetOffset = targetValueSize / 3;
  14527. }
  14528. const lastIndex = referenceTrack.times.length - 1;
  14529. let referenceValue;
  14530. // Find the value to subtract out of the track
  14531. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14532. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14533. const startIndex = referenceOffset;
  14534. const endIndex = referenceValueSize - referenceOffset;
  14535. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14536. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14537. // Reference frame is after the last keyframe, so just use the last keyframe
  14538. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14539. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14540. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14541. } else {
  14542. // Interpolate to the reference value
  14543. const interpolant = referenceTrack.createInterpolant();
  14544. const startIndex = referenceOffset;
  14545. const endIndex = referenceValueSize - referenceOffset;
  14546. interpolant.evaluate( referenceTime );
  14547. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14548. }
  14549. // Conjugate the quaternion
  14550. if ( referenceTrackType === 'quaternion' ) {
  14551. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14552. referenceQuat.toArray( referenceValue );
  14553. }
  14554. // Subtract the reference value from all of the track values
  14555. const numTimes = targetTrack.times.length;
  14556. for ( let j = 0; j < numTimes; ++ j ) {
  14557. const valueStart = j * targetValueSize + targetOffset;
  14558. if ( referenceTrackType === 'quaternion' ) {
  14559. // Multiply the conjugate for quaternion track types
  14560. Quaternion.multiplyQuaternionsFlat(
  14561. targetTrack.values,
  14562. valueStart,
  14563. referenceValue,
  14564. 0,
  14565. targetTrack.values,
  14566. valueStart
  14567. );
  14568. } else {
  14569. const valueEnd = targetValueSize - targetOffset * 2;
  14570. // Subtract each value for all other numeric track types
  14571. for ( let k = 0; k < valueEnd; ++ k ) {
  14572. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14573. }
  14574. }
  14575. }
  14576. }
  14577. targetClip.blendMode = AdditiveAnimationBlendMode;
  14578. return targetClip;
  14579. }
  14580. const AnimationUtils = {
  14581. convertArray: convertArray,
  14582. isTypedArray: isTypedArray,
  14583. getKeyframeOrder: getKeyframeOrder,
  14584. sortedArray: sortedArray,
  14585. flattenJSON: flattenJSON,
  14586. subclip: subclip,
  14587. makeClipAdditive: makeClipAdditive
  14588. };
  14589. /**
  14590. * Abstract base class of interpolants over parametric samples.
  14591. *
  14592. * The parameter domain is one dimensional, typically the time or a path
  14593. * along a curve defined by the data.
  14594. *
  14595. * The sample values can have any dimensionality and derived classes may
  14596. * apply special interpretations to the data.
  14597. *
  14598. * This class provides the interval seek in a Template Method, deferring
  14599. * the actual interpolation to derived classes.
  14600. *
  14601. * Time complexity is O(1) for linear access crossing at most two points
  14602. * and O(log N) for random access, where N is the number of positions.
  14603. *
  14604. * References:
  14605. *
  14606. * http://www.oodesign.com/template-method-pattern.html
  14607. *
  14608. */
  14609. class Interpolant {
  14610. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14611. this.parameterPositions = parameterPositions;
  14612. this._cachedIndex = 0;
  14613. this.resultBuffer = resultBuffer !== undefined ?
  14614. resultBuffer : new sampleValues.constructor( sampleSize );
  14615. this.sampleValues = sampleValues;
  14616. this.valueSize = sampleSize;
  14617. this.settings = null;
  14618. this.DefaultSettings_ = {};
  14619. }
  14620. evaluate( t ) {
  14621. const pp = this.parameterPositions;
  14622. let i1 = this._cachedIndex,
  14623. t1 = pp[ i1 ],
  14624. t0 = pp[ i1 - 1 ];
  14625. validate_interval: {
  14626. seek: {
  14627. let right;
  14628. linear_scan: {
  14629. //- See http://jsperf.com/comparison-to-undefined/3
  14630. //- slower code:
  14631. //-
  14632. //- if ( t >= t1 || t1 === undefined ) {
  14633. forward_scan: if ( ! ( t < t1 ) ) {
  14634. for ( let giveUpAt = i1 + 2; ; ) {
  14635. if ( t1 === undefined ) {
  14636. if ( t < t0 ) break forward_scan;
  14637. // after end
  14638. i1 = pp.length;
  14639. this._cachedIndex = i1;
  14640. return this.copySampleValue_( i1 - 1 );
  14641. }
  14642. if ( i1 === giveUpAt ) break; // this loop
  14643. t0 = t1;
  14644. t1 = pp[ ++ i1 ];
  14645. if ( t < t1 ) {
  14646. // we have arrived at the sought interval
  14647. break seek;
  14648. }
  14649. }
  14650. // prepare binary search on the right side of the index
  14651. right = pp.length;
  14652. break linear_scan;
  14653. }
  14654. //- slower code:
  14655. //- if ( t < t0 || t0 === undefined ) {
  14656. if ( ! ( t >= t0 ) ) {
  14657. // looping?
  14658. const t1global = pp[ 1 ];
  14659. if ( t < t1global ) {
  14660. i1 = 2; // + 1, using the scan for the details
  14661. t0 = t1global;
  14662. }
  14663. // linear reverse scan
  14664. for ( let giveUpAt = i1 - 2; ; ) {
  14665. if ( t0 === undefined ) {
  14666. // before start
  14667. this._cachedIndex = 0;
  14668. return this.copySampleValue_( 0 );
  14669. }
  14670. if ( i1 === giveUpAt ) break; // this loop
  14671. t1 = t0;
  14672. t0 = pp[ -- i1 - 1 ];
  14673. if ( t >= t0 ) {
  14674. // we have arrived at the sought interval
  14675. break seek;
  14676. }
  14677. }
  14678. // prepare binary search on the left side of the index
  14679. right = i1;
  14680. i1 = 0;
  14681. break linear_scan;
  14682. }
  14683. // the interval is valid
  14684. break validate_interval;
  14685. } // linear scan
  14686. // binary search
  14687. while ( i1 < right ) {
  14688. const mid = ( i1 + right ) >>> 1;
  14689. if ( t < pp[ mid ] ) {
  14690. right = mid;
  14691. } else {
  14692. i1 = mid + 1;
  14693. }
  14694. }
  14695. t1 = pp[ i1 ];
  14696. t0 = pp[ i1 - 1 ];
  14697. // check boundary cases, again
  14698. if ( t0 === undefined ) {
  14699. this._cachedIndex = 0;
  14700. return this.copySampleValue_( 0 );
  14701. }
  14702. if ( t1 === undefined ) {
  14703. i1 = pp.length;
  14704. this._cachedIndex = i1;
  14705. return this.copySampleValue_( i1 - 1 );
  14706. }
  14707. } // seek
  14708. this._cachedIndex = i1;
  14709. this.intervalChanged_( i1, t0, t1 );
  14710. } // validate_interval
  14711. return this.interpolate_( i1, t0, t, t1 );
  14712. }
  14713. getSettings_() {
  14714. return this.settings || this.DefaultSettings_;
  14715. }
  14716. copySampleValue_( index ) {
  14717. // copies a sample value to the result buffer
  14718. const result = this.resultBuffer,
  14719. values = this.sampleValues,
  14720. stride = this.valueSize,
  14721. offset = index * stride;
  14722. for ( let i = 0; i !== stride; ++ i ) {
  14723. result[ i ] = values[ offset + i ];
  14724. }
  14725. return result;
  14726. }
  14727. // Template methods for derived classes:
  14728. interpolate_( /* i1, t0, t, t1 */ ) {
  14729. throw new Error( 'call to abstract method' );
  14730. // implementations shall return this.resultBuffer
  14731. }
  14732. intervalChanged_( /* i1, t0, t1 */ ) {
  14733. // empty
  14734. }
  14735. }
  14736. /**
  14737. * Fast and simple cubic spline interpolant.
  14738. *
  14739. * It was derived from a Hermitian construction setting the first derivative
  14740. * at each sample position to the linear slope between neighboring positions
  14741. * over their parameter interval.
  14742. */
  14743. class CubicInterpolant extends Interpolant {
  14744. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14745. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14746. this._weightPrev = - 0;
  14747. this._offsetPrev = - 0;
  14748. this._weightNext = - 0;
  14749. this._offsetNext = - 0;
  14750. this.DefaultSettings_ = {
  14751. endingStart: ZeroCurvatureEnding,
  14752. endingEnd: ZeroCurvatureEnding
  14753. };
  14754. }
  14755. intervalChanged_( i1, t0, t1 ) {
  14756. const pp = this.parameterPositions;
  14757. let iPrev = i1 - 2,
  14758. iNext = i1 + 1,
  14759. tPrev = pp[ iPrev ],
  14760. tNext = pp[ iNext ];
  14761. if ( tPrev === undefined ) {
  14762. switch ( this.getSettings_().endingStart ) {
  14763. case ZeroSlopeEnding:
  14764. // f'(t0) = 0
  14765. iPrev = i1;
  14766. tPrev = 2 * t0 - t1;
  14767. break;
  14768. case WrapAroundEnding:
  14769. // use the other end of the curve
  14770. iPrev = pp.length - 2;
  14771. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14772. break;
  14773. default: // ZeroCurvatureEnding
  14774. // f''(t0) = 0 a.k.a. Natural Spline
  14775. iPrev = i1;
  14776. tPrev = t1;
  14777. }
  14778. }
  14779. if ( tNext === undefined ) {
  14780. switch ( this.getSettings_().endingEnd ) {
  14781. case ZeroSlopeEnding:
  14782. // f'(tN) = 0
  14783. iNext = i1;
  14784. tNext = 2 * t1 - t0;
  14785. break;
  14786. case WrapAroundEnding:
  14787. // use the other end of the curve
  14788. iNext = 1;
  14789. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14790. break;
  14791. default: // ZeroCurvatureEnding
  14792. // f''(tN) = 0, a.k.a. Natural Spline
  14793. iNext = i1 - 1;
  14794. tNext = t0;
  14795. }
  14796. }
  14797. const halfDt = ( t1 - t0 ) * 0.5,
  14798. stride = this.valueSize;
  14799. this._weightPrev = halfDt / ( t0 - tPrev );
  14800. this._weightNext = halfDt / ( tNext - t1 );
  14801. this._offsetPrev = iPrev * stride;
  14802. this._offsetNext = iNext * stride;
  14803. }
  14804. interpolate_( i1, t0, t, t1 ) {
  14805. const result = this.resultBuffer,
  14806. values = this.sampleValues,
  14807. stride = this.valueSize,
  14808. o1 = i1 * stride, o0 = o1 - stride,
  14809. oP = this._offsetPrev, oN = this._offsetNext,
  14810. wP = this._weightPrev, wN = this._weightNext,
  14811. p = ( t - t0 ) / ( t1 - t0 ),
  14812. pp = p * p,
  14813. ppp = pp * p;
  14814. // evaluate polynomials
  14815. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14816. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14817. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14818. const sN = wN * ppp - wN * pp;
  14819. // combine data linearly
  14820. for ( let i = 0; i !== stride; ++ i ) {
  14821. result[ i ] =
  14822. sP * values[ oP + i ] +
  14823. s0 * values[ o0 + i ] +
  14824. s1 * values[ o1 + i ] +
  14825. sN * values[ oN + i ];
  14826. }
  14827. return result;
  14828. }
  14829. }
  14830. class LinearInterpolant extends Interpolant {
  14831. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14832. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14833. }
  14834. interpolate_( i1, t0, t, t1 ) {
  14835. const result = this.resultBuffer,
  14836. values = this.sampleValues,
  14837. stride = this.valueSize,
  14838. offset1 = i1 * stride,
  14839. offset0 = offset1 - stride,
  14840. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14841. weight0 = 1 - weight1;
  14842. for ( let i = 0; i !== stride; ++ i ) {
  14843. result[ i ] =
  14844. values[ offset0 + i ] * weight0 +
  14845. values[ offset1 + i ] * weight1;
  14846. }
  14847. return result;
  14848. }
  14849. }
  14850. /**
  14851. *
  14852. * Interpolant that evaluates to the sample value at the position preceding
  14853. * the parameter.
  14854. */
  14855. class DiscreteInterpolant extends Interpolant {
  14856. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14857. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14858. }
  14859. interpolate_( i1 /*, t0, t, t1 */ ) {
  14860. return this.copySampleValue_( i1 - 1 );
  14861. }
  14862. }
  14863. class KeyframeTrack {
  14864. constructor( name, times, values, interpolation ) {
  14865. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14866. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14867. this.name = name;
  14868. this.times = convertArray( times, this.TimeBufferType );
  14869. this.values = convertArray( values, this.ValueBufferType );
  14870. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14871. }
  14872. // Serialization (in static context, because of constructor invocation
  14873. // and automatic invocation of .toJSON):
  14874. static toJSON( track ) {
  14875. const trackType = track.constructor;
  14876. let json;
  14877. // derived classes can define a static toJSON method
  14878. if ( trackType.toJSON !== this.toJSON ) {
  14879. json = trackType.toJSON( track );
  14880. } else {
  14881. // by default, we assume the data can be serialized as-is
  14882. json = {
  14883. 'name': track.name,
  14884. 'times': convertArray( track.times, Array ),
  14885. 'values': convertArray( track.values, Array )
  14886. };
  14887. const interpolation = track.getInterpolation();
  14888. if ( interpolation !== track.DefaultInterpolation ) {
  14889. json.interpolation = interpolation;
  14890. }
  14891. }
  14892. json.type = track.ValueTypeName; // mandatory
  14893. return json;
  14894. }
  14895. InterpolantFactoryMethodDiscrete( result ) {
  14896. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14897. }
  14898. InterpolantFactoryMethodLinear( result ) {
  14899. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14900. }
  14901. InterpolantFactoryMethodSmooth( result ) {
  14902. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14903. }
  14904. setInterpolation( interpolation ) {
  14905. let factoryMethod;
  14906. switch ( interpolation ) {
  14907. case InterpolateDiscrete:
  14908. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14909. break;
  14910. case InterpolateLinear:
  14911. factoryMethod = this.InterpolantFactoryMethodLinear;
  14912. break;
  14913. case InterpolateSmooth:
  14914. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14915. break;
  14916. }
  14917. if ( factoryMethod === undefined ) {
  14918. const message = 'unsupported interpolation for ' +
  14919. this.ValueTypeName + ' keyframe track named ' + this.name;
  14920. if ( this.createInterpolant === undefined ) {
  14921. // fall back to default, unless the default itself is messed up
  14922. if ( interpolation !== this.DefaultInterpolation ) {
  14923. this.setInterpolation( this.DefaultInterpolation );
  14924. } else {
  14925. throw new Error( message ); // fatal, in this case
  14926. }
  14927. }
  14928. console.warn( 'THREE.KeyframeTrack:', message );
  14929. return this;
  14930. }
  14931. this.createInterpolant = factoryMethod;
  14932. return this;
  14933. }
  14934. getInterpolation() {
  14935. switch ( this.createInterpolant ) {
  14936. case this.InterpolantFactoryMethodDiscrete:
  14937. return InterpolateDiscrete;
  14938. case this.InterpolantFactoryMethodLinear:
  14939. return InterpolateLinear;
  14940. case this.InterpolantFactoryMethodSmooth:
  14941. return InterpolateSmooth;
  14942. }
  14943. }
  14944. getValueSize() {
  14945. return this.values.length / this.times.length;
  14946. }
  14947. // move all keyframes either forwards or backwards in time
  14948. shift( timeOffset ) {
  14949. if ( timeOffset !== 0.0 ) {
  14950. const times = this.times;
  14951. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14952. times[ i ] += timeOffset;
  14953. }
  14954. }
  14955. return this;
  14956. }
  14957. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14958. scale( timeScale ) {
  14959. if ( timeScale !== 1.0 ) {
  14960. const times = this.times;
  14961. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14962. times[ i ] *= timeScale;
  14963. }
  14964. }
  14965. return this;
  14966. }
  14967. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  14968. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  14969. trim( startTime, endTime ) {
  14970. const times = this.times,
  14971. nKeys = times.length;
  14972. let from = 0,
  14973. to = nKeys - 1;
  14974. while ( from !== nKeys && times[ from ] < startTime ) {
  14975. ++ from;
  14976. }
  14977. while ( to !== - 1 && times[ to ] > endTime ) {
  14978. -- to;
  14979. }
  14980. ++ to; // inclusive -> exclusive bound
  14981. if ( from !== 0 || to !== nKeys ) {
  14982. // empty tracks are forbidden, so keep at least one keyframe
  14983. if ( from >= to ) {
  14984. to = Math.max( to, 1 );
  14985. from = to - 1;
  14986. }
  14987. const stride = this.getValueSize();
  14988. this.times = times.slice( from, to );
  14989. this.values = this.values.slice( from * stride, to * stride );
  14990. }
  14991. return this;
  14992. }
  14993. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  14994. validate() {
  14995. let valid = true;
  14996. const valueSize = this.getValueSize();
  14997. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  14998. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  14999. valid = false;
  15000. }
  15001. const times = this.times,
  15002. values = this.values,
  15003. nKeys = times.length;
  15004. if ( nKeys === 0 ) {
  15005. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15006. valid = false;
  15007. }
  15008. let prevTime = null;
  15009. for ( let i = 0; i !== nKeys; i ++ ) {
  15010. const currTime = times[ i ];
  15011. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15012. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15013. valid = false;
  15014. break;
  15015. }
  15016. if ( prevTime !== null && prevTime > currTime ) {
  15017. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15018. valid = false;
  15019. break;
  15020. }
  15021. prevTime = currTime;
  15022. }
  15023. if ( values !== undefined ) {
  15024. if ( isTypedArray( values ) ) {
  15025. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15026. const value = values[ i ];
  15027. if ( isNaN( value ) ) {
  15028. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15029. valid = false;
  15030. break;
  15031. }
  15032. }
  15033. }
  15034. }
  15035. return valid;
  15036. }
  15037. // removes equivalent sequential keys as common in morph target sequences
  15038. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15039. optimize() {
  15040. // times or values may be shared with other tracks, so overwriting is unsafe
  15041. const times = this.times.slice(),
  15042. values = this.values.slice(),
  15043. stride = this.getValueSize(),
  15044. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15045. lastIndex = times.length - 1;
  15046. let writeIndex = 1;
  15047. for ( let i = 1; i < lastIndex; ++ i ) {
  15048. let keep = false;
  15049. const time = times[ i ];
  15050. const timeNext = times[ i + 1 ];
  15051. // remove adjacent keyframes scheduled at the same time
  15052. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15053. if ( ! smoothInterpolation ) {
  15054. // remove unnecessary keyframes same as their neighbors
  15055. const offset = i * stride,
  15056. offsetP = offset - stride,
  15057. offsetN = offset + stride;
  15058. for ( let j = 0; j !== stride; ++ j ) {
  15059. const value = values[ offset + j ];
  15060. if ( value !== values[ offsetP + j ] ||
  15061. value !== values[ offsetN + j ] ) {
  15062. keep = true;
  15063. break;
  15064. }
  15065. }
  15066. } else {
  15067. keep = true;
  15068. }
  15069. }
  15070. // in-place compaction
  15071. if ( keep ) {
  15072. if ( i !== writeIndex ) {
  15073. times[ writeIndex ] = times[ i ];
  15074. const readOffset = i * stride,
  15075. writeOffset = writeIndex * stride;
  15076. for ( let j = 0; j !== stride; ++ j ) {
  15077. values[ writeOffset + j ] = values[ readOffset + j ];
  15078. }
  15079. }
  15080. ++ writeIndex;
  15081. }
  15082. }
  15083. // flush last keyframe (compaction looks ahead)
  15084. if ( lastIndex > 0 ) {
  15085. times[ writeIndex ] = times[ lastIndex ];
  15086. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15087. values[ writeOffset + j ] = values[ readOffset + j ];
  15088. }
  15089. ++ writeIndex;
  15090. }
  15091. if ( writeIndex !== times.length ) {
  15092. this.times = times.slice( 0, writeIndex );
  15093. this.values = values.slice( 0, writeIndex * stride );
  15094. } else {
  15095. this.times = times;
  15096. this.values = values;
  15097. }
  15098. return this;
  15099. }
  15100. clone() {
  15101. const times = this.times.slice();
  15102. const values = this.values.slice();
  15103. const TypedKeyframeTrack = this.constructor;
  15104. const track = new TypedKeyframeTrack( this.name, times, values );
  15105. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15106. track.createInterpolant = this.createInterpolant;
  15107. return track;
  15108. }
  15109. }
  15110. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15111. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15112. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15113. /**
  15114. * A Track of Boolean keyframe values.
  15115. */
  15116. class BooleanKeyframeTrack extends KeyframeTrack {
  15117. // No interpolation parameter because only InterpolateDiscrete is valid.
  15118. constructor( name, times, values ) {
  15119. super( name, times, values );
  15120. }
  15121. }
  15122. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15123. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15124. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15125. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15126. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15127. /**
  15128. * A Track of keyframe values that represent color.
  15129. */
  15130. class ColorKeyframeTrack extends KeyframeTrack {}
  15131. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15132. /**
  15133. * A Track of numeric keyframe values.
  15134. */
  15135. class NumberKeyframeTrack extends KeyframeTrack {}
  15136. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15137. /**
  15138. * Spherical linear unit quaternion interpolant.
  15139. */
  15140. class QuaternionLinearInterpolant extends Interpolant {
  15141. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15142. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15143. }
  15144. interpolate_( i1, t0, t, t1 ) {
  15145. const result = this.resultBuffer,
  15146. values = this.sampleValues,
  15147. stride = this.valueSize,
  15148. alpha = ( t - t0 ) / ( t1 - t0 );
  15149. let offset = i1 * stride;
  15150. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15151. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15152. }
  15153. return result;
  15154. }
  15155. }
  15156. /**
  15157. * A Track of quaternion keyframe values.
  15158. */
  15159. class QuaternionKeyframeTrack extends KeyframeTrack {
  15160. InterpolantFactoryMethodLinear( result ) {
  15161. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15162. }
  15163. }
  15164. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15165. // ValueBufferType is inherited
  15166. // DefaultInterpolation is inherited;
  15167. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15168. /**
  15169. * A Track that interpolates Strings
  15170. */
  15171. class StringKeyframeTrack extends KeyframeTrack {
  15172. // No interpolation parameter because only InterpolateDiscrete is valid.
  15173. constructor( name, times, values ) {
  15174. super( name, times, values );
  15175. }
  15176. }
  15177. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15178. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15179. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15180. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15181. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15182. /**
  15183. * A Track of vectored keyframe values.
  15184. */
  15185. class VectorKeyframeTrack extends KeyframeTrack {}
  15186. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15187. class AnimationClip {
  15188. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15189. this.name = name;
  15190. this.tracks = tracks;
  15191. this.duration = duration;
  15192. this.blendMode = blendMode;
  15193. this.uuid = generateUUID();
  15194. // this means it should figure out its duration by scanning the tracks
  15195. if ( this.duration < 0 ) {
  15196. this.resetDuration();
  15197. }
  15198. }
  15199. static parse( json ) {
  15200. const tracks = [],
  15201. jsonTracks = json.tracks,
  15202. frameTime = 1.0 / ( json.fps || 1.0 );
  15203. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15204. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15205. }
  15206. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15207. clip.uuid = json.uuid;
  15208. return clip;
  15209. }
  15210. static toJSON( clip ) {
  15211. const tracks = [],
  15212. clipTracks = clip.tracks;
  15213. const json = {
  15214. 'name': clip.name,
  15215. 'duration': clip.duration,
  15216. 'tracks': tracks,
  15217. 'uuid': clip.uuid,
  15218. 'blendMode': clip.blendMode
  15219. };
  15220. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15221. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15222. }
  15223. return json;
  15224. }
  15225. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15226. const numMorphTargets = morphTargetSequence.length;
  15227. const tracks = [];
  15228. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15229. let times = [];
  15230. let values = [];
  15231. times.push(
  15232. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15233. i,
  15234. ( i + 1 ) % numMorphTargets );
  15235. values.push( 0, 1, 0 );
  15236. const order = getKeyframeOrder( times );
  15237. times = sortedArray( times, 1, order );
  15238. values = sortedArray( values, 1, order );
  15239. // if there is a key at the first frame, duplicate it as the
  15240. // last frame as well for perfect loop.
  15241. if ( ! noLoop && times[ 0 ] === 0 ) {
  15242. times.push( numMorphTargets );
  15243. values.push( values[ 0 ] );
  15244. }
  15245. tracks.push(
  15246. new NumberKeyframeTrack(
  15247. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15248. times, values
  15249. ).scale( 1.0 / fps ) );
  15250. }
  15251. return new this( name, - 1, tracks );
  15252. }
  15253. static findByName( objectOrClipArray, name ) {
  15254. let clipArray = objectOrClipArray;
  15255. if ( ! Array.isArray( objectOrClipArray ) ) {
  15256. const o = objectOrClipArray;
  15257. clipArray = o.geometry && o.geometry.animations || o.animations;
  15258. }
  15259. for ( let i = 0; i < clipArray.length; i ++ ) {
  15260. if ( clipArray[ i ].name === name ) {
  15261. return clipArray[ i ];
  15262. }
  15263. }
  15264. return null;
  15265. }
  15266. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15267. const animationToMorphTargets = {};
  15268. // tested with https://regex101.com/ on trick sequences
  15269. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15270. const pattern = /^([\w-]*?)([\d]+)$/;
  15271. // sort morph target names into animation groups based
  15272. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15273. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15274. const morphTarget = morphTargets[ i ];
  15275. const parts = morphTarget.name.match( pattern );
  15276. if ( parts && parts.length > 1 ) {
  15277. const name = parts[ 1 ];
  15278. let animationMorphTargets = animationToMorphTargets[ name ];
  15279. if ( ! animationMorphTargets ) {
  15280. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15281. }
  15282. animationMorphTargets.push( morphTarget );
  15283. }
  15284. }
  15285. const clips = [];
  15286. for ( const name in animationToMorphTargets ) {
  15287. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15288. }
  15289. return clips;
  15290. }
  15291. // parse the animation.hierarchy format
  15292. static parseAnimation( animation, bones ) {
  15293. if ( ! animation ) {
  15294. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15295. return null;
  15296. }
  15297. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15298. // only return track if there are actually keys.
  15299. if ( animationKeys.length !== 0 ) {
  15300. const times = [];
  15301. const values = [];
  15302. flattenJSON( animationKeys, times, values, propertyName );
  15303. // empty keys are filtered out, so check again
  15304. if ( times.length !== 0 ) {
  15305. destTracks.push( new trackType( trackName, times, values ) );
  15306. }
  15307. }
  15308. };
  15309. const tracks = [];
  15310. const clipName = animation.name || 'default';
  15311. const fps = animation.fps || 30;
  15312. const blendMode = animation.blendMode;
  15313. // automatic length determination in AnimationClip.
  15314. let duration = animation.length || - 1;
  15315. const hierarchyTracks = animation.hierarchy || [];
  15316. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15317. const animationKeys = hierarchyTracks[ h ].keys;
  15318. // skip empty tracks
  15319. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15320. // process morph targets
  15321. if ( animationKeys[ 0 ].morphTargets ) {
  15322. // figure out all morph targets used in this track
  15323. const morphTargetNames = {};
  15324. let k;
  15325. for ( k = 0; k < animationKeys.length; k ++ ) {
  15326. if ( animationKeys[ k ].morphTargets ) {
  15327. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15328. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15329. }
  15330. }
  15331. }
  15332. // create a track for each morph target with all zero
  15333. // morphTargetInfluences except for the keys in which
  15334. // the morphTarget is named.
  15335. for ( const morphTargetName in morphTargetNames ) {
  15336. const times = [];
  15337. const values = [];
  15338. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15339. const animationKey = animationKeys[ k ];
  15340. times.push( animationKey.time );
  15341. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15342. }
  15343. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15344. }
  15345. duration = morphTargetNames.length * fps;
  15346. } else {
  15347. // ...assume skeletal animation
  15348. const boneName = '.bones[' + bones[ h ].name + ']';
  15349. addNonemptyTrack(
  15350. VectorKeyframeTrack, boneName + '.position',
  15351. animationKeys, 'pos', tracks );
  15352. addNonemptyTrack(
  15353. QuaternionKeyframeTrack, boneName + '.quaternion',
  15354. animationKeys, 'rot', tracks );
  15355. addNonemptyTrack(
  15356. VectorKeyframeTrack, boneName + '.scale',
  15357. animationKeys, 'scl', tracks );
  15358. }
  15359. }
  15360. if ( tracks.length === 0 ) {
  15361. return null;
  15362. }
  15363. const clip = new this( clipName, duration, tracks, blendMode );
  15364. return clip;
  15365. }
  15366. resetDuration() {
  15367. const tracks = this.tracks;
  15368. let duration = 0;
  15369. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15370. const track = this.tracks[ i ];
  15371. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15372. }
  15373. this.duration = duration;
  15374. return this;
  15375. }
  15376. trim() {
  15377. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15378. this.tracks[ i ].trim( 0, this.duration );
  15379. }
  15380. return this;
  15381. }
  15382. validate() {
  15383. let valid = true;
  15384. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15385. valid = valid && this.tracks[ i ].validate();
  15386. }
  15387. return valid;
  15388. }
  15389. optimize() {
  15390. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15391. this.tracks[ i ].optimize();
  15392. }
  15393. return this;
  15394. }
  15395. clone() {
  15396. const tracks = [];
  15397. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15398. tracks.push( this.tracks[ i ].clone() );
  15399. }
  15400. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15401. }
  15402. toJSON() {
  15403. return this.constructor.toJSON( this );
  15404. }
  15405. }
  15406. function getTrackTypeForValueTypeName( typeName ) {
  15407. switch ( typeName.toLowerCase() ) {
  15408. case 'scalar':
  15409. case 'double':
  15410. case 'float':
  15411. case 'number':
  15412. case 'integer':
  15413. return NumberKeyframeTrack;
  15414. case 'vector':
  15415. case 'vector2':
  15416. case 'vector3':
  15417. case 'vector4':
  15418. return VectorKeyframeTrack;
  15419. case 'color':
  15420. return ColorKeyframeTrack;
  15421. case 'quaternion':
  15422. return QuaternionKeyframeTrack;
  15423. case 'bool':
  15424. case 'boolean':
  15425. return BooleanKeyframeTrack;
  15426. case 'string':
  15427. return StringKeyframeTrack;
  15428. }
  15429. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15430. }
  15431. function parseKeyframeTrack( json ) {
  15432. if ( json.type === undefined ) {
  15433. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15434. }
  15435. const trackType = getTrackTypeForValueTypeName( json.type );
  15436. if ( json.times === undefined ) {
  15437. const times = [], values = [];
  15438. flattenJSON( json.keys, times, values, 'value' );
  15439. json.times = times;
  15440. json.values = values;
  15441. }
  15442. // derived classes can define a static parse method
  15443. if ( trackType.parse !== undefined ) {
  15444. return trackType.parse( json );
  15445. } else {
  15446. // by default, we assume a constructor compatible with the base
  15447. return new trackType( json.name, json.times, json.values, json.interpolation );
  15448. }
  15449. }
  15450. const Cache = {
  15451. enabled: false,
  15452. files: {},
  15453. add: function ( key, file ) {
  15454. if ( this.enabled === false ) return;
  15455. // console.log( 'THREE.Cache', 'Adding key:', key );
  15456. this.files[ key ] = file;
  15457. },
  15458. get: function ( key ) {
  15459. if ( this.enabled === false ) return;
  15460. // console.log( 'THREE.Cache', 'Checking key:', key );
  15461. return this.files[ key ];
  15462. },
  15463. remove: function ( key ) {
  15464. delete this.files[ key ];
  15465. },
  15466. clear: function () {
  15467. this.files = {};
  15468. }
  15469. };
  15470. class LoadingManager {
  15471. constructor( onLoad, onProgress, onError ) {
  15472. const scope = this;
  15473. let isLoading = false;
  15474. let itemsLoaded = 0;
  15475. let itemsTotal = 0;
  15476. let urlModifier = undefined;
  15477. const handlers = [];
  15478. // Refer to #5689 for the reason why we don't set .onStart
  15479. // in the constructor
  15480. this.onStart = undefined;
  15481. this.onLoad = onLoad;
  15482. this.onProgress = onProgress;
  15483. this.onError = onError;
  15484. this.itemStart = function ( url ) {
  15485. itemsTotal ++;
  15486. if ( isLoading === false ) {
  15487. if ( scope.onStart !== undefined ) {
  15488. scope.onStart( url, itemsLoaded, itemsTotal );
  15489. }
  15490. }
  15491. isLoading = true;
  15492. };
  15493. this.itemEnd = function ( url ) {
  15494. itemsLoaded ++;
  15495. if ( scope.onProgress !== undefined ) {
  15496. scope.onProgress( url, itemsLoaded, itemsTotal );
  15497. }
  15498. if ( itemsLoaded === itemsTotal ) {
  15499. isLoading = false;
  15500. if ( scope.onLoad !== undefined ) {
  15501. scope.onLoad();
  15502. }
  15503. }
  15504. };
  15505. this.itemError = function ( url ) {
  15506. if ( scope.onError !== undefined ) {
  15507. scope.onError( url );
  15508. }
  15509. };
  15510. this.resolveURL = function ( url ) {
  15511. if ( urlModifier ) {
  15512. return urlModifier( url );
  15513. }
  15514. return url;
  15515. };
  15516. this.setURLModifier = function ( transform ) {
  15517. urlModifier = transform;
  15518. return this;
  15519. };
  15520. this.addHandler = function ( regex, loader ) {
  15521. handlers.push( regex, loader );
  15522. return this;
  15523. };
  15524. this.removeHandler = function ( regex ) {
  15525. const index = handlers.indexOf( regex );
  15526. if ( index !== - 1 ) {
  15527. handlers.splice( index, 2 );
  15528. }
  15529. return this;
  15530. };
  15531. this.getHandler = function ( file ) {
  15532. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15533. const regex = handlers[ i ];
  15534. const loader = handlers[ i + 1 ];
  15535. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15536. if ( regex.test( file ) ) {
  15537. return loader;
  15538. }
  15539. }
  15540. return null;
  15541. };
  15542. }
  15543. }
  15544. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15545. class Loader {
  15546. constructor( manager ) {
  15547. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15548. this.crossOrigin = 'anonymous';
  15549. this.withCredentials = false;
  15550. this.path = '';
  15551. this.resourcePath = '';
  15552. this.requestHeader = {};
  15553. }
  15554. load( /* url, onLoad, onProgress, onError */ ) {}
  15555. loadAsync( url, onProgress ) {
  15556. const scope = this;
  15557. return new Promise( function ( resolve, reject ) {
  15558. scope.load( url, resolve, onProgress, reject );
  15559. } );
  15560. }
  15561. parse( /* data */ ) {}
  15562. setCrossOrigin( crossOrigin ) {
  15563. this.crossOrigin = crossOrigin;
  15564. return this;
  15565. }
  15566. setWithCredentials( value ) {
  15567. this.withCredentials = value;
  15568. return this;
  15569. }
  15570. setPath( path ) {
  15571. this.path = path;
  15572. return this;
  15573. }
  15574. setResourcePath( resourcePath ) {
  15575. this.resourcePath = resourcePath;
  15576. return this;
  15577. }
  15578. setRequestHeader( requestHeader ) {
  15579. this.requestHeader = requestHeader;
  15580. return this;
  15581. }
  15582. }
  15583. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15584. const loading = {};
  15585. class HttpError extends Error {
  15586. constructor( message, response ) {
  15587. super( message );
  15588. this.response = response;
  15589. }
  15590. }
  15591. class FileLoader extends Loader {
  15592. constructor( manager ) {
  15593. super( manager );
  15594. }
  15595. load( url, onLoad, onProgress, onError ) {
  15596. if ( url === undefined ) url = '';
  15597. if ( this.path !== undefined ) url = this.path + url;
  15598. url = this.manager.resolveURL( url );
  15599. const cached = Cache.get( url );
  15600. if ( cached !== undefined ) {
  15601. this.manager.itemStart( url );
  15602. setTimeout( () => {
  15603. if ( onLoad ) onLoad( cached );
  15604. this.manager.itemEnd( url );
  15605. }, 0 );
  15606. return cached;
  15607. }
  15608. // Check if request is duplicate
  15609. if ( loading[ url ] !== undefined ) {
  15610. loading[ url ].push( {
  15611. onLoad: onLoad,
  15612. onProgress: onProgress,
  15613. onError: onError
  15614. } );
  15615. return;
  15616. }
  15617. // Initialise array for duplicate requests
  15618. loading[ url ] = [];
  15619. loading[ url ].push( {
  15620. onLoad: onLoad,
  15621. onProgress: onProgress,
  15622. onError: onError,
  15623. } );
  15624. // create request
  15625. const req = new Request( url, {
  15626. headers: new Headers( this.requestHeader ),
  15627. credentials: this.withCredentials ? 'include' : 'same-origin',
  15628. // An abort controller could be added within a future PR
  15629. } );
  15630. // record states ( avoid data race )
  15631. const mimeType = this.mimeType;
  15632. const responseType = this.responseType;
  15633. // start the fetch
  15634. fetch( req )
  15635. .then( response => {
  15636. if ( response.status === 200 || response.status === 0 ) {
  15637. // Some browsers return HTTP Status 0 when using non-http protocol
  15638. // e.g. 'file://' or 'data://'. Handle as success.
  15639. if ( response.status === 0 ) {
  15640. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15641. }
  15642. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15643. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15644. return response;
  15645. }
  15646. const callbacks = loading[ url ];
  15647. const reader = response.body.getReader();
  15648. // Nginx needs X-File-Size check
  15649. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15650. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15651. const total = contentLength ? parseInt( contentLength ) : 0;
  15652. const lengthComputable = total !== 0;
  15653. let loaded = 0;
  15654. // periodically read data into the new stream tracking while download progress
  15655. const stream = new ReadableStream( {
  15656. start( controller ) {
  15657. readData();
  15658. function readData() {
  15659. reader.read().then( ( { done, value } ) => {
  15660. if ( done ) {
  15661. controller.close();
  15662. } else {
  15663. loaded += value.byteLength;
  15664. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15665. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15666. const callback = callbacks[ i ];
  15667. if ( callback.onProgress ) callback.onProgress( event );
  15668. }
  15669. controller.enqueue( value );
  15670. readData();
  15671. }
  15672. }, ( e ) => {
  15673. controller.error( e );
  15674. } );
  15675. }
  15676. }
  15677. } );
  15678. return new Response( stream );
  15679. } else {
  15680. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15681. }
  15682. } )
  15683. .then( response => {
  15684. switch ( responseType ) {
  15685. case 'arraybuffer':
  15686. return response.arrayBuffer();
  15687. case 'blob':
  15688. return response.blob();
  15689. case 'document':
  15690. return response.text()
  15691. .then( text => {
  15692. const parser = new DOMParser();
  15693. return parser.parseFromString( text, mimeType );
  15694. } );
  15695. case 'json':
  15696. return response.json();
  15697. default:
  15698. if ( mimeType === undefined ) {
  15699. return response.text();
  15700. } else {
  15701. // sniff encoding
  15702. const re = /charset="?([^;"\s]*)"?/i;
  15703. const exec = re.exec( mimeType );
  15704. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15705. const decoder = new TextDecoder( label );
  15706. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15707. }
  15708. }
  15709. } )
  15710. .then( data => {
  15711. // Add to cache only on HTTP success, so that we do not cache
  15712. // error response bodies as proper responses to requests.
  15713. Cache.add( url, data );
  15714. const callbacks = loading[ url ];
  15715. delete loading[ url ];
  15716. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15717. const callback = callbacks[ i ];
  15718. if ( callback.onLoad ) callback.onLoad( data );
  15719. }
  15720. } )
  15721. .catch( err => {
  15722. // Abort errors and other errors are handled the same
  15723. const callbacks = loading[ url ];
  15724. if ( callbacks === undefined ) {
  15725. // When onLoad was called and url was deleted in `loading`
  15726. this.manager.itemError( url );
  15727. throw err;
  15728. }
  15729. delete loading[ url ];
  15730. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15731. const callback = callbacks[ i ];
  15732. if ( callback.onError ) callback.onError( err );
  15733. }
  15734. this.manager.itemError( url );
  15735. } )
  15736. .finally( () => {
  15737. this.manager.itemEnd( url );
  15738. } );
  15739. this.manager.itemStart( url );
  15740. }
  15741. setResponseType( value ) {
  15742. this.responseType = value;
  15743. return this;
  15744. }
  15745. setMimeType( value ) {
  15746. this.mimeType = value;
  15747. return this;
  15748. }
  15749. }
  15750. class AnimationLoader extends Loader {
  15751. constructor( manager ) {
  15752. super( manager );
  15753. }
  15754. load( url, onLoad, onProgress, onError ) {
  15755. const scope = this;
  15756. const loader = new FileLoader( this.manager );
  15757. loader.setPath( this.path );
  15758. loader.setRequestHeader( this.requestHeader );
  15759. loader.setWithCredentials( this.withCredentials );
  15760. loader.load( url, function ( text ) {
  15761. try {
  15762. onLoad( scope.parse( JSON.parse( text ) ) );
  15763. } catch ( e ) {
  15764. if ( onError ) {
  15765. onError( e );
  15766. } else {
  15767. console.error( e );
  15768. }
  15769. scope.manager.itemError( url );
  15770. }
  15771. }, onProgress, onError );
  15772. }
  15773. parse( json ) {
  15774. const animations = [];
  15775. for ( let i = 0; i < json.length; i ++ ) {
  15776. const clip = AnimationClip.parse( json[ i ] );
  15777. animations.push( clip );
  15778. }
  15779. return animations;
  15780. }
  15781. }
  15782. /**
  15783. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15784. *
  15785. * Sub classes have to implement the parse() method which will be used in load().
  15786. */
  15787. class CompressedTextureLoader extends Loader {
  15788. constructor( manager ) {
  15789. super( manager );
  15790. }
  15791. load( url, onLoad, onProgress, onError ) {
  15792. const scope = this;
  15793. const images = [];
  15794. const texture = new CompressedTexture();
  15795. const loader = new FileLoader( this.manager );
  15796. loader.setPath( this.path );
  15797. loader.setResponseType( 'arraybuffer' );
  15798. loader.setRequestHeader( this.requestHeader );
  15799. loader.setWithCredentials( scope.withCredentials );
  15800. let loaded = 0;
  15801. function loadTexture( i ) {
  15802. loader.load( url[ i ], function ( buffer ) {
  15803. const texDatas = scope.parse( buffer, true );
  15804. images[ i ] = {
  15805. width: texDatas.width,
  15806. height: texDatas.height,
  15807. format: texDatas.format,
  15808. mipmaps: texDatas.mipmaps
  15809. };
  15810. loaded += 1;
  15811. if ( loaded === 6 ) {
  15812. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15813. texture.image = images;
  15814. texture.format = texDatas.format;
  15815. texture.needsUpdate = true;
  15816. if ( onLoad ) onLoad( texture );
  15817. }
  15818. }, onProgress, onError );
  15819. }
  15820. if ( Array.isArray( url ) ) {
  15821. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15822. loadTexture( i );
  15823. }
  15824. } else {
  15825. // compressed cubemap texture stored in a single DDS file
  15826. loader.load( url, function ( buffer ) {
  15827. const texDatas = scope.parse( buffer, true );
  15828. if ( texDatas.isCubemap ) {
  15829. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15830. for ( let f = 0; f < faces; f ++ ) {
  15831. images[ f ] = { mipmaps: [] };
  15832. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15833. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15834. images[ f ].format = texDatas.format;
  15835. images[ f ].width = texDatas.width;
  15836. images[ f ].height = texDatas.height;
  15837. }
  15838. }
  15839. texture.image = images;
  15840. } else {
  15841. texture.image.width = texDatas.width;
  15842. texture.image.height = texDatas.height;
  15843. texture.mipmaps = texDatas.mipmaps;
  15844. }
  15845. if ( texDatas.mipmapCount === 1 ) {
  15846. texture.minFilter = LinearFilter;
  15847. }
  15848. texture.format = texDatas.format;
  15849. texture.needsUpdate = true;
  15850. if ( onLoad ) onLoad( texture );
  15851. }, onProgress, onError );
  15852. }
  15853. return texture;
  15854. }
  15855. }
  15856. class ImageLoader extends Loader {
  15857. constructor( manager ) {
  15858. super( manager );
  15859. }
  15860. load( url, onLoad, onProgress, onError ) {
  15861. if ( this.path !== undefined ) url = this.path + url;
  15862. url = this.manager.resolveURL( url );
  15863. const scope = this;
  15864. const cached = Cache.get( url );
  15865. if ( cached !== undefined ) {
  15866. scope.manager.itemStart( url );
  15867. setTimeout( function () {
  15868. if ( onLoad ) onLoad( cached );
  15869. scope.manager.itemEnd( url );
  15870. }, 0 );
  15871. return cached;
  15872. }
  15873. const image = createElementNS( 'img' );
  15874. function onImageLoad() {
  15875. removeEventListeners();
  15876. Cache.add( url, this );
  15877. if ( onLoad ) onLoad( this );
  15878. scope.manager.itemEnd( url );
  15879. }
  15880. function onImageError( event ) {
  15881. removeEventListeners();
  15882. if ( onError ) onError( event );
  15883. scope.manager.itemError( url );
  15884. scope.manager.itemEnd( url );
  15885. }
  15886. function removeEventListeners() {
  15887. image.removeEventListener( 'load', onImageLoad, false );
  15888. image.removeEventListener( 'error', onImageError, false );
  15889. }
  15890. image.addEventListener( 'load', onImageLoad, false );
  15891. image.addEventListener( 'error', onImageError, false );
  15892. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15893. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15894. }
  15895. scope.manager.itemStart( url );
  15896. image.src = url;
  15897. return image;
  15898. }
  15899. }
  15900. class CubeTextureLoader extends Loader {
  15901. constructor( manager ) {
  15902. super( manager );
  15903. }
  15904. load( urls, onLoad, onProgress, onError ) {
  15905. const texture = new CubeTexture();
  15906. texture.colorSpace = SRGBColorSpace;
  15907. const loader = new ImageLoader( this.manager );
  15908. loader.setCrossOrigin( this.crossOrigin );
  15909. loader.setPath( this.path );
  15910. let loaded = 0;
  15911. function loadTexture( i ) {
  15912. loader.load( urls[ i ], function ( image ) {
  15913. texture.images[ i ] = image;
  15914. loaded ++;
  15915. if ( loaded === 6 ) {
  15916. texture.needsUpdate = true;
  15917. if ( onLoad ) onLoad( texture );
  15918. }
  15919. }, undefined, onError );
  15920. }
  15921. for ( let i = 0; i < urls.length; ++ i ) {
  15922. loadTexture( i );
  15923. }
  15924. return texture;
  15925. }
  15926. }
  15927. /**
  15928. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15929. *
  15930. * Sub classes have to implement the parse() method which will be used in load().
  15931. */
  15932. class DataTextureLoader extends Loader {
  15933. constructor( manager ) {
  15934. super( manager );
  15935. }
  15936. load( url, onLoad, onProgress, onError ) {
  15937. const scope = this;
  15938. const texture = new DataTexture();
  15939. const loader = new FileLoader( this.manager );
  15940. loader.setResponseType( 'arraybuffer' );
  15941. loader.setRequestHeader( this.requestHeader );
  15942. loader.setPath( this.path );
  15943. loader.setWithCredentials( scope.withCredentials );
  15944. loader.load( url, function ( buffer ) {
  15945. let texData;
  15946. try {
  15947. texData = scope.parse( buffer );
  15948. } catch ( error ) {
  15949. if ( onError !== undefined ) {
  15950. onError( error );
  15951. } else {
  15952. console.error( error );
  15953. return;
  15954. }
  15955. }
  15956. if ( texData.image !== undefined ) {
  15957. texture.image = texData.image;
  15958. } else if ( texData.data !== undefined ) {
  15959. texture.image.width = texData.width;
  15960. texture.image.height = texData.height;
  15961. texture.image.data = texData.data;
  15962. }
  15963. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  15964. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  15965. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  15966. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  15967. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  15968. if ( texData.colorSpace !== undefined ) {
  15969. texture.colorSpace = texData.colorSpace;
  15970. }
  15971. if ( texData.flipY !== undefined ) {
  15972. texture.flipY = texData.flipY;
  15973. }
  15974. if ( texData.format !== undefined ) {
  15975. texture.format = texData.format;
  15976. }
  15977. if ( texData.type !== undefined ) {
  15978. texture.type = texData.type;
  15979. }
  15980. if ( texData.mipmaps !== undefined ) {
  15981. texture.mipmaps = texData.mipmaps;
  15982. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  15983. }
  15984. if ( texData.mipmapCount === 1 ) {
  15985. texture.minFilter = LinearFilter;
  15986. }
  15987. if ( texData.generateMipmaps !== undefined ) {
  15988. texture.generateMipmaps = texData.generateMipmaps;
  15989. }
  15990. texture.needsUpdate = true;
  15991. if ( onLoad ) onLoad( texture, texData );
  15992. }, onProgress, onError );
  15993. return texture;
  15994. }
  15995. }
  15996. class TextureLoader extends Loader {
  15997. constructor( manager ) {
  15998. super( manager );
  15999. }
  16000. load( url, onLoad, onProgress, onError ) {
  16001. const texture = new Texture();
  16002. const loader = new ImageLoader( this.manager );
  16003. loader.setCrossOrigin( this.crossOrigin );
  16004. loader.setPath( this.path );
  16005. loader.load( url, function ( image ) {
  16006. texture.image = image;
  16007. texture.needsUpdate = true;
  16008. if ( onLoad !== undefined ) {
  16009. onLoad( texture );
  16010. }
  16011. }, onProgress, onError );
  16012. return texture;
  16013. }
  16014. }
  16015. class Light extends Object3D {
  16016. constructor( color, intensity = 1 ) {
  16017. super();
  16018. this.isLight = true;
  16019. this.type = 'Light';
  16020. this.color = new Color( color );
  16021. this.intensity = intensity;
  16022. }
  16023. dispose() {
  16024. // Empty here in base class; some subclasses override.
  16025. }
  16026. copy( source, recursive ) {
  16027. super.copy( source, recursive );
  16028. this.color.copy( source.color );
  16029. this.intensity = source.intensity;
  16030. return this;
  16031. }
  16032. toJSON( meta ) {
  16033. const data = super.toJSON( meta );
  16034. data.object.color = this.color.getHex();
  16035. data.object.intensity = this.intensity;
  16036. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16037. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16038. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16039. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16040. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16041. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16042. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16043. return data;
  16044. }
  16045. }
  16046. class HemisphereLight extends Light {
  16047. constructor( skyColor, groundColor, intensity ) {
  16048. super( skyColor, intensity );
  16049. this.isHemisphereLight = true;
  16050. this.type = 'HemisphereLight';
  16051. this.position.copy( Object3D.DEFAULT_UP );
  16052. this.updateMatrix();
  16053. this.groundColor = new Color( groundColor );
  16054. }
  16055. copy( source, recursive ) {
  16056. super.copy( source, recursive );
  16057. this.groundColor.copy( source.groundColor );
  16058. return this;
  16059. }
  16060. }
  16061. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16062. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16063. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16064. class LightShadow {
  16065. constructor( camera ) {
  16066. this.camera = camera;
  16067. this.intensity = 1;
  16068. this.bias = 0;
  16069. this.normalBias = 0;
  16070. this.radius = 1;
  16071. this.blurSamples = 8;
  16072. this.mapSize = new Vector2( 512, 512 );
  16073. this.map = null;
  16074. this.mapPass = null;
  16075. this.matrix = new Matrix4();
  16076. this.autoUpdate = true;
  16077. this.needsUpdate = false;
  16078. this._frustum = new Frustum();
  16079. this._frameExtents = new Vector2( 1, 1 );
  16080. this._viewportCount = 1;
  16081. this._viewports = [
  16082. new Vector4( 0, 0, 1, 1 )
  16083. ];
  16084. }
  16085. getViewportCount() {
  16086. return this._viewportCount;
  16087. }
  16088. getFrustum() {
  16089. return this._frustum;
  16090. }
  16091. updateMatrices( light ) {
  16092. const shadowCamera = this.camera;
  16093. const shadowMatrix = this.matrix;
  16094. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16095. shadowCamera.position.copy( _lightPositionWorld$1 );
  16096. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16097. shadowCamera.lookAt( _lookTarget$1 );
  16098. shadowCamera.updateMatrixWorld();
  16099. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16100. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16101. shadowMatrix.set(
  16102. 0.5, 0.0, 0.0, 0.5,
  16103. 0.0, 0.5, 0.0, 0.5,
  16104. 0.0, 0.0, 0.5, 0.5,
  16105. 0.0, 0.0, 0.0, 1.0
  16106. );
  16107. shadowMatrix.multiply( _projScreenMatrix$2 );
  16108. }
  16109. getViewport( viewportIndex ) {
  16110. return this._viewports[ viewportIndex ];
  16111. }
  16112. getFrameExtents() {
  16113. return this._frameExtents;
  16114. }
  16115. dispose() {
  16116. if ( this.map ) {
  16117. this.map.dispose();
  16118. }
  16119. if ( this.mapPass ) {
  16120. this.mapPass.dispose();
  16121. }
  16122. }
  16123. copy( source ) {
  16124. this.camera = source.camera.clone();
  16125. this.intensity = source.intensity;
  16126. this.bias = source.bias;
  16127. this.radius = source.radius;
  16128. this.mapSize.copy( source.mapSize );
  16129. return this;
  16130. }
  16131. clone() {
  16132. return new this.constructor().copy( this );
  16133. }
  16134. toJSON() {
  16135. const object = {};
  16136. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16137. if ( this.bias !== 0 ) object.bias = this.bias;
  16138. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16139. if ( this.radius !== 1 ) object.radius = this.radius;
  16140. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16141. object.camera = this.camera.toJSON( false ).object;
  16142. delete object.camera.matrix;
  16143. return object;
  16144. }
  16145. }
  16146. class SpotLightShadow extends LightShadow {
  16147. constructor() {
  16148. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16149. this.isSpotLightShadow = true;
  16150. this.focus = 1;
  16151. }
  16152. updateMatrices( light ) {
  16153. const camera = this.camera;
  16154. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16155. const aspect = this.mapSize.width / this.mapSize.height;
  16156. const far = light.distance || camera.far;
  16157. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16158. camera.fov = fov;
  16159. camera.aspect = aspect;
  16160. camera.far = far;
  16161. camera.updateProjectionMatrix();
  16162. }
  16163. super.updateMatrices( light );
  16164. }
  16165. copy( source ) {
  16166. super.copy( source );
  16167. this.focus = source.focus;
  16168. return this;
  16169. }
  16170. }
  16171. class SpotLight extends Light {
  16172. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16173. super( color, intensity );
  16174. this.isSpotLight = true;
  16175. this.type = 'SpotLight';
  16176. this.position.copy( Object3D.DEFAULT_UP );
  16177. this.updateMatrix();
  16178. this.target = new Object3D();
  16179. this.distance = distance;
  16180. this.angle = angle;
  16181. this.penumbra = penumbra;
  16182. this.decay = decay;
  16183. this.map = null;
  16184. this.shadow = new SpotLightShadow();
  16185. }
  16186. get power() {
  16187. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16188. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16189. return this.intensity * Math.PI;
  16190. }
  16191. set power( power ) {
  16192. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16193. this.intensity = power / Math.PI;
  16194. }
  16195. dispose() {
  16196. this.shadow.dispose();
  16197. }
  16198. copy( source, recursive ) {
  16199. super.copy( source, recursive );
  16200. this.distance = source.distance;
  16201. this.angle = source.angle;
  16202. this.penumbra = source.penumbra;
  16203. this.decay = source.decay;
  16204. this.target = source.target.clone();
  16205. this.shadow = source.shadow.clone();
  16206. return this;
  16207. }
  16208. }
  16209. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16210. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16211. const _lookTarget = /*@__PURE__*/ new Vector3();
  16212. class PointLightShadow extends LightShadow {
  16213. constructor() {
  16214. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16215. this.isPointLightShadow = true;
  16216. this._frameExtents = new Vector2( 4, 2 );
  16217. this._viewportCount = 6;
  16218. this._viewports = [
  16219. // These viewports map a cube-map onto a 2D texture with the
  16220. // following orientation:
  16221. //
  16222. // xzXZ
  16223. // y Y
  16224. //
  16225. // X - Positive x direction
  16226. // x - Negative x direction
  16227. // Y - Positive y direction
  16228. // y - Negative y direction
  16229. // Z - Positive z direction
  16230. // z - Negative z direction
  16231. // positive X
  16232. new Vector4( 2, 1, 1, 1 ),
  16233. // negative X
  16234. new Vector4( 0, 1, 1, 1 ),
  16235. // positive Z
  16236. new Vector4( 3, 1, 1, 1 ),
  16237. // negative Z
  16238. new Vector4( 1, 1, 1, 1 ),
  16239. // positive Y
  16240. new Vector4( 3, 0, 1, 1 ),
  16241. // negative Y
  16242. new Vector4( 1, 0, 1, 1 )
  16243. ];
  16244. this._cubeDirections = [
  16245. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16246. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16247. ];
  16248. this._cubeUps = [
  16249. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16250. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16251. ];
  16252. }
  16253. updateMatrices( light, viewportIndex = 0 ) {
  16254. const camera = this.camera;
  16255. const shadowMatrix = this.matrix;
  16256. const far = light.distance || camera.far;
  16257. if ( far !== camera.far ) {
  16258. camera.far = far;
  16259. camera.updateProjectionMatrix();
  16260. }
  16261. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16262. camera.position.copy( _lightPositionWorld );
  16263. _lookTarget.copy( camera.position );
  16264. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16265. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16266. camera.lookAt( _lookTarget );
  16267. camera.updateMatrixWorld();
  16268. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16269. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16270. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16271. }
  16272. }
  16273. class PointLight extends Light {
  16274. constructor( color, intensity, distance = 0, decay = 2 ) {
  16275. super( color, intensity );
  16276. this.isPointLight = true;
  16277. this.type = 'PointLight';
  16278. this.distance = distance;
  16279. this.decay = decay;
  16280. this.shadow = new PointLightShadow();
  16281. }
  16282. get power() {
  16283. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16284. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16285. return this.intensity * 4 * Math.PI;
  16286. }
  16287. set power( power ) {
  16288. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16289. this.intensity = power / ( 4 * Math.PI );
  16290. }
  16291. dispose() {
  16292. this.shadow.dispose();
  16293. }
  16294. copy( source, recursive ) {
  16295. super.copy( source, recursive );
  16296. this.distance = source.distance;
  16297. this.decay = source.decay;
  16298. this.shadow = source.shadow.clone();
  16299. return this;
  16300. }
  16301. }
  16302. class OrthographicCamera extends Camera {
  16303. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16304. super();
  16305. this.isOrthographicCamera = true;
  16306. this.type = 'OrthographicCamera';
  16307. this.zoom = 1;
  16308. this.view = null;
  16309. this.left = left;
  16310. this.right = right;
  16311. this.top = top;
  16312. this.bottom = bottom;
  16313. this.near = near;
  16314. this.far = far;
  16315. this.updateProjectionMatrix();
  16316. }
  16317. copy( source, recursive ) {
  16318. super.copy( source, recursive );
  16319. this.left = source.left;
  16320. this.right = source.right;
  16321. this.top = source.top;
  16322. this.bottom = source.bottom;
  16323. this.near = source.near;
  16324. this.far = source.far;
  16325. this.zoom = source.zoom;
  16326. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16327. return this;
  16328. }
  16329. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16330. if ( this.view === null ) {
  16331. this.view = {
  16332. enabled: true,
  16333. fullWidth: 1,
  16334. fullHeight: 1,
  16335. offsetX: 0,
  16336. offsetY: 0,
  16337. width: 1,
  16338. height: 1
  16339. };
  16340. }
  16341. this.view.enabled = true;
  16342. this.view.fullWidth = fullWidth;
  16343. this.view.fullHeight = fullHeight;
  16344. this.view.offsetX = x;
  16345. this.view.offsetY = y;
  16346. this.view.width = width;
  16347. this.view.height = height;
  16348. this.updateProjectionMatrix();
  16349. }
  16350. clearViewOffset() {
  16351. if ( this.view !== null ) {
  16352. this.view.enabled = false;
  16353. }
  16354. this.updateProjectionMatrix();
  16355. }
  16356. updateProjectionMatrix() {
  16357. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16358. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16359. const cx = ( this.right + this.left ) / 2;
  16360. const cy = ( this.top + this.bottom ) / 2;
  16361. let left = cx - dx;
  16362. let right = cx + dx;
  16363. let top = cy + dy;
  16364. let bottom = cy - dy;
  16365. if ( this.view !== null && this.view.enabled ) {
  16366. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16367. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16368. left += scaleW * this.view.offsetX;
  16369. right = left + scaleW * this.view.width;
  16370. top -= scaleH * this.view.offsetY;
  16371. bottom = top - scaleH * this.view.height;
  16372. }
  16373. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16374. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16375. }
  16376. toJSON( meta ) {
  16377. const data = super.toJSON( meta );
  16378. data.object.zoom = this.zoom;
  16379. data.object.left = this.left;
  16380. data.object.right = this.right;
  16381. data.object.top = this.top;
  16382. data.object.bottom = this.bottom;
  16383. data.object.near = this.near;
  16384. data.object.far = this.far;
  16385. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16386. return data;
  16387. }
  16388. }
  16389. class DirectionalLightShadow extends LightShadow {
  16390. constructor() {
  16391. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16392. this.isDirectionalLightShadow = true;
  16393. }
  16394. }
  16395. class DirectionalLight extends Light {
  16396. constructor( color, intensity ) {
  16397. super( color, intensity );
  16398. this.isDirectionalLight = true;
  16399. this.type = 'DirectionalLight';
  16400. this.position.copy( Object3D.DEFAULT_UP );
  16401. this.updateMatrix();
  16402. this.target = new Object3D();
  16403. this.shadow = new DirectionalLightShadow();
  16404. }
  16405. dispose() {
  16406. this.shadow.dispose();
  16407. }
  16408. copy( source ) {
  16409. super.copy( source );
  16410. this.target = source.target.clone();
  16411. this.shadow = source.shadow.clone();
  16412. return this;
  16413. }
  16414. }
  16415. class AmbientLight extends Light {
  16416. constructor( color, intensity ) {
  16417. super( color, intensity );
  16418. this.isAmbientLight = true;
  16419. this.type = 'AmbientLight';
  16420. }
  16421. }
  16422. class RectAreaLight extends Light {
  16423. constructor( color, intensity, width = 10, height = 10 ) {
  16424. super( color, intensity );
  16425. this.isRectAreaLight = true;
  16426. this.type = 'RectAreaLight';
  16427. this.width = width;
  16428. this.height = height;
  16429. }
  16430. get power() {
  16431. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16432. return this.intensity * this.width * this.height * Math.PI;
  16433. }
  16434. set power( power ) {
  16435. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16436. this.intensity = power / ( this.width * this.height * Math.PI );
  16437. }
  16438. copy( source ) {
  16439. super.copy( source );
  16440. this.width = source.width;
  16441. this.height = source.height;
  16442. return this;
  16443. }
  16444. toJSON( meta ) {
  16445. const data = super.toJSON( meta );
  16446. data.object.width = this.width;
  16447. data.object.height = this.height;
  16448. return data;
  16449. }
  16450. }
  16451. /**
  16452. * Primary reference:
  16453. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16454. *
  16455. * Secondary reference:
  16456. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16457. */
  16458. // 3-band SH defined by 9 coefficients
  16459. class SphericalHarmonics3 {
  16460. constructor() {
  16461. this.isSphericalHarmonics3 = true;
  16462. this.coefficients = [];
  16463. for ( let i = 0; i < 9; i ++ ) {
  16464. this.coefficients.push( new Vector3() );
  16465. }
  16466. }
  16467. set( coefficients ) {
  16468. for ( let i = 0; i < 9; i ++ ) {
  16469. this.coefficients[ i ].copy( coefficients[ i ] );
  16470. }
  16471. return this;
  16472. }
  16473. zero() {
  16474. for ( let i = 0; i < 9; i ++ ) {
  16475. this.coefficients[ i ].set( 0, 0, 0 );
  16476. }
  16477. return this;
  16478. }
  16479. // get the radiance in the direction of the normal
  16480. // target is a Vector3
  16481. getAt( normal, target ) {
  16482. // normal is assumed to be unit length
  16483. const x = normal.x, y = normal.y, z = normal.z;
  16484. const coeff = this.coefficients;
  16485. // band 0
  16486. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16487. // band 1
  16488. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16489. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16490. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16491. // band 2
  16492. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16493. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16494. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16495. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16496. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16497. return target;
  16498. }
  16499. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16500. // target is a Vector3
  16501. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16502. getIrradianceAt( normal, target ) {
  16503. // normal is assumed to be unit length
  16504. const x = normal.x, y = normal.y, z = normal.z;
  16505. const coeff = this.coefficients;
  16506. // band 0
  16507. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16508. // band 1
  16509. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16510. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16511. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16512. // band 2
  16513. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16514. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16515. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16516. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16517. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16518. return target;
  16519. }
  16520. add( sh ) {
  16521. for ( let i = 0; i < 9; i ++ ) {
  16522. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16523. }
  16524. return this;
  16525. }
  16526. addScaledSH( sh, s ) {
  16527. for ( let i = 0; i < 9; i ++ ) {
  16528. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16529. }
  16530. return this;
  16531. }
  16532. scale( s ) {
  16533. for ( let i = 0; i < 9; i ++ ) {
  16534. this.coefficients[ i ].multiplyScalar( s );
  16535. }
  16536. return this;
  16537. }
  16538. lerp( sh, alpha ) {
  16539. for ( let i = 0; i < 9; i ++ ) {
  16540. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16541. }
  16542. return this;
  16543. }
  16544. equals( sh ) {
  16545. for ( let i = 0; i < 9; i ++ ) {
  16546. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16547. return false;
  16548. }
  16549. }
  16550. return true;
  16551. }
  16552. copy( sh ) {
  16553. return this.set( sh.coefficients );
  16554. }
  16555. clone() {
  16556. return new this.constructor().copy( this );
  16557. }
  16558. fromArray( array, offset = 0 ) {
  16559. const coefficients = this.coefficients;
  16560. for ( let i = 0; i < 9; i ++ ) {
  16561. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16562. }
  16563. return this;
  16564. }
  16565. toArray( array = [], offset = 0 ) {
  16566. const coefficients = this.coefficients;
  16567. for ( let i = 0; i < 9; i ++ ) {
  16568. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16569. }
  16570. return array;
  16571. }
  16572. // evaluate the basis functions
  16573. // shBasis is an Array[ 9 ]
  16574. static getBasisAt( normal, shBasis ) {
  16575. // normal is assumed to be unit length
  16576. const x = normal.x, y = normal.y, z = normal.z;
  16577. // band 0
  16578. shBasis[ 0 ] = 0.282095;
  16579. // band 1
  16580. shBasis[ 1 ] = 0.488603 * y;
  16581. shBasis[ 2 ] = 0.488603 * z;
  16582. shBasis[ 3 ] = 0.488603 * x;
  16583. // band 2
  16584. shBasis[ 4 ] = 1.092548 * x * y;
  16585. shBasis[ 5 ] = 1.092548 * y * z;
  16586. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16587. shBasis[ 7 ] = 1.092548 * x * z;
  16588. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16589. }
  16590. }
  16591. class LightProbe extends Light {
  16592. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16593. super( undefined, intensity );
  16594. this.isLightProbe = true;
  16595. this.sh = sh;
  16596. }
  16597. copy( source ) {
  16598. super.copy( source );
  16599. this.sh.copy( source.sh );
  16600. return this;
  16601. }
  16602. fromJSON( json ) {
  16603. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16604. this.sh.fromArray( json.sh );
  16605. return this;
  16606. }
  16607. toJSON( meta ) {
  16608. const data = super.toJSON( meta );
  16609. data.object.sh = this.sh.toArray();
  16610. return data;
  16611. }
  16612. }
  16613. class MaterialLoader extends Loader {
  16614. constructor( manager ) {
  16615. super( manager );
  16616. this.textures = {};
  16617. }
  16618. load( url, onLoad, onProgress, onError ) {
  16619. const scope = this;
  16620. const loader = new FileLoader( scope.manager );
  16621. loader.setPath( scope.path );
  16622. loader.setRequestHeader( scope.requestHeader );
  16623. loader.setWithCredentials( scope.withCredentials );
  16624. loader.load( url, function ( text ) {
  16625. try {
  16626. onLoad( scope.parse( JSON.parse( text ) ) );
  16627. } catch ( e ) {
  16628. if ( onError ) {
  16629. onError( e );
  16630. } else {
  16631. console.error( e );
  16632. }
  16633. scope.manager.itemError( url );
  16634. }
  16635. }, onProgress, onError );
  16636. }
  16637. parse( json ) {
  16638. const textures = this.textures;
  16639. function getTexture( name ) {
  16640. if ( textures[ name ] === undefined ) {
  16641. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16642. }
  16643. return textures[ name ];
  16644. }
  16645. const material = MaterialLoader.createMaterialFromType( json.type );
  16646. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16647. if ( json.name !== undefined ) material.name = json.name;
  16648. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16649. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16650. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16651. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16652. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16653. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16654. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16655. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16656. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16657. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16658. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16659. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16660. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16661. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16662. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16663. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16664. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16665. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16666. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16667. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16668. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16669. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16670. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16671. if ( json.fog !== undefined ) material.fog = json.fog;
  16672. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16673. if ( json.blending !== undefined ) material.blending = json.blending;
  16674. if ( json.combine !== undefined ) material.combine = json.combine;
  16675. if ( json.side !== undefined ) material.side = json.side;
  16676. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16677. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16678. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16679. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16680. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16681. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16682. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16683. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16684. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16685. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16686. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16687. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16688. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16689. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16690. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16691. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16692. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16693. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16694. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16695. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16696. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16697. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16698. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16699. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16700. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16701. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16702. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16703. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16704. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16705. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16706. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16707. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16708. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16709. if ( json.scale !== undefined ) material.scale = json.scale;
  16710. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16711. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16712. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16713. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16714. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16715. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16716. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16717. if ( json.visible !== undefined ) material.visible = json.visible;
  16718. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16719. if ( json.userData !== undefined ) material.userData = json.userData;
  16720. if ( json.vertexColors !== undefined ) {
  16721. if ( typeof json.vertexColors === 'number' ) {
  16722. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16723. } else {
  16724. material.vertexColors = json.vertexColors;
  16725. }
  16726. }
  16727. // Shader Material
  16728. if ( json.uniforms !== undefined ) {
  16729. for ( const name in json.uniforms ) {
  16730. const uniform = json.uniforms[ name ];
  16731. material.uniforms[ name ] = {};
  16732. switch ( uniform.type ) {
  16733. case 't':
  16734. material.uniforms[ name ].value = getTexture( uniform.value );
  16735. break;
  16736. case 'c':
  16737. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16738. break;
  16739. case 'v2':
  16740. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16741. break;
  16742. case 'v3':
  16743. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16744. break;
  16745. case 'v4':
  16746. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16747. break;
  16748. case 'm3':
  16749. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16750. break;
  16751. case 'm4':
  16752. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16753. break;
  16754. default:
  16755. material.uniforms[ name ].value = uniform.value;
  16756. }
  16757. }
  16758. }
  16759. if ( json.defines !== undefined ) material.defines = json.defines;
  16760. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16761. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16762. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16763. if ( json.extensions !== undefined ) {
  16764. for ( const key in json.extensions ) {
  16765. material.extensions[ key ] = json.extensions[ key ];
  16766. }
  16767. }
  16768. if ( json.lights !== undefined ) material.lights = json.lights;
  16769. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16770. // for PointsMaterial
  16771. if ( json.size !== undefined ) material.size = json.size;
  16772. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16773. // maps
  16774. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16775. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16776. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16777. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16778. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16779. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16780. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16781. if ( json.normalScale !== undefined ) {
  16782. let normalScale = json.normalScale;
  16783. if ( Array.isArray( normalScale ) === false ) {
  16784. // Blender exporter used to export a scalar. See #7459
  16785. normalScale = [ normalScale, normalScale ];
  16786. }
  16787. material.normalScale = new Vector2().fromArray( normalScale );
  16788. }
  16789. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16790. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16791. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16792. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16793. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16794. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16795. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16796. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16797. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16798. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16799. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16800. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16801. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16802. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16803. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16804. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16805. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16806. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16807. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16808. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16809. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16810. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16811. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16812. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16813. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16814. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16815. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16816. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16817. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16818. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16819. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16820. return material;
  16821. }
  16822. setTextures( value ) {
  16823. this.textures = value;
  16824. return this;
  16825. }
  16826. static createMaterialFromType( type ) {
  16827. const materialLib = {
  16828. ShadowMaterial,
  16829. SpriteMaterial,
  16830. RawShaderMaterial,
  16831. ShaderMaterial,
  16832. PointsMaterial,
  16833. MeshPhysicalMaterial,
  16834. MeshStandardMaterial,
  16835. MeshPhongMaterial,
  16836. MeshToonMaterial,
  16837. MeshNormalMaterial,
  16838. MeshLambertMaterial,
  16839. MeshDepthMaterial,
  16840. MeshDistanceMaterial,
  16841. MeshBasicMaterial,
  16842. MeshMatcapMaterial,
  16843. LineDashedMaterial,
  16844. LineBasicMaterial,
  16845. Material
  16846. };
  16847. return new materialLib[ type ]();
  16848. }
  16849. }
  16850. class LoaderUtils {
  16851. static decodeText( array ) { // @deprecated, r165
  16852. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16853. if ( typeof TextDecoder !== 'undefined' ) {
  16854. return new TextDecoder().decode( array );
  16855. }
  16856. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16857. // throws a "maximum call stack size exceeded" error for large arrays.
  16858. let s = '';
  16859. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16860. // Implicitly assumes little-endian.
  16861. s += String.fromCharCode( array[ i ] );
  16862. }
  16863. try {
  16864. // merges multi-byte utf-8 characters.
  16865. return decodeURIComponent( escape( s ) );
  16866. } catch ( e ) { // see #16358
  16867. return s;
  16868. }
  16869. }
  16870. static extractUrlBase( url ) {
  16871. const index = url.lastIndexOf( '/' );
  16872. if ( index === - 1 ) return './';
  16873. return url.slice( 0, index + 1 );
  16874. }
  16875. static resolveURL( url, path ) {
  16876. // Invalid URL
  16877. if ( typeof url !== 'string' || url === '' ) return '';
  16878. // Host Relative URL
  16879. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16880. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16881. }
  16882. // Absolute URL http://,https://,//
  16883. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16884. // Data URI
  16885. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16886. // Blob URL
  16887. if ( /^blob:.*$/i.test( url ) ) return url;
  16888. // Relative URL
  16889. return path + url;
  16890. }
  16891. }
  16892. class InstancedBufferGeometry extends BufferGeometry {
  16893. constructor() {
  16894. super();
  16895. this.isInstancedBufferGeometry = true;
  16896. this.type = 'InstancedBufferGeometry';
  16897. this.instanceCount = Infinity;
  16898. }
  16899. copy( source ) {
  16900. super.copy( source );
  16901. this.instanceCount = source.instanceCount;
  16902. return this;
  16903. }
  16904. toJSON() {
  16905. const data = super.toJSON();
  16906. data.instanceCount = this.instanceCount;
  16907. data.isInstancedBufferGeometry = true;
  16908. return data;
  16909. }
  16910. }
  16911. class BufferGeometryLoader extends Loader {
  16912. constructor( manager ) {
  16913. super( manager );
  16914. }
  16915. load( url, onLoad, onProgress, onError ) {
  16916. const scope = this;
  16917. const loader = new FileLoader( scope.manager );
  16918. loader.setPath( scope.path );
  16919. loader.setRequestHeader( scope.requestHeader );
  16920. loader.setWithCredentials( scope.withCredentials );
  16921. loader.load( url, function ( text ) {
  16922. try {
  16923. onLoad( scope.parse( JSON.parse( text ) ) );
  16924. } catch ( e ) {
  16925. if ( onError ) {
  16926. onError( e );
  16927. } else {
  16928. console.error( e );
  16929. }
  16930. scope.manager.itemError( url );
  16931. }
  16932. }, onProgress, onError );
  16933. }
  16934. parse( json ) {
  16935. const interleavedBufferMap = {};
  16936. const arrayBufferMap = {};
  16937. function getInterleavedBuffer( json, uuid ) {
  16938. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16939. const interleavedBuffers = json.interleavedBuffers;
  16940. const interleavedBuffer = interleavedBuffers[ uuid ];
  16941. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16942. const array = getTypedArray( interleavedBuffer.type, buffer );
  16943. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16944. ib.uuid = interleavedBuffer.uuid;
  16945. interleavedBufferMap[ uuid ] = ib;
  16946. return ib;
  16947. }
  16948. function getArrayBuffer( json, uuid ) {
  16949. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16950. const arrayBuffers = json.arrayBuffers;
  16951. const arrayBuffer = arrayBuffers[ uuid ];
  16952. const ab = new Uint32Array( arrayBuffer ).buffer;
  16953. arrayBufferMap[ uuid ] = ab;
  16954. return ab;
  16955. }
  16956. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16957. const index = json.data.index;
  16958. if ( index !== undefined ) {
  16959. const typedArray = getTypedArray( index.type, index.array );
  16960. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16961. }
  16962. const attributes = json.data.attributes;
  16963. for ( const key in attributes ) {
  16964. const attribute = attributes[ key ];
  16965. let bufferAttribute;
  16966. if ( attribute.isInterleavedBufferAttribute ) {
  16967. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16968. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16969. } else {
  16970. const typedArray = getTypedArray( attribute.type, attribute.array );
  16971. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  16972. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  16973. }
  16974. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16975. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  16976. geometry.setAttribute( key, bufferAttribute );
  16977. }
  16978. const morphAttributes = json.data.morphAttributes;
  16979. if ( morphAttributes ) {
  16980. for ( const key in morphAttributes ) {
  16981. const attributeArray = morphAttributes[ key ];
  16982. const array = [];
  16983. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  16984. const attribute = attributeArray[ i ];
  16985. let bufferAttribute;
  16986. if ( attribute.isInterleavedBufferAttribute ) {
  16987. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  16988. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  16989. } else {
  16990. const typedArray = getTypedArray( attribute.type, attribute.array );
  16991. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  16992. }
  16993. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  16994. array.push( bufferAttribute );
  16995. }
  16996. geometry.morphAttributes[ key ] = array;
  16997. }
  16998. }
  16999. const morphTargetsRelative = json.data.morphTargetsRelative;
  17000. if ( morphTargetsRelative ) {
  17001. geometry.morphTargetsRelative = true;
  17002. }
  17003. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17004. if ( groups !== undefined ) {
  17005. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17006. const group = groups[ i ];
  17007. geometry.addGroup( group.start, group.count, group.materialIndex );
  17008. }
  17009. }
  17010. const boundingSphere = json.data.boundingSphere;
  17011. if ( boundingSphere !== undefined ) {
  17012. const center = new Vector3();
  17013. if ( boundingSphere.center !== undefined ) {
  17014. center.fromArray( boundingSphere.center );
  17015. }
  17016. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17017. }
  17018. if ( json.name ) geometry.name = json.name;
  17019. if ( json.userData ) geometry.userData = json.userData;
  17020. return geometry;
  17021. }
  17022. }
  17023. class ObjectLoader extends Loader {
  17024. constructor( manager ) {
  17025. super( manager );
  17026. }
  17027. load( url, onLoad, onProgress, onError ) {
  17028. const scope = this;
  17029. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17030. this.resourcePath = this.resourcePath || path;
  17031. const loader = new FileLoader( this.manager );
  17032. loader.setPath( this.path );
  17033. loader.setRequestHeader( this.requestHeader );
  17034. loader.setWithCredentials( this.withCredentials );
  17035. loader.load( url, function ( text ) {
  17036. let json = null;
  17037. try {
  17038. json = JSON.parse( text );
  17039. } catch ( error ) {
  17040. if ( onError !== undefined ) onError( error );
  17041. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17042. return;
  17043. }
  17044. const metadata = json.metadata;
  17045. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17046. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17047. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17048. return;
  17049. }
  17050. scope.parse( json, onLoad );
  17051. }, onProgress, onError );
  17052. }
  17053. async loadAsync( url, onProgress ) {
  17054. const scope = this;
  17055. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17056. this.resourcePath = this.resourcePath || path;
  17057. const loader = new FileLoader( this.manager );
  17058. loader.setPath( this.path );
  17059. loader.setRequestHeader( this.requestHeader );
  17060. loader.setWithCredentials( this.withCredentials );
  17061. const text = await loader.loadAsync( url, onProgress );
  17062. const json = JSON.parse( text );
  17063. const metadata = json.metadata;
  17064. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17065. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17066. }
  17067. return await scope.parseAsync( json );
  17068. }
  17069. parse( json, onLoad ) {
  17070. const animations = this.parseAnimations( json.animations );
  17071. const shapes = this.parseShapes( json.shapes );
  17072. const geometries = this.parseGeometries( json.geometries, shapes );
  17073. const images = this.parseImages( json.images, function () {
  17074. if ( onLoad !== undefined ) onLoad( object );
  17075. } );
  17076. const textures = this.parseTextures( json.textures, images );
  17077. const materials = this.parseMaterials( json.materials, textures );
  17078. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17079. const skeletons = this.parseSkeletons( json.skeletons, object );
  17080. this.bindSkeletons( object, skeletons );
  17081. this.bindLightTargets( object );
  17082. //
  17083. if ( onLoad !== undefined ) {
  17084. let hasImages = false;
  17085. for ( const uuid in images ) {
  17086. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17087. hasImages = true;
  17088. break;
  17089. }
  17090. }
  17091. if ( hasImages === false ) onLoad( object );
  17092. }
  17093. return object;
  17094. }
  17095. async parseAsync( json ) {
  17096. const animations = this.parseAnimations( json.animations );
  17097. const shapes = this.parseShapes( json.shapes );
  17098. const geometries = this.parseGeometries( json.geometries, shapes );
  17099. const images = await this.parseImagesAsync( json.images );
  17100. const textures = this.parseTextures( json.textures, images );
  17101. const materials = this.parseMaterials( json.materials, textures );
  17102. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17103. const skeletons = this.parseSkeletons( json.skeletons, object );
  17104. this.bindSkeletons( object, skeletons );
  17105. this.bindLightTargets( object );
  17106. return object;
  17107. }
  17108. parseShapes( json ) {
  17109. const shapes = {};
  17110. if ( json !== undefined ) {
  17111. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17112. const shape = new Shape().fromJSON( json[ i ] );
  17113. shapes[ shape.uuid ] = shape;
  17114. }
  17115. }
  17116. return shapes;
  17117. }
  17118. parseSkeletons( json, object ) {
  17119. const skeletons = {};
  17120. const bones = {};
  17121. // generate bone lookup table
  17122. object.traverse( function ( child ) {
  17123. if ( child.isBone ) bones[ child.uuid ] = child;
  17124. } );
  17125. // create skeletons
  17126. if ( json !== undefined ) {
  17127. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17128. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17129. skeletons[ skeleton.uuid ] = skeleton;
  17130. }
  17131. }
  17132. return skeletons;
  17133. }
  17134. parseGeometries( json, shapes ) {
  17135. const geometries = {};
  17136. if ( json !== undefined ) {
  17137. const bufferGeometryLoader = new BufferGeometryLoader();
  17138. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17139. let geometry;
  17140. const data = json[ i ];
  17141. switch ( data.type ) {
  17142. case 'BufferGeometry':
  17143. case 'InstancedBufferGeometry':
  17144. geometry = bufferGeometryLoader.parse( data );
  17145. break;
  17146. default:
  17147. if ( data.type in Geometries$1 ) {
  17148. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17149. } else {
  17150. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17151. }
  17152. }
  17153. geometry.uuid = data.uuid;
  17154. if ( data.name !== undefined ) geometry.name = data.name;
  17155. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17156. geometries[ data.uuid ] = geometry;
  17157. }
  17158. }
  17159. return geometries;
  17160. }
  17161. parseMaterials( json, textures ) {
  17162. const cache = {}; // MultiMaterial
  17163. const materials = {};
  17164. if ( json !== undefined ) {
  17165. const loader = new MaterialLoader();
  17166. loader.setTextures( textures );
  17167. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17168. const data = json[ i ];
  17169. if ( cache[ data.uuid ] === undefined ) {
  17170. cache[ data.uuid ] = loader.parse( data );
  17171. }
  17172. materials[ data.uuid ] = cache[ data.uuid ];
  17173. }
  17174. }
  17175. return materials;
  17176. }
  17177. parseAnimations( json ) {
  17178. const animations = {};
  17179. if ( json !== undefined ) {
  17180. for ( let i = 0; i < json.length; i ++ ) {
  17181. const data = json[ i ];
  17182. const clip = AnimationClip.parse( data );
  17183. animations[ clip.uuid ] = clip;
  17184. }
  17185. }
  17186. return animations;
  17187. }
  17188. parseImages( json, onLoad ) {
  17189. const scope = this;
  17190. const images = {};
  17191. let loader;
  17192. function loadImage( url ) {
  17193. scope.manager.itemStart( url );
  17194. return loader.load( url, function () {
  17195. scope.manager.itemEnd( url );
  17196. }, undefined, function () {
  17197. scope.manager.itemError( url );
  17198. scope.manager.itemEnd( url );
  17199. } );
  17200. }
  17201. function deserializeImage( image ) {
  17202. if ( typeof image === 'string' ) {
  17203. const url = image;
  17204. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17205. return loadImage( path );
  17206. } else {
  17207. if ( image.data ) {
  17208. return {
  17209. data: getTypedArray( image.type, image.data ),
  17210. width: image.width,
  17211. height: image.height
  17212. };
  17213. } else {
  17214. return null;
  17215. }
  17216. }
  17217. }
  17218. if ( json !== undefined && json.length > 0 ) {
  17219. const manager = new LoadingManager( onLoad );
  17220. loader = new ImageLoader( manager );
  17221. loader.setCrossOrigin( this.crossOrigin );
  17222. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17223. const image = json[ i ];
  17224. const url = image.url;
  17225. if ( Array.isArray( url ) ) {
  17226. // load array of images e.g CubeTexture
  17227. const imageArray = [];
  17228. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17229. const currentUrl = url[ j ];
  17230. const deserializedImage = deserializeImage( currentUrl );
  17231. if ( deserializedImage !== null ) {
  17232. if ( deserializedImage instanceof HTMLImageElement ) {
  17233. imageArray.push( deserializedImage );
  17234. } else {
  17235. // special case: handle array of data textures for cube textures
  17236. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17237. }
  17238. }
  17239. }
  17240. images[ image.uuid ] = new Source( imageArray );
  17241. } else {
  17242. // load single image
  17243. const deserializedImage = deserializeImage( image.url );
  17244. images[ image.uuid ] = new Source( deserializedImage );
  17245. }
  17246. }
  17247. }
  17248. return images;
  17249. }
  17250. async parseImagesAsync( json ) {
  17251. const scope = this;
  17252. const images = {};
  17253. let loader;
  17254. async function deserializeImage( image ) {
  17255. if ( typeof image === 'string' ) {
  17256. const url = image;
  17257. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17258. return await loader.loadAsync( path );
  17259. } else {
  17260. if ( image.data ) {
  17261. return {
  17262. data: getTypedArray( image.type, image.data ),
  17263. width: image.width,
  17264. height: image.height
  17265. };
  17266. } else {
  17267. return null;
  17268. }
  17269. }
  17270. }
  17271. if ( json !== undefined && json.length > 0 ) {
  17272. loader = new ImageLoader( this.manager );
  17273. loader.setCrossOrigin( this.crossOrigin );
  17274. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17275. const image = json[ i ];
  17276. const url = image.url;
  17277. if ( Array.isArray( url ) ) {
  17278. // load array of images e.g CubeTexture
  17279. const imageArray = [];
  17280. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17281. const currentUrl = url[ j ];
  17282. const deserializedImage = await deserializeImage( currentUrl );
  17283. if ( deserializedImage !== null ) {
  17284. if ( deserializedImage instanceof HTMLImageElement ) {
  17285. imageArray.push( deserializedImage );
  17286. } else {
  17287. // special case: handle array of data textures for cube textures
  17288. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17289. }
  17290. }
  17291. }
  17292. images[ image.uuid ] = new Source( imageArray );
  17293. } else {
  17294. // load single image
  17295. const deserializedImage = await deserializeImage( image.url );
  17296. images[ image.uuid ] = new Source( deserializedImage );
  17297. }
  17298. }
  17299. }
  17300. return images;
  17301. }
  17302. parseTextures( json, images ) {
  17303. function parseConstant( value, type ) {
  17304. if ( typeof value === 'number' ) return value;
  17305. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17306. return type[ value ];
  17307. }
  17308. const textures = {};
  17309. if ( json !== undefined ) {
  17310. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17311. const data = json[ i ];
  17312. if ( data.image === undefined ) {
  17313. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17314. }
  17315. if ( images[ data.image ] === undefined ) {
  17316. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17317. }
  17318. const source = images[ data.image ];
  17319. const image = source.data;
  17320. let texture;
  17321. if ( Array.isArray( image ) ) {
  17322. texture = new CubeTexture();
  17323. if ( image.length === 6 ) texture.needsUpdate = true;
  17324. } else {
  17325. if ( image && image.data ) {
  17326. texture = new DataTexture();
  17327. } else {
  17328. texture = new Texture();
  17329. }
  17330. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17331. }
  17332. texture.source = source;
  17333. texture.uuid = data.uuid;
  17334. if ( data.name !== undefined ) texture.name = data.name;
  17335. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17336. if ( data.channel !== undefined ) texture.channel = data.channel;
  17337. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17338. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17339. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17340. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17341. if ( data.wrap !== undefined ) {
  17342. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17343. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17344. }
  17345. if ( data.format !== undefined ) texture.format = data.format;
  17346. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17347. if ( data.type !== undefined ) texture.type = data.type;
  17348. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17349. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17350. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17351. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17352. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17353. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17354. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17355. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17356. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17357. if ( data.userData !== undefined ) texture.userData = data.userData;
  17358. textures[ data.uuid ] = texture;
  17359. }
  17360. }
  17361. return textures;
  17362. }
  17363. parseObject( data, geometries, materials, textures, animations ) {
  17364. let object;
  17365. function getGeometry( name ) {
  17366. if ( geometries[ name ] === undefined ) {
  17367. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17368. }
  17369. return geometries[ name ];
  17370. }
  17371. function getMaterial( name ) {
  17372. if ( name === undefined ) return undefined;
  17373. if ( Array.isArray( name ) ) {
  17374. const array = [];
  17375. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17376. const uuid = name[ i ];
  17377. if ( materials[ uuid ] === undefined ) {
  17378. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17379. }
  17380. array.push( materials[ uuid ] );
  17381. }
  17382. return array;
  17383. }
  17384. if ( materials[ name ] === undefined ) {
  17385. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17386. }
  17387. return materials[ name ];
  17388. }
  17389. function getTexture( uuid ) {
  17390. if ( textures[ uuid ] === undefined ) {
  17391. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17392. }
  17393. return textures[ uuid ];
  17394. }
  17395. let geometry, material;
  17396. switch ( data.type ) {
  17397. case 'Scene':
  17398. object = new Scene();
  17399. if ( data.background !== undefined ) {
  17400. if ( Number.isInteger( data.background ) ) {
  17401. object.background = new Color( data.background );
  17402. } else {
  17403. object.background = getTexture( data.background );
  17404. }
  17405. }
  17406. if ( data.environment !== undefined ) {
  17407. object.environment = getTexture( data.environment );
  17408. }
  17409. if ( data.fog !== undefined ) {
  17410. if ( data.fog.type === 'Fog' ) {
  17411. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17412. } else if ( data.fog.type === 'FogExp2' ) {
  17413. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17414. }
  17415. if ( data.fog.name !== '' ) {
  17416. object.fog.name = data.fog.name;
  17417. }
  17418. }
  17419. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17420. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17421. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17422. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17423. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17424. break;
  17425. case 'PerspectiveCamera':
  17426. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17427. if ( data.focus !== undefined ) object.focus = data.focus;
  17428. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17429. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17430. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17431. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17432. break;
  17433. case 'OrthographicCamera':
  17434. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17435. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17436. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17437. break;
  17438. case 'AmbientLight':
  17439. object = new AmbientLight( data.color, data.intensity );
  17440. break;
  17441. case 'DirectionalLight':
  17442. object = new DirectionalLight( data.color, data.intensity );
  17443. object.target = data.target || '';
  17444. break;
  17445. case 'PointLight':
  17446. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17447. break;
  17448. case 'RectAreaLight':
  17449. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17450. break;
  17451. case 'SpotLight':
  17452. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17453. object.target = data.target || '';
  17454. break;
  17455. case 'HemisphereLight':
  17456. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17457. break;
  17458. case 'LightProbe':
  17459. object = new LightProbe().fromJSON( data );
  17460. break;
  17461. case 'SkinnedMesh':
  17462. geometry = getGeometry( data.geometry );
  17463. material = getMaterial( data.material );
  17464. object = new SkinnedMesh( geometry, material );
  17465. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17466. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17467. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17468. break;
  17469. case 'Mesh':
  17470. geometry = getGeometry( data.geometry );
  17471. material = getMaterial( data.material );
  17472. object = new Mesh( geometry, material );
  17473. break;
  17474. case 'InstancedMesh':
  17475. geometry = getGeometry( data.geometry );
  17476. material = getMaterial( data.material );
  17477. const count = data.count;
  17478. const instanceMatrix = data.instanceMatrix;
  17479. const instanceColor = data.instanceColor;
  17480. object = new InstancedMesh( geometry, material, count );
  17481. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17482. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17483. break;
  17484. case 'BatchedMesh':
  17485. geometry = getGeometry( data.geometry );
  17486. material = getMaterial( data.material );
  17487. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17488. object.geometry = geometry;
  17489. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17490. object.sortObjects = data.sortObjects;
  17491. object._drawRanges = data.drawRanges;
  17492. object._reservedRanges = data.reservedRanges;
  17493. object._visibility = data.visibility;
  17494. object._active = data.active;
  17495. object._bounds = data.bounds.map( bound => {
  17496. const box = new Box3();
  17497. box.min.fromArray( bound.boxMin );
  17498. box.max.fromArray( bound.boxMax );
  17499. const sphere = new Sphere();
  17500. sphere.radius = bound.sphereRadius;
  17501. sphere.center.fromArray( bound.sphereCenter );
  17502. return {
  17503. boxInitialized: bound.boxInitialized,
  17504. box: box,
  17505. sphereInitialized: bound.sphereInitialized,
  17506. sphere: sphere
  17507. };
  17508. } );
  17509. object._maxInstanceCount = data.maxInstanceCount;
  17510. object._maxVertexCount = data.maxVertexCount;
  17511. object._maxIndexCount = data.maxIndexCount;
  17512. object._geometryInitialized = data.geometryInitialized;
  17513. object._geometryCount = data.geometryCount;
  17514. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17515. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17516. break;
  17517. case 'LOD':
  17518. object = new LOD();
  17519. break;
  17520. case 'Line':
  17521. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17522. break;
  17523. case 'LineLoop':
  17524. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17525. break;
  17526. case 'LineSegments':
  17527. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17528. break;
  17529. case 'PointCloud':
  17530. case 'Points':
  17531. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17532. break;
  17533. case 'Sprite':
  17534. object = new Sprite( getMaterial( data.material ) );
  17535. break;
  17536. case 'Group':
  17537. object = new Group();
  17538. break;
  17539. case 'Bone':
  17540. object = new Bone();
  17541. break;
  17542. default:
  17543. object = new Object3D();
  17544. }
  17545. object.uuid = data.uuid;
  17546. if ( data.name !== undefined ) object.name = data.name;
  17547. if ( data.matrix !== undefined ) {
  17548. object.matrix.fromArray( data.matrix );
  17549. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17550. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17551. } else {
  17552. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17553. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17554. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17555. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17556. }
  17557. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17558. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17559. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17560. if ( data.shadow ) {
  17561. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17562. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17563. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17564. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17565. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17566. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17567. }
  17568. if ( data.visible !== undefined ) object.visible = data.visible;
  17569. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17570. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17571. if ( data.userData !== undefined ) object.userData = data.userData;
  17572. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17573. if ( data.children !== undefined ) {
  17574. const children = data.children;
  17575. for ( let i = 0; i < children.length; i ++ ) {
  17576. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17577. }
  17578. }
  17579. if ( data.animations !== undefined ) {
  17580. const objectAnimations = data.animations;
  17581. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17582. const uuid = objectAnimations[ i ];
  17583. object.animations.push( animations[ uuid ] );
  17584. }
  17585. }
  17586. if ( data.type === 'LOD' ) {
  17587. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17588. const levels = data.levels;
  17589. for ( let l = 0; l < levels.length; l ++ ) {
  17590. const level = levels[ l ];
  17591. const child = object.getObjectByProperty( 'uuid', level.object );
  17592. if ( child !== undefined ) {
  17593. object.addLevel( child, level.distance, level.hysteresis );
  17594. }
  17595. }
  17596. }
  17597. return object;
  17598. }
  17599. bindSkeletons( object, skeletons ) {
  17600. if ( Object.keys( skeletons ).length === 0 ) return;
  17601. object.traverse( function ( child ) {
  17602. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17603. const skeleton = skeletons[ child.skeleton ];
  17604. if ( skeleton === undefined ) {
  17605. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17606. } else {
  17607. child.bind( skeleton, child.bindMatrix );
  17608. }
  17609. }
  17610. } );
  17611. }
  17612. bindLightTargets( object ) {
  17613. object.traverse( function ( child ) {
  17614. if ( child.isDirectionalLight || child.isSpotLight ) {
  17615. const uuid = child.target;
  17616. const target = object.getObjectByProperty( 'uuid', uuid );
  17617. if ( target !== undefined ) {
  17618. child.target = target;
  17619. } else {
  17620. child.target = new Object3D();
  17621. }
  17622. }
  17623. } );
  17624. }
  17625. }
  17626. const TEXTURE_MAPPING = {
  17627. UVMapping: UVMapping,
  17628. CubeReflectionMapping: CubeReflectionMapping,
  17629. CubeRefractionMapping: CubeRefractionMapping,
  17630. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17631. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17632. CubeUVReflectionMapping: CubeUVReflectionMapping
  17633. };
  17634. const TEXTURE_WRAPPING = {
  17635. RepeatWrapping: RepeatWrapping,
  17636. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17637. MirroredRepeatWrapping: MirroredRepeatWrapping
  17638. };
  17639. const TEXTURE_FILTER = {
  17640. NearestFilter: NearestFilter,
  17641. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17642. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17643. LinearFilter: LinearFilter,
  17644. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17645. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17646. };
  17647. class ImageBitmapLoader extends Loader {
  17648. constructor( manager ) {
  17649. super( manager );
  17650. this.isImageBitmapLoader = true;
  17651. if ( typeof createImageBitmap === 'undefined' ) {
  17652. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17653. }
  17654. if ( typeof fetch === 'undefined' ) {
  17655. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17656. }
  17657. this.options = { premultiplyAlpha: 'none' };
  17658. }
  17659. setOptions( options ) {
  17660. this.options = options;
  17661. return this;
  17662. }
  17663. load( url, onLoad, onProgress, onError ) {
  17664. if ( url === undefined ) url = '';
  17665. if ( this.path !== undefined ) url = this.path + url;
  17666. url = this.manager.resolveURL( url );
  17667. const scope = this;
  17668. const cached = Cache.get( url );
  17669. if ( cached !== undefined ) {
  17670. scope.manager.itemStart( url );
  17671. // If cached is a promise, wait for it to resolve
  17672. if ( cached.then ) {
  17673. cached.then( imageBitmap => {
  17674. if ( onLoad ) onLoad( imageBitmap );
  17675. scope.manager.itemEnd( url );
  17676. } ).catch( e => {
  17677. if ( onError ) onError( e );
  17678. } );
  17679. return;
  17680. }
  17681. // If cached is not a promise (i.e., it's already an imageBitmap)
  17682. setTimeout( function () {
  17683. if ( onLoad ) onLoad( cached );
  17684. scope.manager.itemEnd( url );
  17685. }, 0 );
  17686. return cached;
  17687. }
  17688. const fetchOptions = {};
  17689. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17690. fetchOptions.headers = this.requestHeader;
  17691. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17692. return res.blob();
  17693. } ).then( function ( blob ) {
  17694. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17695. } ).then( function ( imageBitmap ) {
  17696. Cache.add( url, imageBitmap );
  17697. if ( onLoad ) onLoad( imageBitmap );
  17698. scope.manager.itemEnd( url );
  17699. return imageBitmap;
  17700. } ).catch( function ( e ) {
  17701. if ( onError ) onError( e );
  17702. Cache.remove( url );
  17703. scope.manager.itemError( url );
  17704. scope.manager.itemEnd( url );
  17705. } );
  17706. Cache.add( url, promise );
  17707. scope.manager.itemStart( url );
  17708. }
  17709. }
  17710. let _context;
  17711. class AudioContext {
  17712. static getContext() {
  17713. if ( _context === undefined ) {
  17714. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17715. }
  17716. return _context;
  17717. }
  17718. static setContext( value ) {
  17719. _context = value;
  17720. }
  17721. }
  17722. class AudioLoader extends Loader {
  17723. constructor( manager ) {
  17724. super( manager );
  17725. }
  17726. load( url, onLoad, onProgress, onError ) {
  17727. const scope = this;
  17728. const loader = new FileLoader( this.manager );
  17729. loader.setResponseType( 'arraybuffer' );
  17730. loader.setPath( this.path );
  17731. loader.setRequestHeader( this.requestHeader );
  17732. loader.setWithCredentials( this.withCredentials );
  17733. loader.load( url, function ( buffer ) {
  17734. try {
  17735. // Create a copy of the buffer. The `decodeAudioData` method
  17736. // detaches the buffer when complete, preventing reuse.
  17737. const bufferCopy = buffer.slice( 0 );
  17738. const context = AudioContext.getContext();
  17739. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17740. onLoad( audioBuffer );
  17741. } ).catch( handleError );
  17742. } catch ( e ) {
  17743. handleError( e );
  17744. }
  17745. }, onProgress, onError );
  17746. function handleError( e ) {
  17747. if ( onError ) {
  17748. onError( e );
  17749. } else {
  17750. console.error( e );
  17751. }
  17752. scope.manager.itemError( url );
  17753. }
  17754. }
  17755. }
  17756. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17757. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17758. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17759. class StereoCamera {
  17760. constructor() {
  17761. this.type = 'StereoCamera';
  17762. this.aspect = 1;
  17763. this.eyeSep = 0.064;
  17764. this.cameraL = new PerspectiveCamera();
  17765. this.cameraL.layers.enable( 1 );
  17766. this.cameraL.matrixAutoUpdate = false;
  17767. this.cameraR = new PerspectiveCamera();
  17768. this.cameraR.layers.enable( 2 );
  17769. this.cameraR.matrixAutoUpdate = false;
  17770. this._cache = {
  17771. focus: null,
  17772. fov: null,
  17773. aspect: null,
  17774. near: null,
  17775. far: null,
  17776. zoom: null,
  17777. eyeSep: null
  17778. };
  17779. }
  17780. update( camera ) {
  17781. const cache = this._cache;
  17782. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17783. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17784. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17785. if ( needsUpdate ) {
  17786. cache.focus = camera.focus;
  17787. cache.fov = camera.fov;
  17788. cache.aspect = camera.aspect * this.aspect;
  17789. cache.near = camera.near;
  17790. cache.far = camera.far;
  17791. cache.zoom = camera.zoom;
  17792. cache.eyeSep = this.eyeSep;
  17793. // Off-axis stereoscopic effect based on
  17794. // http://paulbourke.net/stereographics/stereorender/
  17795. _projectionMatrix.copy( camera.projectionMatrix );
  17796. const eyeSepHalf = cache.eyeSep / 2;
  17797. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17798. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17799. let xmin, xmax;
  17800. // translate xOffset
  17801. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17802. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17803. // for left eye
  17804. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17805. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17806. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17807. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17808. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17809. // for right eye
  17810. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17811. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17812. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17813. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17814. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17815. }
  17816. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17817. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17818. }
  17819. }
  17820. class ArrayCamera extends PerspectiveCamera {
  17821. constructor( array = [] ) {
  17822. super();
  17823. this.isArrayCamera = true;
  17824. this.cameras = array;
  17825. }
  17826. }
  17827. class Clock {
  17828. constructor( autoStart = true ) {
  17829. this.autoStart = autoStart;
  17830. this.startTime = 0;
  17831. this.oldTime = 0;
  17832. this.elapsedTime = 0;
  17833. this.running = false;
  17834. }
  17835. start() {
  17836. this.startTime = now();
  17837. this.oldTime = this.startTime;
  17838. this.elapsedTime = 0;
  17839. this.running = true;
  17840. }
  17841. stop() {
  17842. this.getElapsedTime();
  17843. this.running = false;
  17844. this.autoStart = false;
  17845. }
  17846. getElapsedTime() {
  17847. this.getDelta();
  17848. return this.elapsedTime;
  17849. }
  17850. getDelta() {
  17851. let diff = 0;
  17852. if ( this.autoStart && ! this.running ) {
  17853. this.start();
  17854. return 0;
  17855. }
  17856. if ( this.running ) {
  17857. const newTime = now();
  17858. diff = ( newTime - this.oldTime ) / 1000;
  17859. this.oldTime = newTime;
  17860. this.elapsedTime += diff;
  17861. }
  17862. return diff;
  17863. }
  17864. }
  17865. function now() {
  17866. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  17867. }
  17868. const _position$1 = /*@__PURE__*/ new Vector3();
  17869. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17870. const _scale$1 = /*@__PURE__*/ new Vector3();
  17871. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17872. class AudioListener extends Object3D {
  17873. constructor() {
  17874. super();
  17875. this.type = 'AudioListener';
  17876. this.context = AudioContext.getContext();
  17877. this.gain = this.context.createGain();
  17878. this.gain.connect( this.context.destination );
  17879. this.filter = null;
  17880. this.timeDelta = 0;
  17881. // private
  17882. this._clock = new Clock();
  17883. }
  17884. getInput() {
  17885. return this.gain;
  17886. }
  17887. removeFilter() {
  17888. if ( this.filter !== null ) {
  17889. this.gain.disconnect( this.filter );
  17890. this.filter.disconnect( this.context.destination );
  17891. this.gain.connect( this.context.destination );
  17892. this.filter = null;
  17893. }
  17894. return this;
  17895. }
  17896. getFilter() {
  17897. return this.filter;
  17898. }
  17899. setFilter( value ) {
  17900. if ( this.filter !== null ) {
  17901. this.gain.disconnect( this.filter );
  17902. this.filter.disconnect( this.context.destination );
  17903. } else {
  17904. this.gain.disconnect( this.context.destination );
  17905. }
  17906. this.filter = value;
  17907. this.gain.connect( this.filter );
  17908. this.filter.connect( this.context.destination );
  17909. return this;
  17910. }
  17911. getMasterVolume() {
  17912. return this.gain.gain.value;
  17913. }
  17914. setMasterVolume( value ) {
  17915. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17916. return this;
  17917. }
  17918. updateMatrixWorld( force ) {
  17919. super.updateMatrixWorld( force );
  17920. const listener = this.context.listener;
  17921. const up = this.up;
  17922. this.timeDelta = this._clock.getDelta();
  17923. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17924. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17925. if ( listener.positionX ) {
  17926. // code path for Chrome (see #14393)
  17927. const endTime = this.context.currentTime + this.timeDelta;
  17928. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17929. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17930. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17931. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17932. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17933. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17934. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17935. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17936. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17937. } else {
  17938. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17939. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17940. }
  17941. }
  17942. }
  17943. class Audio extends Object3D {
  17944. constructor( listener ) {
  17945. super();
  17946. this.type = 'Audio';
  17947. this.listener = listener;
  17948. this.context = listener.context;
  17949. this.gain = this.context.createGain();
  17950. this.gain.connect( listener.getInput() );
  17951. this.autoplay = false;
  17952. this.buffer = null;
  17953. this.detune = 0;
  17954. this.loop = false;
  17955. this.loopStart = 0;
  17956. this.loopEnd = 0;
  17957. this.offset = 0;
  17958. this.duration = undefined;
  17959. this.playbackRate = 1;
  17960. this.isPlaying = false;
  17961. this.hasPlaybackControl = true;
  17962. this.source = null;
  17963. this.sourceType = 'empty';
  17964. this._startedAt = 0;
  17965. this._progress = 0;
  17966. this._connected = false;
  17967. this.filters = [];
  17968. }
  17969. getOutput() {
  17970. return this.gain;
  17971. }
  17972. setNodeSource( audioNode ) {
  17973. this.hasPlaybackControl = false;
  17974. this.sourceType = 'audioNode';
  17975. this.source = audioNode;
  17976. this.connect();
  17977. return this;
  17978. }
  17979. setMediaElementSource( mediaElement ) {
  17980. this.hasPlaybackControl = false;
  17981. this.sourceType = 'mediaNode';
  17982. this.source = this.context.createMediaElementSource( mediaElement );
  17983. this.connect();
  17984. return this;
  17985. }
  17986. setMediaStreamSource( mediaStream ) {
  17987. this.hasPlaybackControl = false;
  17988. this.sourceType = 'mediaStreamNode';
  17989. this.source = this.context.createMediaStreamSource( mediaStream );
  17990. this.connect();
  17991. return this;
  17992. }
  17993. setBuffer( audioBuffer ) {
  17994. this.buffer = audioBuffer;
  17995. this.sourceType = 'buffer';
  17996. if ( this.autoplay ) this.play();
  17997. return this;
  17998. }
  17999. play( delay = 0 ) {
  18000. if ( this.isPlaying === true ) {
  18001. console.warn( 'THREE.Audio: Audio is already playing.' );
  18002. return;
  18003. }
  18004. if ( this.hasPlaybackControl === false ) {
  18005. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18006. return;
  18007. }
  18008. this._startedAt = this.context.currentTime + delay;
  18009. const source = this.context.createBufferSource();
  18010. source.buffer = this.buffer;
  18011. source.loop = this.loop;
  18012. source.loopStart = this.loopStart;
  18013. source.loopEnd = this.loopEnd;
  18014. source.onended = this.onEnded.bind( this );
  18015. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18016. this.isPlaying = true;
  18017. this.source = source;
  18018. this.setDetune( this.detune );
  18019. this.setPlaybackRate( this.playbackRate );
  18020. return this.connect();
  18021. }
  18022. pause() {
  18023. if ( this.hasPlaybackControl === false ) {
  18024. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18025. return;
  18026. }
  18027. if ( this.isPlaying === true ) {
  18028. // update current progress
  18029. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18030. if ( this.loop === true ) {
  18031. // ensure _progress does not exceed duration with looped audios
  18032. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18033. }
  18034. this.source.stop();
  18035. this.source.onended = null;
  18036. this.isPlaying = false;
  18037. }
  18038. return this;
  18039. }
  18040. stop() {
  18041. if ( this.hasPlaybackControl === false ) {
  18042. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18043. return;
  18044. }
  18045. this._progress = 0;
  18046. if ( this.source !== null ) {
  18047. this.source.stop();
  18048. this.source.onended = null;
  18049. }
  18050. this.isPlaying = false;
  18051. return this;
  18052. }
  18053. connect() {
  18054. if ( this.filters.length > 0 ) {
  18055. this.source.connect( this.filters[ 0 ] );
  18056. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18057. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18058. }
  18059. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18060. } else {
  18061. this.source.connect( this.getOutput() );
  18062. }
  18063. this._connected = true;
  18064. return this;
  18065. }
  18066. disconnect() {
  18067. if ( this._connected === false ) {
  18068. return;
  18069. }
  18070. if ( this.filters.length > 0 ) {
  18071. this.source.disconnect( this.filters[ 0 ] );
  18072. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18073. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18074. }
  18075. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18076. } else {
  18077. this.source.disconnect( this.getOutput() );
  18078. }
  18079. this._connected = false;
  18080. return this;
  18081. }
  18082. getFilters() {
  18083. return this.filters;
  18084. }
  18085. setFilters( value ) {
  18086. if ( ! value ) value = [];
  18087. if ( this._connected === true ) {
  18088. this.disconnect();
  18089. this.filters = value.slice();
  18090. this.connect();
  18091. } else {
  18092. this.filters = value.slice();
  18093. }
  18094. return this;
  18095. }
  18096. setDetune( value ) {
  18097. this.detune = value;
  18098. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18099. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18100. }
  18101. return this;
  18102. }
  18103. getDetune() {
  18104. return this.detune;
  18105. }
  18106. getFilter() {
  18107. return this.getFilters()[ 0 ];
  18108. }
  18109. setFilter( filter ) {
  18110. return this.setFilters( filter ? [ filter ] : [] );
  18111. }
  18112. setPlaybackRate( value ) {
  18113. if ( this.hasPlaybackControl === false ) {
  18114. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18115. return;
  18116. }
  18117. this.playbackRate = value;
  18118. if ( this.isPlaying === true ) {
  18119. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18120. }
  18121. return this;
  18122. }
  18123. getPlaybackRate() {
  18124. return this.playbackRate;
  18125. }
  18126. onEnded() {
  18127. this.isPlaying = false;
  18128. }
  18129. getLoop() {
  18130. if ( this.hasPlaybackControl === false ) {
  18131. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18132. return false;
  18133. }
  18134. return this.loop;
  18135. }
  18136. setLoop( value ) {
  18137. if ( this.hasPlaybackControl === false ) {
  18138. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18139. return;
  18140. }
  18141. this.loop = value;
  18142. if ( this.isPlaying === true ) {
  18143. this.source.loop = this.loop;
  18144. }
  18145. return this;
  18146. }
  18147. setLoopStart( value ) {
  18148. this.loopStart = value;
  18149. return this;
  18150. }
  18151. setLoopEnd( value ) {
  18152. this.loopEnd = value;
  18153. return this;
  18154. }
  18155. getVolume() {
  18156. return this.gain.gain.value;
  18157. }
  18158. setVolume( value ) {
  18159. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18160. return this;
  18161. }
  18162. }
  18163. const _position = /*@__PURE__*/ new Vector3();
  18164. const _quaternion = /*@__PURE__*/ new Quaternion();
  18165. const _scale = /*@__PURE__*/ new Vector3();
  18166. const _orientation = /*@__PURE__*/ new Vector3();
  18167. class PositionalAudio extends Audio {
  18168. constructor( listener ) {
  18169. super( listener );
  18170. this.panner = this.context.createPanner();
  18171. this.panner.panningModel = 'HRTF';
  18172. this.panner.connect( this.gain );
  18173. }
  18174. connect() {
  18175. super.connect();
  18176. this.panner.connect( this.gain );
  18177. }
  18178. disconnect() {
  18179. super.disconnect();
  18180. this.panner.disconnect( this.gain );
  18181. }
  18182. getOutput() {
  18183. return this.panner;
  18184. }
  18185. getRefDistance() {
  18186. return this.panner.refDistance;
  18187. }
  18188. setRefDistance( value ) {
  18189. this.panner.refDistance = value;
  18190. return this;
  18191. }
  18192. getRolloffFactor() {
  18193. return this.panner.rolloffFactor;
  18194. }
  18195. setRolloffFactor( value ) {
  18196. this.panner.rolloffFactor = value;
  18197. return this;
  18198. }
  18199. getDistanceModel() {
  18200. return this.panner.distanceModel;
  18201. }
  18202. setDistanceModel( value ) {
  18203. this.panner.distanceModel = value;
  18204. return this;
  18205. }
  18206. getMaxDistance() {
  18207. return this.panner.maxDistance;
  18208. }
  18209. setMaxDistance( value ) {
  18210. this.panner.maxDistance = value;
  18211. return this;
  18212. }
  18213. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18214. this.panner.coneInnerAngle = coneInnerAngle;
  18215. this.panner.coneOuterAngle = coneOuterAngle;
  18216. this.panner.coneOuterGain = coneOuterGain;
  18217. return this;
  18218. }
  18219. updateMatrixWorld( force ) {
  18220. super.updateMatrixWorld( force );
  18221. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18222. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18223. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18224. const panner = this.panner;
  18225. if ( panner.positionX ) {
  18226. // code path for Chrome and Firefox (see #14393)
  18227. const endTime = this.context.currentTime + this.listener.timeDelta;
  18228. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18229. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18230. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18231. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18232. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18233. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18234. } else {
  18235. panner.setPosition( _position.x, _position.y, _position.z );
  18236. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18237. }
  18238. }
  18239. }
  18240. class AudioAnalyser {
  18241. constructor( audio, fftSize = 2048 ) {
  18242. this.analyser = audio.context.createAnalyser();
  18243. this.analyser.fftSize = fftSize;
  18244. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18245. audio.getOutput().connect( this.analyser );
  18246. }
  18247. getFrequencyData() {
  18248. this.analyser.getByteFrequencyData( this.data );
  18249. return this.data;
  18250. }
  18251. getAverageFrequency() {
  18252. let value = 0;
  18253. const data = this.getFrequencyData();
  18254. for ( let i = 0; i < data.length; i ++ ) {
  18255. value += data[ i ];
  18256. }
  18257. return value / data.length;
  18258. }
  18259. }
  18260. class PropertyMixer {
  18261. constructor( binding, typeName, valueSize ) {
  18262. this.binding = binding;
  18263. this.valueSize = valueSize;
  18264. let mixFunction,
  18265. mixFunctionAdditive,
  18266. setIdentity;
  18267. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18268. //
  18269. // interpolators can use .buffer as their .result
  18270. // the data then goes to 'incoming'
  18271. //
  18272. // 'accu0' and 'accu1' are used frame-interleaved for
  18273. // the cumulative result and are compared to detect
  18274. // changes
  18275. //
  18276. // 'orig' stores the original state of the property
  18277. //
  18278. // 'add' is used for additive cumulative results
  18279. //
  18280. // 'work' is optional and is only present for quaternion types. It is used
  18281. // to store intermediate quaternion multiplication results
  18282. switch ( typeName ) {
  18283. case 'quaternion':
  18284. mixFunction = this._slerp;
  18285. mixFunctionAdditive = this._slerpAdditive;
  18286. setIdentity = this._setAdditiveIdentityQuaternion;
  18287. this.buffer = new Float64Array( valueSize * 6 );
  18288. this._workIndex = 5;
  18289. break;
  18290. case 'string':
  18291. case 'bool':
  18292. mixFunction = this._select;
  18293. // Use the regular mix function and for additive on these types,
  18294. // additive is not relevant for non-numeric types
  18295. mixFunctionAdditive = this._select;
  18296. setIdentity = this._setAdditiveIdentityOther;
  18297. this.buffer = new Array( valueSize * 5 );
  18298. break;
  18299. default:
  18300. mixFunction = this._lerp;
  18301. mixFunctionAdditive = this._lerpAdditive;
  18302. setIdentity = this._setAdditiveIdentityNumeric;
  18303. this.buffer = new Float64Array( valueSize * 5 );
  18304. }
  18305. this._mixBufferRegion = mixFunction;
  18306. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18307. this._setIdentity = setIdentity;
  18308. this._origIndex = 3;
  18309. this._addIndex = 4;
  18310. this.cumulativeWeight = 0;
  18311. this.cumulativeWeightAdditive = 0;
  18312. this.useCount = 0;
  18313. this.referenceCount = 0;
  18314. }
  18315. // accumulate data in the 'incoming' region into 'accu<i>'
  18316. accumulate( accuIndex, weight ) {
  18317. // note: happily accumulating nothing when weight = 0, the caller knows
  18318. // the weight and shouldn't have made the call in the first place
  18319. const buffer = this.buffer,
  18320. stride = this.valueSize,
  18321. offset = accuIndex * stride + stride;
  18322. let currentWeight = this.cumulativeWeight;
  18323. if ( currentWeight === 0 ) {
  18324. // accuN := incoming * weight
  18325. for ( let i = 0; i !== stride; ++ i ) {
  18326. buffer[ offset + i ] = buffer[ i ];
  18327. }
  18328. currentWeight = weight;
  18329. } else {
  18330. // accuN := accuN + incoming * weight
  18331. currentWeight += weight;
  18332. const mix = weight / currentWeight;
  18333. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18334. }
  18335. this.cumulativeWeight = currentWeight;
  18336. }
  18337. // accumulate data in the 'incoming' region into 'add'
  18338. accumulateAdditive( weight ) {
  18339. const buffer = this.buffer,
  18340. stride = this.valueSize,
  18341. offset = stride * this._addIndex;
  18342. if ( this.cumulativeWeightAdditive === 0 ) {
  18343. // add = identity
  18344. this._setIdentity();
  18345. }
  18346. // add := add + incoming * weight
  18347. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18348. this.cumulativeWeightAdditive += weight;
  18349. }
  18350. // apply the state of 'accu<i>' to the binding when accus differ
  18351. apply( accuIndex ) {
  18352. const stride = this.valueSize,
  18353. buffer = this.buffer,
  18354. offset = accuIndex * stride + stride,
  18355. weight = this.cumulativeWeight,
  18356. weightAdditive = this.cumulativeWeightAdditive,
  18357. binding = this.binding;
  18358. this.cumulativeWeight = 0;
  18359. this.cumulativeWeightAdditive = 0;
  18360. if ( weight < 1 ) {
  18361. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18362. const originalValueOffset = stride * this._origIndex;
  18363. this._mixBufferRegion(
  18364. buffer, offset, originalValueOffset, 1 - weight, stride );
  18365. }
  18366. if ( weightAdditive > 0 ) {
  18367. // accuN := accuN + additive accuN
  18368. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18369. }
  18370. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18371. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18372. // value has changed -> update scene graph
  18373. binding.setValue( buffer, offset );
  18374. break;
  18375. }
  18376. }
  18377. }
  18378. // remember the state of the bound property and copy it to both accus
  18379. saveOriginalState() {
  18380. const binding = this.binding;
  18381. const buffer = this.buffer,
  18382. stride = this.valueSize,
  18383. originalValueOffset = stride * this._origIndex;
  18384. binding.getValue( buffer, originalValueOffset );
  18385. // accu[0..1] := orig -- initially detect changes against the original
  18386. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18387. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18388. }
  18389. // Add to identity for additive
  18390. this._setIdentity();
  18391. this.cumulativeWeight = 0;
  18392. this.cumulativeWeightAdditive = 0;
  18393. }
  18394. // apply the state previously taken via 'saveOriginalState' to the binding
  18395. restoreOriginalState() {
  18396. const originalValueOffset = this.valueSize * 3;
  18397. this.binding.setValue( this.buffer, originalValueOffset );
  18398. }
  18399. _setAdditiveIdentityNumeric() {
  18400. const startIndex = this._addIndex * this.valueSize;
  18401. const endIndex = startIndex + this.valueSize;
  18402. for ( let i = startIndex; i < endIndex; i ++ ) {
  18403. this.buffer[ i ] = 0;
  18404. }
  18405. }
  18406. _setAdditiveIdentityQuaternion() {
  18407. this._setAdditiveIdentityNumeric();
  18408. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18409. }
  18410. _setAdditiveIdentityOther() {
  18411. const startIndex = this._origIndex * this.valueSize;
  18412. const targetIndex = this._addIndex * this.valueSize;
  18413. for ( let i = 0; i < this.valueSize; i ++ ) {
  18414. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18415. }
  18416. }
  18417. // mix functions
  18418. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18419. if ( t >= 0.5 ) {
  18420. for ( let i = 0; i !== stride; ++ i ) {
  18421. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18422. }
  18423. }
  18424. }
  18425. _slerp( buffer, dstOffset, srcOffset, t ) {
  18426. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18427. }
  18428. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18429. const workOffset = this._workIndex * stride;
  18430. // Store result in intermediate buffer offset
  18431. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18432. // Slerp to the intermediate result
  18433. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18434. }
  18435. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18436. const s = 1 - t;
  18437. for ( let i = 0; i !== stride; ++ i ) {
  18438. const j = dstOffset + i;
  18439. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18440. }
  18441. }
  18442. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18443. for ( let i = 0; i !== stride; ++ i ) {
  18444. const j = dstOffset + i;
  18445. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18446. }
  18447. }
  18448. }
  18449. // Characters [].:/ are reserved for track binding syntax.
  18450. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18451. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18452. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18453. // only latin characters, and the unicode \p{L} is not yet supported. So
  18454. // instead, we exclude reserved characters and match everything else.
  18455. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18456. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18457. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18458. // be matched to parse the rest of the track name.
  18459. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18460. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18461. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18462. // Object on target node, and accessor. May not contain reserved
  18463. // characters. Accessor may contain any character except closing bracket.
  18464. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18465. // Property and accessor. May not contain reserved characters. Accessor may
  18466. // contain any non-bracket characters.
  18467. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18468. const _trackRe = new RegExp( ''
  18469. + '^'
  18470. + _directoryRe
  18471. + _nodeRe
  18472. + _objectRe
  18473. + _propertyRe
  18474. + '$'
  18475. );
  18476. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18477. class Composite {
  18478. constructor( targetGroup, path, optionalParsedPath ) {
  18479. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18480. this._targetGroup = targetGroup;
  18481. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18482. }
  18483. getValue( array, offset ) {
  18484. this.bind(); // bind all binding
  18485. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18486. binding = this._bindings[ firstValidIndex ];
  18487. // and only call .getValue on the first
  18488. if ( binding !== undefined ) binding.getValue( array, offset );
  18489. }
  18490. setValue( array, offset ) {
  18491. const bindings = this._bindings;
  18492. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18493. bindings[ i ].setValue( array, offset );
  18494. }
  18495. }
  18496. bind() {
  18497. const bindings = this._bindings;
  18498. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18499. bindings[ i ].bind();
  18500. }
  18501. }
  18502. unbind() {
  18503. const bindings = this._bindings;
  18504. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18505. bindings[ i ].unbind();
  18506. }
  18507. }
  18508. }
  18509. // Note: This class uses a State pattern on a per-method basis:
  18510. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18511. // prototype version of these methods with one that represents
  18512. // the bound state. When the property is not found, the methods
  18513. // become no-ops.
  18514. class PropertyBinding {
  18515. constructor( rootNode, path, parsedPath ) {
  18516. this.path = path;
  18517. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18518. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18519. this.rootNode = rootNode;
  18520. // initial state of these methods that calls 'bind'
  18521. this.getValue = this._getValue_unbound;
  18522. this.setValue = this._setValue_unbound;
  18523. }
  18524. static create( root, path, parsedPath ) {
  18525. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18526. return new PropertyBinding( root, path, parsedPath );
  18527. } else {
  18528. return new PropertyBinding.Composite( root, path, parsedPath );
  18529. }
  18530. }
  18531. /**
  18532. * Replaces spaces with underscores and removes unsupported characters from
  18533. * node names, to ensure compatibility with parseTrackName().
  18534. *
  18535. * @param {string} name Node name to be sanitized.
  18536. * @return {string}
  18537. */
  18538. static sanitizeNodeName( name ) {
  18539. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18540. }
  18541. static parseTrackName( trackName ) {
  18542. const matches = _trackRe.exec( trackName );
  18543. if ( matches === null ) {
  18544. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18545. }
  18546. const results = {
  18547. // directoryName: matches[ 1 ], // (tschw) currently unused
  18548. nodeName: matches[ 2 ],
  18549. objectName: matches[ 3 ],
  18550. objectIndex: matches[ 4 ],
  18551. propertyName: matches[ 5 ], // required
  18552. propertyIndex: matches[ 6 ]
  18553. };
  18554. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18555. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18556. const objectName = results.nodeName.substring( lastDot + 1 );
  18557. // Object names must be checked against an allowlist. Otherwise, there
  18558. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18559. // 'bar' could be the objectName, or part of a nodeName (which can
  18560. // include '.' characters).
  18561. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18562. results.nodeName = results.nodeName.substring( 0, lastDot );
  18563. results.objectName = objectName;
  18564. }
  18565. }
  18566. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18567. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18568. }
  18569. return results;
  18570. }
  18571. static findNode( root, nodeName ) {
  18572. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18573. return root;
  18574. }
  18575. // search into skeleton bones.
  18576. if ( root.skeleton ) {
  18577. const bone = root.skeleton.getBoneByName( nodeName );
  18578. if ( bone !== undefined ) {
  18579. return bone;
  18580. }
  18581. }
  18582. // search into node subtree.
  18583. if ( root.children ) {
  18584. const searchNodeSubtree = function ( children ) {
  18585. for ( let i = 0; i < children.length; i ++ ) {
  18586. const childNode = children[ i ];
  18587. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18588. return childNode;
  18589. }
  18590. const result = searchNodeSubtree( childNode.children );
  18591. if ( result ) return result;
  18592. }
  18593. return null;
  18594. };
  18595. const subTreeNode = searchNodeSubtree( root.children );
  18596. if ( subTreeNode ) {
  18597. return subTreeNode;
  18598. }
  18599. }
  18600. return null;
  18601. }
  18602. // these are used to "bind" a nonexistent property
  18603. _getValue_unavailable() {}
  18604. _setValue_unavailable() {}
  18605. // Getters
  18606. _getValue_direct( buffer, offset ) {
  18607. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18608. }
  18609. _getValue_array( buffer, offset ) {
  18610. const source = this.resolvedProperty;
  18611. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18612. buffer[ offset ++ ] = source[ i ];
  18613. }
  18614. }
  18615. _getValue_arrayElement( buffer, offset ) {
  18616. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18617. }
  18618. _getValue_toArray( buffer, offset ) {
  18619. this.resolvedProperty.toArray( buffer, offset );
  18620. }
  18621. // Direct
  18622. _setValue_direct( buffer, offset ) {
  18623. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18624. }
  18625. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18626. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18627. this.targetObject.needsUpdate = true;
  18628. }
  18629. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18630. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18631. this.targetObject.matrixWorldNeedsUpdate = true;
  18632. }
  18633. // EntireArray
  18634. _setValue_array( buffer, offset ) {
  18635. const dest = this.resolvedProperty;
  18636. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18637. dest[ i ] = buffer[ offset ++ ];
  18638. }
  18639. }
  18640. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18641. const dest = this.resolvedProperty;
  18642. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18643. dest[ i ] = buffer[ offset ++ ];
  18644. }
  18645. this.targetObject.needsUpdate = true;
  18646. }
  18647. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18648. const dest = this.resolvedProperty;
  18649. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18650. dest[ i ] = buffer[ offset ++ ];
  18651. }
  18652. this.targetObject.matrixWorldNeedsUpdate = true;
  18653. }
  18654. // ArrayElement
  18655. _setValue_arrayElement( buffer, offset ) {
  18656. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18657. }
  18658. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18659. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18660. this.targetObject.needsUpdate = true;
  18661. }
  18662. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18663. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18664. this.targetObject.matrixWorldNeedsUpdate = true;
  18665. }
  18666. // HasToFromArray
  18667. _setValue_fromArray( buffer, offset ) {
  18668. this.resolvedProperty.fromArray( buffer, offset );
  18669. }
  18670. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18671. this.resolvedProperty.fromArray( buffer, offset );
  18672. this.targetObject.needsUpdate = true;
  18673. }
  18674. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18675. this.resolvedProperty.fromArray( buffer, offset );
  18676. this.targetObject.matrixWorldNeedsUpdate = true;
  18677. }
  18678. _getValue_unbound( targetArray, offset ) {
  18679. this.bind();
  18680. this.getValue( targetArray, offset );
  18681. }
  18682. _setValue_unbound( sourceArray, offset ) {
  18683. this.bind();
  18684. this.setValue( sourceArray, offset );
  18685. }
  18686. // create getter / setter pair for a property in the scene graph
  18687. bind() {
  18688. let targetObject = this.node;
  18689. const parsedPath = this.parsedPath;
  18690. const objectName = parsedPath.objectName;
  18691. const propertyName = parsedPath.propertyName;
  18692. let propertyIndex = parsedPath.propertyIndex;
  18693. if ( ! targetObject ) {
  18694. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18695. this.node = targetObject;
  18696. }
  18697. // set fail state so we can just 'return' on error
  18698. this.getValue = this._getValue_unavailable;
  18699. this.setValue = this._setValue_unavailable;
  18700. // ensure there is a value node
  18701. if ( ! targetObject ) {
  18702. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18703. return;
  18704. }
  18705. if ( objectName ) {
  18706. let objectIndex = parsedPath.objectIndex;
  18707. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18708. switch ( objectName ) {
  18709. case 'materials':
  18710. if ( ! targetObject.material ) {
  18711. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18712. return;
  18713. }
  18714. if ( ! targetObject.material.materials ) {
  18715. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18716. return;
  18717. }
  18718. targetObject = targetObject.material.materials;
  18719. break;
  18720. case 'bones':
  18721. if ( ! targetObject.skeleton ) {
  18722. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18723. return;
  18724. }
  18725. // potential future optimization: skip this if propertyIndex is already an integer
  18726. // and convert the integer string to a true integer.
  18727. targetObject = targetObject.skeleton.bones;
  18728. // support resolving morphTarget names into indices.
  18729. for ( let i = 0; i < targetObject.length; i ++ ) {
  18730. if ( targetObject[ i ].name === objectIndex ) {
  18731. objectIndex = i;
  18732. break;
  18733. }
  18734. }
  18735. break;
  18736. case 'map':
  18737. if ( 'map' in targetObject ) {
  18738. targetObject = targetObject.map;
  18739. break;
  18740. }
  18741. if ( ! targetObject.material ) {
  18742. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18743. return;
  18744. }
  18745. if ( ! targetObject.material.map ) {
  18746. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18747. return;
  18748. }
  18749. targetObject = targetObject.material.map;
  18750. break;
  18751. default:
  18752. if ( targetObject[ objectName ] === undefined ) {
  18753. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18754. return;
  18755. }
  18756. targetObject = targetObject[ objectName ];
  18757. }
  18758. if ( objectIndex !== undefined ) {
  18759. if ( targetObject[ objectIndex ] === undefined ) {
  18760. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18761. return;
  18762. }
  18763. targetObject = targetObject[ objectIndex ];
  18764. }
  18765. }
  18766. // resolve property
  18767. const nodeProperty = targetObject[ propertyName ];
  18768. if ( nodeProperty === undefined ) {
  18769. const nodeName = parsedPath.nodeName;
  18770. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18771. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18772. return;
  18773. }
  18774. // determine versioning scheme
  18775. let versioning = this.Versioning.None;
  18776. this.targetObject = targetObject;
  18777. if ( targetObject.needsUpdate !== undefined ) { // material
  18778. versioning = this.Versioning.NeedsUpdate;
  18779. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18780. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18781. }
  18782. // determine how the property gets bound
  18783. let bindingType = this.BindingType.Direct;
  18784. if ( propertyIndex !== undefined ) {
  18785. // access a sub element of the property array (only primitives are supported right now)
  18786. if ( propertyName === 'morphTargetInfluences' ) {
  18787. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18788. // support resolving morphTarget names into indices.
  18789. if ( ! targetObject.geometry ) {
  18790. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18791. return;
  18792. }
  18793. if ( ! targetObject.geometry.morphAttributes ) {
  18794. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18795. return;
  18796. }
  18797. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18798. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18799. }
  18800. }
  18801. bindingType = this.BindingType.ArrayElement;
  18802. this.resolvedProperty = nodeProperty;
  18803. this.propertyIndex = propertyIndex;
  18804. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18805. // must use copy for Object3D.Euler/Quaternion
  18806. bindingType = this.BindingType.HasFromToArray;
  18807. this.resolvedProperty = nodeProperty;
  18808. } else if ( Array.isArray( nodeProperty ) ) {
  18809. bindingType = this.BindingType.EntireArray;
  18810. this.resolvedProperty = nodeProperty;
  18811. } else {
  18812. this.propertyName = propertyName;
  18813. }
  18814. // select getter / setter
  18815. this.getValue = this.GetterByBindingType[ bindingType ];
  18816. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18817. }
  18818. unbind() {
  18819. this.node = null;
  18820. // back to the prototype version of getValue / setValue
  18821. // note: avoiding to mutate the shape of 'this' via 'delete'
  18822. this.getValue = this._getValue_unbound;
  18823. this.setValue = this._setValue_unbound;
  18824. }
  18825. }
  18826. PropertyBinding.Composite = Composite;
  18827. PropertyBinding.prototype.BindingType = {
  18828. Direct: 0,
  18829. EntireArray: 1,
  18830. ArrayElement: 2,
  18831. HasFromToArray: 3
  18832. };
  18833. PropertyBinding.prototype.Versioning = {
  18834. None: 0,
  18835. NeedsUpdate: 1,
  18836. MatrixWorldNeedsUpdate: 2
  18837. };
  18838. PropertyBinding.prototype.GetterByBindingType = [
  18839. PropertyBinding.prototype._getValue_direct,
  18840. PropertyBinding.prototype._getValue_array,
  18841. PropertyBinding.prototype._getValue_arrayElement,
  18842. PropertyBinding.prototype._getValue_toArray,
  18843. ];
  18844. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18845. [
  18846. // Direct
  18847. PropertyBinding.prototype._setValue_direct,
  18848. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18849. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18850. ], [
  18851. // EntireArray
  18852. PropertyBinding.prototype._setValue_array,
  18853. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18854. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18855. ], [
  18856. // ArrayElement
  18857. PropertyBinding.prototype._setValue_arrayElement,
  18858. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18859. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18860. ], [
  18861. // HasToFromArray
  18862. PropertyBinding.prototype._setValue_fromArray,
  18863. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18864. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18865. ]
  18866. ];
  18867. /**
  18868. *
  18869. * A group of objects that receives a shared animation state.
  18870. *
  18871. * Usage:
  18872. *
  18873. * - Add objects you would otherwise pass as 'root' to the
  18874. * constructor or the .clipAction method of AnimationMixer.
  18875. *
  18876. * - Instead pass this object as 'root'.
  18877. *
  18878. * - You can also add and remove objects later when the mixer
  18879. * is running.
  18880. *
  18881. * Note:
  18882. *
  18883. * Objects of this class appear as one object to the mixer,
  18884. * so cache control of the individual objects must be done
  18885. * on the group.
  18886. *
  18887. * Limitation:
  18888. *
  18889. * - The animated properties must be compatible among the
  18890. * all objects in the group.
  18891. *
  18892. * - A single property can either be controlled through a
  18893. * target group or directly, but not both.
  18894. */
  18895. class AnimationObjectGroup {
  18896. constructor() {
  18897. this.isAnimationObjectGroup = true;
  18898. this.uuid = generateUUID();
  18899. // cached objects followed by the active ones
  18900. this._objects = Array.prototype.slice.call( arguments );
  18901. this.nCachedObjects_ = 0; // threshold
  18902. // note: read by PropertyBinding.Composite
  18903. const indices = {};
  18904. this._indicesByUUID = indices; // for bookkeeping
  18905. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18906. indices[ arguments[ i ].uuid ] = i;
  18907. }
  18908. this._paths = []; // inside: string
  18909. this._parsedPaths = []; // inside: { we don't care, here }
  18910. this._bindings = []; // inside: Array< PropertyBinding >
  18911. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18912. const scope = this;
  18913. this.stats = {
  18914. objects: {
  18915. get total() {
  18916. return scope._objects.length;
  18917. },
  18918. get inUse() {
  18919. return this.total - scope.nCachedObjects_;
  18920. }
  18921. },
  18922. get bindingsPerObject() {
  18923. return scope._bindings.length;
  18924. }
  18925. };
  18926. }
  18927. add() {
  18928. const objects = this._objects,
  18929. indicesByUUID = this._indicesByUUID,
  18930. paths = this._paths,
  18931. parsedPaths = this._parsedPaths,
  18932. bindings = this._bindings,
  18933. nBindings = bindings.length;
  18934. let knownObject = undefined,
  18935. nObjects = objects.length,
  18936. nCachedObjects = this.nCachedObjects_;
  18937. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18938. const object = arguments[ i ],
  18939. uuid = object.uuid;
  18940. let index = indicesByUUID[ uuid ];
  18941. if ( index === undefined ) {
  18942. // unknown object -> add it to the ACTIVE region
  18943. index = nObjects ++;
  18944. indicesByUUID[ uuid ] = index;
  18945. objects.push( object );
  18946. // accounting is done, now do the same for all bindings
  18947. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18948. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18949. }
  18950. } else if ( index < nCachedObjects ) {
  18951. knownObject = objects[ index ];
  18952. // move existing object to the ACTIVE region
  18953. const firstActiveIndex = -- nCachedObjects,
  18954. lastCachedObject = objects[ firstActiveIndex ];
  18955. indicesByUUID[ lastCachedObject.uuid ] = index;
  18956. objects[ index ] = lastCachedObject;
  18957. indicesByUUID[ uuid ] = firstActiveIndex;
  18958. objects[ firstActiveIndex ] = object;
  18959. // accounting is done, now do the same for all bindings
  18960. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18961. const bindingsForPath = bindings[ j ],
  18962. lastCached = bindingsForPath[ firstActiveIndex ];
  18963. let binding = bindingsForPath[ index ];
  18964. bindingsForPath[ index ] = lastCached;
  18965. if ( binding === undefined ) {
  18966. // since we do not bother to create new bindings
  18967. // for objects that are cached, the binding may
  18968. // or may not exist
  18969. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  18970. }
  18971. bindingsForPath[ firstActiveIndex ] = binding;
  18972. }
  18973. } else if ( objects[ index ] !== knownObject ) {
  18974. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  18975. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  18976. } // else the object is already where we want it to be
  18977. } // for arguments
  18978. this.nCachedObjects_ = nCachedObjects;
  18979. }
  18980. remove() {
  18981. const objects = this._objects,
  18982. indicesByUUID = this._indicesByUUID,
  18983. bindings = this._bindings,
  18984. nBindings = bindings.length;
  18985. let nCachedObjects = this.nCachedObjects_;
  18986. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18987. const object = arguments[ i ],
  18988. uuid = object.uuid,
  18989. index = indicesByUUID[ uuid ];
  18990. if ( index !== undefined && index >= nCachedObjects ) {
  18991. // move existing object into the CACHED region
  18992. const lastCachedIndex = nCachedObjects ++,
  18993. firstActiveObject = objects[ lastCachedIndex ];
  18994. indicesByUUID[ firstActiveObject.uuid ] = index;
  18995. objects[ index ] = firstActiveObject;
  18996. indicesByUUID[ uuid ] = lastCachedIndex;
  18997. objects[ lastCachedIndex ] = object;
  18998. // accounting is done, now do the same for all bindings
  18999. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19000. const bindingsForPath = bindings[ j ],
  19001. firstActive = bindingsForPath[ lastCachedIndex ],
  19002. binding = bindingsForPath[ index ];
  19003. bindingsForPath[ index ] = firstActive;
  19004. bindingsForPath[ lastCachedIndex ] = binding;
  19005. }
  19006. }
  19007. } // for arguments
  19008. this.nCachedObjects_ = nCachedObjects;
  19009. }
  19010. // remove & forget
  19011. uncache() {
  19012. const objects = this._objects,
  19013. indicesByUUID = this._indicesByUUID,
  19014. bindings = this._bindings,
  19015. nBindings = bindings.length;
  19016. let nCachedObjects = this.nCachedObjects_,
  19017. nObjects = objects.length;
  19018. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19019. const object = arguments[ i ],
  19020. uuid = object.uuid,
  19021. index = indicesByUUID[ uuid ];
  19022. if ( index !== undefined ) {
  19023. delete indicesByUUID[ uuid ];
  19024. if ( index < nCachedObjects ) {
  19025. // object is cached, shrink the CACHED region
  19026. const firstActiveIndex = -- nCachedObjects,
  19027. lastCachedObject = objects[ firstActiveIndex ],
  19028. lastIndex = -- nObjects,
  19029. lastObject = objects[ lastIndex ];
  19030. // last cached object takes this object's place
  19031. indicesByUUID[ lastCachedObject.uuid ] = index;
  19032. objects[ index ] = lastCachedObject;
  19033. // last object goes to the activated slot and pop
  19034. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19035. objects[ firstActiveIndex ] = lastObject;
  19036. objects.pop();
  19037. // accounting is done, now do the same for all bindings
  19038. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19039. const bindingsForPath = bindings[ j ],
  19040. lastCached = bindingsForPath[ firstActiveIndex ],
  19041. last = bindingsForPath[ lastIndex ];
  19042. bindingsForPath[ index ] = lastCached;
  19043. bindingsForPath[ firstActiveIndex ] = last;
  19044. bindingsForPath.pop();
  19045. }
  19046. } else {
  19047. // object is active, just swap with the last and pop
  19048. const lastIndex = -- nObjects,
  19049. lastObject = objects[ lastIndex ];
  19050. if ( lastIndex > 0 ) {
  19051. indicesByUUID[ lastObject.uuid ] = index;
  19052. }
  19053. objects[ index ] = lastObject;
  19054. objects.pop();
  19055. // accounting is done, now do the same for all bindings
  19056. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19057. const bindingsForPath = bindings[ j ];
  19058. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19059. bindingsForPath.pop();
  19060. }
  19061. } // cached or active
  19062. } // if object is known
  19063. } // for arguments
  19064. this.nCachedObjects_ = nCachedObjects;
  19065. }
  19066. // Internal interface used by befriended PropertyBinding.Composite:
  19067. subscribe_( path, parsedPath ) {
  19068. // returns an array of bindings for the given path that is changed
  19069. // according to the contained objects in the group
  19070. const indicesByPath = this._bindingsIndicesByPath;
  19071. let index = indicesByPath[ path ];
  19072. const bindings = this._bindings;
  19073. if ( index !== undefined ) return bindings[ index ];
  19074. const paths = this._paths,
  19075. parsedPaths = this._parsedPaths,
  19076. objects = this._objects,
  19077. nObjects = objects.length,
  19078. nCachedObjects = this.nCachedObjects_,
  19079. bindingsForPath = new Array( nObjects );
  19080. index = bindings.length;
  19081. indicesByPath[ path ] = index;
  19082. paths.push( path );
  19083. parsedPaths.push( parsedPath );
  19084. bindings.push( bindingsForPath );
  19085. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19086. const object = objects[ i ];
  19087. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19088. }
  19089. return bindingsForPath;
  19090. }
  19091. unsubscribe_( path ) {
  19092. // tells the group to forget about a property path and no longer
  19093. // update the array previously obtained with 'subscribe_'
  19094. const indicesByPath = this._bindingsIndicesByPath,
  19095. index = indicesByPath[ path ];
  19096. if ( index !== undefined ) {
  19097. const paths = this._paths,
  19098. parsedPaths = this._parsedPaths,
  19099. bindings = this._bindings,
  19100. lastBindingsIndex = bindings.length - 1,
  19101. lastBindings = bindings[ lastBindingsIndex ],
  19102. lastBindingsPath = path[ lastBindingsIndex ];
  19103. indicesByPath[ lastBindingsPath ] = index;
  19104. bindings[ index ] = lastBindings;
  19105. bindings.pop();
  19106. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19107. parsedPaths.pop();
  19108. paths[ index ] = paths[ lastBindingsIndex ];
  19109. paths.pop();
  19110. }
  19111. }
  19112. }
  19113. class AnimationAction {
  19114. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19115. this._mixer = mixer;
  19116. this._clip = clip;
  19117. this._localRoot = localRoot;
  19118. this.blendMode = blendMode;
  19119. const tracks = clip.tracks,
  19120. nTracks = tracks.length,
  19121. interpolants = new Array( nTracks );
  19122. const interpolantSettings = {
  19123. endingStart: ZeroCurvatureEnding,
  19124. endingEnd: ZeroCurvatureEnding
  19125. };
  19126. for ( let i = 0; i !== nTracks; ++ i ) {
  19127. const interpolant = tracks[ i ].createInterpolant( null );
  19128. interpolants[ i ] = interpolant;
  19129. interpolant.settings = interpolantSettings;
  19130. }
  19131. this._interpolantSettings = interpolantSettings;
  19132. this._interpolants = interpolants; // bound by the mixer
  19133. // inside: PropertyMixer (managed by the mixer)
  19134. this._propertyBindings = new Array( nTracks );
  19135. this._cacheIndex = null; // for the memory manager
  19136. this._byClipCacheIndex = null; // for the memory manager
  19137. this._timeScaleInterpolant = null;
  19138. this._weightInterpolant = null;
  19139. this.loop = LoopRepeat;
  19140. this._loopCount = - 1;
  19141. // global mixer time when the action is to be started
  19142. // it's set back to 'null' upon start of the action
  19143. this._startTime = null;
  19144. // scaled local time of the action
  19145. // gets clamped or wrapped to 0..clip.duration according to loop
  19146. this.time = 0;
  19147. this.timeScale = 1;
  19148. this._effectiveTimeScale = 1;
  19149. this.weight = 1;
  19150. this._effectiveWeight = 1;
  19151. this.repetitions = Infinity; // no. of repetitions when looping
  19152. this.paused = false; // true -> zero effective time scale
  19153. this.enabled = true; // false -> zero effective weight
  19154. this.clampWhenFinished = false;// keep feeding the last frame?
  19155. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19156. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19157. }
  19158. // State & Scheduling
  19159. play() {
  19160. this._mixer._activateAction( this );
  19161. return this;
  19162. }
  19163. stop() {
  19164. this._mixer._deactivateAction( this );
  19165. return this.reset();
  19166. }
  19167. reset() {
  19168. this.paused = false;
  19169. this.enabled = true;
  19170. this.time = 0; // restart clip
  19171. this._loopCount = - 1;// forget previous loops
  19172. this._startTime = null;// forget scheduling
  19173. return this.stopFading().stopWarping();
  19174. }
  19175. isRunning() {
  19176. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19177. this._startTime === null && this._mixer._isActiveAction( this );
  19178. }
  19179. // return true when play has been called
  19180. isScheduled() {
  19181. return this._mixer._isActiveAction( this );
  19182. }
  19183. startAt( time ) {
  19184. this._startTime = time;
  19185. return this;
  19186. }
  19187. setLoop( mode, repetitions ) {
  19188. this.loop = mode;
  19189. this.repetitions = repetitions;
  19190. return this;
  19191. }
  19192. // Weight
  19193. // set the weight stopping any scheduled fading
  19194. // although .enabled = false yields an effective weight of zero, this
  19195. // method does *not* change .enabled, because it would be confusing
  19196. setEffectiveWeight( weight ) {
  19197. this.weight = weight;
  19198. // note: same logic as when updated at runtime
  19199. this._effectiveWeight = this.enabled ? weight : 0;
  19200. return this.stopFading();
  19201. }
  19202. // return the weight considering fading and .enabled
  19203. getEffectiveWeight() {
  19204. return this._effectiveWeight;
  19205. }
  19206. fadeIn( duration ) {
  19207. return this._scheduleFading( duration, 0, 1 );
  19208. }
  19209. fadeOut( duration ) {
  19210. return this._scheduleFading( duration, 1, 0 );
  19211. }
  19212. crossFadeFrom( fadeOutAction, duration, warp ) {
  19213. fadeOutAction.fadeOut( duration );
  19214. this.fadeIn( duration );
  19215. if ( warp ) {
  19216. const fadeInDuration = this._clip.duration,
  19217. fadeOutDuration = fadeOutAction._clip.duration,
  19218. startEndRatio = fadeOutDuration / fadeInDuration,
  19219. endStartRatio = fadeInDuration / fadeOutDuration;
  19220. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19221. this.warp( endStartRatio, 1.0, duration );
  19222. }
  19223. return this;
  19224. }
  19225. crossFadeTo( fadeInAction, duration, warp ) {
  19226. return fadeInAction.crossFadeFrom( this, duration, warp );
  19227. }
  19228. stopFading() {
  19229. const weightInterpolant = this._weightInterpolant;
  19230. if ( weightInterpolant !== null ) {
  19231. this._weightInterpolant = null;
  19232. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19233. }
  19234. return this;
  19235. }
  19236. // Time Scale Control
  19237. // set the time scale stopping any scheduled warping
  19238. // although .paused = true yields an effective time scale of zero, this
  19239. // method does *not* change .paused, because it would be confusing
  19240. setEffectiveTimeScale( timeScale ) {
  19241. this.timeScale = timeScale;
  19242. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19243. return this.stopWarping();
  19244. }
  19245. // return the time scale considering warping and .paused
  19246. getEffectiveTimeScale() {
  19247. return this._effectiveTimeScale;
  19248. }
  19249. setDuration( duration ) {
  19250. this.timeScale = this._clip.duration / duration;
  19251. return this.stopWarping();
  19252. }
  19253. syncWith( action ) {
  19254. this.time = action.time;
  19255. this.timeScale = action.timeScale;
  19256. return this.stopWarping();
  19257. }
  19258. halt( duration ) {
  19259. return this.warp( this._effectiveTimeScale, 0, duration );
  19260. }
  19261. warp( startTimeScale, endTimeScale, duration ) {
  19262. const mixer = this._mixer,
  19263. now = mixer.time,
  19264. timeScale = this.timeScale;
  19265. let interpolant = this._timeScaleInterpolant;
  19266. if ( interpolant === null ) {
  19267. interpolant = mixer._lendControlInterpolant();
  19268. this._timeScaleInterpolant = interpolant;
  19269. }
  19270. const times = interpolant.parameterPositions,
  19271. values = interpolant.sampleValues;
  19272. times[ 0 ] = now;
  19273. times[ 1 ] = now + duration;
  19274. values[ 0 ] = startTimeScale / timeScale;
  19275. values[ 1 ] = endTimeScale / timeScale;
  19276. return this;
  19277. }
  19278. stopWarping() {
  19279. const timeScaleInterpolant = this._timeScaleInterpolant;
  19280. if ( timeScaleInterpolant !== null ) {
  19281. this._timeScaleInterpolant = null;
  19282. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19283. }
  19284. return this;
  19285. }
  19286. // Object Accessors
  19287. getMixer() {
  19288. return this._mixer;
  19289. }
  19290. getClip() {
  19291. return this._clip;
  19292. }
  19293. getRoot() {
  19294. return this._localRoot || this._mixer._root;
  19295. }
  19296. // Interna
  19297. _update( time, deltaTime, timeDirection, accuIndex ) {
  19298. // called by the mixer
  19299. if ( ! this.enabled ) {
  19300. // call ._updateWeight() to update ._effectiveWeight
  19301. this._updateWeight( time );
  19302. return;
  19303. }
  19304. const startTime = this._startTime;
  19305. if ( startTime !== null ) {
  19306. // check for scheduled start of action
  19307. const timeRunning = ( time - startTime ) * timeDirection;
  19308. if ( timeRunning < 0 || timeDirection === 0 ) {
  19309. deltaTime = 0;
  19310. } else {
  19311. this._startTime = null; // unschedule
  19312. deltaTime = timeDirection * timeRunning;
  19313. }
  19314. }
  19315. // apply time scale and advance time
  19316. deltaTime *= this._updateTimeScale( time );
  19317. const clipTime = this._updateTime( deltaTime );
  19318. // note: _updateTime may disable the action resulting in
  19319. // an effective weight of 0
  19320. const weight = this._updateWeight( time );
  19321. if ( weight > 0 ) {
  19322. const interpolants = this._interpolants;
  19323. const propertyMixers = this._propertyBindings;
  19324. switch ( this.blendMode ) {
  19325. case AdditiveAnimationBlendMode:
  19326. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19327. interpolants[ j ].evaluate( clipTime );
  19328. propertyMixers[ j ].accumulateAdditive( weight );
  19329. }
  19330. break;
  19331. case NormalAnimationBlendMode:
  19332. default:
  19333. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19334. interpolants[ j ].evaluate( clipTime );
  19335. propertyMixers[ j ].accumulate( accuIndex, weight );
  19336. }
  19337. }
  19338. }
  19339. }
  19340. _updateWeight( time ) {
  19341. let weight = 0;
  19342. if ( this.enabled ) {
  19343. weight = this.weight;
  19344. const interpolant = this._weightInterpolant;
  19345. if ( interpolant !== null ) {
  19346. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19347. weight *= interpolantValue;
  19348. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19349. this.stopFading();
  19350. if ( interpolantValue === 0 ) {
  19351. // faded out, disable
  19352. this.enabled = false;
  19353. }
  19354. }
  19355. }
  19356. }
  19357. this._effectiveWeight = weight;
  19358. return weight;
  19359. }
  19360. _updateTimeScale( time ) {
  19361. let timeScale = 0;
  19362. if ( ! this.paused ) {
  19363. timeScale = this.timeScale;
  19364. const interpolant = this._timeScaleInterpolant;
  19365. if ( interpolant !== null ) {
  19366. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19367. timeScale *= interpolantValue;
  19368. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19369. this.stopWarping();
  19370. if ( timeScale === 0 ) {
  19371. // motion has halted, pause
  19372. this.paused = true;
  19373. } else {
  19374. // warp done - apply final time scale
  19375. this.timeScale = timeScale;
  19376. }
  19377. }
  19378. }
  19379. }
  19380. this._effectiveTimeScale = timeScale;
  19381. return timeScale;
  19382. }
  19383. _updateTime( deltaTime ) {
  19384. const duration = this._clip.duration;
  19385. const loop = this.loop;
  19386. let time = this.time + deltaTime;
  19387. let loopCount = this._loopCount;
  19388. const pingPong = ( loop === LoopPingPong );
  19389. if ( deltaTime === 0 ) {
  19390. if ( loopCount === - 1 ) return time;
  19391. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19392. }
  19393. if ( loop === LoopOnce ) {
  19394. if ( loopCount === - 1 ) {
  19395. // just started
  19396. this._loopCount = 0;
  19397. this._setEndings( true, true, false );
  19398. }
  19399. handle_stop: {
  19400. if ( time >= duration ) {
  19401. time = duration;
  19402. } else if ( time < 0 ) {
  19403. time = 0;
  19404. } else {
  19405. this.time = time;
  19406. break handle_stop;
  19407. }
  19408. if ( this.clampWhenFinished ) this.paused = true;
  19409. else this.enabled = false;
  19410. this.time = time;
  19411. this._mixer.dispatchEvent( {
  19412. type: 'finished', action: this,
  19413. direction: deltaTime < 0 ? - 1 : 1
  19414. } );
  19415. }
  19416. } else { // repetitive Repeat or PingPong
  19417. if ( loopCount === - 1 ) {
  19418. // just started
  19419. if ( deltaTime >= 0 ) {
  19420. loopCount = 0;
  19421. this._setEndings( true, this.repetitions === 0, pingPong );
  19422. } else {
  19423. // when looping in reverse direction, the initial
  19424. // transition through zero counts as a repetition,
  19425. // so leave loopCount at -1
  19426. this._setEndings( this.repetitions === 0, true, pingPong );
  19427. }
  19428. }
  19429. if ( time >= duration || time < 0 ) {
  19430. // wrap around
  19431. const loopDelta = Math.floor( time / duration ); // signed
  19432. time -= duration * loopDelta;
  19433. loopCount += Math.abs( loopDelta );
  19434. const pending = this.repetitions - loopCount;
  19435. if ( pending <= 0 ) {
  19436. // have to stop (switch state, clamp time, fire event)
  19437. if ( this.clampWhenFinished ) this.paused = true;
  19438. else this.enabled = false;
  19439. time = deltaTime > 0 ? duration : 0;
  19440. this.time = time;
  19441. this._mixer.dispatchEvent( {
  19442. type: 'finished', action: this,
  19443. direction: deltaTime > 0 ? 1 : - 1
  19444. } );
  19445. } else {
  19446. // keep running
  19447. if ( pending === 1 ) {
  19448. // entering the last round
  19449. const atStart = deltaTime < 0;
  19450. this._setEndings( atStart, ! atStart, pingPong );
  19451. } else {
  19452. this._setEndings( false, false, pingPong );
  19453. }
  19454. this._loopCount = loopCount;
  19455. this.time = time;
  19456. this._mixer.dispatchEvent( {
  19457. type: 'loop', action: this, loopDelta: loopDelta
  19458. } );
  19459. }
  19460. } else {
  19461. this.time = time;
  19462. }
  19463. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19464. // invert time for the "pong round"
  19465. return duration - time;
  19466. }
  19467. }
  19468. return time;
  19469. }
  19470. _setEndings( atStart, atEnd, pingPong ) {
  19471. const settings = this._interpolantSettings;
  19472. if ( pingPong ) {
  19473. settings.endingStart = ZeroSlopeEnding;
  19474. settings.endingEnd = ZeroSlopeEnding;
  19475. } else {
  19476. // assuming for LoopOnce atStart == atEnd == true
  19477. if ( atStart ) {
  19478. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19479. } else {
  19480. settings.endingStart = WrapAroundEnding;
  19481. }
  19482. if ( atEnd ) {
  19483. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19484. } else {
  19485. settings.endingEnd = WrapAroundEnding;
  19486. }
  19487. }
  19488. }
  19489. _scheduleFading( duration, weightNow, weightThen ) {
  19490. const mixer = this._mixer, now = mixer.time;
  19491. let interpolant = this._weightInterpolant;
  19492. if ( interpolant === null ) {
  19493. interpolant = mixer._lendControlInterpolant();
  19494. this._weightInterpolant = interpolant;
  19495. }
  19496. const times = interpolant.parameterPositions,
  19497. values = interpolant.sampleValues;
  19498. times[ 0 ] = now;
  19499. values[ 0 ] = weightNow;
  19500. times[ 1 ] = now + duration;
  19501. values[ 1 ] = weightThen;
  19502. return this;
  19503. }
  19504. }
  19505. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19506. class AnimationMixer extends EventDispatcher {
  19507. constructor( root ) {
  19508. super();
  19509. this._root = root;
  19510. this._initMemoryManager();
  19511. this._accuIndex = 0;
  19512. this.time = 0;
  19513. this.timeScale = 1.0;
  19514. }
  19515. _bindAction( action, prototypeAction ) {
  19516. const root = action._localRoot || this._root,
  19517. tracks = action._clip.tracks,
  19518. nTracks = tracks.length,
  19519. bindings = action._propertyBindings,
  19520. interpolants = action._interpolants,
  19521. rootUuid = root.uuid,
  19522. bindingsByRoot = this._bindingsByRootAndName;
  19523. let bindingsByName = bindingsByRoot[ rootUuid ];
  19524. if ( bindingsByName === undefined ) {
  19525. bindingsByName = {};
  19526. bindingsByRoot[ rootUuid ] = bindingsByName;
  19527. }
  19528. for ( let i = 0; i !== nTracks; ++ i ) {
  19529. const track = tracks[ i ],
  19530. trackName = track.name;
  19531. let binding = bindingsByName[ trackName ];
  19532. if ( binding !== undefined ) {
  19533. ++ binding.referenceCount;
  19534. bindings[ i ] = binding;
  19535. } else {
  19536. binding = bindings[ i ];
  19537. if ( binding !== undefined ) {
  19538. // existing binding, make sure the cache knows
  19539. if ( binding._cacheIndex === null ) {
  19540. ++ binding.referenceCount;
  19541. this._addInactiveBinding( binding, rootUuid, trackName );
  19542. }
  19543. continue;
  19544. }
  19545. const path = prototypeAction && prototypeAction.
  19546. _propertyBindings[ i ].binding.parsedPath;
  19547. binding = new PropertyMixer(
  19548. PropertyBinding.create( root, trackName, path ),
  19549. track.ValueTypeName, track.getValueSize() );
  19550. ++ binding.referenceCount;
  19551. this._addInactiveBinding( binding, rootUuid, trackName );
  19552. bindings[ i ] = binding;
  19553. }
  19554. interpolants[ i ].resultBuffer = binding.buffer;
  19555. }
  19556. }
  19557. _activateAction( action ) {
  19558. if ( ! this._isActiveAction( action ) ) {
  19559. if ( action._cacheIndex === null ) {
  19560. // this action has been forgotten by the cache, but the user
  19561. // appears to be still using it -> rebind
  19562. const rootUuid = ( action._localRoot || this._root ).uuid,
  19563. clipUuid = action._clip.uuid,
  19564. actionsForClip = this._actionsByClip[ clipUuid ];
  19565. this._bindAction( action,
  19566. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19567. this._addInactiveAction( action, clipUuid, rootUuid );
  19568. }
  19569. const bindings = action._propertyBindings;
  19570. // increment reference counts / sort out state
  19571. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19572. const binding = bindings[ i ];
  19573. if ( binding.useCount ++ === 0 ) {
  19574. this._lendBinding( binding );
  19575. binding.saveOriginalState();
  19576. }
  19577. }
  19578. this._lendAction( action );
  19579. }
  19580. }
  19581. _deactivateAction( action ) {
  19582. if ( this._isActiveAction( action ) ) {
  19583. const bindings = action._propertyBindings;
  19584. // decrement reference counts / sort out state
  19585. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19586. const binding = bindings[ i ];
  19587. if ( -- binding.useCount === 0 ) {
  19588. binding.restoreOriginalState();
  19589. this._takeBackBinding( binding );
  19590. }
  19591. }
  19592. this._takeBackAction( action );
  19593. }
  19594. }
  19595. // Memory manager
  19596. _initMemoryManager() {
  19597. this._actions = []; // 'nActiveActions' followed by inactive ones
  19598. this._nActiveActions = 0;
  19599. this._actionsByClip = {};
  19600. // inside:
  19601. // {
  19602. // knownActions: Array< AnimationAction > - used as prototypes
  19603. // actionByRoot: AnimationAction - lookup
  19604. // }
  19605. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19606. this._nActiveBindings = 0;
  19607. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19608. this._controlInterpolants = []; // same game as above
  19609. this._nActiveControlInterpolants = 0;
  19610. const scope = this;
  19611. this.stats = {
  19612. actions: {
  19613. get total() {
  19614. return scope._actions.length;
  19615. },
  19616. get inUse() {
  19617. return scope._nActiveActions;
  19618. }
  19619. },
  19620. bindings: {
  19621. get total() {
  19622. return scope._bindings.length;
  19623. },
  19624. get inUse() {
  19625. return scope._nActiveBindings;
  19626. }
  19627. },
  19628. controlInterpolants: {
  19629. get total() {
  19630. return scope._controlInterpolants.length;
  19631. },
  19632. get inUse() {
  19633. return scope._nActiveControlInterpolants;
  19634. }
  19635. }
  19636. };
  19637. }
  19638. // Memory management for AnimationAction objects
  19639. _isActiveAction( action ) {
  19640. const index = action._cacheIndex;
  19641. return index !== null && index < this._nActiveActions;
  19642. }
  19643. _addInactiveAction( action, clipUuid, rootUuid ) {
  19644. const actions = this._actions,
  19645. actionsByClip = this._actionsByClip;
  19646. let actionsForClip = actionsByClip[ clipUuid ];
  19647. if ( actionsForClip === undefined ) {
  19648. actionsForClip = {
  19649. knownActions: [ action ],
  19650. actionByRoot: {}
  19651. };
  19652. action._byClipCacheIndex = 0;
  19653. actionsByClip[ clipUuid ] = actionsForClip;
  19654. } else {
  19655. const knownActions = actionsForClip.knownActions;
  19656. action._byClipCacheIndex = knownActions.length;
  19657. knownActions.push( action );
  19658. }
  19659. action._cacheIndex = actions.length;
  19660. actions.push( action );
  19661. actionsForClip.actionByRoot[ rootUuid ] = action;
  19662. }
  19663. _removeInactiveAction( action ) {
  19664. const actions = this._actions,
  19665. lastInactiveAction = actions[ actions.length - 1 ],
  19666. cacheIndex = action._cacheIndex;
  19667. lastInactiveAction._cacheIndex = cacheIndex;
  19668. actions[ cacheIndex ] = lastInactiveAction;
  19669. actions.pop();
  19670. action._cacheIndex = null;
  19671. const clipUuid = action._clip.uuid,
  19672. actionsByClip = this._actionsByClip,
  19673. actionsForClip = actionsByClip[ clipUuid ],
  19674. knownActionsForClip = actionsForClip.knownActions,
  19675. lastKnownAction =
  19676. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19677. byClipCacheIndex = action._byClipCacheIndex;
  19678. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19679. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19680. knownActionsForClip.pop();
  19681. action._byClipCacheIndex = null;
  19682. const actionByRoot = actionsForClip.actionByRoot,
  19683. rootUuid = ( action._localRoot || this._root ).uuid;
  19684. delete actionByRoot[ rootUuid ];
  19685. if ( knownActionsForClip.length === 0 ) {
  19686. delete actionsByClip[ clipUuid ];
  19687. }
  19688. this._removeInactiveBindingsForAction( action );
  19689. }
  19690. _removeInactiveBindingsForAction( action ) {
  19691. const bindings = action._propertyBindings;
  19692. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19693. const binding = bindings[ i ];
  19694. if ( -- binding.referenceCount === 0 ) {
  19695. this._removeInactiveBinding( binding );
  19696. }
  19697. }
  19698. }
  19699. _lendAction( action ) {
  19700. // [ active actions | inactive actions ]
  19701. // [ active actions >| inactive actions ]
  19702. // s a
  19703. // <-swap->
  19704. // a s
  19705. const actions = this._actions,
  19706. prevIndex = action._cacheIndex,
  19707. lastActiveIndex = this._nActiveActions ++,
  19708. firstInactiveAction = actions[ lastActiveIndex ];
  19709. action._cacheIndex = lastActiveIndex;
  19710. actions[ lastActiveIndex ] = action;
  19711. firstInactiveAction._cacheIndex = prevIndex;
  19712. actions[ prevIndex ] = firstInactiveAction;
  19713. }
  19714. _takeBackAction( action ) {
  19715. // [ active actions | inactive actions ]
  19716. // [ active actions |< inactive actions ]
  19717. // a s
  19718. // <-swap->
  19719. // s a
  19720. const actions = this._actions,
  19721. prevIndex = action._cacheIndex,
  19722. firstInactiveIndex = -- this._nActiveActions,
  19723. lastActiveAction = actions[ firstInactiveIndex ];
  19724. action._cacheIndex = firstInactiveIndex;
  19725. actions[ firstInactiveIndex ] = action;
  19726. lastActiveAction._cacheIndex = prevIndex;
  19727. actions[ prevIndex ] = lastActiveAction;
  19728. }
  19729. // Memory management for PropertyMixer objects
  19730. _addInactiveBinding( binding, rootUuid, trackName ) {
  19731. const bindingsByRoot = this._bindingsByRootAndName,
  19732. bindings = this._bindings;
  19733. let bindingByName = bindingsByRoot[ rootUuid ];
  19734. if ( bindingByName === undefined ) {
  19735. bindingByName = {};
  19736. bindingsByRoot[ rootUuid ] = bindingByName;
  19737. }
  19738. bindingByName[ trackName ] = binding;
  19739. binding._cacheIndex = bindings.length;
  19740. bindings.push( binding );
  19741. }
  19742. _removeInactiveBinding( binding ) {
  19743. const bindings = this._bindings,
  19744. propBinding = binding.binding,
  19745. rootUuid = propBinding.rootNode.uuid,
  19746. trackName = propBinding.path,
  19747. bindingsByRoot = this._bindingsByRootAndName,
  19748. bindingByName = bindingsByRoot[ rootUuid ],
  19749. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19750. cacheIndex = binding._cacheIndex;
  19751. lastInactiveBinding._cacheIndex = cacheIndex;
  19752. bindings[ cacheIndex ] = lastInactiveBinding;
  19753. bindings.pop();
  19754. delete bindingByName[ trackName ];
  19755. if ( Object.keys( bindingByName ).length === 0 ) {
  19756. delete bindingsByRoot[ rootUuid ];
  19757. }
  19758. }
  19759. _lendBinding( binding ) {
  19760. const bindings = this._bindings,
  19761. prevIndex = binding._cacheIndex,
  19762. lastActiveIndex = this._nActiveBindings ++,
  19763. firstInactiveBinding = bindings[ lastActiveIndex ];
  19764. binding._cacheIndex = lastActiveIndex;
  19765. bindings[ lastActiveIndex ] = binding;
  19766. firstInactiveBinding._cacheIndex = prevIndex;
  19767. bindings[ prevIndex ] = firstInactiveBinding;
  19768. }
  19769. _takeBackBinding( binding ) {
  19770. const bindings = this._bindings,
  19771. prevIndex = binding._cacheIndex,
  19772. firstInactiveIndex = -- this._nActiveBindings,
  19773. lastActiveBinding = bindings[ firstInactiveIndex ];
  19774. binding._cacheIndex = firstInactiveIndex;
  19775. bindings[ firstInactiveIndex ] = binding;
  19776. lastActiveBinding._cacheIndex = prevIndex;
  19777. bindings[ prevIndex ] = lastActiveBinding;
  19778. }
  19779. // Memory management of Interpolants for weight and time scale
  19780. _lendControlInterpolant() {
  19781. const interpolants = this._controlInterpolants,
  19782. lastActiveIndex = this._nActiveControlInterpolants ++;
  19783. let interpolant = interpolants[ lastActiveIndex ];
  19784. if ( interpolant === undefined ) {
  19785. interpolant = new LinearInterpolant(
  19786. new Float32Array( 2 ), new Float32Array( 2 ),
  19787. 1, _controlInterpolantsResultBuffer );
  19788. interpolant.__cacheIndex = lastActiveIndex;
  19789. interpolants[ lastActiveIndex ] = interpolant;
  19790. }
  19791. return interpolant;
  19792. }
  19793. _takeBackControlInterpolant( interpolant ) {
  19794. const interpolants = this._controlInterpolants,
  19795. prevIndex = interpolant.__cacheIndex,
  19796. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19797. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19798. interpolant.__cacheIndex = firstInactiveIndex;
  19799. interpolants[ firstInactiveIndex ] = interpolant;
  19800. lastActiveInterpolant.__cacheIndex = prevIndex;
  19801. interpolants[ prevIndex ] = lastActiveInterpolant;
  19802. }
  19803. // return an action for a clip optionally using a custom root target
  19804. // object (this method allocates a lot of dynamic memory in case a
  19805. // previously unknown clip/root combination is specified)
  19806. clipAction( clip, optionalRoot, blendMode ) {
  19807. const root = optionalRoot || this._root,
  19808. rootUuid = root.uuid;
  19809. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19810. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19811. const actionsForClip = this._actionsByClip[ clipUuid ];
  19812. let prototypeAction = null;
  19813. if ( blendMode === undefined ) {
  19814. if ( clipObject !== null ) {
  19815. blendMode = clipObject.blendMode;
  19816. } else {
  19817. blendMode = NormalAnimationBlendMode;
  19818. }
  19819. }
  19820. if ( actionsForClip !== undefined ) {
  19821. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19822. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19823. return existingAction;
  19824. }
  19825. // we know the clip, so we don't have to parse all
  19826. // the bindings again but can just copy
  19827. prototypeAction = actionsForClip.knownActions[ 0 ];
  19828. // also, take the clip from the prototype action
  19829. if ( clipObject === null )
  19830. clipObject = prototypeAction._clip;
  19831. }
  19832. // clip must be known when specified via string
  19833. if ( clipObject === null ) return null;
  19834. // allocate all resources required to run it
  19835. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19836. this._bindAction( newAction, prototypeAction );
  19837. // and make the action known to the memory manager
  19838. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19839. return newAction;
  19840. }
  19841. // get an existing action
  19842. existingAction( clip, optionalRoot ) {
  19843. const root = optionalRoot || this._root,
  19844. rootUuid = root.uuid,
  19845. clipObject = typeof clip === 'string' ?
  19846. AnimationClip.findByName( root, clip ) : clip,
  19847. clipUuid = clipObject ? clipObject.uuid : clip,
  19848. actionsForClip = this._actionsByClip[ clipUuid ];
  19849. if ( actionsForClip !== undefined ) {
  19850. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19851. }
  19852. return null;
  19853. }
  19854. // deactivates all previously scheduled actions
  19855. stopAllAction() {
  19856. const actions = this._actions,
  19857. nActions = this._nActiveActions;
  19858. for ( let i = nActions - 1; i >= 0; -- i ) {
  19859. actions[ i ].stop();
  19860. }
  19861. return this;
  19862. }
  19863. // advance the time and update apply the animation
  19864. update( deltaTime ) {
  19865. deltaTime *= this.timeScale;
  19866. const actions = this._actions,
  19867. nActions = this._nActiveActions,
  19868. time = this.time += deltaTime,
  19869. timeDirection = Math.sign( deltaTime ),
  19870. accuIndex = this._accuIndex ^= 1;
  19871. // run active actions
  19872. for ( let i = 0; i !== nActions; ++ i ) {
  19873. const action = actions[ i ];
  19874. action._update( time, deltaTime, timeDirection, accuIndex );
  19875. }
  19876. // update scene graph
  19877. const bindings = this._bindings,
  19878. nBindings = this._nActiveBindings;
  19879. for ( let i = 0; i !== nBindings; ++ i ) {
  19880. bindings[ i ].apply( accuIndex );
  19881. }
  19882. return this;
  19883. }
  19884. // Allows you to seek to a specific time in an animation.
  19885. setTime( timeInSeconds ) {
  19886. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19887. for ( let i = 0; i < this._actions.length; i ++ ) {
  19888. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19889. }
  19890. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19891. }
  19892. // return this mixer's root target object
  19893. getRoot() {
  19894. return this._root;
  19895. }
  19896. // free all resources specific to a particular clip
  19897. uncacheClip( clip ) {
  19898. const actions = this._actions,
  19899. clipUuid = clip.uuid,
  19900. actionsByClip = this._actionsByClip,
  19901. actionsForClip = actionsByClip[ clipUuid ];
  19902. if ( actionsForClip !== undefined ) {
  19903. // note: just calling _removeInactiveAction would mess up the
  19904. // iteration state and also require updating the state we can
  19905. // just throw away
  19906. const actionsToRemove = actionsForClip.knownActions;
  19907. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19908. const action = actionsToRemove[ i ];
  19909. this._deactivateAction( action );
  19910. const cacheIndex = action._cacheIndex,
  19911. lastInactiveAction = actions[ actions.length - 1 ];
  19912. action._cacheIndex = null;
  19913. action._byClipCacheIndex = null;
  19914. lastInactiveAction._cacheIndex = cacheIndex;
  19915. actions[ cacheIndex ] = lastInactiveAction;
  19916. actions.pop();
  19917. this._removeInactiveBindingsForAction( action );
  19918. }
  19919. delete actionsByClip[ clipUuid ];
  19920. }
  19921. }
  19922. // free all resources specific to a particular root target object
  19923. uncacheRoot( root ) {
  19924. const rootUuid = root.uuid,
  19925. actionsByClip = this._actionsByClip;
  19926. for ( const clipUuid in actionsByClip ) {
  19927. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19928. action = actionByRoot[ rootUuid ];
  19929. if ( action !== undefined ) {
  19930. this._deactivateAction( action );
  19931. this._removeInactiveAction( action );
  19932. }
  19933. }
  19934. const bindingsByRoot = this._bindingsByRootAndName,
  19935. bindingByName = bindingsByRoot[ rootUuid ];
  19936. if ( bindingByName !== undefined ) {
  19937. for ( const trackName in bindingByName ) {
  19938. const binding = bindingByName[ trackName ];
  19939. binding.restoreOriginalState();
  19940. this._removeInactiveBinding( binding );
  19941. }
  19942. }
  19943. }
  19944. // remove a targeted clip from the cache
  19945. uncacheAction( clip, optionalRoot ) {
  19946. const action = this.existingAction( clip, optionalRoot );
  19947. if ( action !== null ) {
  19948. this._deactivateAction( action );
  19949. this._removeInactiveAction( action );
  19950. }
  19951. }
  19952. }
  19953. let Uniform$1 = class Uniform {
  19954. constructor( value ) {
  19955. this.value = value;
  19956. }
  19957. clone() {
  19958. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  19959. }
  19960. };
  19961. let _id$8 = 0;
  19962. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  19963. constructor() {
  19964. super();
  19965. this.isUniformsGroup = true;
  19966. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  19967. this.name = '';
  19968. this.usage = StaticDrawUsage;
  19969. this.uniforms = [];
  19970. }
  19971. add( uniform ) {
  19972. this.uniforms.push( uniform );
  19973. return this;
  19974. }
  19975. remove( uniform ) {
  19976. const index = this.uniforms.indexOf( uniform );
  19977. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  19978. return this;
  19979. }
  19980. setName( name ) {
  19981. this.name = name;
  19982. return this;
  19983. }
  19984. setUsage( value ) {
  19985. this.usage = value;
  19986. return this;
  19987. }
  19988. dispose() {
  19989. this.dispatchEvent( { type: 'dispose' } );
  19990. return this;
  19991. }
  19992. copy( source ) {
  19993. this.name = source.name;
  19994. this.usage = source.usage;
  19995. const uniformsSource = source.uniforms;
  19996. this.uniforms.length = 0;
  19997. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  19998. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  19999. for ( let j = 0; j < uniforms.length; j ++ ) {
  20000. this.uniforms.push( uniforms[ j ].clone() );
  20001. }
  20002. }
  20003. return this;
  20004. }
  20005. clone() {
  20006. return new this.constructor().copy( this );
  20007. }
  20008. };
  20009. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20010. constructor( array, stride, meshPerAttribute = 1 ) {
  20011. super( array, stride );
  20012. this.isInstancedInterleavedBuffer = true;
  20013. this.meshPerAttribute = meshPerAttribute;
  20014. }
  20015. copy( source ) {
  20016. super.copy( source );
  20017. this.meshPerAttribute = source.meshPerAttribute;
  20018. return this;
  20019. }
  20020. clone( data ) {
  20021. const ib = super.clone( data );
  20022. ib.meshPerAttribute = this.meshPerAttribute;
  20023. return ib;
  20024. }
  20025. toJSON( data ) {
  20026. const json = super.toJSON( data );
  20027. json.isInstancedInterleavedBuffer = true;
  20028. json.meshPerAttribute = this.meshPerAttribute;
  20029. return json;
  20030. }
  20031. }
  20032. class GLBufferAttribute {
  20033. constructor( buffer, type, itemSize, elementSize, count ) {
  20034. this.isGLBufferAttribute = true;
  20035. this.name = '';
  20036. this.buffer = buffer;
  20037. this.type = type;
  20038. this.itemSize = itemSize;
  20039. this.elementSize = elementSize;
  20040. this.count = count;
  20041. this.version = 0;
  20042. }
  20043. set needsUpdate( value ) {
  20044. if ( value === true ) this.version ++;
  20045. }
  20046. setBuffer( buffer ) {
  20047. this.buffer = buffer;
  20048. return this;
  20049. }
  20050. setType( type, elementSize ) {
  20051. this.type = type;
  20052. this.elementSize = elementSize;
  20053. return this;
  20054. }
  20055. setItemSize( itemSize ) {
  20056. this.itemSize = itemSize;
  20057. return this;
  20058. }
  20059. setCount( count ) {
  20060. this.count = count;
  20061. return this;
  20062. }
  20063. }
  20064. const _matrix = /*@__PURE__*/ new Matrix4();
  20065. class Raycaster {
  20066. constructor( origin, direction, near = 0, far = Infinity ) {
  20067. this.ray = new Ray( origin, direction );
  20068. // direction is assumed to be normalized (for accurate distance calculations)
  20069. this.near = near;
  20070. this.far = far;
  20071. this.camera = null;
  20072. this.layers = new Layers();
  20073. this.params = {
  20074. Mesh: {},
  20075. Line: { threshold: 1 },
  20076. LOD: {},
  20077. Points: { threshold: 1 },
  20078. Sprite: {}
  20079. };
  20080. }
  20081. set( origin, direction ) {
  20082. // direction is assumed to be normalized (for accurate distance calculations)
  20083. this.ray.set( origin, direction );
  20084. }
  20085. setFromCamera( coords, camera ) {
  20086. if ( camera.isPerspectiveCamera ) {
  20087. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20088. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20089. this.camera = camera;
  20090. } else if ( camera.isOrthographicCamera ) {
  20091. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20092. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20093. this.camera = camera;
  20094. } else {
  20095. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20096. }
  20097. }
  20098. setFromXRController( controller ) {
  20099. _matrix.identity().extractRotation( controller.matrixWorld );
  20100. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20101. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20102. return this;
  20103. }
  20104. intersectObject( object, recursive = true, intersects = [] ) {
  20105. intersect( object, this, intersects, recursive );
  20106. intersects.sort( ascSort );
  20107. return intersects;
  20108. }
  20109. intersectObjects( objects, recursive = true, intersects = [] ) {
  20110. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20111. intersect( objects[ i ], this, intersects, recursive );
  20112. }
  20113. intersects.sort( ascSort );
  20114. return intersects;
  20115. }
  20116. }
  20117. function ascSort( a, b ) {
  20118. return a.distance - b.distance;
  20119. }
  20120. function intersect( object, raycaster, intersects, recursive ) {
  20121. let propagate = true;
  20122. if ( object.layers.test( raycaster.layers ) ) {
  20123. const result = object.raycast( raycaster, intersects );
  20124. if ( result === false ) propagate = false;
  20125. }
  20126. if ( propagate === true && recursive === true ) {
  20127. const children = object.children;
  20128. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20129. intersect( children[ i ], raycaster, intersects, true );
  20130. }
  20131. }
  20132. }
  20133. /**
  20134. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20135. *
  20136. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20137. * theta (the azimuthal angle) is measured from the positive z-axis.
  20138. */
  20139. class Spherical {
  20140. constructor( radius = 1, phi = 0, theta = 0 ) {
  20141. this.radius = radius;
  20142. this.phi = phi; // polar angle
  20143. this.theta = theta; // azimuthal angle
  20144. return this;
  20145. }
  20146. set( radius, phi, theta ) {
  20147. this.radius = radius;
  20148. this.phi = phi;
  20149. this.theta = theta;
  20150. return this;
  20151. }
  20152. copy( other ) {
  20153. this.radius = other.radius;
  20154. this.phi = other.phi;
  20155. this.theta = other.theta;
  20156. return this;
  20157. }
  20158. // restrict phi to be between EPS and PI-EPS
  20159. makeSafe() {
  20160. const EPS = 0.000001;
  20161. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20162. return this;
  20163. }
  20164. setFromVector3( v ) {
  20165. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20166. }
  20167. setFromCartesianCoords( x, y, z ) {
  20168. this.radius = Math.sqrt( x * x + y * y + z * z );
  20169. if ( this.radius === 0 ) {
  20170. this.theta = 0;
  20171. this.phi = 0;
  20172. } else {
  20173. this.theta = Math.atan2( x, z );
  20174. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20175. }
  20176. return this;
  20177. }
  20178. clone() {
  20179. return new this.constructor().copy( this );
  20180. }
  20181. }
  20182. /**
  20183. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20184. */
  20185. class Cylindrical {
  20186. constructor( radius = 1, theta = 0, y = 0 ) {
  20187. this.radius = radius; // distance from the origin to a point in the x-z plane
  20188. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20189. this.y = y; // height above the x-z plane
  20190. return this;
  20191. }
  20192. set( radius, theta, y ) {
  20193. this.radius = radius;
  20194. this.theta = theta;
  20195. this.y = y;
  20196. return this;
  20197. }
  20198. copy( other ) {
  20199. this.radius = other.radius;
  20200. this.theta = other.theta;
  20201. this.y = other.y;
  20202. return this;
  20203. }
  20204. setFromVector3( v ) {
  20205. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20206. }
  20207. setFromCartesianCoords( x, y, z ) {
  20208. this.radius = Math.sqrt( x * x + z * z );
  20209. this.theta = Math.atan2( x, z );
  20210. this.y = y;
  20211. return this;
  20212. }
  20213. clone() {
  20214. return new this.constructor().copy( this );
  20215. }
  20216. }
  20217. class Matrix2 {
  20218. constructor( n11, n12, n21, n22 ) {
  20219. Matrix2.prototype.isMatrix2 = true;
  20220. this.elements = [
  20221. 1, 0,
  20222. 0, 1,
  20223. ];
  20224. if ( n11 !== undefined ) {
  20225. this.set( n11, n12, n21, n22 );
  20226. }
  20227. }
  20228. identity() {
  20229. this.set(
  20230. 1, 0,
  20231. 0, 1,
  20232. );
  20233. return this;
  20234. }
  20235. fromArray( array, offset = 0 ) {
  20236. for ( let i = 0; i < 4; i ++ ) {
  20237. this.elements[ i ] = array[ i + offset ];
  20238. }
  20239. return this;
  20240. }
  20241. set( n11, n12, n21, n22 ) {
  20242. const te = this.elements;
  20243. te[ 0 ] = n11; te[ 2 ] = n12;
  20244. te[ 1 ] = n21; te[ 3 ] = n22;
  20245. return this;
  20246. }
  20247. }
  20248. const _vector$4 = /*@__PURE__*/ new Vector2();
  20249. class Box2 {
  20250. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20251. this.isBox2 = true;
  20252. this.min = min;
  20253. this.max = max;
  20254. }
  20255. set( min, max ) {
  20256. this.min.copy( min );
  20257. this.max.copy( max );
  20258. return this;
  20259. }
  20260. setFromPoints( points ) {
  20261. this.makeEmpty();
  20262. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20263. this.expandByPoint( points[ i ] );
  20264. }
  20265. return this;
  20266. }
  20267. setFromCenterAndSize( center, size ) {
  20268. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20269. this.min.copy( center ).sub( halfSize );
  20270. this.max.copy( center ).add( halfSize );
  20271. return this;
  20272. }
  20273. clone() {
  20274. return new this.constructor().copy( this );
  20275. }
  20276. copy( box ) {
  20277. this.min.copy( box.min );
  20278. this.max.copy( box.max );
  20279. return this;
  20280. }
  20281. makeEmpty() {
  20282. this.min.x = this.min.y = + Infinity;
  20283. this.max.x = this.max.y = - Infinity;
  20284. return this;
  20285. }
  20286. isEmpty() {
  20287. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20288. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20289. }
  20290. getCenter( target ) {
  20291. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20292. }
  20293. getSize( target ) {
  20294. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20295. }
  20296. expandByPoint( point ) {
  20297. this.min.min( point );
  20298. this.max.max( point );
  20299. return this;
  20300. }
  20301. expandByVector( vector ) {
  20302. this.min.sub( vector );
  20303. this.max.add( vector );
  20304. return this;
  20305. }
  20306. expandByScalar( scalar ) {
  20307. this.min.addScalar( - scalar );
  20308. this.max.addScalar( scalar );
  20309. return this;
  20310. }
  20311. containsPoint( point ) {
  20312. return point.x >= this.min.x && point.x <= this.max.x &&
  20313. point.y >= this.min.y && point.y <= this.max.y;
  20314. }
  20315. containsBox( box ) {
  20316. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20317. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20318. }
  20319. getParameter( point, target ) {
  20320. // This can potentially have a divide by zero if the box
  20321. // has a size dimension of 0.
  20322. return target.set(
  20323. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20324. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20325. );
  20326. }
  20327. intersectsBox( box ) {
  20328. // using 4 splitting planes to rule out intersections
  20329. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20330. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20331. }
  20332. clampPoint( point, target ) {
  20333. return target.copy( point ).clamp( this.min, this.max );
  20334. }
  20335. distanceToPoint( point ) {
  20336. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20337. }
  20338. intersect( box ) {
  20339. this.min.max( box.min );
  20340. this.max.min( box.max );
  20341. if ( this.isEmpty() ) this.makeEmpty();
  20342. return this;
  20343. }
  20344. union( box ) {
  20345. this.min.min( box.min );
  20346. this.max.max( box.max );
  20347. return this;
  20348. }
  20349. translate( offset ) {
  20350. this.min.add( offset );
  20351. this.max.add( offset );
  20352. return this;
  20353. }
  20354. equals( box ) {
  20355. return box.min.equals( this.min ) && box.max.equals( this.max );
  20356. }
  20357. }
  20358. const _startP = /*@__PURE__*/ new Vector3();
  20359. const _startEnd = /*@__PURE__*/ new Vector3();
  20360. class Line3 {
  20361. constructor( start = new Vector3(), end = new Vector3() ) {
  20362. this.start = start;
  20363. this.end = end;
  20364. }
  20365. set( start, end ) {
  20366. this.start.copy( start );
  20367. this.end.copy( end );
  20368. return this;
  20369. }
  20370. copy( line ) {
  20371. this.start.copy( line.start );
  20372. this.end.copy( line.end );
  20373. return this;
  20374. }
  20375. getCenter( target ) {
  20376. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20377. }
  20378. delta( target ) {
  20379. return target.subVectors( this.end, this.start );
  20380. }
  20381. distanceSq() {
  20382. return this.start.distanceToSquared( this.end );
  20383. }
  20384. distance() {
  20385. return this.start.distanceTo( this.end );
  20386. }
  20387. at( t, target ) {
  20388. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20389. }
  20390. closestPointToPointParameter( point, clampToLine ) {
  20391. _startP.subVectors( point, this.start );
  20392. _startEnd.subVectors( this.end, this.start );
  20393. const startEnd2 = _startEnd.dot( _startEnd );
  20394. const startEnd_startP = _startEnd.dot( _startP );
  20395. let t = startEnd_startP / startEnd2;
  20396. if ( clampToLine ) {
  20397. t = clamp$1( t, 0, 1 );
  20398. }
  20399. return t;
  20400. }
  20401. closestPointToPoint( point, clampToLine, target ) {
  20402. const t = this.closestPointToPointParameter( point, clampToLine );
  20403. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20404. }
  20405. applyMatrix4( matrix ) {
  20406. this.start.applyMatrix4( matrix );
  20407. this.end.applyMatrix4( matrix );
  20408. return this;
  20409. }
  20410. equals( line ) {
  20411. return line.start.equals( this.start ) && line.end.equals( this.end );
  20412. }
  20413. clone() {
  20414. return new this.constructor().copy( this );
  20415. }
  20416. }
  20417. const _vector$3 = /*@__PURE__*/ new Vector3();
  20418. class SpotLightHelper extends Object3D {
  20419. constructor( light, color ) {
  20420. super();
  20421. this.light = light;
  20422. this.matrixAutoUpdate = false;
  20423. this.color = color;
  20424. this.type = 'SpotLightHelper';
  20425. const geometry = new BufferGeometry();
  20426. const positions = [
  20427. 0, 0, 0, 0, 0, 1,
  20428. 0, 0, 0, 1, 0, 1,
  20429. 0, 0, 0, - 1, 0, 1,
  20430. 0, 0, 0, 0, 1, 1,
  20431. 0, 0, 0, 0, - 1, 1
  20432. ];
  20433. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20434. const p1 = ( i / l ) * Math.PI * 2;
  20435. const p2 = ( j / l ) * Math.PI * 2;
  20436. positions.push(
  20437. Math.cos( p1 ), Math.sin( p1 ), 1,
  20438. Math.cos( p2 ), Math.sin( p2 ), 1
  20439. );
  20440. }
  20441. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20442. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20443. this.cone = new LineSegments( geometry, material );
  20444. this.add( this.cone );
  20445. this.update();
  20446. }
  20447. dispose() {
  20448. this.cone.geometry.dispose();
  20449. this.cone.material.dispose();
  20450. }
  20451. update() {
  20452. this.light.updateWorldMatrix( true, false );
  20453. this.light.target.updateWorldMatrix( true, false );
  20454. // update the local matrix based on the parent and light target transforms
  20455. if ( this.parent ) {
  20456. this.parent.updateWorldMatrix( true );
  20457. this.matrix
  20458. .copy( this.parent.matrixWorld )
  20459. .invert()
  20460. .multiply( this.light.matrixWorld );
  20461. } else {
  20462. this.matrix.copy( this.light.matrixWorld );
  20463. }
  20464. this.matrixWorld.copy( this.light.matrixWorld );
  20465. const coneLength = this.light.distance ? this.light.distance : 1000;
  20466. const coneWidth = coneLength * Math.tan( this.light.angle );
  20467. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20468. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20469. this.cone.lookAt( _vector$3 );
  20470. if ( this.color !== undefined ) {
  20471. this.cone.material.color.set( this.color );
  20472. } else {
  20473. this.cone.material.color.copy( this.light.color );
  20474. }
  20475. }
  20476. }
  20477. const _vector$2 = /*@__PURE__*/ new Vector3();
  20478. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20479. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20480. class SkeletonHelper extends LineSegments {
  20481. constructor( object ) {
  20482. const bones = getBoneList( object );
  20483. const geometry = new BufferGeometry();
  20484. const vertices = [];
  20485. const colors = [];
  20486. const color1 = new Color( 0, 0, 1 );
  20487. const color2 = new Color( 0, 1, 0 );
  20488. for ( let i = 0; i < bones.length; i ++ ) {
  20489. const bone = bones[ i ];
  20490. if ( bone.parent && bone.parent.isBone ) {
  20491. vertices.push( 0, 0, 0 );
  20492. vertices.push( 0, 0, 0 );
  20493. colors.push( color1.r, color1.g, color1.b );
  20494. colors.push( color2.r, color2.g, color2.b );
  20495. }
  20496. }
  20497. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20498. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20499. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20500. super( geometry, material );
  20501. this.isSkeletonHelper = true;
  20502. this.type = 'SkeletonHelper';
  20503. this.root = object;
  20504. this.bones = bones;
  20505. this.matrix = object.matrixWorld;
  20506. this.matrixAutoUpdate = false;
  20507. }
  20508. updateMatrixWorld( force ) {
  20509. const bones = this.bones;
  20510. const geometry = this.geometry;
  20511. const position = geometry.getAttribute( 'position' );
  20512. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20513. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20514. const bone = bones[ i ];
  20515. if ( bone.parent && bone.parent.isBone ) {
  20516. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20517. _vector$2.setFromMatrixPosition( _boneMatrix );
  20518. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20519. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20520. _vector$2.setFromMatrixPosition( _boneMatrix );
  20521. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20522. j += 2;
  20523. }
  20524. }
  20525. geometry.getAttribute( 'position' ).needsUpdate = true;
  20526. super.updateMatrixWorld( force );
  20527. }
  20528. dispose() {
  20529. this.geometry.dispose();
  20530. this.material.dispose();
  20531. }
  20532. }
  20533. function getBoneList( object ) {
  20534. const boneList = [];
  20535. if ( object.isBone === true ) {
  20536. boneList.push( object );
  20537. }
  20538. for ( let i = 0; i < object.children.length; i ++ ) {
  20539. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20540. }
  20541. return boneList;
  20542. }
  20543. class PointLightHelper extends Mesh {
  20544. constructor( light, sphereSize, color ) {
  20545. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20546. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20547. super( geometry, material );
  20548. this.light = light;
  20549. this.color = color;
  20550. this.type = 'PointLightHelper';
  20551. this.matrix = this.light.matrixWorld;
  20552. this.matrixAutoUpdate = false;
  20553. this.update();
  20554. /*
  20555. // TODO: delete this comment?
  20556. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20557. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20558. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20559. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20560. const d = light.distance;
  20561. if ( d === 0.0 ) {
  20562. this.lightDistance.visible = false;
  20563. } else {
  20564. this.lightDistance.scale.set( d, d, d );
  20565. }
  20566. this.add( this.lightDistance );
  20567. */
  20568. }
  20569. dispose() {
  20570. this.geometry.dispose();
  20571. this.material.dispose();
  20572. }
  20573. update() {
  20574. this.light.updateWorldMatrix( true, false );
  20575. if ( this.color !== undefined ) {
  20576. this.material.color.set( this.color );
  20577. } else {
  20578. this.material.color.copy( this.light.color );
  20579. }
  20580. /*
  20581. const d = this.light.distance;
  20582. if ( d === 0.0 ) {
  20583. this.lightDistance.visible = false;
  20584. } else {
  20585. this.lightDistance.visible = true;
  20586. this.lightDistance.scale.set( d, d, d );
  20587. }
  20588. */
  20589. }
  20590. }
  20591. const _vector$1 = /*@__PURE__*/ new Vector3();
  20592. const _color1 = /*@__PURE__*/ new Color();
  20593. const _color2 = /*@__PURE__*/ new Color();
  20594. class HemisphereLightHelper extends Object3D {
  20595. constructor( light, size, color ) {
  20596. super();
  20597. this.light = light;
  20598. this.matrix = light.matrixWorld;
  20599. this.matrixAutoUpdate = false;
  20600. this.color = color;
  20601. this.type = 'HemisphereLightHelper';
  20602. const geometry = new OctahedronGeometry( size );
  20603. geometry.rotateY( Math.PI * 0.5 );
  20604. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20605. if ( this.color === undefined ) this.material.vertexColors = true;
  20606. const position = geometry.getAttribute( 'position' );
  20607. const colors = new Float32Array( position.count * 3 );
  20608. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20609. this.add( new Mesh( geometry, this.material ) );
  20610. this.update();
  20611. }
  20612. dispose() {
  20613. this.children[ 0 ].geometry.dispose();
  20614. this.children[ 0 ].material.dispose();
  20615. }
  20616. update() {
  20617. const mesh = this.children[ 0 ];
  20618. if ( this.color !== undefined ) {
  20619. this.material.color.set( this.color );
  20620. } else {
  20621. const colors = mesh.geometry.getAttribute( 'color' );
  20622. _color1.copy( this.light.color );
  20623. _color2.copy( this.light.groundColor );
  20624. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20625. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20626. colors.setXYZ( i, color.r, color.g, color.b );
  20627. }
  20628. colors.needsUpdate = true;
  20629. }
  20630. this.light.updateWorldMatrix( true, false );
  20631. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20632. }
  20633. }
  20634. class GridHelper extends LineSegments {
  20635. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20636. color1 = new Color( color1 );
  20637. color2 = new Color( color2 );
  20638. const center = divisions / 2;
  20639. const step = size / divisions;
  20640. const halfSize = size / 2;
  20641. const vertices = [], colors = [];
  20642. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20643. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20644. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20645. const color = i === center ? color1 : color2;
  20646. color.toArray( colors, j ); j += 3;
  20647. color.toArray( colors, j ); j += 3;
  20648. color.toArray( colors, j ); j += 3;
  20649. color.toArray( colors, j ); j += 3;
  20650. }
  20651. const geometry = new BufferGeometry();
  20652. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20653. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20654. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20655. super( geometry, material );
  20656. this.type = 'GridHelper';
  20657. }
  20658. dispose() {
  20659. this.geometry.dispose();
  20660. this.material.dispose();
  20661. }
  20662. }
  20663. class PolarGridHelper extends LineSegments {
  20664. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20665. color1 = new Color( color1 );
  20666. color2 = new Color( color2 );
  20667. const vertices = [];
  20668. const colors = [];
  20669. // create the sectors
  20670. if ( sectors > 1 ) {
  20671. for ( let i = 0; i < sectors; i ++ ) {
  20672. const v = ( i / sectors ) * ( Math.PI * 2 );
  20673. const x = Math.sin( v ) * radius;
  20674. const z = Math.cos( v ) * radius;
  20675. vertices.push( 0, 0, 0 );
  20676. vertices.push( x, 0, z );
  20677. const color = ( i & 1 ) ? color1 : color2;
  20678. colors.push( color.r, color.g, color.b );
  20679. colors.push( color.r, color.g, color.b );
  20680. }
  20681. }
  20682. // create the rings
  20683. for ( let i = 0; i < rings; i ++ ) {
  20684. const color = ( i & 1 ) ? color1 : color2;
  20685. const r = radius - ( radius / rings * i );
  20686. for ( let j = 0; j < divisions; j ++ ) {
  20687. // first vertex
  20688. let v = ( j / divisions ) * ( Math.PI * 2 );
  20689. let x = Math.sin( v ) * r;
  20690. let z = Math.cos( v ) * r;
  20691. vertices.push( x, 0, z );
  20692. colors.push( color.r, color.g, color.b );
  20693. // second vertex
  20694. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20695. x = Math.sin( v ) * r;
  20696. z = Math.cos( v ) * r;
  20697. vertices.push( x, 0, z );
  20698. colors.push( color.r, color.g, color.b );
  20699. }
  20700. }
  20701. const geometry = new BufferGeometry();
  20702. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20703. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20704. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20705. super( geometry, material );
  20706. this.type = 'PolarGridHelper';
  20707. }
  20708. dispose() {
  20709. this.geometry.dispose();
  20710. this.material.dispose();
  20711. }
  20712. }
  20713. const _v1 = /*@__PURE__*/ new Vector3();
  20714. const _v2 = /*@__PURE__*/ new Vector3();
  20715. const _v3 = /*@__PURE__*/ new Vector3();
  20716. class DirectionalLightHelper extends Object3D {
  20717. constructor( light, size, color ) {
  20718. super();
  20719. this.light = light;
  20720. this.matrix = light.matrixWorld;
  20721. this.matrixAutoUpdate = false;
  20722. this.color = color;
  20723. this.type = 'DirectionalLightHelper';
  20724. if ( size === undefined ) size = 1;
  20725. let geometry = new BufferGeometry();
  20726. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20727. - size, size, 0,
  20728. size, size, 0,
  20729. size, - size, 0,
  20730. - size, - size, 0,
  20731. - size, size, 0
  20732. ], 3 ) );
  20733. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20734. this.lightPlane = new Line( geometry, material );
  20735. this.add( this.lightPlane );
  20736. geometry = new BufferGeometry();
  20737. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20738. this.targetLine = new Line( geometry, material );
  20739. this.add( this.targetLine );
  20740. this.update();
  20741. }
  20742. dispose() {
  20743. this.lightPlane.geometry.dispose();
  20744. this.lightPlane.material.dispose();
  20745. this.targetLine.geometry.dispose();
  20746. this.targetLine.material.dispose();
  20747. }
  20748. update() {
  20749. this.light.updateWorldMatrix( true, false );
  20750. this.light.target.updateWorldMatrix( true, false );
  20751. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20752. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20753. _v3.subVectors( _v2, _v1 );
  20754. this.lightPlane.lookAt( _v2 );
  20755. if ( this.color !== undefined ) {
  20756. this.lightPlane.material.color.set( this.color );
  20757. this.targetLine.material.color.set( this.color );
  20758. } else {
  20759. this.lightPlane.material.color.copy( this.light.color );
  20760. this.targetLine.material.color.copy( this.light.color );
  20761. }
  20762. this.targetLine.lookAt( _v2 );
  20763. this.targetLine.scale.z = _v3.length();
  20764. }
  20765. }
  20766. const _vector = /*@__PURE__*/ new Vector3();
  20767. const _camera$1 = /*@__PURE__*/ new Camera();
  20768. /**
  20769. * - shows frustum, line of sight and up of the camera
  20770. * - suitable for fast updates
  20771. * - based on frustum visualization in lightgl.js shadowmap example
  20772. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20773. */
  20774. class CameraHelper extends LineSegments {
  20775. constructor( camera ) {
  20776. const geometry = new BufferGeometry();
  20777. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20778. const vertices = [];
  20779. const colors = [];
  20780. const pointMap = {};
  20781. // near
  20782. addLine( 'n1', 'n2' );
  20783. addLine( 'n2', 'n4' );
  20784. addLine( 'n4', 'n3' );
  20785. addLine( 'n3', 'n1' );
  20786. // far
  20787. addLine( 'f1', 'f2' );
  20788. addLine( 'f2', 'f4' );
  20789. addLine( 'f4', 'f3' );
  20790. addLine( 'f3', 'f1' );
  20791. // sides
  20792. addLine( 'n1', 'f1' );
  20793. addLine( 'n2', 'f2' );
  20794. addLine( 'n3', 'f3' );
  20795. addLine( 'n4', 'f4' );
  20796. // cone
  20797. addLine( 'p', 'n1' );
  20798. addLine( 'p', 'n2' );
  20799. addLine( 'p', 'n3' );
  20800. addLine( 'p', 'n4' );
  20801. // up
  20802. addLine( 'u1', 'u2' );
  20803. addLine( 'u2', 'u3' );
  20804. addLine( 'u3', 'u1' );
  20805. // target
  20806. addLine( 'c', 't' );
  20807. addLine( 'p', 'c' );
  20808. // cross
  20809. addLine( 'cn1', 'cn2' );
  20810. addLine( 'cn3', 'cn4' );
  20811. addLine( 'cf1', 'cf2' );
  20812. addLine( 'cf3', 'cf4' );
  20813. function addLine( a, b ) {
  20814. addPoint( a );
  20815. addPoint( b );
  20816. }
  20817. function addPoint( id ) {
  20818. vertices.push( 0, 0, 0 );
  20819. colors.push( 0, 0, 0 );
  20820. if ( pointMap[ id ] === undefined ) {
  20821. pointMap[ id ] = [];
  20822. }
  20823. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20824. }
  20825. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20826. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20827. super( geometry, material );
  20828. this.type = 'CameraHelper';
  20829. this.camera = camera;
  20830. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20831. this.matrix = camera.matrixWorld;
  20832. this.matrixAutoUpdate = false;
  20833. this.pointMap = pointMap;
  20834. this.update();
  20835. // colors
  20836. const colorFrustum = new Color( 0xffaa00 );
  20837. const colorCone = new Color( 0xff0000 );
  20838. const colorUp = new Color( 0x00aaff );
  20839. const colorTarget = new Color( 0xffffff );
  20840. const colorCross = new Color( 0x333333 );
  20841. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20842. }
  20843. setColors( frustum, cone, up, target, cross ) {
  20844. const geometry = this.geometry;
  20845. const colorAttribute = geometry.getAttribute( 'color' );
  20846. // near
  20847. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20848. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20849. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20850. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20851. // far
  20852. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20853. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20854. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20855. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20856. // sides
  20857. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20858. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20859. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20860. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20861. // cone
  20862. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20863. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20864. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20865. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20866. // up
  20867. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20868. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20869. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20870. // target
  20871. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20872. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20873. // cross
  20874. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20875. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20876. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20877. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20878. colorAttribute.needsUpdate = true;
  20879. }
  20880. update() {
  20881. const geometry = this.geometry;
  20882. const pointMap = this.pointMap;
  20883. const w = 1, h = 1;
  20884. // we need just camera projection matrix inverse
  20885. // world matrix must be identity
  20886. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20887. // center / target
  20888. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20889. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20890. // near
  20891. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20892. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20893. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20894. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20895. // far
  20896. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20897. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20898. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20899. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20900. // up
  20901. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20902. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20903. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20904. // cross
  20905. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20906. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20907. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20908. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20909. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20910. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20911. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20912. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20913. geometry.getAttribute( 'position' ).needsUpdate = true;
  20914. }
  20915. dispose() {
  20916. this.geometry.dispose();
  20917. this.material.dispose();
  20918. }
  20919. }
  20920. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20921. _vector.set( x, y, z ).unproject( camera );
  20922. const points = pointMap[ point ];
  20923. if ( points !== undefined ) {
  20924. const position = geometry.getAttribute( 'position' );
  20925. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20926. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20927. }
  20928. }
  20929. }
  20930. const _box = /*@__PURE__*/ new Box3();
  20931. class BoxHelper extends LineSegments {
  20932. constructor( object, color = 0xffff00 ) {
  20933. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  20934. const positions = new Float32Array( 8 * 3 );
  20935. const geometry = new BufferGeometry();
  20936. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20937. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20938. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20939. this.object = object;
  20940. this.type = 'BoxHelper';
  20941. this.matrixAutoUpdate = false;
  20942. this.update();
  20943. }
  20944. update( object ) {
  20945. if ( object !== undefined ) {
  20946. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20947. }
  20948. if ( this.object !== undefined ) {
  20949. _box.setFromObject( this.object );
  20950. }
  20951. if ( _box.isEmpty() ) return;
  20952. const min = _box.min;
  20953. const max = _box.max;
  20954. /*
  20955. 5____4
  20956. 1/___0/|
  20957. | 6__|_7
  20958. 2/___3/
  20959. 0: max.x, max.y, max.z
  20960. 1: min.x, max.y, max.z
  20961. 2: min.x, min.y, max.z
  20962. 3: max.x, min.y, max.z
  20963. 4: max.x, max.y, min.z
  20964. 5: min.x, max.y, min.z
  20965. 6: min.x, min.y, min.z
  20966. 7: max.x, min.y, min.z
  20967. */
  20968. const position = this.geometry.attributes.position;
  20969. const array = position.array;
  20970. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20971. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20972. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20973. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20974. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20975. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20976. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20977. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20978. position.needsUpdate = true;
  20979. this.geometry.computeBoundingSphere();
  20980. }
  20981. setFromObject( object ) {
  20982. this.object = object;
  20983. this.update();
  20984. return this;
  20985. }
  20986. copy( source, recursive ) {
  20987. super.copy( source, recursive );
  20988. this.object = source.object;
  20989. return this;
  20990. }
  20991. dispose() {
  20992. this.geometry.dispose();
  20993. this.material.dispose();
  20994. }
  20995. }
  20996. class Box3Helper extends LineSegments {
  20997. constructor( box, color = 0xffff00 ) {
  20998. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  20999. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  21000. const geometry = new BufferGeometry();
  21001. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21002. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21003. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21004. this.box = box;
  21005. this.type = 'Box3Helper';
  21006. this.geometry.computeBoundingSphere();
  21007. }
  21008. updateMatrixWorld( force ) {
  21009. const box = this.box;
  21010. if ( box.isEmpty() ) return;
  21011. box.getCenter( this.position );
  21012. box.getSize( this.scale );
  21013. this.scale.multiplyScalar( 0.5 );
  21014. super.updateMatrixWorld( force );
  21015. }
  21016. dispose() {
  21017. this.geometry.dispose();
  21018. this.material.dispose();
  21019. }
  21020. }
  21021. class PlaneHelper extends Line {
  21022. constructor( plane, size = 1, hex = 0xffff00 ) {
  21023. const color = hex;
  21024. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  21025. const geometry = new BufferGeometry();
  21026. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21027. geometry.computeBoundingSphere();
  21028. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21029. this.type = 'PlaneHelper';
  21030. this.plane = plane;
  21031. this.size = size;
  21032. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21033. const geometry2 = new BufferGeometry();
  21034. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21035. geometry2.computeBoundingSphere();
  21036. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21037. }
  21038. updateMatrixWorld( force ) {
  21039. this.position.set( 0, 0, 0 );
  21040. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21041. this.lookAt( this.plane.normal );
  21042. this.translateZ( - this.plane.constant );
  21043. super.updateMatrixWorld( force );
  21044. }
  21045. dispose() {
  21046. this.geometry.dispose();
  21047. this.material.dispose();
  21048. this.children[ 0 ].geometry.dispose();
  21049. this.children[ 0 ].material.dispose();
  21050. }
  21051. }
  21052. const _axis = /*@__PURE__*/ new Vector3();
  21053. let _lineGeometry, _coneGeometry;
  21054. class ArrowHelper extends Object3D {
  21055. // dir is assumed to be normalized
  21056. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21057. super();
  21058. this.type = 'ArrowHelper';
  21059. if ( _lineGeometry === undefined ) {
  21060. _lineGeometry = new BufferGeometry();
  21061. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21062. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21063. _coneGeometry.translate( 0, - 0.5, 0 );
  21064. }
  21065. this.position.copy( origin );
  21066. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21067. this.line.matrixAutoUpdate = false;
  21068. this.add( this.line );
  21069. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21070. this.cone.matrixAutoUpdate = false;
  21071. this.add( this.cone );
  21072. this.setDirection( dir );
  21073. this.setLength( length, headLength, headWidth );
  21074. }
  21075. setDirection( dir ) {
  21076. // dir is assumed to be normalized
  21077. if ( dir.y > 0.99999 ) {
  21078. this.quaternion.set( 0, 0, 0, 1 );
  21079. } else if ( dir.y < - 0.99999 ) {
  21080. this.quaternion.set( 1, 0, 0, 0 );
  21081. } else {
  21082. _axis.set( dir.z, 0, - dir.x ).normalize();
  21083. const radians = Math.acos( dir.y );
  21084. this.quaternion.setFromAxisAngle( _axis, radians );
  21085. }
  21086. }
  21087. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21088. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21089. this.line.updateMatrix();
  21090. this.cone.scale.set( headWidth, headLength, headWidth );
  21091. this.cone.position.y = length;
  21092. this.cone.updateMatrix();
  21093. }
  21094. setColor( color ) {
  21095. this.line.material.color.set( color );
  21096. this.cone.material.color.set( color );
  21097. }
  21098. copy( source ) {
  21099. super.copy( source, false );
  21100. this.line.copy( source.line );
  21101. this.cone.copy( source.cone );
  21102. return this;
  21103. }
  21104. dispose() {
  21105. this.line.geometry.dispose();
  21106. this.line.material.dispose();
  21107. this.cone.geometry.dispose();
  21108. this.cone.material.dispose();
  21109. }
  21110. }
  21111. class AxesHelper extends LineSegments {
  21112. constructor( size = 1 ) {
  21113. const vertices = [
  21114. 0, 0, 0, size, 0, 0,
  21115. 0, 0, 0, 0, size, 0,
  21116. 0, 0, 0, 0, 0, size
  21117. ];
  21118. const colors = [
  21119. 1, 0, 0, 1, 0.6, 0,
  21120. 0, 1, 0, 0.6, 1, 0,
  21121. 0, 0, 1, 0, 0.6, 1
  21122. ];
  21123. const geometry = new BufferGeometry();
  21124. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21125. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21126. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21127. super( geometry, material );
  21128. this.type = 'AxesHelper';
  21129. }
  21130. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21131. const color = new Color();
  21132. const array = this.geometry.attributes.color.array;
  21133. color.set( xAxisColor );
  21134. color.toArray( array, 0 );
  21135. color.toArray( array, 3 );
  21136. color.set( yAxisColor );
  21137. color.toArray( array, 6 );
  21138. color.toArray( array, 9 );
  21139. color.set( zAxisColor );
  21140. color.toArray( array, 12 );
  21141. color.toArray( array, 15 );
  21142. this.geometry.attributes.color.needsUpdate = true;
  21143. return this;
  21144. }
  21145. dispose() {
  21146. this.geometry.dispose();
  21147. this.material.dispose();
  21148. }
  21149. }
  21150. class ShapePath {
  21151. constructor() {
  21152. this.type = 'ShapePath';
  21153. this.color = new Color();
  21154. this.subPaths = [];
  21155. this.currentPath = null;
  21156. }
  21157. moveTo( x, y ) {
  21158. this.currentPath = new Path();
  21159. this.subPaths.push( this.currentPath );
  21160. this.currentPath.moveTo( x, y );
  21161. return this;
  21162. }
  21163. lineTo( x, y ) {
  21164. this.currentPath.lineTo( x, y );
  21165. return this;
  21166. }
  21167. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21168. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21169. return this;
  21170. }
  21171. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21172. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21173. return this;
  21174. }
  21175. splineThru( pts ) {
  21176. this.currentPath.splineThru( pts );
  21177. return this;
  21178. }
  21179. toShapes( isCCW ) {
  21180. function toShapesNoHoles( inSubpaths ) {
  21181. const shapes = [];
  21182. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21183. const tmpPath = inSubpaths[ i ];
  21184. const tmpShape = new Shape();
  21185. tmpShape.curves = tmpPath.curves;
  21186. shapes.push( tmpShape );
  21187. }
  21188. return shapes;
  21189. }
  21190. function isPointInsidePolygon( inPt, inPolygon ) {
  21191. const polyLen = inPolygon.length;
  21192. // inPt on polygon contour => immediate success or
  21193. // toggling of inside/outside at every single! intersection point of an edge
  21194. // with the horizontal line through inPt, left of inPt
  21195. // not counting lowerY endpoints of edges and whole edges on that line
  21196. let inside = false;
  21197. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21198. let edgeLowPt = inPolygon[ p ];
  21199. let edgeHighPt = inPolygon[ q ];
  21200. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21201. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21202. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21203. // not parallel
  21204. if ( edgeDy < 0 ) {
  21205. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21206. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21207. }
  21208. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21209. if ( inPt.y === edgeLowPt.y ) {
  21210. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21211. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21212. } else {
  21213. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21214. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21215. if ( perpEdge < 0 ) continue;
  21216. inside = ! inside; // true intersection left of inPt
  21217. }
  21218. } else {
  21219. // parallel or collinear
  21220. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21221. // edge lies on the same horizontal line as inPt
  21222. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21223. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21224. // continue;
  21225. }
  21226. }
  21227. return inside;
  21228. }
  21229. const isClockWise = ShapeUtils.isClockWise;
  21230. const subPaths = this.subPaths;
  21231. if ( subPaths.length === 0 ) return [];
  21232. let solid, tmpPath, tmpShape;
  21233. const shapes = [];
  21234. if ( subPaths.length === 1 ) {
  21235. tmpPath = subPaths[ 0 ];
  21236. tmpShape = new Shape();
  21237. tmpShape.curves = tmpPath.curves;
  21238. shapes.push( tmpShape );
  21239. return shapes;
  21240. }
  21241. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21242. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21243. // console.log("Holes first", holesFirst);
  21244. const betterShapeHoles = [];
  21245. const newShapes = [];
  21246. let newShapeHoles = [];
  21247. let mainIdx = 0;
  21248. let tmpPoints;
  21249. newShapes[ mainIdx ] = undefined;
  21250. newShapeHoles[ mainIdx ] = [];
  21251. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21252. tmpPath = subPaths[ i ];
  21253. tmpPoints = tmpPath.getPoints();
  21254. solid = isClockWise( tmpPoints );
  21255. solid = isCCW ? ! solid : solid;
  21256. if ( solid ) {
  21257. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21258. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21259. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21260. if ( holesFirst ) mainIdx ++;
  21261. newShapeHoles[ mainIdx ] = [];
  21262. //console.log('cw', i);
  21263. } else {
  21264. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21265. //console.log('ccw', i);
  21266. }
  21267. }
  21268. // only Holes? -> probably all Shapes with wrong orientation
  21269. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21270. if ( newShapes.length > 1 ) {
  21271. let ambiguous = false;
  21272. let toChange = 0;
  21273. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21274. betterShapeHoles[ sIdx ] = [];
  21275. }
  21276. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21277. const sho = newShapeHoles[ sIdx ];
  21278. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21279. const ho = sho[ hIdx ];
  21280. let hole_unassigned = true;
  21281. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21282. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21283. if ( sIdx !== s2Idx ) toChange ++;
  21284. if ( hole_unassigned ) {
  21285. hole_unassigned = false;
  21286. betterShapeHoles[ s2Idx ].push( ho );
  21287. } else {
  21288. ambiguous = true;
  21289. }
  21290. }
  21291. }
  21292. if ( hole_unassigned ) {
  21293. betterShapeHoles[ sIdx ].push( ho );
  21294. }
  21295. }
  21296. }
  21297. if ( toChange > 0 && ambiguous === false ) {
  21298. newShapeHoles = betterShapeHoles;
  21299. }
  21300. }
  21301. let tmpHoles;
  21302. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21303. tmpShape = newShapes[ i ].s;
  21304. shapes.push( tmpShape );
  21305. tmpHoles = newShapeHoles[ i ];
  21306. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21307. tmpShape.holes.push( tmpHoles[ j ].h );
  21308. }
  21309. }
  21310. //console.log("shape", shapes);
  21311. return shapes;
  21312. }
  21313. }
  21314. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21315. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21316. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21317. super( width, height, { ...options, count } );
  21318. this.isWebGLMultipleRenderTargets = true;
  21319. }
  21320. get texture() {
  21321. return this.textures;
  21322. }
  21323. }
  21324. if ( self.GPUShaderStage === undefined ) {
  21325. self.GPUShaderStage = { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  21326. }
  21327. // statics
  21328. let isAvailable = navigator.gpu !== undefined;
  21329. if ( typeof window !== 'undefined' && isAvailable ) {
  21330. isAvailable = await navigator.gpu.requestAdapter();
  21331. }
  21332. class WebGPU {
  21333. static isAvailable() {
  21334. return Boolean( isAvailable );
  21335. }
  21336. static getStaticAdapter() {
  21337. return isAvailable;
  21338. }
  21339. static getErrorMessage() {
  21340. const message = 'Your browser does not support <a href="https://gpuweb.github.io/gpuweb/" style="color:blue">WebGPU</a> yet';
  21341. const element = document.createElement( 'div' );
  21342. element.id = 'webgpumessage';
  21343. element.style.fontFamily = 'monospace';
  21344. element.style.fontSize = '13px';
  21345. element.style.fontWeight = 'normal';
  21346. element.style.textAlign = 'center';
  21347. element.style.background = '#fff';
  21348. element.style.color = '#000';
  21349. element.style.padding = '1.5em';
  21350. element.style.maxWidth = '400px';
  21351. element.style.margin = '5em auto 0';
  21352. element.innerHTML = message;
  21353. return element;
  21354. }
  21355. }
  21356. class Animation {
  21357. constructor( nodes, info ) {
  21358. this.nodes = nodes;
  21359. this.info = info;
  21360. this.animationLoop = null;
  21361. this.requestId = null;
  21362. this._init();
  21363. }
  21364. _init() {
  21365. const update = ( time, frame ) => {
  21366. this.requestId = self.requestAnimationFrame( update );
  21367. if ( this.info.autoReset === true ) this.info.reset();
  21368. this.nodes.nodeFrame.update();
  21369. this.info.frame = this.nodes.nodeFrame.frameId;
  21370. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  21371. };
  21372. update();
  21373. }
  21374. dispose() {
  21375. self.cancelAnimationFrame( this.requestId );
  21376. this.requestId = null;
  21377. }
  21378. setAnimationLoop( callback ) {
  21379. this.animationLoop = callback;
  21380. }
  21381. }
  21382. class ChainMap {
  21383. constructor() {
  21384. this.weakMap = new WeakMap();
  21385. }
  21386. get( keys ) {
  21387. let map = this.weakMap;
  21388. for ( let i = 0; i < keys.length; i ++ ) {
  21389. map = map.get( keys[ i ] );
  21390. if ( map === undefined ) return undefined;
  21391. }
  21392. return map.get( keys[ keys.length - 1 ] );
  21393. }
  21394. set( keys, value ) {
  21395. let map = this.weakMap;
  21396. for ( let i = 0; i < keys.length; i ++ ) {
  21397. const key = keys[ i ];
  21398. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  21399. map = map.get( key );
  21400. }
  21401. return map.set( keys[ keys.length - 1 ], value );
  21402. }
  21403. delete( keys ) {
  21404. let map = this.weakMap;
  21405. for ( let i = 0; i < keys.length; i ++ ) {
  21406. map = map.get( keys[ i ] );
  21407. if ( map === undefined ) return false;
  21408. }
  21409. return map.delete( keys[ keys.length - 1 ] );
  21410. }
  21411. }
  21412. const _plane = /*@__PURE__*/ new Plane();
  21413. let _clippingContextVersion = 0;
  21414. class ClippingContext {
  21415. constructor() {
  21416. this.version = ++ _clippingContextVersion;
  21417. this.globalClippingCount = 0;
  21418. this.localClippingCount = 0;
  21419. this.localClippingEnabled = false;
  21420. this.localClipIntersection = false;
  21421. this.planes = [];
  21422. this.parentVersion = 0;
  21423. this.viewNormalMatrix = new Matrix3();
  21424. }
  21425. projectPlanes( source, offset ) {
  21426. const l = source.length;
  21427. const planes = this.planes;
  21428. for ( let i = 0; i < l; i ++ ) {
  21429. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  21430. const v = planes[ offset + i ];
  21431. const normal = _plane.normal;
  21432. v.x = - normal.x;
  21433. v.y = - normal.y;
  21434. v.z = - normal.z;
  21435. v.w = _plane.constant;
  21436. }
  21437. }
  21438. updateGlobal( renderer, camera ) {
  21439. const rendererClippingPlanes = renderer.clippingPlanes;
  21440. this.viewMatrix = camera.matrixWorldInverse;
  21441. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  21442. let update = false;
  21443. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  21444. const l = rendererClippingPlanes.length;
  21445. if ( l !== this.globalClippingCount ) {
  21446. const planes = [];
  21447. for ( let i = 0; i < l; i ++ ) {
  21448. planes.push( new Vector4() );
  21449. }
  21450. this.globalClippingCount = l;
  21451. this.planes = planes;
  21452. update = true;
  21453. }
  21454. this.projectPlanes( rendererClippingPlanes, 0 );
  21455. } else if ( this.globalClippingCount !== 0 ) {
  21456. this.globalClippingCount = 0;
  21457. this.planes = [];
  21458. update = true;
  21459. }
  21460. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  21461. this.localClippingEnabled = renderer.localClippingEnabled;
  21462. update = true;
  21463. }
  21464. if ( update ) this.version = _clippingContextVersion ++;
  21465. }
  21466. update( parent, material ) {
  21467. let update = false;
  21468. if ( this !== parent && parent.version !== this.parentVersion ) {
  21469. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  21470. this.localClippingEnabled = parent.localClippingEnabled;
  21471. this.planes = Array.from( parent.planes );
  21472. this.parentVersion = parent.version;
  21473. this.viewMatrix = parent.viewMatrix;
  21474. this.viewNormalMatrix = parent.viewNormalMatrix;
  21475. update = true;
  21476. }
  21477. if ( this.localClippingEnabled ) {
  21478. const localClippingPlanes = material.clippingPlanes;
  21479. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  21480. const l = localClippingPlanes.length;
  21481. const planes = this.planes;
  21482. const offset = this.globalClippingCount;
  21483. if ( update || l !== this.localClippingCount ) {
  21484. planes.length = offset + l;
  21485. for ( let i = 0; i < l; i ++ ) {
  21486. planes[ offset + i ] = new Vector4();
  21487. }
  21488. this.localClippingCount = l;
  21489. update = true;
  21490. }
  21491. this.projectPlanes( localClippingPlanes, offset );
  21492. } else if ( this.localClippingCount !== 0 ) {
  21493. this.localClippingCount = 0;
  21494. update = true;
  21495. }
  21496. if ( this.localClipIntersection !== material.clipIntersection ) {
  21497. this.localClipIntersection = material.clipIntersection;
  21498. update = true;
  21499. }
  21500. }
  21501. if ( update ) this.version = _clippingContextVersion ++;
  21502. }
  21503. }
  21504. let _id$7 = 0;
  21505. function getKeys( obj ) {
  21506. const keys = Object.keys( obj );
  21507. let proto = Object.getPrototypeOf( obj );
  21508. while ( proto ) {
  21509. const descriptors = Object.getOwnPropertyDescriptors( proto );
  21510. for ( const key in descriptors ) {
  21511. if ( descriptors[ key ] !== undefined ) {
  21512. const descriptor = descriptors[ key ];
  21513. if ( descriptor && typeof descriptor.get === 'function' ) {
  21514. keys.push( key );
  21515. }
  21516. }
  21517. }
  21518. proto = Object.getPrototypeOf( proto );
  21519. }
  21520. return keys;
  21521. }
  21522. class RenderObject {
  21523. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  21524. this._nodes = nodes;
  21525. this._geometries = geometries;
  21526. this.id = _id$7 ++;
  21527. this.renderer = renderer;
  21528. this.object = object;
  21529. this.material = material;
  21530. this.scene = scene;
  21531. this.camera = camera;
  21532. this.lightsNode = lightsNode;
  21533. this.context = renderContext;
  21534. this.geometry = object.geometry;
  21535. this.version = material.version;
  21536. this.drawRange = null;
  21537. this.attributes = null;
  21538. this.pipeline = null;
  21539. this.vertexBuffers = null;
  21540. this.updateClipping( renderContext.clippingContext );
  21541. this.clippingContextVersion = this.clippingContext.version;
  21542. this.initialNodesCacheKey = this.getDynamicCacheKey();
  21543. this.initialCacheKey = this.getCacheKey();
  21544. this._nodeBuilderState = null;
  21545. this._bindings = null;
  21546. this.onDispose = null;
  21547. this.isRenderObject = true;
  21548. this.onMaterialDispose = () => {
  21549. this.dispose();
  21550. };
  21551. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  21552. }
  21553. updateClipping( parent ) {
  21554. const material = this.material;
  21555. let clippingContext = this.clippingContext;
  21556. if ( Array.isArray( material.clippingPlanes ) ) {
  21557. if ( clippingContext === parent || ! clippingContext ) {
  21558. clippingContext = new ClippingContext();
  21559. this.clippingContext = clippingContext;
  21560. }
  21561. clippingContext.update( parent, material );
  21562. } else if ( this.clippingContext !== parent ) {
  21563. this.clippingContext = parent;
  21564. }
  21565. }
  21566. get clippingNeedsUpdate() {
  21567. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  21568. this.clippingContextVersion = this.clippingContext.version;
  21569. return true;
  21570. }
  21571. getNodeBuilderState() {
  21572. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  21573. }
  21574. getBindings() {
  21575. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  21576. }
  21577. getIndex() {
  21578. return this._geometries.getIndex( this );
  21579. }
  21580. getChainArray() {
  21581. return [ this.object, this.material, this.context, this.lightsNode ];
  21582. }
  21583. getAttributes() {
  21584. if ( this.attributes !== null ) return this.attributes;
  21585. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  21586. const geometry = this.geometry;
  21587. const attributes = [];
  21588. const vertexBuffers = new Set();
  21589. for ( const nodeAttribute of nodeAttributes ) {
  21590. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  21591. if ( attribute === undefined ) continue;
  21592. attributes.push( attribute );
  21593. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  21594. vertexBuffers.add( bufferAttribute );
  21595. }
  21596. this.attributes = attributes;
  21597. this.vertexBuffers = Array.from( vertexBuffers.values() );
  21598. return attributes;
  21599. }
  21600. getVertexBuffers() {
  21601. if ( this.vertexBuffers === null ) this.getAttributes();
  21602. return this.vertexBuffers;
  21603. }
  21604. getMaterialCacheKey() {
  21605. const { object, material } = this;
  21606. let cacheKey = material.customProgramCacheKey();
  21607. for ( const property of getKeys( material ) ) {
  21608. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  21609. const value = material[ property ];
  21610. let valueKey;
  21611. if ( value !== null ) {
  21612. // some material values require a formatting
  21613. const type = typeof value;
  21614. if ( type === 'number' ) {
  21615. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  21616. } else if ( type === 'object' ) {
  21617. valueKey = '{';
  21618. if ( value.isTexture ) {
  21619. valueKey += value.mapping;
  21620. }
  21621. valueKey += '}';
  21622. } else {
  21623. valueKey = String( value );
  21624. }
  21625. } else {
  21626. valueKey = String( value );
  21627. }
  21628. cacheKey += /*property + ':' +*/ valueKey + ',';
  21629. }
  21630. cacheKey += this.clippingContextVersion + ',';
  21631. if ( object.skeleton ) {
  21632. cacheKey += object.skeleton.bones.length + ',';
  21633. }
  21634. if ( object.morphTargetInfluences ) {
  21635. cacheKey += object.morphTargetInfluences.length + ',';
  21636. }
  21637. if ( object.isBatchedMesh ) {
  21638. cacheKey += object._matricesTexture.uuid + ',';
  21639. if ( object._colorsTexture !== null ) {
  21640. cacheKey += object._colorsTexture.uuid + ',';
  21641. }
  21642. }
  21643. if ( object.count > 1 ) {
  21644. cacheKey += object.count + ',';
  21645. }
  21646. return cacheKey;
  21647. }
  21648. get needsUpdate() {
  21649. return this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate;
  21650. }
  21651. getDynamicCacheKey() {
  21652. // Environment Nodes Cache Key
  21653. return this.object.receiveShadow + ',' + this._nodes.getCacheKey( this.scene, this.lightsNode );
  21654. }
  21655. getCacheKey() {
  21656. return this.getMaterialCacheKey() + ',' + this.getDynamicCacheKey();
  21657. }
  21658. dispose() {
  21659. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  21660. this.onDispose();
  21661. }
  21662. }
  21663. class RenderObjects {
  21664. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  21665. this.renderer = renderer;
  21666. this.nodes = nodes;
  21667. this.geometries = geometries;
  21668. this.pipelines = pipelines;
  21669. this.bindings = bindings;
  21670. this.info = info;
  21671. this.chainMaps = {};
  21672. }
  21673. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  21674. const chainMap = this.getChainMap( passId );
  21675. const chainArray = [ object, material, renderContext, lightsNode ];
  21676. let renderObject = chainMap.get( chainArray );
  21677. if ( renderObject === undefined ) {
  21678. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  21679. chainMap.set( chainArray, renderObject );
  21680. } else {
  21681. renderObject.updateClipping( renderContext.clippingContext );
  21682. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  21683. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  21684. renderObject.dispose();
  21685. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  21686. } else {
  21687. renderObject.version = material.version;
  21688. }
  21689. }
  21690. }
  21691. return renderObject;
  21692. }
  21693. getChainMap( passId = 'default' ) {
  21694. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  21695. }
  21696. dispose() {
  21697. this.chainMaps = {};
  21698. }
  21699. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  21700. const chainMap = this.getChainMap( passId );
  21701. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  21702. renderObject.onDispose = () => {
  21703. this.pipelines.delete( renderObject );
  21704. this.bindings.delete( renderObject );
  21705. this.nodes.delete( renderObject );
  21706. chainMap.delete( renderObject.getChainArray() );
  21707. };
  21708. return renderObject;
  21709. }
  21710. }
  21711. class DataMap {
  21712. constructor() {
  21713. this.data = new WeakMap();
  21714. }
  21715. get( object ) {
  21716. let map = this.data.get( object );
  21717. if ( map === undefined ) {
  21718. map = {};
  21719. this.data.set( object, map );
  21720. }
  21721. return map;
  21722. }
  21723. delete( object ) {
  21724. let map;
  21725. if ( this.data.has( object ) ) {
  21726. map = this.data.get( object );
  21727. this.data.delete( object );
  21728. }
  21729. return map;
  21730. }
  21731. has( object ) {
  21732. return this.data.has( object );
  21733. }
  21734. dispose() {
  21735. this.data = new WeakMap();
  21736. }
  21737. }
  21738. const AttributeType = {
  21739. VERTEX: 1,
  21740. INDEX: 2,
  21741. STORAGE: 4
  21742. };
  21743. // size of a chunk in bytes (STD140 layout)
  21744. const GPU_CHUNK_BYTES = 16;
  21745. // @TODO: Move to src/constants.js
  21746. const BlendColorFactor = 211;
  21747. const OneMinusBlendColorFactor = 212;
  21748. class Attributes extends DataMap {
  21749. constructor( backend ) {
  21750. super();
  21751. this.backend = backend;
  21752. }
  21753. delete( attribute ) {
  21754. const attributeData = super.delete( attribute );
  21755. if ( attributeData !== undefined ) {
  21756. this.backend.destroyAttribute( attribute );
  21757. }
  21758. return attributeData;
  21759. }
  21760. update( attribute, type ) {
  21761. const data = this.get( attribute );
  21762. if ( data.version === undefined ) {
  21763. if ( type === AttributeType.VERTEX ) {
  21764. this.backend.createAttribute( attribute );
  21765. } else if ( type === AttributeType.INDEX ) {
  21766. this.backend.createIndexAttribute( attribute );
  21767. } else if ( type === AttributeType.STORAGE ) {
  21768. this.backend.createStorageAttribute( attribute );
  21769. }
  21770. data.version = this._getBufferAttribute( attribute ).version;
  21771. } else {
  21772. const bufferAttribute = this._getBufferAttribute( attribute );
  21773. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  21774. this.backend.updateAttribute( attribute );
  21775. data.version = bufferAttribute.version;
  21776. }
  21777. }
  21778. }
  21779. _getBufferAttribute( attribute ) {
  21780. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  21781. return attribute;
  21782. }
  21783. }
  21784. function arrayNeedsUint32( array ) {
  21785. // assumes larger values usually on last
  21786. for ( let i = array.length - 1; i >= 0; -- i ) {
  21787. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  21788. }
  21789. return false;
  21790. }
  21791. function getWireframeVersion( geometry ) {
  21792. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  21793. }
  21794. function getWireframeIndex( geometry ) {
  21795. const indices = [];
  21796. const geometryIndex = geometry.index;
  21797. const geometryPosition = geometry.attributes.position;
  21798. if ( geometryIndex !== null ) {
  21799. const array = geometryIndex.array;
  21800. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  21801. const a = array[ i + 0 ];
  21802. const b = array[ i + 1 ];
  21803. const c = array[ i + 2 ];
  21804. indices.push( a, b, b, c, c, a );
  21805. }
  21806. } else {
  21807. const array = geometryPosition.array;
  21808. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  21809. const a = i + 0;
  21810. const b = i + 1;
  21811. const c = i + 2;
  21812. indices.push( a, b, b, c, c, a );
  21813. }
  21814. }
  21815. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  21816. attribute.version = getWireframeVersion( geometry );
  21817. return attribute;
  21818. }
  21819. class Geometries extends DataMap {
  21820. constructor( attributes, info ) {
  21821. super();
  21822. this.attributes = attributes;
  21823. this.info = info;
  21824. this.wireframes = new WeakMap();
  21825. this.attributeCall = new WeakMap();
  21826. }
  21827. has( renderObject ) {
  21828. const geometry = renderObject.geometry;
  21829. return super.has( geometry ) && this.get( geometry ).initialized === true;
  21830. }
  21831. updateForRender( renderObject ) {
  21832. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  21833. this.updateAttributes( renderObject );
  21834. }
  21835. initGeometry( renderObject ) {
  21836. const geometry = renderObject.geometry;
  21837. const geometryData = this.get( geometry );
  21838. geometryData.initialized = true;
  21839. this.info.memory.geometries ++;
  21840. const onDispose = () => {
  21841. this.info.memory.geometries --;
  21842. const index = geometry.index;
  21843. const geometryAttributes = renderObject.getAttributes();
  21844. if ( index !== null ) {
  21845. this.attributes.delete( index );
  21846. }
  21847. for ( const geometryAttribute of geometryAttributes ) {
  21848. this.attributes.delete( geometryAttribute );
  21849. }
  21850. const wireframeAttribute = this.wireframes.get( geometry );
  21851. if ( wireframeAttribute !== undefined ) {
  21852. this.attributes.delete( wireframeAttribute );
  21853. }
  21854. geometry.removeEventListener( 'dispose', onDispose );
  21855. };
  21856. geometry.addEventListener( 'dispose', onDispose );
  21857. }
  21858. updateAttributes( renderObject ) {
  21859. const attributes = renderObject.getAttributes();
  21860. for ( const attribute of attributes ) {
  21861. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  21862. this.updateAttribute( attribute, AttributeType.STORAGE );
  21863. } else {
  21864. this.updateAttribute( attribute, AttributeType.VERTEX );
  21865. }
  21866. }
  21867. const index = this.getIndex( renderObject );
  21868. if ( index !== null ) {
  21869. this.updateAttribute( index, AttributeType.INDEX );
  21870. }
  21871. }
  21872. updateAttribute( attribute, type ) {
  21873. const callId = this.info.render.calls;
  21874. if ( ! attribute.isInterleavedBufferAttribute ) {
  21875. if ( this.attributeCall.get( attribute ) !== callId ) {
  21876. this.attributes.update( attribute, type );
  21877. this.attributeCall.set( attribute, callId );
  21878. }
  21879. } else {
  21880. if ( this.attributeCall.get( attribute ) === undefined ) {
  21881. this.attributes.update( attribute, type );
  21882. this.attributeCall.set( attribute, callId );
  21883. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  21884. this.attributes.update( attribute, type );
  21885. this.attributeCall.set( attribute.data, callId );
  21886. this.attributeCall.set( attribute, callId );
  21887. }
  21888. }
  21889. }
  21890. getIndex( renderObject ) {
  21891. const { geometry, material } = renderObject;
  21892. let index = geometry.index;
  21893. if ( material.wireframe === true ) {
  21894. const wireframes = this.wireframes;
  21895. let wireframeAttribute = wireframes.get( geometry );
  21896. if ( wireframeAttribute === undefined ) {
  21897. wireframeAttribute = getWireframeIndex( geometry );
  21898. wireframes.set( geometry, wireframeAttribute );
  21899. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  21900. this.attributes.delete( wireframeAttribute );
  21901. wireframeAttribute = getWireframeIndex( geometry );
  21902. wireframes.set( geometry, wireframeAttribute );
  21903. }
  21904. index = wireframeAttribute;
  21905. }
  21906. return index;
  21907. }
  21908. }
  21909. class Info {
  21910. constructor() {
  21911. this.autoReset = true;
  21912. this.frame = 0;
  21913. this.calls = 0;
  21914. this.render = {
  21915. calls: 0,
  21916. frameCalls: 0,
  21917. drawCalls: 0,
  21918. triangles: 0,
  21919. points: 0,
  21920. lines: 0,
  21921. timestamp: 0,
  21922. previousFrameCalls: 0,
  21923. timestampCalls: 0
  21924. };
  21925. this.compute = {
  21926. calls: 0,
  21927. frameCalls: 0,
  21928. timestamp: 0,
  21929. previousFrameCalls: 0,
  21930. timestampCalls: 0
  21931. };
  21932. this.memory = {
  21933. geometries: 0,
  21934. textures: 0
  21935. };
  21936. }
  21937. update( object, count, instanceCount ) {
  21938. this.render.drawCalls ++;
  21939. if ( object.isMesh || object.isSprite ) {
  21940. this.render.triangles += instanceCount * ( count / 3 );
  21941. } else if ( object.isPoints ) {
  21942. this.render.points += instanceCount * count;
  21943. } else if ( object.isLineSegments ) {
  21944. this.render.lines += instanceCount * ( count / 2 );
  21945. } else if ( object.isLine ) {
  21946. this.render.lines += instanceCount * ( count - 1 );
  21947. } else {
  21948. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  21949. }
  21950. }
  21951. updateTimestamp( type, time ) {
  21952. if ( this[ type ].timestampCalls === 0 ) {
  21953. this[ type ].timestamp = 0;
  21954. }
  21955. this[ type ].timestamp += time;
  21956. this[ type ].timestampCalls ++;
  21957. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  21958. this[ type ].timestampCalls = 0;
  21959. }
  21960. }
  21961. reset() {
  21962. const previousRenderFrameCalls = this.render.frameCalls;
  21963. this.render.previousFrameCalls = previousRenderFrameCalls;
  21964. const previousComputeFrameCalls = this.compute.frameCalls;
  21965. this.compute.previousFrameCalls = previousComputeFrameCalls;
  21966. this.render.drawCalls = 0;
  21967. this.render.frameCalls = 0;
  21968. this.compute.frameCalls = 0;
  21969. this.render.triangles = 0;
  21970. this.render.points = 0;
  21971. this.render.lines = 0;
  21972. }
  21973. dispose() {
  21974. this.reset();
  21975. this.calls = 0;
  21976. this.render.calls = 0;
  21977. this.compute.calls = 0;
  21978. this.render.timestamp = 0;
  21979. this.compute.timestamp = 0;
  21980. this.memory.geometries = 0;
  21981. this.memory.textures = 0;
  21982. }
  21983. }
  21984. class Pipeline {
  21985. constructor( cacheKey ) {
  21986. this.cacheKey = cacheKey;
  21987. this.usedTimes = 0;
  21988. }
  21989. }
  21990. class RenderPipeline extends Pipeline {
  21991. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  21992. super( cacheKey );
  21993. this.vertexProgram = vertexProgram;
  21994. this.fragmentProgram = fragmentProgram;
  21995. }
  21996. }
  21997. class ComputePipeline extends Pipeline {
  21998. constructor( cacheKey, computeProgram ) {
  21999. super( cacheKey );
  22000. this.computeProgram = computeProgram;
  22001. this.isComputePipeline = true;
  22002. }
  22003. }
  22004. let _id$6 = 0;
  22005. class ProgrammableStage {
  22006. constructor( code, type, transforms = null, attributes = null ) {
  22007. this.id = _id$6 ++;
  22008. this.code = code;
  22009. this.stage = type;
  22010. this.transforms = transforms;
  22011. this.attributes = attributes;
  22012. this.usedTimes = 0;
  22013. }
  22014. }
  22015. class Pipelines extends DataMap {
  22016. constructor( backend, nodes ) {
  22017. super();
  22018. this.backend = backend;
  22019. this.nodes = nodes;
  22020. this.bindings = null; // set by the bindings
  22021. this.caches = new Map();
  22022. this.programs = {
  22023. vertex: new Map(),
  22024. fragment: new Map(),
  22025. compute: new Map()
  22026. };
  22027. }
  22028. getForCompute( computeNode, bindings ) {
  22029. const { backend } = this;
  22030. const data = this.get( computeNode );
  22031. if ( this._needsComputeUpdate( computeNode ) ) {
  22032. const previousPipeline = data.pipeline;
  22033. if ( previousPipeline ) {
  22034. previousPipeline.usedTimes --;
  22035. previousPipeline.computeProgram.usedTimes --;
  22036. }
  22037. // get shader
  22038. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  22039. // programmable stage
  22040. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  22041. if ( stageCompute === undefined ) {
  22042. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  22043. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  22044. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  22045. backend.createProgram( stageCompute );
  22046. }
  22047. // determine compute pipeline
  22048. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  22049. let pipeline = this.caches.get( cacheKey );
  22050. if ( pipeline === undefined ) {
  22051. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22052. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  22053. }
  22054. // keep track of all used times
  22055. pipeline.usedTimes ++;
  22056. stageCompute.usedTimes ++;
  22057. //
  22058. data.version = computeNode.version;
  22059. data.pipeline = pipeline;
  22060. }
  22061. return data.pipeline;
  22062. }
  22063. getForRender( renderObject, promises = null ) {
  22064. const { backend } = this;
  22065. const data = this.get( renderObject );
  22066. if ( this._needsRenderUpdate( renderObject ) ) {
  22067. const previousPipeline = data.pipeline;
  22068. if ( previousPipeline ) {
  22069. previousPipeline.usedTimes --;
  22070. previousPipeline.vertexProgram.usedTimes --;
  22071. previousPipeline.fragmentProgram.usedTimes --;
  22072. }
  22073. // get shader
  22074. const nodeBuilderState = renderObject.getNodeBuilderState();
  22075. // programmable stages
  22076. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  22077. if ( stageVertex === undefined ) {
  22078. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  22079. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  22080. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  22081. backend.createProgram( stageVertex );
  22082. }
  22083. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  22084. if ( stageFragment === undefined ) {
  22085. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  22086. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  22087. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  22088. backend.createProgram( stageFragment );
  22089. }
  22090. // determine render pipeline
  22091. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22092. let pipeline = this.caches.get( cacheKey );
  22093. if ( pipeline === undefined ) {
  22094. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  22095. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  22096. } else {
  22097. renderObject.pipeline = pipeline;
  22098. }
  22099. // keep track of all used times
  22100. pipeline.usedTimes ++;
  22101. stageVertex.usedTimes ++;
  22102. stageFragment.usedTimes ++;
  22103. //
  22104. data.pipeline = pipeline;
  22105. }
  22106. return data.pipeline;
  22107. }
  22108. delete( object ) {
  22109. const pipeline = this.get( object ).pipeline;
  22110. if ( pipeline ) {
  22111. // pipeline
  22112. pipeline.usedTimes --;
  22113. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  22114. // programs
  22115. if ( pipeline.isComputePipeline ) {
  22116. pipeline.computeProgram.usedTimes --;
  22117. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  22118. } else {
  22119. pipeline.fragmentProgram.usedTimes --;
  22120. pipeline.vertexProgram.usedTimes --;
  22121. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  22122. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  22123. }
  22124. }
  22125. return super.delete( object );
  22126. }
  22127. dispose() {
  22128. super.dispose();
  22129. this.caches = new Map();
  22130. this.programs = {
  22131. vertex: new Map(),
  22132. fragment: new Map(),
  22133. compute: new Map()
  22134. };
  22135. }
  22136. updateForRender( renderObject ) {
  22137. this.getForRender( renderObject );
  22138. }
  22139. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  22140. // check for existing pipeline
  22141. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  22142. let pipeline = this.caches.get( cacheKey );
  22143. if ( pipeline === undefined ) {
  22144. pipeline = new ComputePipeline( cacheKey, stageCompute );
  22145. this.caches.set( cacheKey, pipeline );
  22146. this.backend.createComputePipeline( pipeline, bindings );
  22147. }
  22148. return pipeline;
  22149. }
  22150. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  22151. // check for existing pipeline
  22152. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  22153. let pipeline = this.caches.get( cacheKey );
  22154. if ( pipeline === undefined ) {
  22155. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  22156. this.caches.set( cacheKey, pipeline );
  22157. renderObject.pipeline = pipeline;
  22158. this.backend.createRenderPipeline( renderObject, promises );
  22159. }
  22160. return pipeline;
  22161. }
  22162. _getComputeCacheKey( computeNode, stageCompute ) {
  22163. return computeNode.id + ',' + stageCompute.id;
  22164. }
  22165. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  22166. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  22167. }
  22168. _releasePipeline( pipeline ) {
  22169. this.caches.delete( pipeline.cacheKey );
  22170. }
  22171. _releaseProgram( program ) {
  22172. const code = program.code;
  22173. const stage = program.stage;
  22174. this.programs[ stage ].delete( code );
  22175. }
  22176. _needsComputeUpdate( computeNode ) {
  22177. const data = this.get( computeNode );
  22178. return data.pipeline === undefined || data.version !== computeNode.version;
  22179. }
  22180. _needsRenderUpdate( renderObject ) {
  22181. const data = this.get( renderObject );
  22182. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  22183. }
  22184. }
  22185. class Bindings extends DataMap {
  22186. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  22187. super();
  22188. this.backend = backend;
  22189. this.textures = textures;
  22190. this.pipelines = pipelines;
  22191. this.attributes = attributes;
  22192. this.nodes = nodes;
  22193. this.info = info;
  22194. this.pipelines.bindings = this; // assign bindings to pipelines
  22195. }
  22196. getForRender( renderObject ) {
  22197. const bindings = renderObject.getBindings();
  22198. for ( const bindGroup of bindings ) {
  22199. const groupData = this.get( bindGroup );
  22200. if ( groupData.bindGroup === undefined ) {
  22201. // each object defines an array of bindings (ubos, textures, samplers etc.)
  22202. this._init( bindGroup );
  22203. this.backend.createBindings( bindGroup, bindings );
  22204. groupData.bindGroup = bindGroup;
  22205. }
  22206. }
  22207. return bindings;
  22208. }
  22209. getForCompute( computeNode ) {
  22210. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  22211. for ( const bindGroup of bindings ) {
  22212. const groupData = this.get( bindGroup );
  22213. if ( groupData.bindGroup === undefined ) {
  22214. this._init( bindGroup );
  22215. this.backend.createBindings( bindGroup, bindings );
  22216. groupData.bindGroup = bindGroup;
  22217. }
  22218. }
  22219. return bindings;
  22220. }
  22221. updateForCompute( computeNode ) {
  22222. this._updateBindings( computeNode, this.getForCompute( computeNode ) );
  22223. }
  22224. updateForRender( renderObject ) {
  22225. this._updateBindings( renderObject, this.getForRender( renderObject ) );
  22226. }
  22227. _updateBindings( object, bindings ) {
  22228. for ( const bindGroup of bindings ) {
  22229. this._update( object, bindGroup, bindings );
  22230. }
  22231. }
  22232. _init( bindGroup ) {
  22233. for ( const binding of bindGroup.bindings ) {
  22234. if ( binding.isSampledTexture ) {
  22235. this.textures.updateTexture( binding.texture );
  22236. } else if ( binding.isStorageBuffer ) {
  22237. const attribute = binding.attribute;
  22238. this.attributes.update( attribute, AttributeType.STORAGE );
  22239. }
  22240. }
  22241. }
  22242. _update( object, bindGroup, bindings ) {
  22243. const { backend } = this;
  22244. let needsBindingsUpdate = false;
  22245. // iterate over all bindings and check if buffer updates or a new binding group is required
  22246. for ( const binding of bindGroup.bindings ) {
  22247. if ( binding.isNodeUniformsGroup ) {
  22248. const updated = this.nodes.updateGroup( binding );
  22249. if ( ! updated ) continue;
  22250. }
  22251. if ( binding.isUniformBuffer ) {
  22252. const updated = binding.update();
  22253. if ( updated ) {
  22254. backend.updateBinding( binding );
  22255. }
  22256. } else if ( binding.isSampler ) {
  22257. binding.update();
  22258. } else if ( binding.isSampledTexture ) {
  22259. const texture = binding.texture;
  22260. if ( binding.needsBindingsUpdate ) needsBindingsUpdate = true;
  22261. const updated = binding.update();
  22262. if ( updated ) {
  22263. this.textures.updateTexture( binding.texture );
  22264. }
  22265. const textureData = backend.get( binding.texture );
  22266. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  22267. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  22268. console.error( 'Bindings._update: binding should be available:', binding, updated, binding.texture, binding.textureNode.value );
  22269. this.textures.updateTexture( binding.texture );
  22270. needsBindingsUpdate = true;
  22271. }
  22272. if ( texture.isStorageTexture === true ) {
  22273. const textureData = this.get( texture );
  22274. if ( binding.store === true ) {
  22275. textureData.needsMipmap = true;
  22276. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  22277. this.backend.generateMipmaps( texture );
  22278. textureData.needsMipmap = false;
  22279. }
  22280. }
  22281. }
  22282. }
  22283. if ( needsBindingsUpdate === true ) {
  22284. const pipeline = this.pipelines.getForRender( object );
  22285. this.backend.updateBindings( bindGroup, bindings, pipeline );
  22286. }
  22287. }
  22288. }
  22289. const NodeShaderStage = {
  22290. VERTEX: 'vertex',
  22291. FRAGMENT: 'fragment'
  22292. };
  22293. const NodeUpdateType = {
  22294. NONE: 'none',
  22295. FRAME: 'frame',
  22296. RENDER: 'render',
  22297. OBJECT: 'object'
  22298. };
  22299. const NodeType = {
  22300. BOOLEAN: 'bool',
  22301. INTEGER: 'int',
  22302. FLOAT: 'float',
  22303. VECTOR2: 'vec2',
  22304. VECTOR3: 'vec3',
  22305. VECTOR4: 'vec4',
  22306. MATRIX2: 'mat2',
  22307. MATRIX3: 'mat3',
  22308. MATRIX4: 'mat4'
  22309. };
  22310. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22311. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22312. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22313. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22314. function getCacheKey( object, force = false ) {
  22315. let cacheKey = '{';
  22316. if ( object.isNode === true ) {
  22317. cacheKey += object.id;
  22318. }
  22319. for ( const { property, childNode } of getNodeChildren( object ) ) {
  22320. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  22321. }
  22322. cacheKey += '}';
  22323. return cacheKey;
  22324. }
  22325. function* getNodeChildren( node, toJSON = false ) {
  22326. for ( const property in node ) {
  22327. // Ignore private properties.
  22328. if ( property.startsWith( '_' ) === true ) continue;
  22329. const object = node[ property ];
  22330. if ( Array.isArray( object ) === true ) {
  22331. for ( let i = 0; i < object.length; i ++ ) {
  22332. const child = object[ i ];
  22333. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22334. yield { property, index: i, childNode: child };
  22335. }
  22336. }
  22337. } else if ( object && object.isNode === true ) {
  22338. yield { property, childNode: object };
  22339. } else if ( typeof object === 'object' ) {
  22340. for ( const subProperty in object ) {
  22341. const child = object[ subProperty ];
  22342. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  22343. yield { property, index: subProperty, childNode: child };
  22344. }
  22345. }
  22346. }
  22347. }
  22348. }
  22349. function getValueType( value ) {
  22350. if ( value === undefined || value === null ) return null;
  22351. const typeOf = typeof value;
  22352. if ( value.isNode === true ) {
  22353. return 'node';
  22354. } else if ( typeOf === 'number' ) {
  22355. return 'float';
  22356. } else if ( typeOf === 'boolean' ) {
  22357. return 'bool';
  22358. } else if ( typeOf === 'string' ) {
  22359. return 'string';
  22360. } else if ( typeOf === 'function' ) {
  22361. return 'shader';
  22362. } else if ( value.isVector2 === true ) {
  22363. return 'vec2';
  22364. } else if ( value.isVector3 === true ) {
  22365. return 'vec3';
  22366. } else if ( value.isVector4 === true ) {
  22367. return 'vec4';
  22368. } else if ( value.isMatrix3 === true ) {
  22369. return 'mat3';
  22370. } else if ( value.isMatrix4 === true ) {
  22371. return 'mat4';
  22372. } else if ( value.isColor === true ) {
  22373. return 'color';
  22374. } else if ( value instanceof ArrayBuffer ) {
  22375. return 'ArrayBuffer';
  22376. }
  22377. return null;
  22378. }
  22379. function getValueFromType( type, ...params ) {
  22380. const last4 = type ? type.slice( - 4 ) : undefined;
  22381. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  22382. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  22383. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  22384. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  22385. }
  22386. if ( type === 'color' ) {
  22387. return new Color( ...params );
  22388. } else if ( last4 === 'vec2' ) {
  22389. return new Vector2( ...params );
  22390. } else if ( last4 === 'vec3' ) {
  22391. return new Vector3( ...params );
  22392. } else if ( last4 === 'vec4' ) {
  22393. return new Vector4( ...params );
  22394. } else if ( last4 === 'mat3' ) {
  22395. return new Matrix3( ...params );
  22396. } else if ( last4 === 'mat4' ) {
  22397. return new Matrix4( ...params );
  22398. } else if ( type === 'bool' ) {
  22399. return params[ 0 ] || false;
  22400. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  22401. return params[ 0 ] || 0;
  22402. } else if ( type === 'string' ) {
  22403. return params[ 0 ] || '';
  22404. } else if ( type === 'ArrayBuffer' ) {
  22405. return base64ToArrayBuffer( params[ 0 ] );
  22406. }
  22407. return null;
  22408. }
  22409. function arrayBufferToBase64( arrayBuffer ) {
  22410. let chars = '';
  22411. const array = new Uint8Array( arrayBuffer );
  22412. for ( let i = 0; i < array.length; i ++ ) {
  22413. chars += String.fromCharCode( array[ i ] );
  22414. }
  22415. return btoa( chars );
  22416. }
  22417. function base64ToArrayBuffer( base64 ) {
  22418. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  22419. }
  22420. var NodeUtils = /*#__PURE__*/Object.freeze({
  22421. __proto__: null,
  22422. arrayBufferToBase64: arrayBufferToBase64,
  22423. base64ToArrayBuffer: base64ToArrayBuffer,
  22424. getCacheKey: getCacheKey,
  22425. getNodeChildren: getNodeChildren,
  22426. getValueFromType: getValueFromType,
  22427. getValueType: getValueType
  22428. });
  22429. const NodeClasses = new Map();
  22430. let _nodeId = 0;
  22431. class Node extends EventDispatcher {
  22432. constructor( nodeType = null ) {
  22433. super();
  22434. this.nodeType = nodeType;
  22435. this.updateType = NodeUpdateType.NONE;
  22436. this.updateBeforeType = NodeUpdateType.NONE;
  22437. this.updateAfterType = NodeUpdateType.NONE;
  22438. this.uuid = MathUtils.generateUUID();
  22439. this.version = 0;
  22440. this._cacheKey = null;
  22441. this._cacheKeyVersion = 0;
  22442. this.global = false;
  22443. this.isNode = true;
  22444. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22445. }
  22446. set needsUpdate( value ) {
  22447. if ( value === true ) {
  22448. this.version ++;
  22449. }
  22450. }
  22451. get type() {
  22452. return this.constructor.type;
  22453. }
  22454. onUpdate( callback, updateType ) {
  22455. this.updateType = updateType;
  22456. this.update = callback.bind( this.getSelf() );
  22457. return this;
  22458. }
  22459. onFrameUpdate( callback ) {
  22460. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22461. }
  22462. onRenderUpdate( callback ) {
  22463. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22464. }
  22465. onObjectUpdate( callback ) {
  22466. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22467. }
  22468. onReference( callback ) {
  22469. this.updateReference = callback.bind( this.getSelf() );
  22470. return this;
  22471. }
  22472. getSelf() {
  22473. // Returns non-node object.
  22474. return this.self || this;
  22475. }
  22476. updateReference( /*state*/ ) {
  22477. return this;
  22478. }
  22479. isGlobal( /*builder*/ ) {
  22480. return this.global;
  22481. }
  22482. * getChildren() {
  22483. for ( const { childNode } of getNodeChildren( this ) ) {
  22484. yield childNode;
  22485. }
  22486. }
  22487. dispose() {
  22488. this.dispatchEvent( { type: 'dispose' } );
  22489. }
  22490. traverse( callback ) {
  22491. callback( this );
  22492. for ( const childNode of this.getChildren() ) {
  22493. childNode.traverse( callback );
  22494. }
  22495. }
  22496. getCacheKey( force = false ) {
  22497. force = force || this.version !== this._cacheKeyVersion;
  22498. if ( force === true || this._cacheKey === null ) {
  22499. this._cacheKey = getCacheKey( this, force );
  22500. this._cacheKeyVersion = this.version;
  22501. }
  22502. return this._cacheKey;
  22503. }
  22504. getHash( /*builder*/ ) {
  22505. return this.uuid;
  22506. }
  22507. getUpdateType() {
  22508. return this.updateType;
  22509. }
  22510. getUpdateBeforeType() {
  22511. return this.updateBeforeType;
  22512. }
  22513. getUpdateAfterType() {
  22514. return this.updateAfterType;
  22515. }
  22516. getElementType( builder ) {
  22517. const type = this.getNodeType( builder );
  22518. const elementType = builder.getElementType( type );
  22519. return elementType;
  22520. }
  22521. getNodeType( builder ) {
  22522. const nodeProperties = builder.getNodeProperties( this );
  22523. if ( nodeProperties.outputNode ) {
  22524. return nodeProperties.outputNode.getNodeType( builder );
  22525. }
  22526. return this.nodeType;
  22527. }
  22528. getShared( builder ) {
  22529. const hash = this.getHash( builder );
  22530. const nodeFromHash = builder.getNodeFromHash( hash );
  22531. return nodeFromHash || this;
  22532. }
  22533. setup( builder ) {
  22534. const nodeProperties = builder.getNodeProperties( this );
  22535. let index = 0;
  22536. for ( const childNode of this.getChildren() ) {
  22537. nodeProperties[ 'node' + index ++ ] = childNode;
  22538. }
  22539. // return a outputNode if exists
  22540. return null;
  22541. }
  22542. increaseUsage( builder ) {
  22543. const nodeData = builder.getDataFromNode( this );
  22544. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  22545. return nodeData.usageCount;
  22546. }
  22547. analyze( builder ) {
  22548. const usageCount = this.increaseUsage( builder );
  22549. if ( usageCount === 1 ) {
  22550. // node flow children
  22551. const nodeProperties = builder.getNodeProperties( this );
  22552. for ( const childNode of Object.values( nodeProperties ) ) {
  22553. if ( childNode && childNode.isNode === true ) {
  22554. childNode.build( builder );
  22555. }
  22556. }
  22557. }
  22558. }
  22559. generate( builder, output ) {
  22560. const { outputNode } = builder.getNodeProperties( this );
  22561. if ( outputNode && outputNode.isNode === true ) {
  22562. return outputNode.build( builder, output );
  22563. }
  22564. }
  22565. updateBefore( /*frame*/ ) {
  22566. console.warn( 'Abstract function.' );
  22567. }
  22568. updateAfter( /*frame*/ ) {
  22569. console.warn( 'Abstract function.' );
  22570. }
  22571. update( /*frame*/ ) {
  22572. console.warn( 'Abstract function.' );
  22573. }
  22574. build( builder, output = null ) {
  22575. const refNode = this.getShared( builder );
  22576. if ( this !== refNode ) {
  22577. return refNode.build( builder, output );
  22578. }
  22579. builder.addNode( this );
  22580. builder.addChain( this );
  22581. /* Build stages expected results:
  22582. - "setup" -> Node
  22583. - "analyze" -> null
  22584. - "generate" -> String
  22585. */
  22586. let result = null;
  22587. const buildStage = builder.getBuildStage();
  22588. if ( buildStage === 'setup' ) {
  22589. this.updateReference( builder );
  22590. const properties = builder.getNodeProperties( this );
  22591. if ( properties.initialized !== true ) {
  22592. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22593. properties.initialized = true;
  22594. properties.outputNode = this.setup( builder );
  22595. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  22596. properties.outputNode = builder.stack;
  22597. }
  22598. for ( const childNode of Object.values( properties ) ) {
  22599. if ( childNode && childNode.isNode === true ) {
  22600. childNode.build( builder );
  22601. }
  22602. }
  22603. }
  22604. } else if ( buildStage === 'analyze' ) {
  22605. this.analyze( builder );
  22606. } else if ( buildStage === 'generate' ) {
  22607. const isGenerateOnce = this.generate.length === 1;
  22608. if ( isGenerateOnce ) {
  22609. const type = this.getNodeType( builder );
  22610. const nodeData = builder.getDataFromNode( this );
  22611. result = nodeData.snippet;
  22612. if ( result === undefined ) {
  22613. result = this.generate( builder ) || '';
  22614. nodeData.snippet = result;
  22615. }
  22616. result = builder.format( result, type, output );
  22617. } else {
  22618. result = this.generate( builder, output ) || '';
  22619. }
  22620. }
  22621. builder.removeChain( this );
  22622. return result;
  22623. }
  22624. getSerializeChildren() {
  22625. return getNodeChildren( this );
  22626. }
  22627. serialize( json ) {
  22628. const nodeChildren = this.getSerializeChildren();
  22629. const inputNodes = {};
  22630. for ( const { property, index, childNode } of nodeChildren ) {
  22631. if ( index !== undefined ) {
  22632. if ( inputNodes[ property ] === undefined ) {
  22633. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22634. }
  22635. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22636. } else {
  22637. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22638. }
  22639. }
  22640. if ( Object.keys( inputNodes ).length > 0 ) {
  22641. json.inputNodes = inputNodes;
  22642. }
  22643. }
  22644. deserialize( json ) {
  22645. if ( json.inputNodes !== undefined ) {
  22646. const nodes = json.meta.nodes;
  22647. for ( const property in json.inputNodes ) {
  22648. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22649. const inputArray = [];
  22650. for ( const uuid of json.inputNodes[ property ] ) {
  22651. inputArray.push( nodes[ uuid ] );
  22652. }
  22653. this[ property ] = inputArray;
  22654. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22655. const inputObject = {};
  22656. for ( const subProperty in json.inputNodes[ property ] ) {
  22657. const uuid = json.inputNodes[ property ][ subProperty ];
  22658. inputObject[ subProperty ] = nodes[ uuid ];
  22659. }
  22660. this[ property ] = inputObject;
  22661. } else {
  22662. const uuid = json.inputNodes[ property ];
  22663. this[ property ] = nodes[ uuid ];
  22664. }
  22665. }
  22666. }
  22667. }
  22668. toJSON( meta ) {
  22669. const { uuid, type } = this;
  22670. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22671. if ( isRoot ) {
  22672. meta = {
  22673. textures: {},
  22674. images: {},
  22675. nodes: {}
  22676. };
  22677. }
  22678. // serialize
  22679. let data = meta.nodes[ uuid ];
  22680. if ( data === undefined ) {
  22681. data = {
  22682. uuid,
  22683. type,
  22684. meta,
  22685. metadata: {
  22686. version: 4.6,
  22687. type: 'Node',
  22688. generator: 'Node.toJSON'
  22689. }
  22690. };
  22691. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22692. this.serialize( data );
  22693. delete data.meta;
  22694. }
  22695. // TODO: Copied from Object3D.toJSON
  22696. function extractFromCache( cache ) {
  22697. const values = [];
  22698. for ( const key in cache ) {
  22699. const data = cache[ key ];
  22700. delete data.metadata;
  22701. values.push( data );
  22702. }
  22703. return values;
  22704. }
  22705. if ( isRoot ) {
  22706. const textures = extractFromCache( meta.textures );
  22707. const images = extractFromCache( meta.images );
  22708. const nodes = extractFromCache( meta.nodes );
  22709. if ( textures.length > 0 ) data.textures = textures;
  22710. if ( images.length > 0 ) data.images = images;
  22711. if ( nodes.length > 0 ) data.nodes = nodes;
  22712. }
  22713. return data;
  22714. }
  22715. }
  22716. function addNodeClass( type, nodeClass ) {
  22717. if ( typeof nodeClass !== 'function' || ! type ) throw new Error( `Node class ${ type } is not a class` );
  22718. if ( NodeClasses.has( type ) ) {
  22719. console.warn( `Redefinition of node class ${ type }` );
  22720. return;
  22721. }
  22722. NodeClasses.set( type, nodeClass );
  22723. nodeClass.type = type;
  22724. }
  22725. function createNodeFromType( type ) {
  22726. const Class = NodeClasses.get( type );
  22727. if ( Class !== undefined ) {
  22728. return new Class();
  22729. }
  22730. }
  22731. class TempNode extends Node {
  22732. constructor( type ) {
  22733. super( type );
  22734. this.isTempNode = true;
  22735. }
  22736. hasDependencies( builder ) {
  22737. return builder.getDataFromNode( this ).usageCount > 1;
  22738. }
  22739. build( builder, output ) {
  22740. const buildStage = builder.getBuildStage();
  22741. if ( buildStage === 'generate' ) {
  22742. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22743. const nodeData = builder.getDataFromNode( this );
  22744. if ( nodeData.propertyName !== undefined ) {
  22745. return builder.format( nodeData.propertyName, type, output );
  22746. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22747. const snippet = super.build( builder, type );
  22748. const nodeVar = builder.getVarFromNode( this, null, type );
  22749. const propertyName = builder.getPropertyName( nodeVar );
  22750. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22751. nodeData.snippet = snippet;
  22752. nodeData.propertyName = propertyName;
  22753. return builder.format( nodeData.propertyName, type, output );
  22754. }
  22755. }
  22756. return super.build( builder, output );
  22757. }
  22758. }
  22759. addNodeClass( 'TempNode', TempNode );
  22760. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  22761. constructor( node, indexNode ) {
  22762. super();
  22763. this.node = node;
  22764. this.indexNode = indexNode;
  22765. this.isArrayElementNode = true;
  22766. }
  22767. getNodeType( builder ) {
  22768. return this.node.getElementType( builder );
  22769. }
  22770. generate( builder ) {
  22771. const nodeSnippet = this.node.build( builder );
  22772. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22773. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22774. }
  22775. }
  22776. addNodeClass( 'ArrayElementNode', ArrayElementNode );
  22777. class ConvertNode extends Node {
  22778. constructor( node, convertTo ) {
  22779. super();
  22780. this.node = node;
  22781. this.convertTo = convertTo;
  22782. }
  22783. getNodeType( builder ) {
  22784. const requestType = this.node.getNodeType( builder );
  22785. let convertTo = null;
  22786. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22787. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22788. convertTo = overloadingType;
  22789. }
  22790. }
  22791. return convertTo;
  22792. }
  22793. serialize( data ) {
  22794. super.serialize( data );
  22795. data.convertTo = this.convertTo;
  22796. }
  22797. deserialize( data ) {
  22798. super.deserialize( data );
  22799. this.convertTo = data.convertTo;
  22800. }
  22801. generate( builder, output ) {
  22802. const node = this.node;
  22803. const type = this.getNodeType( builder );
  22804. const snippet = node.build( builder, type );
  22805. return builder.format( snippet, type, output );
  22806. }
  22807. }
  22808. addNodeClass( 'ConvertNode', ConvertNode );
  22809. class JoinNode extends TempNode {
  22810. constructor( nodes = [], nodeType = null ) {
  22811. super( nodeType );
  22812. this.nodes = nodes;
  22813. }
  22814. getNodeType( builder ) {
  22815. if ( this.nodeType !== null ) {
  22816. return builder.getVectorType( this.nodeType );
  22817. }
  22818. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22819. }
  22820. generate( builder, output ) {
  22821. const type = this.getNodeType( builder );
  22822. const nodes = this.nodes;
  22823. const primitiveType = builder.getComponentType( type );
  22824. const snippetValues = [];
  22825. for ( const input of nodes ) {
  22826. let inputSnippet = input.build( builder );
  22827. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22828. if ( inputPrimitiveType !== primitiveType ) {
  22829. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22830. }
  22831. snippetValues.push( inputSnippet );
  22832. }
  22833. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22834. return builder.format( snippet, type, output );
  22835. }
  22836. }
  22837. addNodeClass( 'JoinNode', JoinNode );
  22838. const stringVectorComponents = vectorComponents.join( '' );
  22839. class SplitNode extends Node {
  22840. constructor( node, components = 'x' ) {
  22841. super();
  22842. this.node = node;
  22843. this.components = components;
  22844. this.isSplitNode = true;
  22845. }
  22846. getVectorLength() {
  22847. let vectorLength = this.components.length;
  22848. for ( const c of this.components ) {
  22849. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22850. }
  22851. return vectorLength;
  22852. }
  22853. getComponentType( builder ) {
  22854. return builder.getComponentType( this.node.getNodeType( builder ) );
  22855. }
  22856. getNodeType( builder ) {
  22857. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22858. }
  22859. generate( builder, output ) {
  22860. const node = this.node;
  22861. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22862. let snippet = null;
  22863. if ( nodeTypeLength > 1 ) {
  22864. let type = null;
  22865. const componentsLength = this.getVectorLength();
  22866. if ( componentsLength >= nodeTypeLength ) {
  22867. // needed expand the input node
  22868. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22869. }
  22870. const nodeSnippet = node.build( builder, type );
  22871. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22872. // unnecessary swizzle
  22873. snippet = builder.format( nodeSnippet, type, output );
  22874. } else {
  22875. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22876. }
  22877. } else {
  22878. // ignore .components if .node returns float/integer
  22879. snippet = node.build( builder, output );
  22880. }
  22881. return snippet;
  22882. }
  22883. serialize( data ) {
  22884. super.serialize( data );
  22885. data.components = this.components;
  22886. }
  22887. deserialize( data ) {
  22888. super.deserialize( data );
  22889. this.components = data.components;
  22890. }
  22891. }
  22892. addNodeClass( 'SplitNode', SplitNode );
  22893. class SetNode extends TempNode {
  22894. constructor( sourceNode, components, targetNode ) {
  22895. super();
  22896. this.sourceNode = sourceNode;
  22897. this.components = components;
  22898. this.targetNode = targetNode;
  22899. }
  22900. getNodeType( builder ) {
  22901. return this.sourceNode.getNodeType( builder );
  22902. }
  22903. generate( builder ) {
  22904. const { sourceNode, components, targetNode } = this;
  22905. const sourceType = this.getNodeType( builder );
  22906. const targetType = builder.getTypeFromLength( components.length );
  22907. const targetSnippet = targetNode.build( builder, targetType );
  22908. const sourceSnippet = sourceNode.build( builder, sourceType );
  22909. const length = builder.getTypeLength( sourceType );
  22910. const snippetValues = [];
  22911. for ( let i = 0; i < length; i ++ ) {
  22912. const component = vectorComponents[ i ];
  22913. if ( component === components[ 0 ] ) {
  22914. snippetValues.push( targetSnippet );
  22915. i += components.length - 1;
  22916. } else {
  22917. snippetValues.push( sourceSnippet + '.' + component );
  22918. }
  22919. }
  22920. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22921. }
  22922. }
  22923. addNodeClass( 'SetNode', SetNode );
  22924. class InputNode extends Node {
  22925. constructor( value, nodeType = null ) {
  22926. super( nodeType );
  22927. this.isInputNode = true;
  22928. this.value = value;
  22929. this.precision = null;
  22930. }
  22931. getNodeType( /*builder*/ ) {
  22932. if ( this.nodeType === null ) {
  22933. return getValueType( this.value );
  22934. }
  22935. return this.nodeType;
  22936. }
  22937. getInputType( builder ) {
  22938. return this.getNodeType( builder );
  22939. }
  22940. setPrecision( precision ) {
  22941. this.precision = precision;
  22942. return this;
  22943. }
  22944. serialize( data ) {
  22945. super.serialize( data );
  22946. data.value = this.value;
  22947. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22948. data.valueType = getValueType( this.value );
  22949. data.nodeType = this.nodeType;
  22950. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22951. data.precision = this.precision;
  22952. }
  22953. deserialize( data ) {
  22954. super.deserialize( data );
  22955. this.nodeType = data.nodeType;
  22956. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22957. this.precision = data.precision || null;
  22958. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22959. }
  22960. generate( /*builder, output*/ ) {
  22961. console.warn( 'Abstract function.' );
  22962. }
  22963. }
  22964. addNodeClass( 'InputNode', InputNode );
  22965. class ConstNode extends InputNode {
  22966. constructor( value, nodeType = null ) {
  22967. super( value, nodeType );
  22968. this.isConstNode = true;
  22969. }
  22970. generateConst( builder ) {
  22971. return builder.generateConst( this.getNodeType( builder ), this.value );
  22972. }
  22973. generate( builder, output ) {
  22974. const type = this.getNodeType( builder );
  22975. return builder.format( this.generateConst( builder ), type, output );
  22976. }
  22977. }
  22978. addNodeClass( 'ConstNode', ConstNode );
  22979. //
  22980. let currentStack = null;
  22981. const NodeElements = new Map(); // @TODO: Currently only a few nodes are added, probably also add others
  22982. function addNodeElement( name, nodeElement ) {
  22983. if ( NodeElements.has( name ) ) {
  22984. console.warn( `Redefinition of node element ${ name }` );
  22985. return;
  22986. }
  22987. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22988. NodeElements.set( name, nodeElement );
  22989. }
  22990. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22991. const shaderNodeHandler = {
  22992. setup( NodeClosure, params ) {
  22993. const inputs = params.shift();
  22994. return NodeClosure( nodeObjects( inputs ), ...params );
  22995. },
  22996. get( node, prop, nodeObj ) {
  22997. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22998. if ( node.isStackNode !== true && prop === 'assign' ) {
  22999. return ( ...params ) => {
  23000. currentStack.assign( nodeObj, ...params );
  23001. return nodeObj;
  23002. };
  23003. } else if ( NodeElements.has( prop ) ) {
  23004. const nodeElement = NodeElements.get( prop );
  23005. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  23006. } else if ( prop === 'self' ) {
  23007. return node;
  23008. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  23009. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  23010. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  23011. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  23012. // accessing properties ( swizzle )
  23013. prop = parseSwizzle( prop );
  23014. return nodeObject( new SplitNode( nodeObj, prop ) );
  23015. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  23016. // set properties ( swizzle )
  23017. prop = parseSwizzle( prop.slice( 3 ).toLowerCase() );
  23018. // sort to xyzw sequence
  23019. prop = prop.split( '' ).sort().join( '' );
  23020. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  23021. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  23022. // accessing property
  23023. if ( prop === 'width' ) prop = 'x';
  23024. else if ( prop === 'height' ) prop = 'y';
  23025. else if ( prop === 'depth' ) prop = 'z';
  23026. return nodeObject( new SplitNode( node, prop ) );
  23027. } else if ( /^\d+$/.test( prop ) === true ) {
  23028. // accessing array
  23029. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  23030. }
  23031. }
  23032. return Reflect.get( node, prop, nodeObj );
  23033. },
  23034. set( node, prop, value, nodeObj ) {
  23035. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  23036. // setting properties
  23037. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  23038. nodeObj[ prop ].assign( value );
  23039. return true;
  23040. }
  23041. }
  23042. return Reflect.set( node, prop, value, nodeObj );
  23043. }
  23044. };
  23045. const nodeObjectsCacheMap = new WeakMap();
  23046. const nodeBuilderFunctionsCacheMap = new WeakMap();
  23047. const ShaderNodeObject = function ( obj, altType = null ) {
  23048. const type = getValueType( obj );
  23049. if ( type === 'node' ) {
  23050. let nodeObject = nodeObjectsCacheMap.get( obj );
  23051. if ( nodeObject === undefined ) {
  23052. nodeObject = new Proxy( obj, shaderNodeHandler );
  23053. nodeObjectsCacheMap.set( obj, nodeObject );
  23054. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  23055. }
  23056. return nodeObject;
  23057. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  23058. return nodeObject( getConstNode( obj, altType ) );
  23059. } else if ( type === 'shader' ) {
  23060. return tslFn( obj );
  23061. }
  23062. return obj;
  23063. };
  23064. const ShaderNodeObjects = function ( objects, altType = null ) {
  23065. for ( const name in objects ) {
  23066. objects[ name ] = nodeObject( objects[ name ], altType );
  23067. }
  23068. return objects;
  23069. };
  23070. const ShaderNodeArray = function ( array, altType = null ) {
  23071. const len = array.length;
  23072. for ( let i = 0; i < len; i ++ ) {
  23073. array[ i ] = nodeObject( array[ i ], altType );
  23074. }
  23075. return array;
  23076. };
  23077. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  23078. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  23079. if ( scope === null ) {
  23080. return ( ...params ) => {
  23081. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  23082. };
  23083. } else if ( factor !== null ) {
  23084. factor = nodeObject( factor );
  23085. return ( ...params ) => {
  23086. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  23087. };
  23088. } else {
  23089. return ( ...params ) => {
  23090. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  23091. };
  23092. }
  23093. };
  23094. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  23095. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  23096. };
  23097. class ShaderCallNodeInternal extends Node {
  23098. constructor( shaderNode, inputNodes ) {
  23099. super();
  23100. this.shaderNode = shaderNode;
  23101. this.inputNodes = inputNodes;
  23102. }
  23103. getNodeType( builder ) {
  23104. const properties = builder.getNodeProperties( this );
  23105. if ( properties.outputNode === null ) {
  23106. properties.outputNode = this.setupOutput( builder );
  23107. }
  23108. return properties.outputNode.getNodeType( builder );
  23109. }
  23110. call( builder ) {
  23111. const { shaderNode, inputNodes } = this;
  23112. if ( shaderNode.layout ) {
  23113. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  23114. if ( functionNodesCacheMap === undefined ) {
  23115. functionNodesCacheMap = new WeakMap();
  23116. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  23117. }
  23118. let functionNode = functionNodesCacheMap.get( shaderNode );
  23119. if ( functionNode === undefined ) {
  23120. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  23121. functionNodesCacheMap.set( shaderNode, functionNode );
  23122. }
  23123. if ( builder.currentFunctionNode !== null ) {
  23124. builder.currentFunctionNode.includes.push( functionNode );
  23125. }
  23126. return nodeObject( functionNode.call( inputNodes ) );
  23127. }
  23128. const jsFunc = shaderNode.jsFunc;
  23129. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder.stack, builder ) : jsFunc( builder.stack, builder );
  23130. return nodeObject( outputNode );
  23131. }
  23132. setup( builder ) {
  23133. const { outputNode } = builder.getNodeProperties( this );
  23134. return outputNode || this.setupOutput( builder );
  23135. }
  23136. setupOutput( builder ) {
  23137. builder.addStack();
  23138. builder.stack.outputNode = this.call( builder );
  23139. return builder.removeStack();
  23140. }
  23141. generate( builder, output ) {
  23142. const { outputNode } = builder.getNodeProperties( this );
  23143. if ( outputNode === null ) {
  23144. // TSL: It's recommended to use `tslFn` in setup() pass.
  23145. return this.call( builder ).build( builder, output );
  23146. }
  23147. return super.generate( builder, output );
  23148. }
  23149. }
  23150. class ShaderNodeInternal extends Node {
  23151. constructor( jsFunc ) {
  23152. super();
  23153. this.jsFunc = jsFunc;
  23154. this.layout = null;
  23155. this.global = true;
  23156. }
  23157. get isArrayInput() {
  23158. return /^\((\s+)?\[/.test( this.jsFunc.toString() );
  23159. }
  23160. setLayout( layout ) {
  23161. this.layout = layout;
  23162. return this;
  23163. }
  23164. call( inputs = null ) {
  23165. nodeObjects( inputs );
  23166. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  23167. }
  23168. setup() {
  23169. return this.call();
  23170. }
  23171. }
  23172. const bools = [ false, true ];
  23173. const uints = [ 0, 1, 2, 3 ];
  23174. const ints = [ - 1, - 2 ];
  23175. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  23176. const boolsCacheMap = new Map();
  23177. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  23178. const uintsCacheMap = new Map();
  23179. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  23180. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  23181. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  23182. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  23183. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  23184. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  23185. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  23186. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  23187. const getConstNode = ( value, type ) => {
  23188. if ( constNodesCacheMap.has( value ) ) {
  23189. return constNodesCacheMap.get( value );
  23190. } else if ( value.isNode === true ) {
  23191. return value;
  23192. } else {
  23193. return new ConstNode( value, type );
  23194. }
  23195. };
  23196. const safeGetNodeType = ( node ) => {
  23197. try {
  23198. return node.getNodeType();
  23199. } catch ( _ ) {
  23200. return undefined;
  23201. }
  23202. };
  23203. const ConvertType = function ( type, cacheMap = null ) {
  23204. return ( ...params ) => {
  23205. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  23206. params = [ getValueFromType( type, ...params ) ];
  23207. }
  23208. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  23209. return nodeObject( cacheMap.get( params[ 0 ] ) );
  23210. }
  23211. if ( params.length === 1 ) {
  23212. const node = getConstNode( params[ 0 ], type );
  23213. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  23214. return nodeObject( new ConvertNode( node, type ) );
  23215. }
  23216. const nodes = params.map( param => getConstNode( param ) );
  23217. return nodeObject( new JoinNode( nodes, type ) );
  23218. };
  23219. };
  23220. // exports
  23221. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  23222. // utils
  23223. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  23224. // shader node base
  23225. function ShaderNode( jsFunc ) {
  23226. return new Proxy( new ShaderNodeInternal( jsFunc ), shaderNodeHandler );
  23227. }
  23228. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  23229. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  23230. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  23231. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  23232. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  23233. const tslFn = ( jsFunc ) => {
  23234. const shaderNode = new ShaderNode( jsFunc );
  23235. const fn = ( ...params ) => {
  23236. let inputs;
  23237. nodeObjects( params );
  23238. if ( params[ 0 ] && params[ 0 ].isNode ) {
  23239. inputs = [ ...params ];
  23240. } else {
  23241. inputs = params[ 0 ];
  23242. }
  23243. return shaderNode.call( inputs );
  23244. };
  23245. fn.shaderNode = shaderNode;
  23246. fn.setLayout = ( layout ) => {
  23247. shaderNode.setLayout( layout );
  23248. return fn;
  23249. };
  23250. return fn;
  23251. };
  23252. addNodeClass( 'ShaderNode', ShaderNode );
  23253. //
  23254. addNodeElement( 'toGlobal', ( node ) => {
  23255. node.global = true;
  23256. return node;
  23257. } );
  23258. //
  23259. const setCurrentStack = ( stack ) => {
  23260. currentStack = stack;
  23261. };
  23262. const getCurrentStack = () => currentStack;
  23263. const If = ( ...params ) => currentStack.if( ...params );
  23264. function append( node ) {
  23265. if ( currentStack ) currentStack.add( node );
  23266. return node;
  23267. }
  23268. addNodeElement( 'append', append );
  23269. // types
  23270. // @TODO: Maybe export from ConstNode.js?
  23271. const color = new ConvertType( 'color' );
  23272. const float = new ConvertType( 'float', cacheMaps.float );
  23273. const int = new ConvertType( 'int', cacheMaps.ints );
  23274. const uint = new ConvertType( 'uint', cacheMaps.uint );
  23275. const bool = new ConvertType( 'bool', cacheMaps.bool );
  23276. const vec2 = new ConvertType( 'vec2' );
  23277. const ivec2 = new ConvertType( 'ivec2' );
  23278. const uvec2 = new ConvertType( 'uvec2' );
  23279. const bvec2 = new ConvertType( 'bvec2' );
  23280. const vec3 = new ConvertType( 'vec3' );
  23281. const ivec3 = new ConvertType( 'ivec3' );
  23282. const uvec3 = new ConvertType( 'uvec3' );
  23283. const bvec3 = new ConvertType( 'bvec3' );
  23284. const vec4 = new ConvertType( 'vec4' );
  23285. const ivec4 = new ConvertType( 'ivec4' );
  23286. const uvec4 = new ConvertType( 'uvec4' );
  23287. const bvec4 = new ConvertType( 'bvec4' );
  23288. const mat2 = new ConvertType( 'mat2' );
  23289. const imat2 = new ConvertType( 'imat2' );
  23290. const umat2 = new ConvertType( 'umat2' );
  23291. const bmat2 = new ConvertType( 'bmat2' );
  23292. const mat3 = new ConvertType( 'mat3' );
  23293. const imat3 = new ConvertType( 'imat3' );
  23294. const umat3 = new ConvertType( 'umat3' );
  23295. const bmat3 = new ConvertType( 'bmat3' );
  23296. const mat4 = new ConvertType( 'mat4' );
  23297. const imat4 = new ConvertType( 'imat4' );
  23298. const umat4 = new ConvertType( 'umat4' );
  23299. const bmat4 = new ConvertType( 'bmat4' );
  23300. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  23301. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  23302. addNodeElement( 'toColor', color );
  23303. addNodeElement( 'toFloat', float );
  23304. addNodeElement( 'toInt', int );
  23305. addNodeElement( 'toUint', uint );
  23306. addNodeElement( 'toBool', bool );
  23307. addNodeElement( 'toVec2', vec2 );
  23308. addNodeElement( 'toIvec2', ivec2 );
  23309. addNodeElement( 'toUvec2', uvec2 );
  23310. addNodeElement( 'toBvec2', bvec2 );
  23311. addNodeElement( 'toVec3', vec3 );
  23312. addNodeElement( 'toIvec3', ivec3 );
  23313. addNodeElement( 'toUvec3', uvec3 );
  23314. addNodeElement( 'toBvec3', bvec3 );
  23315. addNodeElement( 'toVec4', vec4 );
  23316. addNodeElement( 'toIvec4', ivec4 );
  23317. addNodeElement( 'toUvec4', uvec4 );
  23318. addNodeElement( 'toBvec4', bvec4 );
  23319. addNodeElement( 'toMat2', mat2 );
  23320. addNodeElement( 'toImat2', imat2 );
  23321. addNodeElement( 'toUmat2', umat2 );
  23322. addNodeElement( 'toBmat2', bmat2 );
  23323. addNodeElement( 'toMat3', mat3 );
  23324. addNodeElement( 'toImat3', imat3 );
  23325. addNodeElement( 'toUmat3', umat3 );
  23326. addNodeElement( 'toBmat3', bmat3 );
  23327. addNodeElement( 'toMat4', mat4 );
  23328. addNodeElement( 'toImat4', imat4 );
  23329. addNodeElement( 'toUmat4', umat4 );
  23330. addNodeElement( 'toBmat4', bmat4 );
  23331. // basic nodes
  23332. // HACK - we cannot export them from the corresponding files because of the cyclic dependency
  23333. const element = nodeProxy( ArrayElementNode );
  23334. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  23335. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  23336. addNodeElement( 'element', element );
  23337. addNodeElement( 'convert', convert );
  23338. class AssignNode extends TempNode {
  23339. constructor( targetNode, sourceNode ) {
  23340. super();
  23341. this.targetNode = targetNode;
  23342. this.sourceNode = sourceNode;
  23343. }
  23344. hasDependencies() {
  23345. return false;
  23346. }
  23347. getNodeType( builder, output ) {
  23348. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23349. }
  23350. needsSplitAssign( builder ) {
  23351. const { targetNode } = this;
  23352. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23353. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23354. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23355. return assignDiferentVector;
  23356. }
  23357. return false;
  23358. }
  23359. generate( builder, output ) {
  23360. const { targetNode, sourceNode } = this;
  23361. const needsSplitAssign = this.needsSplitAssign( builder );
  23362. const targetType = targetNode.getNodeType( builder );
  23363. const target = targetNode.context( { assign: true } ).build( builder );
  23364. const source = sourceNode.build( builder, targetType );
  23365. const sourceType = sourceNode.getNodeType( builder );
  23366. const nodeData = builder.getDataFromNode( this );
  23367. //
  23368. let snippet;
  23369. if ( nodeData.initialized === true ) {
  23370. if ( output !== 'void' ) {
  23371. snippet = target;
  23372. }
  23373. } else if ( needsSplitAssign ) {
  23374. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23375. const sourceProperty = builder.getPropertyName( sourceVar );
  23376. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  23377. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23378. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23379. const component = targetNode.components[ i ];
  23380. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  23381. }
  23382. if ( output !== 'void' ) {
  23383. snippet = target;
  23384. }
  23385. } else {
  23386. snippet = `${ target } = ${ source }`;
  23387. if ( output === 'void' || sourceType === 'void' ) {
  23388. builder.addLineFlowCode( snippet );
  23389. if ( output !== 'void' ) {
  23390. snippet = target;
  23391. }
  23392. }
  23393. }
  23394. nodeData.initialized = true;
  23395. return builder.format( snippet, targetType, output );
  23396. }
  23397. }
  23398. const assign = nodeProxy( AssignNode );
  23399. addNodeClass( 'AssignNode', AssignNode );
  23400. addNodeElement( 'assign', assign );
  23401. class VaryingNode extends Node {
  23402. constructor( node, name = null ) {
  23403. super();
  23404. this.node = node;
  23405. this.name = name;
  23406. this.isVaryingNode = true;
  23407. }
  23408. isGlobal() {
  23409. return true;
  23410. }
  23411. getHash( builder ) {
  23412. return this.name || super.getHash( builder );
  23413. }
  23414. getNodeType( builder ) {
  23415. // VaryingNode is auto type
  23416. return this.node.getNodeType( builder );
  23417. }
  23418. setupVarying( builder ) {
  23419. const properties = builder.getNodeProperties( this );
  23420. let varying = properties.varying;
  23421. if ( varying === undefined ) {
  23422. const name = this.name;
  23423. const type = this.getNodeType( builder );
  23424. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23425. properties.node = this.node;
  23426. }
  23427. // this property can be used to check if the varying can be optimized for a variable
  23428. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23429. return varying;
  23430. }
  23431. setup( builder ) {
  23432. this.setupVarying( builder );
  23433. }
  23434. analyze( builder ) {
  23435. this.setupVarying( builder );
  23436. return this.node.analyze( builder );
  23437. }
  23438. generate( builder ) {
  23439. const properties = builder.getNodeProperties( this );
  23440. const varying = this.setupVarying( builder );
  23441. if ( properties.propertyName === undefined ) {
  23442. const type = this.getNodeType( builder );
  23443. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23444. // force node run in vertex stage
  23445. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23446. properties.propertyName = propertyName;
  23447. }
  23448. return builder.getPropertyName( varying );
  23449. }
  23450. }
  23451. const varying = nodeProxy( VaryingNode );
  23452. addNodeElement( 'varying', varying );
  23453. addNodeClass( 'VaryingNode', VaryingNode );
  23454. class AttributeNode extends Node {
  23455. constructor( attributeName, nodeType = null, defaultNode = null ) {
  23456. super( nodeType );
  23457. this.defaultNode = defaultNode;
  23458. this.global = true;
  23459. this._attributeName = attributeName;
  23460. }
  23461. getHash( builder ) {
  23462. return this.getAttributeName( builder );
  23463. }
  23464. getNodeType( builder ) {
  23465. let nodeType = super.getNodeType( builder );
  23466. if ( nodeType === null ) {
  23467. const attributeName = this.getAttributeName( builder );
  23468. if ( builder.hasGeometryAttribute( attributeName ) ) {
  23469. const attribute = builder.geometry.getAttribute( attributeName );
  23470. nodeType = builder.getTypeFromAttribute( attribute );
  23471. } else {
  23472. nodeType = 'float';
  23473. }
  23474. }
  23475. return nodeType;
  23476. }
  23477. setAttributeName( attributeName ) {
  23478. this._attributeName = attributeName;
  23479. return this;
  23480. }
  23481. getAttributeName( /*builder*/ ) {
  23482. return this._attributeName;
  23483. }
  23484. generate( builder ) {
  23485. const attributeName = this.getAttributeName( builder );
  23486. const nodeType = this.getNodeType( builder );
  23487. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  23488. if ( geometryAttribute === true ) {
  23489. const attribute = builder.geometry.getAttribute( attributeName );
  23490. const attributeType = builder.getTypeFromAttribute( attribute );
  23491. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  23492. if ( builder.shaderStage === 'vertex' ) {
  23493. return builder.format( nodeAttribute.name, attributeType, nodeType );
  23494. } else {
  23495. const nodeVarying = varying( this );
  23496. return nodeVarying.build( builder, nodeType );
  23497. }
  23498. } else {
  23499. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  23500. const { defaultNode } = this;
  23501. if ( defaultNode !== null ) {
  23502. return defaultNode.build( builder, nodeType );
  23503. } else {
  23504. return builder.generateConst( nodeType );
  23505. }
  23506. }
  23507. }
  23508. serialize( data ) {
  23509. super.serialize( data );
  23510. data.global = this.global;
  23511. data._attributeName = this._attributeName;
  23512. }
  23513. deserialize( data ) {
  23514. super.deserialize( data );
  23515. this.global = data.global;
  23516. this._attributeName = data._attributeName;
  23517. }
  23518. }
  23519. const attribute = ( name, nodeType, defaultNode ) => nodeObject( new AttributeNode( name, nodeType, nodeObject( defaultNode ) ) );
  23520. addNodeClass( 'AttributeNode', AttributeNode );
  23521. class BypassNode extends Node {
  23522. constructor( returnNode, callNode ) {
  23523. super();
  23524. this.isBypassNode = true;
  23525. this.outputNode = returnNode;
  23526. this.callNode = callNode;
  23527. }
  23528. getNodeType( builder ) {
  23529. return this.outputNode.getNodeType( builder );
  23530. }
  23531. generate( builder ) {
  23532. const snippet = this.callNode.build( builder, 'void' );
  23533. if ( snippet !== '' ) {
  23534. builder.addLineFlowCode( snippet );
  23535. }
  23536. return this.outputNode.build( builder );
  23537. }
  23538. }
  23539. const bypass = nodeProxy( BypassNode );
  23540. addNodeElement( 'bypass', bypass );
  23541. addNodeClass( 'BypassNode', BypassNode );
  23542. class CacheNode extends Node {
  23543. constructor( node, parent = true ) {
  23544. super();
  23545. this.node = node;
  23546. this.parent = parent;
  23547. this.isCacheNode = true;
  23548. }
  23549. getNodeType( builder ) {
  23550. return this.node.getNodeType( builder );
  23551. }
  23552. build( builder, ...params ) {
  23553. const previousCache = builder.getCache();
  23554. const cache = builder.getCacheFromNode( this, parent );
  23555. builder.setCache( cache );
  23556. const data = this.node.build( builder, ...params );
  23557. builder.setCache( previousCache );
  23558. return data;
  23559. }
  23560. }
  23561. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23562. addNodeElement( 'cache', cache );
  23563. addNodeClass( 'CacheNode', CacheNode );
  23564. class ContextNode extends Node {
  23565. constructor( node, context = {} ) {
  23566. super();
  23567. this.isContextNode = true;
  23568. this.node = node;
  23569. this.context = context;
  23570. }
  23571. getNodeType( builder ) {
  23572. return this.node.getNodeType( builder );
  23573. }
  23574. analyze( builder ) {
  23575. this.node.build( builder );
  23576. }
  23577. setup( builder ) {
  23578. const previousContext = builder.getContext();
  23579. builder.setContext( { ...builder.context, ...this.context } );
  23580. const node = this.node.build( builder );
  23581. builder.setContext( previousContext );
  23582. return node;
  23583. }
  23584. generate( builder, output ) {
  23585. const previousContext = builder.getContext();
  23586. builder.setContext( { ...builder.context, ...this.context } );
  23587. const snippet = this.node.build( builder, output );
  23588. builder.setContext( previousContext );
  23589. return snippet;
  23590. }
  23591. }
  23592. const context = nodeProxy( ContextNode );
  23593. const label = ( node, name ) => context( node, { label: name } );
  23594. addNodeElement( 'context', context );
  23595. addNodeElement( 'label', label );
  23596. addNodeClass( 'ContextNode', ContextNode );
  23597. class IndexNode extends Node {
  23598. constructor( scope ) {
  23599. super( 'uint' );
  23600. this.scope = scope;
  23601. this.isInstanceIndexNode = true;
  23602. }
  23603. generate( builder ) {
  23604. const nodeType = this.getNodeType( builder );
  23605. const scope = this.scope;
  23606. let propertyName;
  23607. if ( scope === IndexNode.VERTEX ) {
  23608. propertyName = builder.getVertexIndex();
  23609. } else if ( scope === IndexNode.INSTANCE ) {
  23610. propertyName = builder.getInstanceIndex();
  23611. } else if ( scope === IndexNode.DRAW ) {
  23612. propertyName = builder.getDrawIndex();
  23613. } else {
  23614. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  23615. }
  23616. let output;
  23617. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23618. output = propertyName;
  23619. } else {
  23620. const nodeVarying = varying( this );
  23621. output = nodeVarying.build( builder, nodeType );
  23622. }
  23623. return output;
  23624. }
  23625. }
  23626. IndexNode.VERTEX = 'vertex';
  23627. IndexNode.INSTANCE = 'instance';
  23628. IndexNode.DRAW = 'draw';
  23629. const vertexIndex = nodeImmutable( IndexNode, IndexNode.VERTEX );
  23630. const instanceIndex = nodeImmutable( IndexNode, IndexNode.INSTANCE );
  23631. const drawIndex = nodeImmutable( IndexNode, IndexNode.DRAW );
  23632. addNodeClass( 'IndexNode', IndexNode );
  23633. class LightingModel {
  23634. start( /*input, stack, builder*/ ) { }
  23635. finish( /*input, stack, builder*/ ) { }
  23636. direct( /*input, stack, builder*/ ) { }
  23637. directRectArea( /*input, stack, builder*/ ) {}
  23638. indirect( /*input, stack, builder*/ ) { }
  23639. ambientOcclusion( /*input, stack, builder*/ ) { }
  23640. }
  23641. class VarNode extends Node {
  23642. constructor( node, name = null ) {
  23643. super();
  23644. this.node = node;
  23645. this.name = name;
  23646. this.global = true;
  23647. this.isVarNode = true;
  23648. }
  23649. getHash( builder ) {
  23650. return this.name || super.getHash( builder );
  23651. }
  23652. getNodeType( builder ) {
  23653. return this.node.getNodeType( builder );
  23654. }
  23655. generate( builder ) {
  23656. const { node, name } = this;
  23657. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23658. const propertyName = builder.getPropertyName( nodeVar );
  23659. const snippet = node.build( builder, nodeVar.type );
  23660. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23661. return propertyName;
  23662. }
  23663. }
  23664. const temp = nodeProxy( VarNode );
  23665. addNodeElement( 'temp', temp ); // @TODO: Will be removed in the future
  23666. addNodeElement( 'toVar', ( ...params ) => temp( ...params ).append() );
  23667. addNodeClass( 'VarNode', VarNode );
  23668. class NodeAttribute {
  23669. constructor( name, type, node = null ) {
  23670. this.isNodeAttribute = true;
  23671. this.name = name;
  23672. this.type = type;
  23673. this.node = node;
  23674. }
  23675. }
  23676. class NodeUniform {
  23677. constructor( name, type, node ) {
  23678. this.isNodeUniform = true;
  23679. this.name = name;
  23680. this.type = type;
  23681. this.node = node.getSelf();
  23682. }
  23683. get value() {
  23684. return this.node.value;
  23685. }
  23686. set value( val ) {
  23687. this.node.value = val;
  23688. }
  23689. get id() {
  23690. return this.node.id;
  23691. }
  23692. get groupNode() {
  23693. return this.node.groupNode;
  23694. }
  23695. }
  23696. class NodeVar {
  23697. constructor( name, type ) {
  23698. this.isNodeVar = true;
  23699. this.name = name;
  23700. this.type = type;
  23701. }
  23702. }
  23703. class NodeVarying extends NodeVar {
  23704. constructor( name, type ) {
  23705. super( name, type );
  23706. this.needsInterpolation = false;
  23707. this.isNodeVarying = true;
  23708. }
  23709. }
  23710. class NodeCode {
  23711. constructor( name, type, code = '' ) {
  23712. this.name = name;
  23713. this.type = type;
  23714. this.code = code;
  23715. Object.defineProperty( this, 'isNodeCode', { value: true } );
  23716. }
  23717. }
  23718. class NodeKeywords {
  23719. constructor() {
  23720. this.keywords = [];
  23721. this.nodes = {};
  23722. this.keywordsCallback = {};
  23723. }
  23724. getNode( name ) {
  23725. let node = this.nodes[ name ];
  23726. if ( node === undefined && this.keywordsCallback[ name ] !== undefined ) {
  23727. node = this.keywordsCallback[ name ]( name );
  23728. this.nodes[ name ] = node;
  23729. }
  23730. return node;
  23731. }
  23732. addKeyword( name, callback ) {
  23733. this.keywords.push( name );
  23734. this.keywordsCallback[ name ] = callback;
  23735. return this;
  23736. }
  23737. parse( code ) {
  23738. const keywordNames = this.keywords;
  23739. const regExp = new RegExp( `\\b${keywordNames.join( '\\b|\\b' )}\\b`, 'g' );
  23740. const codeKeywords = code.match( regExp );
  23741. const keywordNodes = [];
  23742. if ( codeKeywords !== null ) {
  23743. for ( const keyword of codeKeywords ) {
  23744. const node = this.getNode( keyword );
  23745. if ( node !== undefined && keywordNodes.indexOf( node ) === - 1 ) {
  23746. keywordNodes.push( node );
  23747. }
  23748. }
  23749. }
  23750. return keywordNodes;
  23751. }
  23752. include( builder, code ) {
  23753. const keywordNodes = this.parse( code );
  23754. for ( const keywordNode of keywordNodes ) {
  23755. keywordNode.build( builder );
  23756. }
  23757. }
  23758. }
  23759. let id$1 = 0;
  23760. class NodeCache {
  23761. constructor( parent = null ) {
  23762. this.id = id$1 ++;
  23763. this.nodesData = new WeakMap();
  23764. this.parent = parent;
  23765. }
  23766. getData( node ) {
  23767. let data = this.nodesData.get( node );
  23768. if ( data === undefined && this.parent !== null ) {
  23769. data = this.parent.getData( node );
  23770. }
  23771. return data;
  23772. }
  23773. setData( node, data ) {
  23774. this.nodesData.set( node, data );
  23775. }
  23776. }
  23777. class PropertyNode extends Node {
  23778. constructor( nodeType, name = null, varying = false ) {
  23779. super( nodeType );
  23780. this.name = name;
  23781. this.varying = varying;
  23782. this.isPropertyNode = true;
  23783. }
  23784. getHash( builder ) {
  23785. return this.name || super.getHash( builder );
  23786. }
  23787. isGlobal( /*builder*/ ) {
  23788. return true;
  23789. }
  23790. generate( builder ) {
  23791. let nodeVar;
  23792. if ( this.varying === true ) {
  23793. nodeVar = builder.getVaryingFromNode( this, this.name );
  23794. nodeVar.needsInterpolation = true;
  23795. } else {
  23796. nodeVar = builder.getVarFromNode( this, this.name );
  23797. }
  23798. return builder.getPropertyName( nodeVar );
  23799. }
  23800. }
  23801. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23802. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23803. const diffuseColor = nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23804. const emissive = nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23805. const roughness = nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23806. const metalness = nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23807. const clearcoat = nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23808. const clearcoatRoughness = nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23809. const sheen = nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23810. const sheenRoughness = nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23811. const iridescence = nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23812. const iridescenceIOR = nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23813. const iridescenceThickness = nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23814. const alphaT = nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23815. const anisotropy = nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23816. const anisotropyT = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23817. const anisotropyB = nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23818. const specularColor = nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23819. const specularF90 = nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23820. const shininess = nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23821. const output = nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23822. const dashSize = nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23823. const gapSize = nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23824. const pointWidth = nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23825. const ior = nodeImmutable( PropertyNode, 'float', 'IOR' );
  23826. const transmission = nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23827. const thickness = nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23828. const attenuationDistance = nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23829. const attenuationColor = nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23830. const dispersion = nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23831. addNodeClass( 'PropertyNode', PropertyNode );
  23832. class ParameterNode extends PropertyNode {
  23833. constructor( nodeType, name = null ) {
  23834. super( nodeType, name );
  23835. this.isParameterNode = true;
  23836. }
  23837. getHash() {
  23838. return this.uuid;
  23839. }
  23840. generate() {
  23841. return this.name;
  23842. }
  23843. }
  23844. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  23845. addNodeClass( 'ParameterNode', ParameterNode );
  23846. class CodeNode extends Node {
  23847. constructor( code = '', includes = [], language = '' ) {
  23848. super( 'code' );
  23849. this.isCodeNode = true;
  23850. this.code = code;
  23851. this.language = language;
  23852. this.includes = includes;
  23853. }
  23854. isGlobal() {
  23855. return true;
  23856. }
  23857. setIncludes( includes ) {
  23858. this.includes = includes;
  23859. return this;
  23860. }
  23861. getIncludes( /*builder*/ ) {
  23862. return this.includes;
  23863. }
  23864. generate( builder ) {
  23865. const includes = this.getIncludes( builder );
  23866. for ( const include of includes ) {
  23867. include.build( builder );
  23868. }
  23869. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23870. nodeCode.code = this.code;
  23871. return nodeCode.code;
  23872. }
  23873. serialize( data ) {
  23874. super.serialize( data );
  23875. data.code = this.code;
  23876. data.language = this.language;
  23877. }
  23878. deserialize( data ) {
  23879. super.deserialize( data );
  23880. this.code = data.code;
  23881. this.language = data.language;
  23882. }
  23883. }
  23884. const code = nodeProxy( CodeNode );
  23885. const js = ( src, includes ) => code( src, includes, 'js' );
  23886. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23887. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23888. addNodeClass( 'CodeNode', CodeNode );
  23889. class FunctionNode extends CodeNode {
  23890. constructor( code = '', includes = [], language = '' ) {
  23891. super( code, includes, language );
  23892. this.keywords = {};
  23893. }
  23894. getNodeType( builder ) {
  23895. return this.getNodeFunction( builder ).type;
  23896. }
  23897. getInputs( builder ) {
  23898. return this.getNodeFunction( builder ).inputs;
  23899. }
  23900. getNodeFunction( builder ) {
  23901. const nodeData = builder.getDataFromNode( this );
  23902. let nodeFunction = nodeData.nodeFunction;
  23903. if ( nodeFunction === undefined ) {
  23904. nodeFunction = builder.parser.parseFunction( this.code );
  23905. nodeData.nodeFunction = nodeFunction;
  23906. }
  23907. return nodeFunction;
  23908. }
  23909. generate( builder, output ) {
  23910. super.generate( builder );
  23911. const nodeFunction = this.getNodeFunction( builder );
  23912. const name = nodeFunction.name;
  23913. const type = nodeFunction.type;
  23914. const nodeCode = builder.getCodeFromNode( this, type );
  23915. if ( name !== '' ) {
  23916. // use a custom property name
  23917. nodeCode.name = name;
  23918. }
  23919. const propertyName = builder.getPropertyName( nodeCode );
  23920. let code = this.getNodeFunction( builder ).getCode( propertyName );
  23921. const keywords = this.keywords;
  23922. const keywordsProperties = Object.keys( keywords );
  23923. if ( keywordsProperties.length > 0 ) {
  23924. for ( const property of keywordsProperties ) {
  23925. const propertyRegExp = new RegExp( `\\b${property}\\b`, 'g' );
  23926. const nodeProperty = keywords[ property ].build( builder, 'property' );
  23927. code = code.replace( propertyRegExp, nodeProperty );
  23928. }
  23929. }
  23930. nodeCode.code = code + '\n';
  23931. if ( output === 'property' ) {
  23932. return propertyName;
  23933. } else {
  23934. return builder.format( `${ propertyName }()`, type, output );
  23935. }
  23936. }
  23937. }
  23938. const nativeFn = ( code, includes = [], language = '' ) => {
  23939. for ( let i = 0; i < includes.length; i ++ ) {
  23940. const include = includes[ i ];
  23941. // TSL Function: glslFn, wgslFn
  23942. if ( typeof include === 'function' ) {
  23943. includes[ i ] = include.functionNode;
  23944. }
  23945. }
  23946. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23947. const fn = ( ...params ) => functionNode.call( ...params );
  23948. fn.functionNode = functionNode;
  23949. return fn;
  23950. };
  23951. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23952. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23953. addNodeClass( 'FunctionNode', FunctionNode );
  23954. class UniformGroupNode extends Node {
  23955. constructor( name, shared = false ) {
  23956. super( 'string' );
  23957. this.name = name;
  23958. this.version = 0;
  23959. this.shared = shared;
  23960. this.isUniformGroup = true;
  23961. }
  23962. set needsUpdate( value ) {
  23963. if ( value === true ) this.version ++;
  23964. }
  23965. serialize( data ) {
  23966. super.serialize( data );
  23967. data.name = this.name;
  23968. data.version = this.version;
  23969. data.shared = this.shared;
  23970. }
  23971. deserialize( data ) {
  23972. super.deserialize( data );
  23973. this.name = data.name;
  23974. this.version = data.version;
  23975. this.shared = data.shared;
  23976. }
  23977. }
  23978. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23979. const sharedUniformGroup = ( name ) => new UniformGroupNode( name, true );
  23980. const frameGroup = sharedUniformGroup( 'frame' );
  23981. const renderGroup = sharedUniformGroup( 'render' );
  23982. const objectGroup = uniformGroup( 'object' );
  23983. addNodeClass( 'UniformGroupNode', UniformGroupNode );
  23984. class UniformNode extends InputNode {
  23985. constructor( value, nodeType = null ) {
  23986. super( value, nodeType );
  23987. this.isUniformNode = true;
  23988. this.name = '';
  23989. this.groupNode = objectGroup;
  23990. }
  23991. label( name ) {
  23992. this.name = name;
  23993. return this;
  23994. }
  23995. setGroup( group ) {
  23996. this.groupNode = group;
  23997. return this;
  23998. }
  23999. getGroup() {
  24000. return this.groupNode;
  24001. }
  24002. getUniformHash( builder ) {
  24003. return this.getHash( builder );
  24004. }
  24005. onUpdate( callback, updateType ) {
  24006. const self = this.getSelf();
  24007. callback = callback.bind( self );
  24008. return super.onUpdate( ( frame ) => {
  24009. const value = callback( frame, self );
  24010. if ( value !== undefined ) {
  24011. this.value = value;
  24012. }
  24013. }, updateType );
  24014. }
  24015. generate( builder, output ) {
  24016. const type = this.getNodeType( builder );
  24017. const hash = this.getUniformHash( builder );
  24018. let sharedNode = builder.getNodeFromHash( hash );
  24019. if ( sharedNode === undefined ) {
  24020. builder.setHashNode( this, hash );
  24021. sharedNode = this;
  24022. }
  24023. const sharedNodeType = sharedNode.getInputType( builder );
  24024. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  24025. const propertyName = builder.getPropertyName( nodeUniform );
  24026. if ( builder.context.label !== undefined ) delete builder.context.label;
  24027. return builder.format( propertyName, type, output );
  24028. }
  24029. }
  24030. const uniform = ( arg1, arg2 ) => {
  24031. const nodeType = getConstNodeType( arg2 || arg1 );
  24032. // @TODO: get ConstNode from .traverse() in the future
  24033. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  24034. return nodeObject( new UniformNode( value, nodeType ) );
  24035. };
  24036. addNodeClass( 'UniformNode', UniformNode );
  24037. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24038. class TextureSizeNode extends Node {
  24039. constructor( textureNode, levelNode = null ) {
  24040. super( 'uvec2' );
  24041. this.isTextureSizeNode = true;
  24042. this.textureNode = textureNode;
  24043. this.levelNode = levelNode;
  24044. }
  24045. generate( builder, output ) {
  24046. const textureProperty = this.textureNode.build( builder, 'property' );
  24047. const levelNode = this.levelNode.build( builder, 'int' );
  24048. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ levelNode } )`, this.getNodeType( builder ), output );
  24049. }
  24050. }
  24051. const textureSize = nodeProxy( TextureSizeNode );
  24052. addNodeElement( 'textureSize', textureSize );
  24053. addNodeClass( 'TextureSizeNode', TextureSizeNode );
  24054. class OperatorNode extends TempNode {
  24055. constructor( op, aNode, bNode, ...params ) {
  24056. super();
  24057. if ( params.length > 0 ) {
  24058. let finalOp = new OperatorNode( op, aNode, bNode );
  24059. for ( let i = 0; i < params.length - 1; i ++ ) {
  24060. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  24061. }
  24062. aNode = finalOp;
  24063. bNode = params[ params.length - 1 ];
  24064. }
  24065. this.op = op;
  24066. this.aNode = aNode;
  24067. this.bNode = bNode;
  24068. }
  24069. getNodeType( builder, output ) {
  24070. const op = this.op;
  24071. const aNode = this.aNode;
  24072. const bNode = this.bNode;
  24073. const typeA = aNode.getNodeType( builder );
  24074. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24075. if ( typeA === 'void' || typeB === 'void' ) {
  24076. return 'void';
  24077. } else if ( op === '%' ) {
  24078. return typeA;
  24079. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  24080. return builder.getIntegerType( typeA );
  24081. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  24082. return 'bool';
  24083. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  24084. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  24085. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  24086. } else {
  24087. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  24088. return typeB;
  24089. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24090. // matrix x vector
  24091. return builder.getVectorFromMatrix( typeA );
  24092. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24093. // vector x matrix
  24094. return builder.getVectorFromMatrix( typeB );
  24095. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  24096. // anytype x anytype: use the greater length vector
  24097. return typeB;
  24098. }
  24099. return typeA;
  24100. }
  24101. }
  24102. generate( builder, output ) {
  24103. const op = this.op;
  24104. const aNode = this.aNode;
  24105. const bNode = this.bNode;
  24106. const type = this.getNodeType( builder, output );
  24107. let typeA = null;
  24108. let typeB = null;
  24109. if ( type !== 'void' ) {
  24110. typeA = aNode.getNodeType( builder );
  24111. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  24112. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  24113. if ( builder.isVector( typeA ) ) {
  24114. typeB = typeA;
  24115. } else {
  24116. typeA = typeB = 'float';
  24117. }
  24118. } else if ( op === '>>' || op === '<<' ) {
  24119. typeA = type;
  24120. typeB = builder.changeComponentType( typeB, 'uint' );
  24121. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  24122. // matrix x vector
  24123. typeB = builder.getVectorFromMatrix( typeA );
  24124. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  24125. // vector x matrix
  24126. typeA = builder.getVectorFromMatrix( typeB );
  24127. } else {
  24128. // anytype x anytype
  24129. typeA = typeB = type;
  24130. }
  24131. } else {
  24132. typeA = typeB = type;
  24133. }
  24134. const a = aNode.build( builder, typeA );
  24135. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  24136. const outputLength = builder.getTypeLength( output );
  24137. const fnOpSnippet = builder.getFunctionOperator( op );
  24138. if ( output !== 'void' ) {
  24139. if ( op === '<' && outputLength > 1 ) {
  24140. return builder.format( `${ builder.getMethod( 'lessThan' ) }( ${ a }, ${ b } )`, type, output );
  24141. } else if ( op === '<=' && outputLength > 1 ) {
  24142. return builder.format( `${ builder.getMethod( 'lessThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24143. } else if ( op === '>' && outputLength > 1 ) {
  24144. return builder.format( `${ builder.getMethod( 'greaterThan' ) }( ${ a }, ${ b } )`, type, output );
  24145. } else if ( op === '>=' && outputLength > 1 ) {
  24146. return builder.format( `${ builder.getMethod( 'greaterThanEqual' ) }( ${ a }, ${ b } )`, type, output );
  24147. } else if ( op === '!' || op === '~' ) {
  24148. return builder.format( `(${op}${a})`, typeA, output );
  24149. } else if ( fnOpSnippet ) {
  24150. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24151. } else {
  24152. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  24153. }
  24154. } else if ( typeA !== 'void' ) {
  24155. if ( fnOpSnippet ) {
  24156. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  24157. } else {
  24158. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  24159. }
  24160. }
  24161. }
  24162. serialize( data ) {
  24163. super.serialize( data );
  24164. data.op = this.op;
  24165. }
  24166. deserialize( data ) {
  24167. super.deserialize( data );
  24168. this.op = data.op;
  24169. }
  24170. }
  24171. const add = nodeProxy( OperatorNode, '+' );
  24172. const sub = nodeProxy( OperatorNode, '-' );
  24173. const mul = nodeProxy( OperatorNode, '*' );
  24174. const div = nodeProxy( OperatorNode, '/' );
  24175. const remainder = nodeProxy( OperatorNode, '%' );
  24176. const equal = nodeProxy( OperatorNode, '==' );
  24177. const notEqual = nodeProxy( OperatorNode, '!=' );
  24178. const lessThan = nodeProxy( OperatorNode, '<' );
  24179. const greaterThan = nodeProxy( OperatorNode, '>' );
  24180. const lessThanEqual = nodeProxy( OperatorNode, '<=' );
  24181. const greaterThanEqual = nodeProxy( OperatorNode, '>=' );
  24182. const and = nodeProxy( OperatorNode, '&&' );
  24183. const or = nodeProxy( OperatorNode, '||' );
  24184. const not = nodeProxy( OperatorNode, '!' );
  24185. const xor = nodeProxy( OperatorNode, '^^' );
  24186. const bitAnd = nodeProxy( OperatorNode, '&' );
  24187. const bitNot = nodeProxy( OperatorNode, '~' );
  24188. const bitOr = nodeProxy( OperatorNode, '|' );
  24189. const bitXor = nodeProxy( OperatorNode, '^' );
  24190. const shiftLeft = nodeProxy( OperatorNode, '<<' );
  24191. const shiftRight = nodeProxy( OperatorNode, '>>' );
  24192. addNodeElement( 'add', add );
  24193. addNodeElement( 'sub', sub );
  24194. addNodeElement( 'mul', mul );
  24195. addNodeElement( 'div', div );
  24196. addNodeElement( 'remainder', remainder );
  24197. addNodeElement( 'equal', equal );
  24198. addNodeElement( 'notEqual', notEqual );
  24199. addNodeElement( 'lessThan', lessThan );
  24200. addNodeElement( 'greaterThan', greaterThan );
  24201. addNodeElement( 'lessThanEqual', lessThanEqual );
  24202. addNodeElement( 'greaterThanEqual', greaterThanEqual );
  24203. addNodeElement( 'and', and );
  24204. addNodeElement( 'or', or );
  24205. addNodeElement( 'not', not );
  24206. addNodeElement( 'xor', xor );
  24207. addNodeElement( 'bitAnd', bitAnd );
  24208. addNodeElement( 'bitNot', bitNot );
  24209. addNodeElement( 'bitOr', bitOr );
  24210. addNodeElement( 'bitXor', bitXor );
  24211. addNodeElement( 'shiftLeft', shiftLeft );
  24212. addNodeElement( 'shiftRight', shiftRight );
  24213. addNodeClass( 'OperatorNode', OperatorNode );
  24214. class MathNode extends TempNode {
  24215. constructor( method, aNode, bNode = null, cNode = null ) {
  24216. super();
  24217. this.method = method;
  24218. this.aNode = aNode;
  24219. this.bNode = bNode;
  24220. this.cNode = cNode;
  24221. }
  24222. getInputType( builder ) {
  24223. const aType = this.aNode.getNodeType( builder );
  24224. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  24225. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  24226. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  24227. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  24228. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  24229. if ( aLen > bLen && aLen > cLen ) {
  24230. return aType;
  24231. } else if ( bLen > cLen ) {
  24232. return bType;
  24233. } else if ( cLen > aLen ) {
  24234. return cType;
  24235. }
  24236. return aType;
  24237. }
  24238. getNodeType( builder ) {
  24239. const method = this.method;
  24240. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  24241. return 'float';
  24242. } else if ( method === MathNode.CROSS ) {
  24243. return 'vec3';
  24244. } else if ( method === MathNode.ALL ) {
  24245. return 'bool';
  24246. } else if ( method === MathNode.EQUALS ) {
  24247. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  24248. } else if ( method === MathNode.MOD ) {
  24249. return this.aNode.getNodeType( builder );
  24250. } else {
  24251. return this.getInputType( builder );
  24252. }
  24253. }
  24254. generate( builder, output ) {
  24255. const method = this.method;
  24256. const type = this.getNodeType( builder );
  24257. const inputType = this.getInputType( builder );
  24258. const a = this.aNode;
  24259. const b = this.bNode;
  24260. const c = this.cNode;
  24261. const isWebGL = builder.renderer.isWebGLRenderer === true;
  24262. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  24263. // dir can be either a direction vector or a normal vector
  24264. // upper-left 3x3 of matrix is assumed to be orthogonal
  24265. let tA = a;
  24266. let tB = b;
  24267. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  24268. tB = vec4( vec3( tB ), 0.0 );
  24269. } else {
  24270. tA = vec4( vec3( tA ), 0.0 );
  24271. }
  24272. const mulNode = mul( tA, tB ).xyz;
  24273. return normalize( mulNode ).build( builder, output );
  24274. } else if ( method === MathNode.NEGATE ) {
  24275. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  24276. } else if ( method === MathNode.ONE_MINUS ) {
  24277. return sub( 1.0, a ).build( builder, output );
  24278. } else if ( method === MathNode.RECIPROCAL ) {
  24279. return div( 1.0, a ).build( builder, output );
  24280. } else if ( method === MathNode.DIFFERENCE ) {
  24281. return abs( sub( a, b ) ).build( builder, output );
  24282. } else {
  24283. const params = [];
  24284. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  24285. params.push(
  24286. a.build( builder, type ),
  24287. b.build( builder, type )
  24288. );
  24289. } else if ( method === MathNode.STEP ) {
  24290. params.push(
  24291. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  24292. b.build( builder, inputType )
  24293. );
  24294. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  24295. params.push(
  24296. a.build( builder, inputType ),
  24297. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24298. );
  24299. } else if ( method === MathNode.REFRACT ) {
  24300. params.push(
  24301. a.build( builder, inputType ),
  24302. b.build( builder, inputType ),
  24303. c.build( builder, 'float' )
  24304. );
  24305. } else if ( method === MathNode.MIX ) {
  24306. params.push(
  24307. a.build( builder, inputType ),
  24308. b.build( builder, inputType ),
  24309. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  24310. );
  24311. } else {
  24312. params.push( a.build( builder, inputType ) );
  24313. if ( b !== null ) params.push( b.build( builder, inputType ) );
  24314. if ( c !== null ) params.push( c.build( builder, inputType ) );
  24315. }
  24316. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  24317. }
  24318. }
  24319. serialize( data ) {
  24320. super.serialize( data );
  24321. data.method = this.method;
  24322. }
  24323. deserialize( data ) {
  24324. super.deserialize( data );
  24325. this.method = data.method;
  24326. }
  24327. }
  24328. // 1 input
  24329. MathNode.ALL = 'all';
  24330. MathNode.ANY = 'any';
  24331. MathNode.EQUALS = 'equals';
  24332. MathNode.RADIANS = 'radians';
  24333. MathNode.DEGREES = 'degrees';
  24334. MathNode.EXP = 'exp';
  24335. MathNode.EXP2 = 'exp2';
  24336. MathNode.LOG = 'log';
  24337. MathNode.LOG2 = 'log2';
  24338. MathNode.SQRT = 'sqrt';
  24339. MathNode.INVERSE_SQRT = 'inversesqrt';
  24340. MathNode.FLOOR = 'floor';
  24341. MathNode.CEIL = 'ceil';
  24342. MathNode.NORMALIZE = 'normalize';
  24343. MathNode.FRACT = 'fract';
  24344. MathNode.SIN = 'sin';
  24345. MathNode.COS = 'cos';
  24346. MathNode.TAN = 'tan';
  24347. MathNode.ASIN = 'asin';
  24348. MathNode.ACOS = 'acos';
  24349. MathNode.ATAN = 'atan';
  24350. MathNode.ABS = 'abs';
  24351. MathNode.SIGN = 'sign';
  24352. MathNode.LENGTH = 'length';
  24353. MathNode.NEGATE = 'negate';
  24354. MathNode.ONE_MINUS = 'oneMinus';
  24355. MathNode.DFDX = 'dFdx';
  24356. MathNode.DFDY = 'dFdy';
  24357. MathNode.ROUND = 'round';
  24358. MathNode.RECIPROCAL = 'reciprocal';
  24359. MathNode.TRUNC = 'trunc';
  24360. MathNode.FWIDTH = 'fwidth';
  24361. MathNode.BITCAST = 'bitcast';
  24362. MathNode.TRANSPOSE = 'transpose';
  24363. // 2 inputs
  24364. MathNode.ATAN2 = 'atan2';
  24365. MathNode.MIN = 'min';
  24366. MathNode.MAX = 'max';
  24367. MathNode.MOD = 'mod';
  24368. MathNode.STEP = 'step';
  24369. MathNode.REFLECT = 'reflect';
  24370. MathNode.DISTANCE = 'distance';
  24371. MathNode.DIFFERENCE = 'difference';
  24372. MathNode.DOT = 'dot';
  24373. MathNode.CROSS = 'cross';
  24374. MathNode.POW = 'pow';
  24375. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  24376. // 3 inputs
  24377. MathNode.MIX = 'mix';
  24378. MathNode.CLAMP = 'clamp';
  24379. MathNode.REFRACT = 'refract';
  24380. MathNode.SMOOTHSTEP = 'smoothstep';
  24381. MathNode.FACEFORWARD = 'faceforward';
  24382. const EPSILON = float( 1e-6 );
  24383. const INFINITY = float( 1e6 );
  24384. const PI = float( Math.PI );
  24385. const PI2 = float( Math.PI * 2 );
  24386. const all = nodeProxy( MathNode, MathNode.ALL );
  24387. const any = nodeProxy( MathNode, MathNode.ANY );
  24388. const equals = nodeProxy( MathNode, MathNode.EQUALS );
  24389. const radians = nodeProxy( MathNode, MathNode.RADIANS );
  24390. const degrees = nodeProxy( MathNode, MathNode.DEGREES );
  24391. const exp = nodeProxy( MathNode, MathNode.EXP );
  24392. const exp2 = nodeProxy( MathNode, MathNode.EXP2 );
  24393. const log = nodeProxy( MathNode, MathNode.LOG );
  24394. const log2 = nodeProxy( MathNode, MathNode.LOG2 );
  24395. const sqrt = nodeProxy( MathNode, MathNode.SQRT );
  24396. const inverseSqrt = nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  24397. const floor = nodeProxy( MathNode, MathNode.FLOOR );
  24398. const ceil = nodeProxy( MathNode, MathNode.CEIL );
  24399. const normalize = nodeProxy( MathNode, MathNode.NORMALIZE );
  24400. const fract = nodeProxy( MathNode, MathNode.FRACT );
  24401. const sin = nodeProxy( MathNode, MathNode.SIN );
  24402. const cos = nodeProxy( MathNode, MathNode.COS );
  24403. const tan = nodeProxy( MathNode, MathNode.TAN );
  24404. const asin = nodeProxy( MathNode, MathNode.ASIN );
  24405. const acos = nodeProxy( MathNode, MathNode.ACOS );
  24406. const atan = nodeProxy( MathNode, MathNode.ATAN );
  24407. const abs = nodeProxy( MathNode, MathNode.ABS );
  24408. const sign = nodeProxy( MathNode, MathNode.SIGN );
  24409. const length = nodeProxy( MathNode, MathNode.LENGTH );
  24410. const negate = nodeProxy( MathNode, MathNode.NEGATE );
  24411. const oneMinus = nodeProxy( MathNode, MathNode.ONE_MINUS );
  24412. const dFdx = nodeProxy( MathNode, MathNode.DFDX );
  24413. const dFdy = nodeProxy( MathNode, MathNode.DFDY );
  24414. const round = nodeProxy( MathNode, MathNode.ROUND );
  24415. const reciprocal = nodeProxy( MathNode, MathNode.RECIPROCAL );
  24416. const trunc = nodeProxy( MathNode, MathNode.TRUNC );
  24417. const fwidth = nodeProxy( MathNode, MathNode.FWIDTH );
  24418. const bitcast = nodeProxy( MathNode, MathNode.BITCAST );
  24419. const transpose = nodeProxy( MathNode, MathNode.TRANSPOSE );
  24420. const atan2 = nodeProxy( MathNode, MathNode.ATAN2 );
  24421. const min$1 = nodeProxy( MathNode, MathNode.MIN );
  24422. const max$1 = nodeProxy( MathNode, MathNode.MAX );
  24423. const mod = nodeProxy( MathNode, MathNode.MOD );
  24424. const step = nodeProxy( MathNode, MathNode.STEP );
  24425. const reflect = nodeProxy( MathNode, MathNode.REFLECT );
  24426. const distance = nodeProxy( MathNode, MathNode.DISTANCE );
  24427. const difference = nodeProxy( MathNode, MathNode.DIFFERENCE );
  24428. const dot = nodeProxy( MathNode, MathNode.DOT );
  24429. const cross = nodeProxy( MathNode, MathNode.CROSS );
  24430. const pow = nodeProxy( MathNode, MathNode.POW );
  24431. const pow2 = nodeProxy( MathNode, MathNode.POW, 2 );
  24432. const pow3 = nodeProxy( MathNode, MathNode.POW, 3 );
  24433. const pow4 = nodeProxy( MathNode, MathNode.POW, 4 );
  24434. const transformDirection = nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  24435. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  24436. const lengthSq = ( a ) => dot( a, a );
  24437. const mix = nodeProxy( MathNode, MathNode.MIX );
  24438. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  24439. const saturate = ( value ) => clamp( value );
  24440. const refract = nodeProxy( MathNode, MathNode.REFRACT );
  24441. const smoothstep = nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  24442. const faceForward = nodeProxy( MathNode, MathNode.FACEFORWARD );
  24443. const rand = tslFn( ( [ uv ] ) => {
  24444. const a = 12.9898, b = 78.233, c = 43758.5453;
  24445. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  24446. return fract( sin( sn ).mul( c ) );
  24447. } );
  24448. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  24449. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  24450. addNodeElement( 'all', all );
  24451. addNodeElement( 'any', any );
  24452. addNodeElement( 'equals', equals );
  24453. addNodeElement( 'radians', radians );
  24454. addNodeElement( 'degrees', degrees );
  24455. addNodeElement( 'exp', exp );
  24456. addNodeElement( 'exp2', exp2 );
  24457. addNodeElement( 'log', log );
  24458. addNodeElement( 'log2', log2 );
  24459. addNodeElement( 'sqrt', sqrt );
  24460. addNodeElement( 'inverseSqrt', inverseSqrt );
  24461. addNodeElement( 'floor', floor );
  24462. addNodeElement( 'ceil', ceil );
  24463. addNodeElement( 'normalize', normalize );
  24464. addNodeElement( 'fract', fract );
  24465. addNodeElement( 'sin', sin );
  24466. addNodeElement( 'cos', cos );
  24467. addNodeElement( 'tan', tan );
  24468. addNodeElement( 'asin', asin );
  24469. addNodeElement( 'acos', acos );
  24470. addNodeElement( 'atan', atan );
  24471. addNodeElement( 'abs', abs );
  24472. addNodeElement( 'sign', sign );
  24473. addNodeElement( 'length', length );
  24474. addNodeElement( 'lengthSq', lengthSq );
  24475. addNodeElement( 'negate', negate );
  24476. addNodeElement( 'oneMinus', oneMinus );
  24477. addNodeElement( 'dFdx', dFdx );
  24478. addNodeElement( 'dFdy', dFdy );
  24479. addNodeElement( 'round', round );
  24480. addNodeElement( 'reciprocal', reciprocal );
  24481. addNodeElement( 'trunc', trunc );
  24482. addNodeElement( 'fwidth', fwidth );
  24483. addNodeElement( 'atan2', atan2 );
  24484. addNodeElement( 'min', min$1 );
  24485. addNodeElement( 'max', max$1 );
  24486. addNodeElement( 'mod', mod );
  24487. addNodeElement( 'step', step );
  24488. addNodeElement( 'reflect', reflect );
  24489. addNodeElement( 'distance', distance );
  24490. addNodeElement( 'dot', dot );
  24491. addNodeElement( 'cross', cross );
  24492. addNodeElement( 'pow', pow );
  24493. addNodeElement( 'pow2', pow2 );
  24494. addNodeElement( 'pow3', pow3 );
  24495. addNodeElement( 'pow4', pow4 );
  24496. addNodeElement( 'transformDirection', transformDirection );
  24497. addNodeElement( 'mix', mixElement );
  24498. addNodeElement( 'clamp', clamp );
  24499. addNodeElement( 'refract', refract );
  24500. addNodeElement( 'smoothstep', smoothstepElement );
  24501. addNodeElement( 'faceForward', faceForward );
  24502. addNodeElement( 'difference', difference );
  24503. addNodeElement( 'saturate', saturate );
  24504. addNodeElement( 'cbrt', cbrt );
  24505. addNodeElement( 'transpose', transpose );
  24506. addNodeElement( 'rand', rand );
  24507. addNodeClass( 'MathNode', MathNode );
  24508. const sRGBToLinearShader = tslFn( ( inputs ) => {
  24509. const { value } = inputs;
  24510. const { rgb } = value;
  24511. const a = rgb.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  24512. const b = rgb.mul( 0.0773993808 );
  24513. const factor = rgb.lessThanEqual( 0.04045 );
  24514. const rgbResult = mix( a, b, factor );
  24515. return vec4( rgbResult, value.a );
  24516. } );
  24517. const LinearTosRGBShader = tslFn( ( inputs ) => {
  24518. const { value } = inputs;
  24519. const { rgb } = value;
  24520. const a = rgb.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  24521. const b = rgb.mul( 12.92 );
  24522. const factor = rgb.lessThanEqual( 0.0031308 );
  24523. const rgbResult = mix( a, b, factor );
  24524. return vec4( rgbResult, value.a );
  24525. } );
  24526. const getColorSpaceMethod = ( colorSpace ) => {
  24527. let method = null;
  24528. if ( colorSpace === LinearSRGBColorSpace ) {
  24529. method = 'Linear';
  24530. } else if ( colorSpace === SRGBColorSpace ) {
  24531. method = 'sRGB';
  24532. }
  24533. return method;
  24534. };
  24535. const getMethod = ( source, target ) => {
  24536. return getColorSpaceMethod( source ) + 'To' + getColorSpaceMethod( target );
  24537. };
  24538. class ColorSpaceNode extends TempNode {
  24539. constructor( method, node ) {
  24540. super( 'vec4' );
  24541. this.method = method;
  24542. this.node = node;
  24543. }
  24544. setup() {
  24545. const { method, node } = this;
  24546. if ( method === ColorSpaceNode.LINEAR_TO_LINEAR )
  24547. return node;
  24548. return Methods[ method ]( { value: node } );
  24549. }
  24550. }
  24551. ColorSpaceNode.LINEAR_TO_LINEAR = 'LinearToLinear';
  24552. ColorSpaceNode.LINEAR_TO_sRGB = 'LinearTosRGB';
  24553. ColorSpaceNode.sRGB_TO_LINEAR = 'sRGBToLinear';
  24554. const Methods = {
  24555. [ ColorSpaceNode.LINEAR_TO_sRGB ]: LinearTosRGBShader,
  24556. [ ColorSpaceNode.sRGB_TO_LINEAR ]: sRGBToLinearShader
  24557. };
  24558. const linearToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( LinearSRGBColorSpace, colorSpace ), nodeObject( node ) ) );
  24559. const colorSpaceToLinear = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( getMethod( colorSpace, LinearSRGBColorSpace ), nodeObject( node ) ) );
  24560. const linearTosRGB = nodeProxy( ColorSpaceNode, ColorSpaceNode.LINEAR_TO_sRGB );
  24561. const sRGBToLinear = nodeProxy( ColorSpaceNode, ColorSpaceNode.sRGB_TO_LINEAR );
  24562. addNodeElement( 'linearTosRGB', linearTosRGB );
  24563. addNodeElement( 'sRGBToLinear', sRGBToLinear );
  24564. addNodeElement( 'linearToColorSpace', linearToColorSpace );
  24565. addNodeElement( 'colorSpaceToLinear', colorSpaceToLinear );
  24566. addNodeClass( 'ColorSpaceNode', ColorSpaceNode );
  24567. class ExpressionNode extends Node {
  24568. constructor( snippet = '', nodeType = 'void' ) {
  24569. super( nodeType );
  24570. this.snippet = snippet;
  24571. }
  24572. generate( builder, output ) {
  24573. const type = this.getNodeType( builder );
  24574. const snippet = this.snippet;
  24575. if ( type === 'void' ) {
  24576. builder.addLineFlowCode( snippet );
  24577. } else {
  24578. return builder.format( `( ${ snippet } )`, type, output );
  24579. }
  24580. }
  24581. }
  24582. const expression = nodeProxy( ExpressionNode );
  24583. addNodeClass( 'ExpressionNode', ExpressionNode );
  24584. class MaxMipLevelNode extends UniformNode {
  24585. constructor( textureNode ) {
  24586. super( 0 );
  24587. this._textureNode = textureNode;
  24588. this.updateType = NodeUpdateType.FRAME;
  24589. }
  24590. get textureNode() {
  24591. return this._textureNode;
  24592. }
  24593. get texture() {
  24594. return this._textureNode.value;
  24595. }
  24596. update() {
  24597. const texture = this.texture;
  24598. const images = texture.images;
  24599. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24600. if ( image && image.width !== undefined ) {
  24601. const { width, height } = image;
  24602. this.value = Math.log2( Math.max( width, height ) );
  24603. }
  24604. }
  24605. }
  24606. const maxMipLevel = nodeProxy( MaxMipLevelNode );
  24607. addNodeClass( 'MaxMipLevelNode', MaxMipLevelNode );
  24608. class TextureNode extends UniformNode {
  24609. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24610. super( value );
  24611. this.isTextureNode = true;
  24612. this.uvNode = uvNode;
  24613. this.levelNode = levelNode;
  24614. this.biasNode = biasNode;
  24615. this.compareNode = null;
  24616. this.depthNode = null;
  24617. this.gradNode = null;
  24618. this.sampler = true;
  24619. this.updateMatrix = false;
  24620. this.updateType = NodeUpdateType.NONE;
  24621. this.referenceNode = null;
  24622. this._value = value;
  24623. this._matrixUniform = null;
  24624. this.setUpdateMatrix( uvNode === null );
  24625. }
  24626. set value( value ) {
  24627. if ( this.referenceNode ) {
  24628. this.referenceNode.value = value;
  24629. } else {
  24630. this._value = value;
  24631. }
  24632. }
  24633. get value() {
  24634. return this.referenceNode ? this.referenceNode.value : this._value;
  24635. }
  24636. getUniformHash( /*builder*/ ) {
  24637. return this.value.uuid;
  24638. }
  24639. getNodeType( /*builder*/ ) {
  24640. if ( this.value.isDepthTexture === true ) return 'float';
  24641. if ( this.value.type === UnsignedIntType ) {
  24642. return 'uvec4';
  24643. } else if ( this.value.type === IntType ) {
  24644. return 'ivec4';
  24645. }
  24646. return 'vec4';
  24647. }
  24648. getInputType( /*builder*/ ) {
  24649. return 'texture';
  24650. }
  24651. getDefaultUV() {
  24652. return uv( this.value.channel );
  24653. }
  24654. updateReference( /*state*/ ) {
  24655. return this.value;
  24656. }
  24657. getTransformedUV( uvNode ) {
  24658. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24659. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24660. }
  24661. setUpdateMatrix( value ) {
  24662. this.updateMatrix = value;
  24663. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24664. return this;
  24665. }
  24666. setupUV( builder, uvNode ) {
  24667. const texture = this.value;
  24668. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24669. uvNode = uvNode.setY( uvNode.y.oneMinus() );
  24670. }
  24671. return uvNode;
  24672. }
  24673. setup( builder ) {
  24674. const properties = builder.getNodeProperties( this );
  24675. properties.referenceNode = this.referenceNode;
  24676. //
  24677. let uvNode = this.uvNode;
  24678. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24679. uvNode = builder.context.getUV( this );
  24680. }
  24681. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24682. if ( this.updateMatrix === true ) {
  24683. uvNode = this.getTransformedUV( uvNode );
  24684. }
  24685. uvNode = this.setupUV( builder, uvNode );
  24686. //
  24687. let levelNode = this.levelNode;
  24688. if ( levelNode === null && builder.context.getTextureLevel ) {
  24689. levelNode = builder.context.getTextureLevel( this );
  24690. }
  24691. //
  24692. properties.uvNode = uvNode;
  24693. properties.levelNode = levelNode;
  24694. properties.biasNode = this.biasNode;
  24695. properties.compareNode = this.compareNode;
  24696. properties.gradNode = this.gradNode;
  24697. properties.depthNode = this.depthNode;
  24698. }
  24699. generateUV( builder, uvNode ) {
  24700. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24701. }
  24702. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24703. const texture = this.value;
  24704. let snippet;
  24705. if ( levelSnippet ) {
  24706. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24707. } else if ( biasSnippet ) {
  24708. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24709. } else if ( gradSnippet ) {
  24710. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24711. } else if ( compareSnippet ) {
  24712. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24713. } else if ( this.sampler === false ) {
  24714. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24715. } else {
  24716. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24717. }
  24718. return snippet;
  24719. }
  24720. generate( builder, output ) {
  24721. const properties = builder.getNodeProperties( this );
  24722. const texture = this.value;
  24723. if ( ! texture || texture.isTexture !== true ) {
  24724. throw new Error( 'TextureNode: Need a three.js texture.' );
  24725. }
  24726. const textureProperty = super.generate( builder, 'property' );
  24727. if ( output === 'sampler' ) {
  24728. return textureProperty + '_sampler';
  24729. } else if ( builder.isReference( output ) ) {
  24730. return textureProperty;
  24731. } else {
  24732. const nodeData = builder.getDataFromNode( this );
  24733. let propertyName = nodeData.propertyName;
  24734. if ( propertyName === undefined ) {
  24735. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24736. const uvSnippet = this.generateUV( builder, uvNode );
  24737. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24738. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24739. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24740. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24741. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24742. const nodeVar = builder.getVarFromNode( this );
  24743. propertyName = builder.getPropertyName( nodeVar );
  24744. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24745. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24746. nodeData.snippet = snippet;
  24747. nodeData.propertyName = propertyName;
  24748. }
  24749. let snippet = propertyName;
  24750. const nodeType = this.getNodeType( builder );
  24751. if ( builder.needsColorSpaceToLinear( texture ) ) {
  24752. snippet = colorSpaceToLinear( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24753. }
  24754. return builder.format( snippet, nodeType, output );
  24755. }
  24756. }
  24757. setSampler( value ) {
  24758. this.sampler = value;
  24759. return this;
  24760. }
  24761. getSampler() {
  24762. return this.sampler;
  24763. }
  24764. // @TODO: Move to TSL
  24765. uv( uvNode ) {
  24766. const textureNode = this.clone();
  24767. textureNode.uvNode = nodeObject( uvNode );
  24768. textureNode.referenceNode = this;
  24769. return nodeObject( textureNode );
  24770. }
  24771. blur( amountNode ) {
  24772. const textureNode = this.clone();
  24773. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24774. textureNode.referenceNode = this;
  24775. return nodeObject( textureNode );
  24776. }
  24777. level( levelNode ) {
  24778. const textureNode = this.clone();
  24779. textureNode.levelNode = nodeObject( levelNode );
  24780. textureNode.referenceNode = this;
  24781. return nodeObject( textureNode );
  24782. }
  24783. size( levelNode ) {
  24784. return textureSize( this, levelNode );
  24785. }
  24786. bias( biasNode ) {
  24787. const textureNode = this.clone();
  24788. textureNode.biasNode = nodeObject( biasNode );
  24789. textureNode.referenceNode = this;
  24790. return nodeObject( textureNode );
  24791. }
  24792. compare( compareNode ) {
  24793. const textureNode = this.clone();
  24794. textureNode.compareNode = nodeObject( compareNode );
  24795. textureNode.referenceNode = this;
  24796. return nodeObject( textureNode );
  24797. }
  24798. grad( gradNodeX, gradNodeY ) {
  24799. const textureNode = this.clone();
  24800. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24801. textureNode.referenceNode = this;
  24802. return nodeObject( textureNode );
  24803. }
  24804. depth( depthNode ) {
  24805. const textureNode = this.clone();
  24806. textureNode.depthNode = nodeObject( depthNode );
  24807. textureNode.referenceNode = this;
  24808. return nodeObject( textureNode );
  24809. }
  24810. // --
  24811. serialize( data ) {
  24812. super.serialize( data );
  24813. data.value = this.value.toJSON( data.meta ).uuid;
  24814. data.sampler = this.sampler;
  24815. data.updateMatrix = this.updateMatrix;
  24816. data.updateType = this.updateType;
  24817. }
  24818. deserialize( data ) {
  24819. super.deserialize( data );
  24820. this.value = data.meta.textures[ data.value ];
  24821. this.sampler = data.sampler;
  24822. this.updateMatrix = data.updateMatrix;
  24823. this.updateType = data.updateType;
  24824. }
  24825. update() {
  24826. const texture = this.value;
  24827. const matrixUniform = this._matrixUniform;
  24828. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24829. if ( texture.matrixAutoUpdate === true ) {
  24830. texture.updateMatrix();
  24831. }
  24832. }
  24833. clone() {
  24834. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24835. newNode.sampler = this.sampler;
  24836. return newNode;
  24837. }
  24838. }
  24839. const texture = nodeProxy( TextureNode );
  24840. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24841. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24842. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24843. addNodeElement( 'texture', texture );
  24844. //addNodeElement( 'textureLevel', textureLevel );
  24845. addNodeClass( 'TextureNode', TextureNode );
  24846. class BufferNode extends UniformNode {
  24847. constructor( value, bufferType, bufferCount = 0 ) {
  24848. super( value, bufferType );
  24849. this.isBufferNode = true;
  24850. this.bufferType = bufferType;
  24851. this.bufferCount = bufferCount;
  24852. }
  24853. getElementType( builder ) {
  24854. return this.getNodeType( builder );
  24855. }
  24856. getInputType( /*builder*/ ) {
  24857. return 'buffer';
  24858. }
  24859. }
  24860. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24861. addNodeClass( 'BufferNode', BufferNode );
  24862. class UniformArrayElementNode extends ArrayElementNode {
  24863. constructor( arrayBuffer, indexNode ) {
  24864. super( arrayBuffer, indexNode );
  24865. this.isArrayBufferElementNode = true;
  24866. }
  24867. getNodeType( builder ) {
  24868. return this.node.getElementType( builder );
  24869. }
  24870. generate( builder ) {
  24871. const snippet = super.generate( builder );
  24872. const type = this.getNodeType();
  24873. return builder.format( snippet, 'vec4', type );
  24874. }
  24875. }
  24876. class UniformArrayNode extends BufferNode {
  24877. constructor( value, elementType = null ) {
  24878. super( null, 'vec4' );
  24879. this.array = value;
  24880. this.elementType = elementType;
  24881. this._elementType = null;
  24882. this._elementLength = 0;
  24883. this.updateType = NodeUpdateType.RENDER;
  24884. this.isArrayBufferNode = true;
  24885. }
  24886. getElementType() {
  24887. return this.elementType || this._elementType;
  24888. }
  24889. getElementLength() {
  24890. return this._elementLength;
  24891. }
  24892. update( /*frame*/ ) {
  24893. const { array, value } = this;
  24894. const elementLength = this.getElementLength();
  24895. const elementType = this.getElementType();
  24896. if ( elementLength === 1 ) {
  24897. for ( let i = 0; i < array.length; i ++ ) {
  24898. const index = i * 4;
  24899. value[ index ] = array[ i ];
  24900. }
  24901. } else if ( elementType === 'color' ) {
  24902. for ( let i = 0; i < array.length; i ++ ) {
  24903. const index = i * 4;
  24904. const vector = array[ i ];
  24905. value[ index ] = vector.r;
  24906. value[ index + 1 ] = vector.g;
  24907. value[ index + 2 ] = vector.b || 0;
  24908. //value[ index + 3 ] = vector.a || 0;
  24909. }
  24910. } else {
  24911. for ( let i = 0; i < array.length; i ++ ) {
  24912. const index = i * 4;
  24913. const vector = array[ i ];
  24914. value[ index ] = vector.x;
  24915. value[ index + 1 ] = vector.y;
  24916. value[ index + 2 ] = vector.z || 0;
  24917. value[ index + 3 ] = vector.w || 0;
  24918. }
  24919. }
  24920. }
  24921. setup( builder ) {
  24922. const length = this.array.length;
  24923. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24924. this._elementLength = builder.getTypeLength( this._elementType );
  24925. let arrayType = Float32Array;
  24926. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24927. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24928. this.value = new arrayType( length * 4 );
  24929. this.bufferCount = length;
  24930. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24931. return super.setup( builder );
  24932. }
  24933. element( indexNode ) {
  24934. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  24935. }
  24936. }
  24937. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  24938. addNodeClass( 'UniformArrayNode', UniformArrayNode );
  24939. class ReferenceElementNode extends ArrayElementNode {
  24940. constructor( referenceNode, indexNode ) {
  24941. super( referenceNode, indexNode );
  24942. this.referenceNode = referenceNode;
  24943. this.isReferenceElementNode = true;
  24944. }
  24945. getNodeType() {
  24946. return this.referenceNode.uniformType;
  24947. }
  24948. generate( builder ) {
  24949. const snippet = super.generate( builder );
  24950. const arrayType = this.referenceNode.getNodeType();
  24951. const elementType = this.getNodeType();
  24952. return builder.format( snippet, arrayType, elementType );
  24953. }
  24954. }
  24955. class ReferenceNode extends Node {
  24956. constructor( property, uniformType, object = null, count = null ) {
  24957. super();
  24958. this.property = property;
  24959. this.uniformType = uniformType;
  24960. this.object = object;
  24961. this.count = count;
  24962. this.properties = property.split( '.' );
  24963. this.reference = object;
  24964. this.node = null;
  24965. this.updateType = NodeUpdateType.OBJECT;
  24966. }
  24967. element( indexNode ) {
  24968. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24969. }
  24970. setNodeType( uniformType ) {
  24971. let node = null;
  24972. if ( this.count !== null ) {
  24973. node = buffer( null, uniformType, this.count );
  24974. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24975. node = uniformArray( null, uniformType );
  24976. } else if ( uniformType === 'texture' ) {
  24977. node = texture( null );
  24978. } else {
  24979. node = uniform( null, uniformType );
  24980. }
  24981. this.node = node;
  24982. }
  24983. getNodeType( builder ) {
  24984. if ( this.node === null ) {
  24985. this.updateValue();
  24986. }
  24987. return this.node.getNodeType( builder );
  24988. }
  24989. getValueFromReference( object = this.reference ) {
  24990. const { properties } = this;
  24991. let value = object[ properties[ 0 ] ];
  24992. for ( let i = 1; i < properties.length; i ++ ) {
  24993. value = value[ properties[ i ] ];
  24994. }
  24995. return value;
  24996. }
  24997. updateReference( state ) {
  24998. this.reference = this.object !== null ? this.object : state.object;
  24999. return this.reference;
  25000. }
  25001. setup() {
  25002. this.updateValue();
  25003. return this.node;
  25004. }
  25005. update( /*frame*/ ) {
  25006. this.updateValue();
  25007. }
  25008. updateValue() {
  25009. if ( this.node === null ) this.setNodeType( this.uniformType );
  25010. const value = this.getValueFromReference();
  25011. if ( Array.isArray( value ) ) {
  25012. this.node.array = value;
  25013. } else {
  25014. this.node.value = value;
  25015. }
  25016. }
  25017. }
  25018. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25019. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25020. addNodeClass( 'ReferenceNode', ReferenceNode );
  25021. class MaterialReferenceNode extends ReferenceNode {
  25022. constructor( property, inputType, material = null ) {
  25023. super( property, inputType, material );
  25024. this.material = material;
  25025. //this.updateType = NodeUpdateType.RENDER;
  25026. }
  25027. /*setNodeType( node ) {
  25028. super.setNodeType( node );
  25029. this.node.groupNode = renderGroup;
  25030. }*/
  25031. updateReference( state ) {
  25032. this.reference = this.material !== null ? this.material : state.material;
  25033. return this.reference;
  25034. }
  25035. }
  25036. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25037. addNodeClass( 'MaterialReferenceNode', MaterialReferenceNode );
  25038. const cameraGroup = /*#__PURE__*/ sharedUniformGroup( 'camera' ).onRenderUpdate( () => {
  25039. cameraGroup.needsUpdate = true;
  25040. } );
  25041. const cameraNear = /*#__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  25042. const cameraFar = /*#__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  25043. const cameraLogDepth = /*#__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  25044. const cameraProjectionMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  25045. const cameraProjectionMatrixInverse = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  25046. const cameraViewMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  25047. const cameraWorldMatrix = /*#__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  25048. const cameraNormalMatrix = /*#__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  25049. const cameraPosition = /*#__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( cameraGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  25050. class Object3DNode extends Node {
  25051. constructor( scope = Object3DNode.VIEW_MATRIX, object3d = null ) {
  25052. super();
  25053. this.scope = scope;
  25054. this.object3d = object3d;
  25055. this.updateType = NodeUpdateType.OBJECT;
  25056. this._uniformNode = new UniformNode( null );
  25057. }
  25058. getNodeType() {
  25059. const scope = this.scope;
  25060. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25061. return 'mat4';
  25062. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25063. return 'mat3';
  25064. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25065. return 'vec3';
  25066. }
  25067. }
  25068. update( frame ) {
  25069. const object = this.object3d;
  25070. const uniformNode = this._uniformNode;
  25071. const scope = this.scope;
  25072. if ( scope === Object3DNode.VIEW_MATRIX ) {
  25073. uniformNode.value = object.modelViewMatrix;
  25074. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25075. uniformNode.value = object.normalMatrix;
  25076. } else if ( scope === Object3DNode.WORLD_MATRIX ) {
  25077. uniformNode.value = object.matrixWorld;
  25078. } else if ( scope === Object3DNode.POSITION ) {
  25079. uniformNode.value = uniformNode.value || new Vector3();
  25080. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25081. } else if ( scope === Object3DNode.SCALE ) {
  25082. uniformNode.value = uniformNode.value || new Vector3();
  25083. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  25084. } else if ( scope === Object3DNode.DIRECTION ) {
  25085. uniformNode.value = uniformNode.value || new Vector3();
  25086. object.getWorldDirection( uniformNode.value );
  25087. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  25088. const camera = frame.camera;
  25089. uniformNode.value = uniformNode.value || new Vector3();
  25090. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  25091. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  25092. }
  25093. }
  25094. generate( builder ) {
  25095. const scope = this.scope;
  25096. if ( scope === Object3DNode.WORLD_MATRIX || scope === Object3DNode.VIEW_MATRIX ) {
  25097. this._uniformNode.nodeType = 'mat4';
  25098. } else if ( scope === Object3DNode.NORMAL_MATRIX ) {
  25099. this._uniformNode.nodeType = 'mat3';
  25100. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  25101. this._uniformNode.nodeType = 'vec3';
  25102. }
  25103. return this._uniformNode.build( builder );
  25104. }
  25105. serialize( data ) {
  25106. super.serialize( data );
  25107. data.scope = this.scope;
  25108. }
  25109. deserialize( data ) {
  25110. super.deserialize( data );
  25111. this.scope = data.scope;
  25112. }
  25113. }
  25114. Object3DNode.VIEW_MATRIX = 'viewMatrix';
  25115. Object3DNode.NORMAL_MATRIX = 'normalMatrix';
  25116. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  25117. Object3DNode.POSITION = 'position';
  25118. Object3DNode.SCALE = 'scale';
  25119. Object3DNode.VIEW_POSITION = 'viewPosition';
  25120. Object3DNode.DIRECTION = 'direction';
  25121. const objectDirection = nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  25122. const objectViewMatrix = nodeProxy( Object3DNode, Object3DNode.VIEW_MATRIX );
  25123. const objectNormalMatrix = nodeProxy( Object3DNode, Object3DNode.NORMAL_MATRIX );
  25124. const objectWorldMatrix = nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  25125. const objectPosition = nodeProxy( Object3DNode, Object3DNode.POSITION );
  25126. const objectScale = nodeProxy( Object3DNode, Object3DNode.SCALE );
  25127. const objectViewPosition = nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  25128. addNodeClass( 'Object3DNode', Object3DNode );
  25129. class ModelNode extends Object3DNode {
  25130. constructor( scope = ModelNode.VIEW_MATRIX ) {
  25131. super( scope );
  25132. }
  25133. update( frame ) {
  25134. this.object3d = frame.object;
  25135. super.update( frame );
  25136. }
  25137. }
  25138. const modelDirection = nodeImmutable( ModelNode, ModelNode.DIRECTION );
  25139. const modelViewMatrix = nodeImmutable( ModelNode, ModelNode.VIEW_MATRIX ).label( 'modelViewMatrix' ).temp( 'ModelViewMatrix' );
  25140. const modelNormalMatrix = nodeImmutable( ModelNode, ModelNode.NORMAL_MATRIX );
  25141. const modelWorldMatrix = nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  25142. const modelPosition = nodeImmutable( ModelNode, ModelNode.POSITION );
  25143. const modelScale = nodeImmutable( ModelNode, ModelNode.SCALE );
  25144. const modelViewPosition = nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  25145. const modelWorldMatrixInverse = uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  25146. addNodeClass( 'ModelNode', ModelNode );
  25147. const normalGeometry = /*#__PURE__*/ attribute( 'normal', 'vec3', vec3( 0, 1, 0 ) );
  25148. const normalLocal = /*#__PURE__*/ normalGeometry.toVar( 'normalLocal' );
  25149. const normalView = /*#__PURE__*/ varying( modelNormalMatrix.mul( normalLocal ), 'v_normalView' ).normalize().toVar( 'normalView' );
  25150. const normalWorld = /*#__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  25151. const transformedNormalView = /*#__PURE__*/ property( 'vec3', 'transformedNormalView' );
  25152. const transformedNormalWorld = /*#__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedNormalWorld' );
  25153. const transformedClearcoatNormalView = /*#__PURE__*/ property( 'vec3', 'transformedClearcoatNormalView' );
  25154. const _propertyCache = new Map();
  25155. class MaterialNode extends Node {
  25156. constructor( scope ) {
  25157. super();
  25158. this.scope = scope;
  25159. }
  25160. getCache( property, type ) {
  25161. let node = _propertyCache.get( property );
  25162. if ( node === undefined ) {
  25163. node = materialReference( property, type );
  25164. _propertyCache.set( property, node );
  25165. }
  25166. return node;
  25167. }
  25168. getFloat( property ) {
  25169. return this.getCache( property, 'float' );
  25170. }
  25171. getColor( property ) {
  25172. return this.getCache( property, 'color' );
  25173. }
  25174. getTexture( property ) {
  25175. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25176. }
  25177. setup( builder ) {
  25178. const material = builder.context.material;
  25179. const scope = this.scope;
  25180. let node = null;
  25181. if ( scope === MaterialNode.COLOR ) {
  25182. const colorNode = this.getColor( scope );
  25183. if ( material.map && material.map.isTexture === true ) {
  25184. node = colorNode.mul( this.getTexture( 'map' ) );
  25185. } else {
  25186. node = colorNode;
  25187. }
  25188. } else if ( scope === MaterialNode.OPACITY ) {
  25189. const opacityNode = this.getFloat( scope );
  25190. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25191. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25192. } else {
  25193. node = opacityNode;
  25194. }
  25195. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25196. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25197. node = this.getTexture( 'specular' ).r;
  25198. } else {
  25199. node = float( 1 );
  25200. }
  25201. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25202. const specularIntensity = this.getFloat( scope );
  25203. if ( material.specularMap ) {
  25204. node = specularIntensity.mul( this.getTexture( scope ).a );
  25205. } else {
  25206. node = specularIntensity;
  25207. }
  25208. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25209. const specularColorNode = this.getColor( scope );
  25210. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25211. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25212. } else {
  25213. node = specularColorNode;
  25214. }
  25215. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25216. const roughnessNode = this.getFloat( scope );
  25217. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25218. node = roughnessNode.mul( this.getTexture( scope ).g );
  25219. } else {
  25220. node = roughnessNode;
  25221. }
  25222. } else if ( scope === MaterialNode.METALNESS ) {
  25223. const metalnessNode = this.getFloat( scope );
  25224. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25225. node = metalnessNode.mul( this.getTexture( scope ).b );
  25226. } else {
  25227. node = metalnessNode;
  25228. }
  25229. } else if ( scope === MaterialNode.EMISSIVE ) {
  25230. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25231. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25232. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25233. node = emissiveNode.mul( this.getTexture( scope ) );
  25234. } else {
  25235. node = emissiveNode;
  25236. }
  25237. } else if ( scope === MaterialNode.NORMAL ) {
  25238. if ( material.normalMap ) {
  25239. node = this.getTexture( 'normal' ).normalMap( this.getCache( 'normalScale', 'vec2' ) );
  25240. } else if ( material.bumpMap ) {
  25241. node = this.getTexture( 'bump' ).r.bumpMap( this.getFloat( 'bumpScale' ) );
  25242. } else {
  25243. node = normalView;
  25244. }
  25245. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25246. const clearcoatNode = this.getFloat( scope );
  25247. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25248. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25249. } else {
  25250. node = clearcoatNode;
  25251. }
  25252. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25253. const clearcoatRoughnessNode = this.getFloat( scope );
  25254. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25255. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25256. } else {
  25257. node = clearcoatRoughnessNode;
  25258. }
  25259. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25260. if ( material.clearcoatNormalMap ) {
  25261. node = this.getTexture( scope ).normalMap( this.getCache( scope + 'Scale', 'vec2' ) );
  25262. } else {
  25263. node = normalView;
  25264. }
  25265. } else if ( scope === MaterialNode.SHEEN ) {
  25266. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25267. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25268. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25269. } else {
  25270. node = sheenNode;
  25271. }
  25272. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25273. const sheenRoughnessNode = this.getFloat( scope );
  25274. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25275. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25276. } else {
  25277. node = sheenRoughnessNode;
  25278. }
  25279. node = node.clamp( 0.07, 1.0 );
  25280. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25281. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25282. const anisotropyPolar = this.getTexture( scope );
  25283. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25284. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25285. } else {
  25286. node = materialAnisotropyVector;
  25287. }
  25288. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25289. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25290. if ( material.iridescenceThicknessMap ) {
  25291. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25292. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25293. } else {
  25294. node = iridescenceThicknessMaximum;
  25295. }
  25296. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25297. const transmissionNode = this.getFloat( scope );
  25298. if ( material.transmissionMap ) {
  25299. node = transmissionNode.mul( this.getTexture( scope ).r );
  25300. } else {
  25301. node = transmissionNode;
  25302. }
  25303. } else if ( scope === MaterialNode.THICKNESS ) {
  25304. const thicknessNode = this.getFloat( scope );
  25305. if ( material.thicknessMap ) {
  25306. node = thicknessNode.mul( this.getTexture( scope ).g );
  25307. } else {
  25308. node = thicknessNode;
  25309. }
  25310. } else if ( scope === MaterialNode.IOR ) {
  25311. node = this.getFloat( scope );
  25312. } else if ( scope === MaterialNode.REFRACTION_RATIO ) {
  25313. node = this.getFloat( scope );
  25314. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25315. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25316. } else if ( scope === MaterialNode.AO_MAP ) {
  25317. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25318. } else {
  25319. const outputType = this.getNodeType( builder );
  25320. node = this.getCache( scope, outputType );
  25321. }
  25322. return node;
  25323. }
  25324. }
  25325. MaterialNode.ALPHA_TEST = 'alphaTest';
  25326. MaterialNode.COLOR = 'color';
  25327. MaterialNode.OPACITY = 'opacity';
  25328. MaterialNode.SHININESS = 'shininess';
  25329. MaterialNode.SPECULAR = 'specular';
  25330. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25331. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25332. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25333. MaterialNode.REFLECTIVITY = 'reflectivity';
  25334. MaterialNode.ROUGHNESS = 'roughness';
  25335. MaterialNode.METALNESS = 'metalness';
  25336. MaterialNode.NORMAL = 'normal';
  25337. MaterialNode.CLEARCOAT = 'clearcoat';
  25338. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25339. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25340. MaterialNode.EMISSIVE = 'emissive';
  25341. MaterialNode.ROTATION = 'rotation';
  25342. MaterialNode.SHEEN = 'sheen';
  25343. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25344. MaterialNode.ANISOTROPY = 'anisotropy';
  25345. MaterialNode.IRIDESCENCE = 'iridescence';
  25346. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25347. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25348. MaterialNode.IOR = 'ior';
  25349. MaterialNode.TRANSMISSION = 'transmission';
  25350. MaterialNode.THICKNESS = 'thickness';
  25351. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25352. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25353. MaterialNode.LINE_SCALE = 'scale';
  25354. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25355. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25356. MaterialNode.LINE_WIDTH = 'linewidth';
  25357. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25358. MaterialNode.POINT_WIDTH = 'pointWidth';
  25359. MaterialNode.DISPERSION = 'dispersion';
  25360. MaterialNode.LIGHT_MAP = 'light';
  25361. MaterialNode.AO_MAP = 'ao';
  25362. MaterialNode.REFRACTION_RATIO = 'refractionRatio';
  25363. const materialAlphaTest = nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25364. const materialColor = nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25365. const materialShininess = nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25366. const materialEmissive = nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25367. const materialOpacity = nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25368. const materialSpecular = nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25369. const materialSpecularIntensity = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25370. const materialSpecularColor = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25371. const materialSpecularStrength = nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25372. const materialReflectivity = nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25373. const materialRoughness = nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25374. const materialMetalness = nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25375. const materialNormal = nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  25376. const materialClearcoat = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25377. const materialClearcoatRoughness = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25378. const materialClearcoatNormal = nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  25379. const materialRotation = nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25380. const materialSheen = nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25381. const materialSheenRoughness = nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25382. const materialAnisotropy = nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25383. const materialIridescence = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25384. const materialIridescenceIOR = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25385. const materialIridescenceThickness = nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25386. const materialTransmission = nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25387. const materialThickness = nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25388. const materialIOR = nodeImmutable( MaterialNode, MaterialNode.IOR );
  25389. const materialAttenuationDistance = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25390. const materialAttenuationColor = nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25391. const materialLineScale = nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25392. const materialLineDashSize = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25393. const materialLineGapSize = nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25394. const materialLineWidth = nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25395. const materialLineDashOffset = nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25396. const materialPointWidth = nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25397. const materialDispersion = nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25398. const materialLightMap = nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25399. const materialAOMap = nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25400. const materialRefractionRatio = nodeImmutable( MaterialNode, MaterialNode.REFRACTION_RATIO );
  25401. const materialAnisotropyVector = uniform( new Vector2() ).onReference( function ( frame ) {
  25402. return frame.material;
  25403. } ).onRenderUpdate( function ( { material } ) {
  25404. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25405. } );
  25406. addNodeClass( 'MaterialNode', MaterialNode );
  25407. const positionGeometry = /*#__PURE__*/ attribute( 'position', 'vec3' );
  25408. const positionLocal = /*#__PURE__*/ positionGeometry.toVar( 'positionLocal' );
  25409. const positionWorld = /*#__PURE__*/ varying( modelWorldMatrix.mul( positionLocal ).xyz, 'v_positionWorld' );
  25410. const positionWorldDirection = /*#__PURE__*/ varying( positionLocal.transformDirection( modelWorldMatrix ), 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  25411. const positionView = /*#__PURE__*/ varying( modelViewMatrix.mul( positionLocal ).xyz, 'v_positionView' );
  25412. const positionViewDirection = /*#__PURE__*/ varying( positionView.negate(), 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  25413. class ModelViewProjectionNode extends TempNode {
  25414. constructor( positionNode = null ) {
  25415. super( 'vec4' );
  25416. this.positionNode = positionNode;
  25417. }
  25418. setup( builder ) {
  25419. if ( builder.shaderStage === 'fragment' ) {
  25420. return varying( builder.context.mvp );
  25421. }
  25422. const position = this.positionNode || positionLocal;
  25423. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( position );
  25424. }
  25425. }
  25426. const modelViewProjection = nodeProxy( ModelViewProjectionNode );
  25427. addNodeClass( 'ModelViewProjectionNode', ModelViewProjectionNode );
  25428. class BufferAttributeNode extends InputNode {
  25429. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  25430. super( value, bufferType );
  25431. this.isBufferNode = true;
  25432. this.bufferType = bufferType;
  25433. this.bufferStride = bufferStride;
  25434. this.bufferOffset = bufferOffset;
  25435. this.usage = StaticDrawUsage;
  25436. this.instanced = false;
  25437. this.attribute = null;
  25438. this.global = true;
  25439. if ( value && value.isBufferAttribute === true ) {
  25440. this.attribute = value;
  25441. this.usage = value.usage;
  25442. this.instanced = value.isInstancedBufferAttribute;
  25443. }
  25444. }
  25445. getHash( builder ) {
  25446. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  25447. let bufferData = builder.globalCache.getData( this.value );
  25448. if ( bufferData === undefined ) {
  25449. bufferData = {
  25450. node: this
  25451. };
  25452. builder.globalCache.setData( this.value, bufferData );
  25453. }
  25454. return bufferData.node.uuid;
  25455. }
  25456. return this.uuid;
  25457. }
  25458. getNodeType( builder ) {
  25459. if ( this.bufferType === null ) {
  25460. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  25461. }
  25462. return this.bufferType;
  25463. }
  25464. setup( builder ) {
  25465. if ( this.attribute !== null ) return;
  25466. const type = this.getNodeType( builder );
  25467. const array = this.value;
  25468. const itemSize = builder.getTypeLength( type );
  25469. const stride = this.bufferStride || itemSize;
  25470. const offset = this.bufferOffset;
  25471. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  25472. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  25473. buffer.setUsage( this.usage );
  25474. this.attribute = bufferAttribute;
  25475. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  25476. }
  25477. generate( builder ) {
  25478. const nodeType = this.getNodeType( builder );
  25479. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  25480. const propertyName = builder.getPropertyName( nodeAttribute );
  25481. let output = null;
  25482. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25483. this.name = propertyName;
  25484. output = propertyName;
  25485. } else {
  25486. const nodeVarying = varying( this );
  25487. output = nodeVarying.build( builder, nodeType );
  25488. }
  25489. return output;
  25490. }
  25491. getInputType( /*builder*/ ) {
  25492. return 'bufferAttribute';
  25493. }
  25494. setUsage( value ) {
  25495. this.usage = value;
  25496. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  25497. this.attribute.usage = value;
  25498. }
  25499. return this;
  25500. }
  25501. setInstanced( value ) {
  25502. this.instanced = value;
  25503. return this;
  25504. }
  25505. }
  25506. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  25507. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  25508. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  25509. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  25510. addNodeElement( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  25511. addNodeClass( 'BufferAttributeNode', BufferAttributeNode );
  25512. class InstanceNode extends Node {
  25513. constructor( instanceMesh ) {
  25514. super( 'void' );
  25515. this.instanceMesh = instanceMesh;
  25516. this.instanceMatrixNode = null;
  25517. this.instanceColorNode = null;
  25518. this.updateType = NodeUpdateType.FRAME;
  25519. this.buffer = null;
  25520. this.bufferColor = null;
  25521. }
  25522. setup( /*builder*/ ) {
  25523. let instanceMatrixNode = this.instanceMatrixNode;
  25524. let instanceColorNode = this.instanceColorNode;
  25525. const instanceMesh = this.instanceMesh;
  25526. if ( instanceMatrixNode === null ) {
  25527. const instanceAttribute = instanceMesh.instanceMatrix;
  25528. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  25529. if ( instanceMesh.count <= 1000 ) {
  25530. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', instanceMesh.count ).element( instanceIndex );
  25531. } else {
  25532. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25533. this.buffer = buffer;
  25534. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25535. const instanceBuffers = [
  25536. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25537. bufferFn( buffer, 'vec4', 16, 0 ),
  25538. bufferFn( buffer, 'vec4', 16, 4 ),
  25539. bufferFn( buffer, 'vec4', 16, 8 ),
  25540. bufferFn( buffer, 'vec4', 16, 12 )
  25541. ];
  25542. instanceMatrixNode = mat4( ...instanceBuffers );
  25543. }
  25544. this.instanceMatrixNode = instanceMatrixNode;
  25545. }
  25546. const instanceColorAttribute = instanceMesh.instanceColor;
  25547. if ( instanceColorAttribute && instanceColorNode === null ) {
  25548. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25549. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25550. this.bufferColor = buffer;
  25551. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25552. this.instanceColorNode = instanceColorNode;
  25553. }
  25554. // POSITION
  25555. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25556. // NORMAL
  25557. const m = mat3( instanceMatrixNode );
  25558. const transformedNormal = normalLocal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  25559. const instanceNormal = m.mul( transformedNormal ).xyz;
  25560. // ASSIGNS
  25561. positionLocal.assign( instancePosition );
  25562. normalLocal.assign( instanceNormal );
  25563. // COLOR
  25564. if ( this.instanceColorNode !== null ) {
  25565. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25566. }
  25567. }
  25568. update( /*frame*/ ) {
  25569. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25570. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25571. }
  25572. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25573. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25574. }
  25575. }
  25576. }
  25577. const instance = nodeProxy( InstanceNode );
  25578. addNodeClass( 'InstanceNode', InstanceNode );
  25579. const tangentGeometry = /*#__PURE__*/ tslFn( ( stack, builder ) => {
  25580. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25581. builder.geometry.computeTangents();
  25582. }
  25583. return attribute( 'tangent', 'vec4' );
  25584. } )();
  25585. const tangentLocal = /*#__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25586. const tangentView = /*#__PURE__*/ varying( modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz, 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25587. const tangentWorld = /*#__PURE__*/ varying( tangentView.transformDirection( cameraViewMatrix ), 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25588. const transformedTangentView = /*#__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25589. const transformedTangentWorld = /*#__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25590. class BatchNode extends Node {
  25591. constructor( batchMesh ) {
  25592. super( 'void' );
  25593. this.batchMesh = batchMesh;
  25594. this.instanceColorNode = null;
  25595. this.batchingIdNode = null;
  25596. }
  25597. setup( builder ) {
  25598. // POSITION
  25599. if ( this.batchingIdNode === null ) {
  25600. if ( builder.getDrawIndex() === null ) {
  25601. this.batchingIdNode = instanceIndex;
  25602. } else {
  25603. this.batchingIdNode = drawIndex;
  25604. }
  25605. }
  25606. const getIndirectIndex = tslFn( ( [ id ] ) => {
  25607. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25608. const x = int( id ).remainder( int( size ) );
  25609. const y = int( id ).div( int( size ) );
  25610. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25611. } ).setLayout( {
  25612. name: 'getIndirectIndex',
  25613. type: 'uint',
  25614. inputs: [
  25615. { name: 'id', type: 'int' }
  25616. ]
  25617. } );
  25618. const matriceTexture = this.batchMesh._matricesTexture;
  25619. const size = textureSize( textureLoad( matriceTexture ), 0 );
  25620. const j = float( getIndirectIndex( int( this.batchingIdNode ) ) ).mul( 4 ).toVar();
  25621. const x = int( j.mod( size ) );
  25622. const y = int( j ).div( int( size ) );
  25623. const batchingMatrix = mat4(
  25624. textureLoad( matriceTexture, ivec2( x, y ) ),
  25625. textureLoad( matriceTexture, ivec2( x.add( 1 ), y ) ),
  25626. textureLoad( matriceTexture, ivec2( x.add( 2 ), y ) ),
  25627. textureLoad( matriceTexture, ivec2( x.add( 3 ), y ) )
  25628. );
  25629. const bm = mat3( batchingMatrix );
  25630. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25631. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25632. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25633. normalLocal.assign( batchingNormal );
  25634. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25635. tangentLocal.mulAssign( bm );
  25636. }
  25637. }
  25638. }
  25639. const batch = nodeProxy( BatchNode );
  25640. addNodeClass( 'batch', BatchNode );
  25641. class SkinningNode extends Node {
  25642. constructor( skinnedMesh, useReference = false ) {
  25643. super( 'void' );
  25644. this.skinnedMesh = skinnedMesh;
  25645. this.useReference = useReference;
  25646. this.updateType = NodeUpdateType.OBJECT;
  25647. //
  25648. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25649. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25650. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25651. if ( useReference ) {
  25652. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25653. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25654. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25655. } else {
  25656. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25657. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25658. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25659. }
  25660. this.bindMatrixNode = bindMatrixNode;
  25661. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25662. this.boneMatricesNode = boneMatricesNode;
  25663. }
  25664. setup( builder ) {
  25665. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode, boneMatricesNode } = this;
  25666. const boneMatX = boneMatricesNode.element( skinIndexNode.x );
  25667. const boneMatY = boneMatricesNode.element( skinIndexNode.y );
  25668. const boneMatZ = boneMatricesNode.element( skinIndexNode.z );
  25669. const boneMatW = boneMatricesNode.element( skinIndexNode.w );
  25670. // POSITION
  25671. const skinVertex = bindMatrixNode.mul( positionLocal );
  25672. const skinned = add(
  25673. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25674. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25675. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25676. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25677. );
  25678. const skinPosition = bindMatrixInverseNode.mul( skinned ).xyz;
  25679. // NORMAL
  25680. let skinMatrix = add(
  25681. skinWeightNode.x.mul( boneMatX ),
  25682. skinWeightNode.y.mul( boneMatY ),
  25683. skinWeightNode.z.mul( boneMatZ ),
  25684. skinWeightNode.w.mul( boneMatW )
  25685. );
  25686. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25687. const skinNormal = skinMatrix.transformDirection( normalLocal ).xyz;
  25688. // ASSIGNS
  25689. positionLocal.assign( skinPosition );
  25690. normalLocal.assign( skinNormal );
  25691. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25692. tangentLocal.assign( skinNormal );
  25693. }
  25694. }
  25695. generate( builder, output ) {
  25696. if ( output !== 'void' ) {
  25697. return positionLocal.build( builder, output );
  25698. }
  25699. }
  25700. update( frame ) {
  25701. const object = this.useReference ? frame.object : this.skinnedMesh;
  25702. object.skeleton.update();
  25703. }
  25704. }
  25705. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25706. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25707. addNodeClass( 'SkinningNode', SkinningNode );
  25708. class LoopNode extends Node {
  25709. constructor( params = [] ) {
  25710. super();
  25711. this.params = params;
  25712. }
  25713. getVarName( index ) {
  25714. return String.fromCharCode( 'i'.charCodeAt() + index );
  25715. }
  25716. getProperties( builder ) {
  25717. const properties = builder.getNodeProperties( this );
  25718. if ( properties.stackNode !== undefined ) return properties;
  25719. //
  25720. const inputs = {};
  25721. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25722. const param = this.params[ i ];
  25723. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25724. const type = ( param.isNode !== true && param.type ) || 'int';
  25725. inputs[ name ] = expression( name, type );
  25726. }
  25727. const stack = builder.addStack(); // TODO: cache() it
  25728. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25729. properties.stackNode = stack;
  25730. builder.removeStack();
  25731. return properties;
  25732. }
  25733. getNodeType( builder ) {
  25734. const { returnsNode } = this.getProperties( builder );
  25735. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25736. }
  25737. setup( builder ) {
  25738. // setup properties
  25739. this.getProperties( builder );
  25740. }
  25741. generate( builder ) {
  25742. const properties = this.getProperties( builder );
  25743. const params = this.params;
  25744. const stackNode = properties.stackNode;
  25745. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25746. const param = params[ i ];
  25747. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25748. if ( param.isNode ) {
  25749. type = 'int';
  25750. name = this.getVarName( i );
  25751. start = '0';
  25752. end = param.build( builder, type );
  25753. condition = '<';
  25754. } else {
  25755. type = param.type || 'int';
  25756. name = param.name || this.getVarName( i );
  25757. start = param.start;
  25758. end = param.end;
  25759. condition = param.condition;
  25760. update = param.update;
  25761. if ( typeof start === 'number' ) start = start.toString();
  25762. else if ( start && start.isNode ) start = start.build( builder, type );
  25763. if ( typeof end === 'number' ) end = end.toString();
  25764. else if ( end && end.isNode ) end = end.build( builder, type );
  25765. if ( start !== undefined && end === undefined ) {
  25766. start = start + ' - 1';
  25767. end = '0';
  25768. condition = '>=';
  25769. } else if ( end !== undefined && start === undefined ) {
  25770. start = '0';
  25771. condition = '<';
  25772. }
  25773. if ( condition === undefined ) {
  25774. if ( Number( start ) > Number( end ) ) {
  25775. condition = '>=';
  25776. } else {
  25777. condition = '<';
  25778. }
  25779. }
  25780. }
  25781. const internalParam = { start, end, condition };
  25782. //
  25783. const startSnippet = internalParam.start;
  25784. const endSnippet = internalParam.end;
  25785. let declarationSnippet = '';
  25786. let conditionalSnippet = '';
  25787. let updateSnippet = '';
  25788. if ( ! update ) {
  25789. if ( type === 'int' || type === 'uint' ) {
  25790. if ( condition.includes( '<' ) ) update = '++';
  25791. else update = '--';
  25792. } else {
  25793. if ( condition.includes( '<' ) ) update = '+= 1.';
  25794. else update = '-= 1.';
  25795. }
  25796. }
  25797. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25798. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25799. updateSnippet += name + ' ' + update;
  25800. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25801. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25802. }
  25803. const stackSnippet = stackNode.build( builder, 'void' );
  25804. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25805. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25806. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25807. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25808. }
  25809. builder.addFlowTab();
  25810. return returnsSnippet;
  25811. }
  25812. }
  25813. const loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25814. const Continue = () => expression( 'continue' ).append();
  25815. const Break = () => expression( 'break' ).append();
  25816. addNodeElement( 'loop', ( returns, ...params ) => bypass( returns, loop( ...params ) ) );
  25817. addNodeClass( 'LoopNode', LoopNode );
  25818. const _morphTextures = new WeakMap();
  25819. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25820. const getMorph = tslFn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25821. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25822. const y = texelIndex.div( width );
  25823. const x = texelIndex.sub( y.mul( width ) );
  25824. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25825. return bufferAttrib.mul( influence );
  25826. } );
  25827. function getEntry( geometry ) {
  25828. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25829. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25830. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25831. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25832. // into an array of data textures. Each layer represents a single morph target.
  25833. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25834. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25835. let entry = _morphTextures.get( geometry );
  25836. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25837. if ( entry !== undefined ) entry.texture.dispose();
  25838. const morphTargets = geometry.morphAttributes.position || [];
  25839. const morphNormals = geometry.morphAttributes.normal || [];
  25840. const morphColors = geometry.morphAttributes.color || [];
  25841. let vertexDataCount = 0;
  25842. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25843. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25844. if ( hasMorphColors === true ) vertexDataCount = 3;
  25845. let width = geometry.attributes.position.count * vertexDataCount;
  25846. let height = 1;
  25847. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25848. if ( width > maxTextureSize ) {
  25849. height = Math.ceil( width / maxTextureSize );
  25850. width = maxTextureSize;
  25851. }
  25852. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25853. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25854. bufferTexture.type = FloatType;
  25855. bufferTexture.needsUpdate = true;
  25856. // fill buffer
  25857. const vertexDataStride = vertexDataCount * 4;
  25858. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25859. const morphTarget = morphTargets[ i ];
  25860. const morphNormal = morphNormals[ i ];
  25861. const morphColor = morphColors[ i ];
  25862. const offset = width * height * 4 * i;
  25863. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25864. const stride = j * vertexDataStride;
  25865. if ( hasMorphPosition === true ) {
  25866. _morphVec4.fromBufferAttribute( morphTarget, j );
  25867. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25868. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25869. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25870. buffer[ offset + stride + 3 ] = 0;
  25871. }
  25872. if ( hasMorphNormals === true ) {
  25873. _morphVec4.fromBufferAttribute( morphNormal, j );
  25874. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25875. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25876. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25877. buffer[ offset + stride + 7 ] = 0;
  25878. }
  25879. if ( hasMorphColors === true ) {
  25880. _morphVec4.fromBufferAttribute( morphColor, j );
  25881. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25882. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25883. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25884. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25885. }
  25886. }
  25887. }
  25888. entry = {
  25889. count: morphTargetsCount,
  25890. texture: bufferTexture,
  25891. stride: vertexDataCount,
  25892. size: new Vector2( width, height )
  25893. };
  25894. _morphTextures.set( geometry, entry );
  25895. function disposeTexture() {
  25896. bufferTexture.dispose();
  25897. _morphTextures.delete( geometry );
  25898. geometry.removeEventListener( 'dispose', disposeTexture );
  25899. }
  25900. geometry.addEventListener( 'dispose', disposeTexture );
  25901. }
  25902. return entry;
  25903. }
  25904. class MorphNode extends Node {
  25905. constructor( mesh ) {
  25906. super( 'void' );
  25907. this.mesh = mesh;
  25908. this.morphBaseInfluence = uniform( 1 );
  25909. this.updateType = NodeUpdateType.OBJECT;
  25910. }
  25911. setup( builder ) {
  25912. const { geometry } = builder;
  25913. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25914. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25915. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25916. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25917. // nodes
  25918. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25919. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25920. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25921. const width = int( size.width );
  25922. loop( morphTargetsCount, ( { i } ) => {
  25923. const influence = float( 0 ).toVar();
  25924. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25925. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25926. } else {
  25927. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25928. }
  25929. if ( hasMorphPosition === true ) {
  25930. positionLocal.addAssign( getMorph( {
  25931. bufferMap,
  25932. influence,
  25933. stride,
  25934. width,
  25935. depth: i,
  25936. offset: int( 0 )
  25937. } ) );
  25938. }
  25939. if ( hasMorphNormals === true ) {
  25940. normalLocal.addAssign( getMorph( {
  25941. bufferMap,
  25942. influence,
  25943. stride,
  25944. width,
  25945. depth: i,
  25946. offset: int( 1 )
  25947. } ) );
  25948. }
  25949. } );
  25950. }
  25951. update() {
  25952. const morphBaseInfluence = this.morphBaseInfluence;
  25953. if ( this.mesh.geometry.morphTargetsRelative ) {
  25954. morphBaseInfluence.value = 1;
  25955. } else {
  25956. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25957. }
  25958. }
  25959. }
  25960. const morphReference = nodeProxy( MorphNode );
  25961. addNodeClass( 'MorphNode', MorphNode );
  25962. const reflectView = /*#__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  25963. const refractView = /*#__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  25964. const reflectVector = /*#__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25965. const refractVector = /*#__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  25966. class CubeTextureNode extends TextureNode {
  25967. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  25968. super( value, uvNode, levelNode, biasNode );
  25969. this.isCubeTextureNode = true;
  25970. }
  25971. getInputType( /*builder*/ ) {
  25972. return 'cubeTexture';
  25973. }
  25974. getDefaultUV() {
  25975. const texture = this.value;
  25976. if ( texture.mapping === CubeReflectionMapping ) {
  25977. return reflectVector;
  25978. } else if ( texture.mapping === CubeRefractionMapping ) {
  25979. return refractVector;
  25980. } else {
  25981. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  25982. return vec3( 0, 0, 0 );
  25983. }
  25984. }
  25985. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  25986. setupUV( builder, uvNode ) {
  25987. const texture = this.value;
  25988. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  25989. return vec3( uvNode.x.negate(), uvNode.yz );
  25990. } else {
  25991. return uvNode;
  25992. }
  25993. }
  25994. generateUV( builder, cubeUV ) {
  25995. return cubeUV.build( builder, 'vec3' );
  25996. }
  25997. }
  25998. const cubeTexture = nodeProxy( CubeTextureNode );
  25999. addNodeElement( 'cubeTexture', cubeTexture );
  26000. addNodeClass( 'CubeTextureNode', CubeTextureNode );
  26001. class LightingNode extends Node {
  26002. constructor() {
  26003. super( 'vec3' );
  26004. this.isLightingNode = true;
  26005. }
  26006. generate( /*builder*/ ) {
  26007. console.warn( 'Abstract function.' );
  26008. }
  26009. }
  26010. addNodeClass( 'LightingNode', LightingNode );
  26011. const BasicShadowMap = tslFn( ( { depthTexture, shadowCoord } ) => {
  26012. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  26013. } );
  26014. const PCFShadowMap = tslFn( ( { depthTexture, shadowCoord, shadow } ) => {
  26015. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26016. const mapSize = reference( 'mapSize', 'vec2', shadow );
  26017. const radius = reference( 'radius', 'float', shadow );
  26018. const texelSize = vec2( 1 ).div( mapSize );
  26019. const dx0 = texelSize.x.negate().mul( radius );
  26020. const dy0 = texelSize.y.negate().mul( radius );
  26021. const dx1 = texelSize.x.mul( radius );
  26022. const dy1 = texelSize.y.mul( radius );
  26023. const dx2 = dx0.div( 2 );
  26024. const dy2 = dy0.div( 2 );
  26025. const dx3 = dx1.div( 2 );
  26026. const dy3 = dy1.div( 2 );
  26027. return add(
  26028. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  26029. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  26030. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  26031. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  26032. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  26033. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  26034. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  26035. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  26036. depthCompare( shadowCoord.xy, shadowCoord.z ),
  26037. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  26038. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26039. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26040. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26041. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26042. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26043. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26044. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26045. ).mul( 1 / 17 );
  26046. } );
  26047. const PCFSoftShadowMap = tslFn( ( { depthTexture, shadowCoord, shadow } ) => {
  26048. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26049. const mapSize = reference( 'mapSize', 'vec2', shadow );
  26050. const texelSize = vec2( 1 ).div( mapSize );
  26051. const dx = texelSize.x;
  26052. const dy = texelSize.y;
  26053. const uv = shadowCoord.xy;
  26054. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  26055. uv.subAssign( f.mul( texelSize ) );
  26056. return add(
  26057. depthCompare( uv, shadowCoord.z ),
  26058. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  26059. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  26060. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  26061. mix(
  26062. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  26063. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  26064. f.x
  26065. ),
  26066. mix(
  26067. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  26068. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  26069. f.x
  26070. ),
  26071. mix(
  26072. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  26073. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  26074. f.y
  26075. ),
  26076. mix(
  26077. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  26078. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  26079. f.y
  26080. ),
  26081. mix(
  26082. mix(
  26083. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  26084. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  26085. f.x
  26086. ),
  26087. mix(
  26088. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  26089. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  26090. f.x
  26091. ),
  26092. f.y
  26093. )
  26094. ).mul( 1 / 9 );
  26095. } );
  26096. const shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap ];
  26097. //
  26098. let overrideMaterial = null;
  26099. class AnalyticLightNode extends LightingNode {
  26100. constructor( light = null ) {
  26101. super();
  26102. this.updateType = NodeUpdateType.FRAME;
  26103. this.light = light;
  26104. this.color = new Color();
  26105. this.colorNode = uniform( this.color );
  26106. this.baseColorNode = null;
  26107. this.shadowMap = null;
  26108. this.shadowNode = null;
  26109. this.shadowColorNode = null;
  26110. this.isAnalyticLightNode = true;
  26111. }
  26112. getCacheKey() {
  26113. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  26114. }
  26115. getHash() {
  26116. return this.light.uuid;
  26117. }
  26118. setupShadow( builder ) {
  26119. const { object, renderer } = builder;
  26120. let shadowColorNode = this.shadowColorNode;
  26121. if ( shadowColorNode === null ) {
  26122. if ( overrideMaterial === null ) {
  26123. overrideMaterial = builder.createNodeMaterial();
  26124. overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  26125. overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  26126. }
  26127. const depthTexture = new DepthTexture();
  26128. depthTexture.compareFunction = LessCompare;
  26129. const shadow = this.light.shadow;
  26130. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  26131. shadowMap.depthTexture = depthTexture;
  26132. shadow.camera.updateProjectionMatrix();
  26133. //
  26134. const shadowIntensity = reference( 'intensity', 'float', shadow );
  26135. const bias = reference( 'bias', 'float', shadow );
  26136. const normalBias = reference( 'normalBias', 'float', shadow );
  26137. const position = object.material.shadowPositionNode || positionWorld;
  26138. let shadowCoord = uniform( shadow.matrix ).mul( position.add( normalWorld.mul( normalBias ) ) );
  26139. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26140. let coordZ = shadowCoord.z.add( bias );
  26141. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26142. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  26143. }
  26144. shadowCoord = vec3(
  26145. shadowCoord.x,
  26146. shadowCoord.y.oneMinus(), // follow webgpu standards
  26147. coordZ
  26148. );
  26149. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26150. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26151. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26152. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26153. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26154. //
  26155. const filterFn = shadow.filterNode || shadowFilterLib[ renderer.shadowMap.type ] || null;
  26156. if ( filterFn === null ) {
  26157. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  26158. }
  26159. const shadowColor = texture( shadowMap.texture, shadowCoord );
  26160. const shadowNode = frustumTest.cond( filterFn( { depthTexture, shadowCoord, shadow } ), float( 1 ) );
  26161. this.shadowMap = shadowMap;
  26162. this.shadowNode = shadowNode;
  26163. this.shadowColorNode = shadowColorNode = this.colorNode.mul( mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ) );
  26164. this.baseColorNode = this.colorNode;
  26165. }
  26166. //
  26167. this.colorNode = shadowColorNode;
  26168. this.updateBeforeType = NodeUpdateType.RENDER;
  26169. }
  26170. setup( builder ) {
  26171. this.colorNode = this.baseColorNode || this.colorNode;
  26172. if ( this.light.castShadow ) {
  26173. if ( builder.object.receiveShadow ) {
  26174. this.setupShadow( builder );
  26175. }
  26176. } else if ( this.shadowNode !== null ) {
  26177. this.disposeShadow();
  26178. }
  26179. }
  26180. updateShadow( frame ) {
  26181. const { shadowMap, light } = this;
  26182. const { renderer, scene, camera } = frame;
  26183. const currentOverrideMaterial = scene.overrideMaterial;
  26184. scene.overrideMaterial = overrideMaterial;
  26185. shadowMap.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  26186. light.shadow.updateMatrices( light );
  26187. light.shadow.camera.layers.mask = camera.layers.mask;
  26188. const currentRenderTarget = renderer.getRenderTarget();
  26189. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26190. renderer.setRenderObjectFunction( ( object, ...params ) => {
  26191. if ( object.castShadow === true ) {
  26192. renderer.renderObject( object, ...params );
  26193. }
  26194. } );
  26195. renderer.setRenderTarget( shadowMap );
  26196. renderer.render( scene, light.shadow.camera );
  26197. renderer.setRenderTarget( currentRenderTarget );
  26198. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26199. scene.overrideMaterial = currentOverrideMaterial;
  26200. }
  26201. disposeShadow() {
  26202. this.shadowMap.dispose();
  26203. this.shadowMap = null;
  26204. this.shadowNode = null;
  26205. this.shadowColorNode = null;
  26206. this.baseColorNode = null;
  26207. this.updateBeforeType = NodeUpdateType.NONE;
  26208. }
  26209. updateBefore( frame ) {
  26210. this.updateShadow( frame );
  26211. }
  26212. update( /*frame*/ ) {
  26213. const { light } = this;
  26214. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26215. }
  26216. }
  26217. addNodeClass( 'AnalyticLightNode', AnalyticLightNode );
  26218. const LightNodes = new WeakMap();
  26219. const sortLights = ( lights ) => {
  26220. return lights.sort( ( a, b ) => a.id - b.id );
  26221. };
  26222. class LightsNode extends Node {
  26223. constructor( lightNodes = [] ) {
  26224. super( 'vec3' );
  26225. this.totalDiffuseNode = vec3().temp( 'totalDiffuse' );
  26226. this.totalSpecularNode = vec3().temp( 'totalSpecular' );
  26227. this.outgoingLightNode = vec3().temp( 'outgoingLight' );
  26228. this.lightNodes = lightNodes;
  26229. this._hash = null;
  26230. }
  26231. get hasLight() {
  26232. return this.lightNodes.length > 0;
  26233. }
  26234. getHash() {
  26235. if ( this._hash === null ) {
  26236. const hash = [];
  26237. for ( const lightNode of this.lightNodes ) {
  26238. hash.push( lightNode.getHash() );
  26239. }
  26240. this._hash = 'lights-' + hash.join( ',' );
  26241. }
  26242. return this._hash;
  26243. }
  26244. analyze( builder ) {
  26245. const properties = builder.getDataFromNode( this );
  26246. for ( const node of properties.nodes ) {
  26247. node.build( builder );
  26248. }
  26249. }
  26250. setup( builder ) {
  26251. const context = builder.context;
  26252. const lightingModel = context.lightingModel;
  26253. let outgoingLightNode = this.outgoingLightNode;
  26254. if ( lightingModel ) {
  26255. const { lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26256. context.outgoingLight = outgoingLightNode;
  26257. const stack = builder.addStack();
  26258. //
  26259. const properties = builder.getDataFromNode( this );
  26260. properties.nodes = stack.nodes;
  26261. //
  26262. lightingModel.start( context, stack, builder );
  26263. // lights
  26264. for ( const lightNode of lightNodes ) {
  26265. lightNode.build( builder );
  26266. }
  26267. //
  26268. lightingModel.indirect( context, stack, builder );
  26269. //
  26270. const { backdrop, backdropAlpha } = context;
  26271. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26272. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26273. if ( backdrop !== null ) {
  26274. if ( backdropAlpha !== null ) {
  26275. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26276. } else {
  26277. totalDiffuse = vec3( backdrop );
  26278. }
  26279. context.material.transparent = true;
  26280. }
  26281. totalDiffuseNode.assign( totalDiffuse );
  26282. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26283. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26284. //
  26285. lightingModel.finish( context, stack, builder );
  26286. //
  26287. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26288. }
  26289. return outgoingLightNode;
  26290. }
  26291. _getLightNodeById( id ) {
  26292. for ( const lightNode of this.lightNodes ) {
  26293. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26294. return lightNode;
  26295. }
  26296. }
  26297. return null;
  26298. }
  26299. fromLights( lights = [] ) {
  26300. const lightNodes = [];
  26301. lights = sortLights( lights );
  26302. for ( const light of lights ) {
  26303. let lightNode = this._getLightNodeById( light.id );
  26304. if ( lightNode === null ) {
  26305. const lightClass = light.constructor;
  26306. const lightNodeClass = LightNodes.has( lightClass ) ? LightNodes.get( lightClass ) : AnalyticLightNode;
  26307. lightNode = nodeObject( new lightNodeClass( light ) );
  26308. }
  26309. lightNodes.push( lightNode );
  26310. }
  26311. this.lightNodes = lightNodes;
  26312. this._hash = null;
  26313. return this;
  26314. }
  26315. }
  26316. const lights = ( lights ) => nodeObject( new LightsNode().fromLights( lights ) );
  26317. const lightsNode = nodeProxy( LightsNode );
  26318. function addLightNode( lightClass, lightNodeClass ) {
  26319. if ( LightNodes.has( lightClass ) ) {
  26320. console.warn( `Redefinition of light node ${ lightNodeClass.type }` );
  26321. return;
  26322. }
  26323. if ( typeof lightClass !== 'function' ) throw new Error( `Light ${ lightClass.name } is not a class` );
  26324. if ( typeof lightNodeClass !== 'function' || ! lightNodeClass.type ) throw new Error( `Light node ${ lightNodeClass.type } is not a class` );
  26325. LightNodes.set( lightClass, lightNodeClass );
  26326. }
  26327. class AONode extends LightingNode {
  26328. constructor( aoNode = null ) {
  26329. super();
  26330. this.aoNode = aoNode;
  26331. }
  26332. setup( builder ) {
  26333. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26334. }
  26335. }
  26336. addNodeClass( 'AONode', AONode );
  26337. class LightingContextNode extends ContextNode {
  26338. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26339. super( node );
  26340. this.lightingModel = lightingModel;
  26341. this.backdropNode = backdropNode;
  26342. this.backdropAlphaNode = backdropAlphaNode;
  26343. this._context = null;
  26344. }
  26345. getContext() {
  26346. const { backdropNode, backdropAlphaNode } = this;
  26347. const directDiffuse = vec3().temp( 'directDiffuse' ),
  26348. directSpecular = vec3().temp( 'directSpecular' ),
  26349. indirectDiffuse = vec3().temp( 'indirectDiffuse' ),
  26350. indirectSpecular = vec3().temp( 'indirectSpecular' );
  26351. const reflectedLight = {
  26352. directDiffuse,
  26353. directSpecular,
  26354. indirectDiffuse,
  26355. indirectSpecular
  26356. };
  26357. const context = {
  26358. radiance: vec3().temp( 'radiance' ),
  26359. irradiance: vec3().temp( 'irradiance' ),
  26360. iblIrradiance: vec3().temp( 'iblIrradiance' ),
  26361. ambientOcclusion: float( 1 ).temp( 'ambientOcclusion' ),
  26362. reflectedLight,
  26363. backdrop: backdropNode,
  26364. backdropAlpha: backdropAlphaNode
  26365. };
  26366. return context;
  26367. }
  26368. setup( builder ) {
  26369. this.context = this._context || ( this._context = this.getContext() );
  26370. this.context.lightingModel = this.lightingModel || builder.context.lightingModel;
  26371. return super.setup( builder );
  26372. }
  26373. }
  26374. const lightingContext = nodeProxy( LightingContextNode );
  26375. addNodeElement( 'lightingContext', lightingContext );
  26376. addNodeClass( 'LightingContextNode', LightingContextNode );
  26377. class IrradianceNode extends LightingNode {
  26378. constructor( node ) {
  26379. super();
  26380. this.node = node;
  26381. }
  26382. setup( builder ) {
  26383. builder.context.irradiance.addAssign( this.node );
  26384. }
  26385. }
  26386. addNodeClass( 'IrradianceNode', IrradianceNode );
  26387. let resolution, viewportResult;
  26388. class ViewportNode extends Node {
  26389. constructor( scope ) {
  26390. super();
  26391. this.scope = scope;
  26392. this.isViewportNode = true;
  26393. }
  26394. getNodeType() {
  26395. if ( this.scope === ViewportNode.VIEWPORT ) return 'vec4';
  26396. else if ( this.scope === ViewportNode.COORDINATE ) return 'vec3';
  26397. else return 'vec2';
  26398. }
  26399. getUpdateType() {
  26400. let updateType = NodeUpdateType.NONE;
  26401. if ( this.scope === ViewportNode.RESOLUTION || this.scope === ViewportNode.VIEWPORT ) {
  26402. updateType = NodeUpdateType.RENDER;
  26403. }
  26404. this.updateType = updateType;
  26405. return updateType;
  26406. }
  26407. update( { renderer } ) {
  26408. if ( this.scope === ViewportNode.VIEWPORT ) {
  26409. renderer.getViewport( viewportResult );
  26410. } else {
  26411. renderer.getDrawingBufferSize( resolution );
  26412. }
  26413. }
  26414. setup( /*builder*/ ) {
  26415. const scope = this.scope;
  26416. let output = null;
  26417. if ( scope === ViewportNode.RESOLUTION ) {
  26418. output = uniform( resolution || ( resolution = new Vector2() ) );
  26419. } else if ( scope === ViewportNode.VIEWPORT ) {
  26420. output = uniform( viewportResult || ( viewportResult = new Vector4() ) );
  26421. } else {
  26422. output = viewportCoordinate.div( viewportResolution );
  26423. let outX = output.x;
  26424. let outY = output.y;
  26425. if ( /bottom/i.test( scope ) ) outY = outY.oneMinus();
  26426. if ( /right/i.test( scope ) ) outX = outX.oneMinus();
  26427. output = vec2( outX, outY );
  26428. }
  26429. return output;
  26430. }
  26431. generate( builder ) {
  26432. if ( this.scope === ViewportNode.COORDINATE ) {
  26433. let coord = builder.getFragCoord();
  26434. if ( builder.isFlipY() ) {
  26435. // follow webgpu standards
  26436. const resolution = builder.getNodeProperties( viewportResolution ).outputNode.build( builder );
  26437. coord = `${ builder.getType( 'vec3' ) }( ${ coord }.x, ${ resolution }.y - ${ coord }.y, ${ coord }.z )`;
  26438. }
  26439. return coord;
  26440. }
  26441. return super.generate( builder );
  26442. }
  26443. }
  26444. ViewportNode.COORDINATE = 'coordinate';
  26445. ViewportNode.RESOLUTION = 'resolution';
  26446. ViewportNode.VIEWPORT = 'viewport';
  26447. ViewportNode.TOP_LEFT = 'topLeft';
  26448. ViewportNode.BOTTOM_LEFT = 'bottomLeft';
  26449. ViewportNode.TOP_RIGHT = 'topRight';
  26450. ViewportNode.BOTTOM_RIGHT = 'bottomRight';
  26451. const viewportCoordinate = nodeImmutable( ViewportNode, ViewportNode.COORDINATE );
  26452. const viewportResolution = nodeImmutable( ViewportNode, ViewportNode.RESOLUTION );
  26453. const viewport = nodeImmutable( ViewportNode, ViewportNode.VIEWPORT );
  26454. const viewportTopLeft = nodeImmutable( ViewportNode, ViewportNode.TOP_LEFT );
  26455. const viewportBottomLeft = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_LEFT );
  26456. const viewportTopRight = nodeImmutable( ViewportNode, ViewportNode.TOP_RIGHT );
  26457. const viewportBottomRight = nodeImmutable( ViewportNode, ViewportNode.BOTTOM_RIGHT );
  26458. addNodeClass( 'ViewportNode', ViewportNode );
  26459. const _size$7 = /*@__PURE__*/ new Vector2();
  26460. class ViewportTextureNode extends TextureNode {
  26461. constructor( uvNode = viewportTopLeft, levelNode = null, framebufferTexture = null ) {
  26462. if ( framebufferTexture === null ) {
  26463. framebufferTexture = new FramebufferTexture();
  26464. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26465. }
  26466. super( framebufferTexture, uvNode, levelNode );
  26467. this.generateMipmaps = false;
  26468. this.isOutputTextureNode = true;
  26469. this.updateBeforeType = NodeUpdateType.FRAME;
  26470. }
  26471. updateBefore( frame ) {
  26472. const renderer = frame.renderer;
  26473. renderer.getDrawingBufferSize( _size$7 );
  26474. //
  26475. const framebufferTexture = this.value;
  26476. if ( framebufferTexture.image.width !== _size$7.width || framebufferTexture.image.height !== _size$7.height ) {
  26477. framebufferTexture.image.width = _size$7.width;
  26478. framebufferTexture.image.height = _size$7.height;
  26479. framebufferTexture.needsUpdate = true;
  26480. }
  26481. //
  26482. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26483. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26484. renderer.copyFramebufferToTexture( framebufferTexture );
  26485. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26486. }
  26487. clone() {
  26488. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26489. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26490. return viewportTextureNode;
  26491. }
  26492. }
  26493. const viewportTexture = nodeProxy( ViewportTextureNode );
  26494. const viewportMipTexture = nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26495. addNodeElement( 'viewportTexture', viewportTexture );
  26496. addNodeElement( 'viewportMipTexture', viewportMipTexture );
  26497. addNodeClass( 'ViewportTextureNode', ViewportTextureNode );
  26498. let sharedDepthbuffer = null;
  26499. class ViewportDepthTextureNode extends ViewportTextureNode {
  26500. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  26501. if ( sharedDepthbuffer === null ) {
  26502. sharedDepthbuffer = new DepthTexture();
  26503. }
  26504. super( uvNode, levelNode, sharedDepthbuffer );
  26505. }
  26506. }
  26507. const viewportDepthTexture = nodeProxy( ViewportDepthTextureNode );
  26508. addNodeElement( 'viewportDepthTexture', viewportDepthTexture );
  26509. addNodeClass( 'ViewportDepthTextureNode', ViewportDepthTextureNode );
  26510. class ViewportDepthNode extends Node {
  26511. constructor( scope, valueNode = null ) {
  26512. super( 'float' );
  26513. this.scope = scope;
  26514. this.valueNode = valueNode;
  26515. this.isViewportDepthNode = true;
  26516. }
  26517. generate( builder ) {
  26518. const { scope } = this;
  26519. if ( scope === ViewportDepthNode.DEPTH ) {
  26520. return builder.getFragDepth();
  26521. }
  26522. return super.generate( builder );
  26523. }
  26524. setup( { camera } ) {
  26525. const { scope } = this;
  26526. const texture = this.valueNode;
  26527. let node = null;
  26528. if ( scope === ViewportDepthNode.DEPTH ) {
  26529. if ( texture !== null ) {
  26530. node = depthBase().assign( texture );
  26531. } else {
  26532. if ( camera.isPerspectiveCamera ) {
  26533. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26534. } else {
  26535. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26536. }
  26537. }
  26538. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26539. if ( texture !== null ) {
  26540. if ( camera.isPerspectiveCamera ) {
  26541. const viewZ = perspectiveDepthToViewZ( texture, cameraNear, cameraFar );
  26542. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26543. } else {
  26544. node = texture;
  26545. }
  26546. } else {
  26547. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26548. }
  26549. }
  26550. return node;
  26551. }
  26552. }
  26553. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26554. // -near maps to 0; -far maps to 1
  26555. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26556. // maps orthographic depth in [ 0, 1 ] to viewZ
  26557. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26558. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26559. // -near maps to 0; -far maps to 1
  26560. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26561. // maps perspective depth in [ 0, 1 ] to viewZ
  26562. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26563. ViewportDepthNode.DEPTH = 'depth';
  26564. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26565. const depthBase = nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26566. const depth = nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26567. const linearDepth = nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26568. const viewportLinearDepth = linearDepth( viewportDepthTexture() );
  26569. depth.assign = ( value ) => depthBase( value );
  26570. addNodeClass( 'ViewportDepthNode', ViewportDepthNode );
  26571. class ClippingNode extends Node {
  26572. constructor( scope = ClippingNode.DEFAULT ) {
  26573. super();
  26574. this.scope = scope;
  26575. }
  26576. setup( builder ) {
  26577. super.setup( builder );
  26578. const clippingContext = builder.clippingContext;
  26579. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26580. const numClippingPlanes = globalClippingCount + localClippingCount;
  26581. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26582. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26583. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26584. } else {
  26585. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26586. }
  26587. }
  26588. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26589. return tslFn( () => {
  26590. const clippingPlanes = uniformArray( planes );
  26591. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26592. const distanceGradient = property( 'float', 'distanceToGradient' );
  26593. const clipOpacity = property( 'float', 'clipOpacity' );
  26594. clipOpacity.assign( 1 );
  26595. let plane;
  26596. loop( numUnionClippingPlanes, ( { i } ) => {
  26597. plane = clippingPlanes.element( i );
  26598. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26599. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26600. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26601. clipOpacity.equal( 0.0 ).discard();
  26602. } );
  26603. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26604. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26605. unionClipOpacity.assign( 1 );
  26606. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26607. plane = clippingPlanes.element( i );
  26608. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26609. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26610. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26611. } );
  26612. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26613. }
  26614. diffuseColor.a.mulAssign( clipOpacity );
  26615. diffuseColor.a.equal( 0.0 ).discard();
  26616. } )();
  26617. }
  26618. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26619. return tslFn( () => {
  26620. const clippingPlanes = uniformArray( planes );
  26621. let plane;
  26622. loop( numUnionClippingPlanes, ( { i } ) => {
  26623. plane = clippingPlanes.element( i );
  26624. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26625. } );
  26626. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26627. const clipped = property( 'bool', 'clipped' );
  26628. clipped.assign( true );
  26629. loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26630. plane = clippingPlanes.element( i );
  26631. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26632. } );
  26633. clipped.discard();
  26634. }
  26635. } )();
  26636. }
  26637. }
  26638. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26639. ClippingNode.DEFAULT = 'default';
  26640. const clipping = () => nodeObject( new ClippingNode() );
  26641. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26642. class FrontFacingNode extends Node {
  26643. constructor() {
  26644. super( 'bool' );
  26645. this.isFrontFacingNode = true;
  26646. }
  26647. generate( builder ) {
  26648. const { renderer, material } = builder;
  26649. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  26650. if ( material.side === BackSide ) {
  26651. return 'false';
  26652. }
  26653. }
  26654. return builder.getFrontFacing();
  26655. }
  26656. }
  26657. const frontFacing = nodeImmutable( FrontFacingNode );
  26658. const faceDirection = float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  26659. addNodeClass( 'FrontFacingNode', FrontFacingNode );
  26660. const NodeMaterials = new Map();
  26661. class NodeMaterial extends Material {
  26662. constructor() {
  26663. super();
  26664. this.isNodeMaterial = true;
  26665. this.type = this.constructor.type;
  26666. this.forceSinglePass = false;
  26667. this.fog = true;
  26668. this.lights = false;
  26669. this.normals = true;
  26670. this.lightsNode = null;
  26671. this.envNode = null;
  26672. this.aoNode = null;
  26673. this.colorNode = null;
  26674. this.normalNode = null;
  26675. this.opacityNode = null;
  26676. this.backdropNode = null;
  26677. this.backdropAlphaNode = null;
  26678. this.alphaTestNode = null;
  26679. this.positionNode = null;
  26680. this.depthNode = null;
  26681. this.shadowNode = null;
  26682. this.shadowPositionNode = null;
  26683. this.outputNode = null;
  26684. this.mrtNode = null;
  26685. this.fragmentNode = null;
  26686. this.vertexNode = null;
  26687. }
  26688. customProgramCacheKey() {
  26689. return this.type + getCacheKey( this );
  26690. }
  26691. build( builder ) {
  26692. this.setup( builder );
  26693. }
  26694. setup( builder ) {
  26695. // < VERTEX STAGE >
  26696. builder.addStack();
  26697. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26698. builder.addFlow( 'vertex', builder.removeStack() );
  26699. // < FRAGMENT STAGE >
  26700. builder.addStack();
  26701. let resultNode;
  26702. const clippingNode = this.setupClipping( builder );
  26703. if ( this.depthWrite === true ) this.setupDepth( builder );
  26704. if ( this.fragmentNode === null ) {
  26705. if ( this.normals === true ) this.setupNormal( builder );
  26706. this.setupDiffuseColor( builder );
  26707. this.setupVariants( builder );
  26708. const outgoingLightNode = this.setupLighting( builder );
  26709. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26710. // force unsigned floats - useful for RenderTargets
  26711. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26712. resultNode = this.setupOutput( builder, basicOutput );
  26713. // OUTPUT NODE
  26714. output.assign( resultNode );
  26715. //
  26716. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26717. // MRT
  26718. const renderTarget = builder.renderer.getRenderTarget();
  26719. if ( renderTarget !== null ) {
  26720. const mrt = builder.renderer.getMRT();
  26721. const materialMRT = this.mrtNode;
  26722. if ( mrt !== null ) {
  26723. resultNode = mrt;
  26724. if ( materialMRT !== null ) {
  26725. resultNode = mrt.merge( materialMRT );
  26726. }
  26727. } else if ( materialMRT !== null ) {
  26728. resultNode = materialMRT;
  26729. }
  26730. }
  26731. } else {
  26732. let fragmentNode = this.fragmentNode;
  26733. if ( fragmentNode.isOutputStructNode !== true ) {
  26734. fragmentNode = vec4( fragmentNode );
  26735. }
  26736. resultNode = this.setupOutput( builder, fragmentNode );
  26737. }
  26738. builder.stack.outputNode = resultNode;
  26739. builder.addFlow( 'fragment', builder.removeStack() );
  26740. }
  26741. setupClipping( builder ) {
  26742. if ( builder.clippingContext === null ) return null;
  26743. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26744. let result = null;
  26745. if ( globalClippingCount || localClippingCount ) {
  26746. if ( this.alphaToCoverage ) {
  26747. // to be added to flow when the color/alpha value has been determined
  26748. result = clippingAlpha();
  26749. } else {
  26750. builder.stack.add( clipping() );
  26751. }
  26752. }
  26753. return result;
  26754. }
  26755. setupDepth( builder ) {
  26756. const { renderer } = builder;
  26757. // Depth
  26758. let depthNode = this.depthNode;
  26759. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  26760. const fragDepth = modelViewProjection().w.add( 1 );
  26761. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26762. }
  26763. if ( depthNode !== null ) {
  26764. depth.assign( depthNode ).append();
  26765. }
  26766. }
  26767. setupPosition( builder ) {
  26768. const { object } = builder;
  26769. const geometry = object.geometry;
  26770. builder.addStack();
  26771. // Vertex
  26772. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26773. morphReference( object ).append();
  26774. }
  26775. if ( object.isSkinnedMesh === true ) {
  26776. skinningReference( object ).append();
  26777. }
  26778. if ( this.displacementMap ) {
  26779. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26780. const displacementScale = materialReference( 'displacementScale', 'float' );
  26781. const displacementBias = materialReference( 'displacementBias', 'float' );
  26782. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26783. }
  26784. if ( object.isBatchedMesh ) {
  26785. batch( object ).append();
  26786. }
  26787. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26788. instance( object ).append();
  26789. }
  26790. if ( this.positionNode !== null ) {
  26791. positionLocal.assign( this.positionNode );
  26792. }
  26793. const mvp = modelViewProjection();
  26794. builder.context.vertex = builder.removeStack();
  26795. builder.context.mvp = mvp;
  26796. return mvp;
  26797. }
  26798. setupDiffuseColor( { object, geometry } ) {
  26799. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26800. // VERTEX COLORS
  26801. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26802. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26803. }
  26804. // Instanced colors
  26805. if ( object.instanceColor ) {
  26806. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26807. colorNode = instanceColor.mul( colorNode );
  26808. }
  26809. // COLOR
  26810. diffuseColor.assign( colorNode );
  26811. // OPACITY
  26812. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26813. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26814. // ALPHA TEST
  26815. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26816. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26817. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26818. }
  26819. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26820. diffuseColor.a.assign( 1.0 );
  26821. }
  26822. }
  26823. setupVariants( /*builder*/ ) {
  26824. // Interface function.
  26825. }
  26826. setupOutgoingLight() {
  26827. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26828. }
  26829. setupNormal() {
  26830. // NORMAL VIEW
  26831. if ( this.flatShading === true ) {
  26832. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  26833. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26834. } else {
  26835. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26836. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  26837. }
  26838. }
  26839. setupEnvironment( /*builder*/ ) {
  26840. let node = null;
  26841. if ( this.envNode ) {
  26842. node = this.envNode;
  26843. } else if ( this.envMap ) {
  26844. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  26845. }
  26846. return node;
  26847. }
  26848. setupLightMap( builder ) {
  26849. let node = null;
  26850. if ( builder.material.lightMap ) {
  26851. node = new IrradianceNode( materialLightMap );
  26852. }
  26853. return node;
  26854. }
  26855. setupLights( builder ) {
  26856. const materialLightsNode = [];
  26857. //
  26858. const envNode = this.setupEnvironment( builder );
  26859. if ( envNode && envNode.isLightingNode ) {
  26860. materialLightsNode.push( envNode );
  26861. }
  26862. const lightMapNode = this.setupLightMap( builder );
  26863. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26864. materialLightsNode.push( lightMapNode );
  26865. }
  26866. if ( this.aoNode !== null || builder.material.aoMap ) {
  26867. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26868. materialLightsNode.push( new AONode( aoNode ) );
  26869. }
  26870. let lightsN = this.lightsNode || builder.lightsNode;
  26871. if ( materialLightsNode.length > 0 ) {
  26872. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  26873. }
  26874. return lightsN;
  26875. }
  26876. setupLightingModel( /*builder*/ ) {
  26877. // Interface function.
  26878. }
  26879. setupLighting( builder ) {
  26880. const { material } = builder;
  26881. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26882. // OUTGOING LIGHT
  26883. const lights = this.lights === true || this.lightsNode !== null;
  26884. const lightsNode = lights ? this.setupLights( builder ) : null;
  26885. let outgoingLightNode = this.setupOutgoingLight( builder );
  26886. if ( lightsNode && lightsNode.hasLight !== false ) {
  26887. const lightingModel = this.setupLightingModel( builder );
  26888. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26889. } else if ( backdropNode !== null ) {
  26890. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26891. }
  26892. // EMISSIVE
  26893. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26894. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26895. outgoingLightNode = outgoingLightNode.add( emissive );
  26896. }
  26897. return outgoingLightNode;
  26898. }
  26899. setupOutput( builder, outputNode ) {
  26900. // FOG
  26901. if ( this.fog === true ) {
  26902. const fogNode = builder.fogNode;
  26903. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26904. }
  26905. return outputNode;
  26906. }
  26907. setDefaultValues( material ) {
  26908. // This approach is to reuse the native refreshUniforms*
  26909. // and turn available the use of features like transmission and environment in core
  26910. for ( const property in material ) {
  26911. const value = material[ property ];
  26912. if ( this[ property ] === undefined ) {
  26913. this[ property ] = value;
  26914. if ( value && value.clone ) this[ property ] = value.clone();
  26915. }
  26916. }
  26917. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26918. for ( const key in descriptors ) {
  26919. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26920. descriptors[ key ].get !== undefined ) {
  26921. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26922. }
  26923. }
  26924. }
  26925. toJSON( meta ) {
  26926. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26927. if ( isRoot ) {
  26928. meta = {
  26929. textures: {},
  26930. images: {},
  26931. nodes: {}
  26932. };
  26933. }
  26934. const data = Material.prototype.toJSON.call( this, meta );
  26935. const nodeChildren = getNodeChildren( this );
  26936. data.inputNodes = {};
  26937. for ( const { property, childNode } of nodeChildren ) {
  26938. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26939. }
  26940. // TODO: Copied from Object3D.toJSON
  26941. function extractFromCache( cache ) {
  26942. const values = [];
  26943. for ( const key in cache ) {
  26944. const data = cache[ key ];
  26945. delete data.metadata;
  26946. values.push( data );
  26947. }
  26948. return values;
  26949. }
  26950. if ( isRoot ) {
  26951. const textures = extractFromCache( meta.textures );
  26952. const images = extractFromCache( meta.images );
  26953. const nodes = extractFromCache( meta.nodes );
  26954. if ( textures.length > 0 ) data.textures = textures;
  26955. if ( images.length > 0 ) data.images = images;
  26956. if ( nodes.length > 0 ) data.nodes = nodes;
  26957. }
  26958. return data;
  26959. }
  26960. copy( source ) {
  26961. this.lightsNode = source.lightsNode;
  26962. this.envNode = source.envNode;
  26963. this.colorNode = source.colorNode;
  26964. this.normalNode = source.normalNode;
  26965. this.opacityNode = source.opacityNode;
  26966. this.backdropNode = source.backdropNode;
  26967. this.backdropAlphaNode = source.backdropAlphaNode;
  26968. this.alphaTestNode = source.alphaTestNode;
  26969. this.positionNode = source.positionNode;
  26970. this.depthNode = source.depthNode;
  26971. this.shadowNode = source.shadowNode;
  26972. this.shadowPositionNode = source.shadowPositionNode;
  26973. this.outputNode = source.outputNode;
  26974. this.mrtNode = source.mrtNode;
  26975. this.fragmentNode = source.fragmentNode;
  26976. this.vertexNode = source.vertexNode;
  26977. return super.copy( source );
  26978. }
  26979. static fromMaterial( material ) {
  26980. if ( material.isNodeMaterial === true ) { // is already a node material
  26981. return material;
  26982. }
  26983. const type = material.type.replace( 'Material', 'NodeMaterial' );
  26984. const nodeMaterial = createNodeMaterialFromType( type );
  26985. if ( nodeMaterial === undefined ) {
  26986. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  26987. }
  26988. for ( const key in material ) {
  26989. nodeMaterial[ key ] = material[ key ];
  26990. }
  26991. return nodeMaterial;
  26992. }
  26993. }
  26994. function addNodeMaterial( type, nodeMaterial ) {
  26995. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  26996. if ( NodeMaterials.has( type ) ) {
  26997. console.warn( `Redefinition of node material ${ type }` );
  26998. return;
  26999. }
  27000. NodeMaterials.set( type, nodeMaterial );
  27001. nodeMaterial.type = type;
  27002. }
  27003. function createNodeMaterialFromType( type ) {
  27004. const Material = NodeMaterials.get( type );
  27005. if ( Material !== undefined ) {
  27006. return new Material();
  27007. }
  27008. }
  27009. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  27010. class Uniform {
  27011. constructor( name, value ) {
  27012. this.name = name;
  27013. this.value = value;
  27014. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  27015. this.itemSize = 0;
  27016. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  27017. }
  27018. setValue( value ) {
  27019. this.value = value;
  27020. }
  27021. getValue() {
  27022. return this.value;
  27023. }
  27024. }
  27025. class NumberUniform extends Uniform {
  27026. constructor( name, value = 0 ) {
  27027. super( name, value );
  27028. this.isNumberUniform = true;
  27029. this.boundary = 4;
  27030. this.itemSize = 1;
  27031. }
  27032. }
  27033. class Vector2Uniform extends Uniform {
  27034. constructor( name, value = new Vector2() ) {
  27035. super( name, value );
  27036. this.isVector2Uniform = true;
  27037. this.boundary = 8;
  27038. this.itemSize = 2;
  27039. }
  27040. }
  27041. class Vector3Uniform extends Uniform {
  27042. constructor( name, value = new Vector3() ) {
  27043. super( name, value );
  27044. this.isVector3Uniform = true;
  27045. this.boundary = 16;
  27046. this.itemSize = 3;
  27047. }
  27048. }
  27049. class Vector4Uniform extends Uniform {
  27050. constructor( name, value = new Vector4() ) {
  27051. super( name, value );
  27052. this.isVector4Uniform = true;
  27053. this.boundary = 16;
  27054. this.itemSize = 4;
  27055. }
  27056. }
  27057. class ColorUniform extends Uniform {
  27058. constructor( name, value = new Color() ) {
  27059. super( name, value );
  27060. this.isColorUniform = true;
  27061. this.boundary = 16;
  27062. this.itemSize = 3;
  27063. }
  27064. }
  27065. class Matrix3Uniform extends Uniform {
  27066. constructor( name, value = new Matrix3() ) {
  27067. super( name, value );
  27068. this.isMatrix3Uniform = true;
  27069. this.boundary = 48;
  27070. this.itemSize = 12;
  27071. }
  27072. }
  27073. class Matrix4Uniform extends Uniform {
  27074. constructor( name, value = new Matrix4() ) {
  27075. super( name, value );
  27076. this.isMatrix4Uniform = true;
  27077. this.boundary = 64;
  27078. this.itemSize = 16;
  27079. }
  27080. }
  27081. class NumberNodeUniform extends NumberUniform {
  27082. constructor( nodeUniform ) {
  27083. super( nodeUniform.name, nodeUniform.value );
  27084. this.nodeUniform = nodeUniform;
  27085. }
  27086. getValue() {
  27087. return this.nodeUniform.value;
  27088. }
  27089. }
  27090. class Vector2NodeUniform extends Vector2Uniform {
  27091. constructor( nodeUniform ) {
  27092. super( nodeUniform.name, nodeUniform.value );
  27093. this.nodeUniform = nodeUniform;
  27094. }
  27095. getValue() {
  27096. return this.nodeUniform.value;
  27097. }
  27098. }
  27099. class Vector3NodeUniform extends Vector3Uniform {
  27100. constructor( nodeUniform ) {
  27101. super( nodeUniform.name, nodeUniform.value );
  27102. this.nodeUniform = nodeUniform;
  27103. }
  27104. getValue() {
  27105. return this.nodeUniform.value;
  27106. }
  27107. }
  27108. class Vector4NodeUniform extends Vector4Uniform {
  27109. constructor( nodeUniform ) {
  27110. super( nodeUniform.name, nodeUniform.value );
  27111. this.nodeUniform = nodeUniform;
  27112. }
  27113. getValue() {
  27114. return this.nodeUniform.value;
  27115. }
  27116. }
  27117. class ColorNodeUniform extends ColorUniform {
  27118. constructor( nodeUniform ) {
  27119. super( nodeUniform.name, nodeUniform.value );
  27120. this.nodeUniform = nodeUniform;
  27121. }
  27122. getValue() {
  27123. return this.nodeUniform.value;
  27124. }
  27125. }
  27126. class Matrix3NodeUniform extends Matrix3Uniform {
  27127. constructor( nodeUniform ) {
  27128. super( nodeUniform.name, nodeUniform.value );
  27129. this.nodeUniform = nodeUniform;
  27130. }
  27131. getValue() {
  27132. return this.nodeUniform.value;
  27133. }
  27134. }
  27135. class Matrix4NodeUniform extends Matrix4Uniform {
  27136. constructor( nodeUniform ) {
  27137. super( nodeUniform.name, nodeUniform.value );
  27138. this.nodeUniform = nodeUniform;
  27139. }
  27140. getValue() {
  27141. return this.nodeUniform.value;
  27142. }
  27143. }
  27144. class CondNode extends Node {
  27145. constructor( condNode, ifNode, elseNode = null ) {
  27146. super();
  27147. this.condNode = condNode;
  27148. this.ifNode = ifNode;
  27149. this.elseNode = elseNode;
  27150. }
  27151. getNodeType( builder ) {
  27152. const ifType = this.ifNode.getNodeType( builder );
  27153. if ( this.elseNode !== null ) {
  27154. const elseType = this.elseNode.getNodeType( builder );
  27155. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  27156. return elseType;
  27157. }
  27158. }
  27159. return ifType;
  27160. }
  27161. setup( builder ) {
  27162. const properties = builder.getNodeProperties( this );
  27163. properties.condNode = this.condNode.cache();
  27164. properties.ifNode = this.ifNode.cache();
  27165. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  27166. }
  27167. generate( builder, output ) {
  27168. const type = this.getNodeType( builder );
  27169. const nodeData = builder.getDataFromNode( this );
  27170. if ( nodeData.nodeProperty !== undefined ) {
  27171. return nodeData.nodeProperty;
  27172. }
  27173. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  27174. const needsOutput = output !== 'void';
  27175. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  27176. nodeData.nodeProperty = nodeProperty;
  27177. const nodeSnippet = condNode.build( builder, 'bool' );
  27178. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  27179. let ifSnippet = ifNode.build( builder, type );
  27180. if ( ifSnippet ) {
  27181. if ( needsOutput ) {
  27182. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  27183. } else {
  27184. ifSnippet = 'return ' + ifSnippet + ';';
  27185. }
  27186. }
  27187. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  27188. if ( elseNode !== null ) {
  27189. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  27190. let elseSnippet = elseNode.build( builder, type );
  27191. if ( elseSnippet ) {
  27192. if ( needsOutput ) {
  27193. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  27194. } else {
  27195. elseSnippet = 'return ' + elseSnippet + ';';
  27196. }
  27197. }
  27198. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  27199. } else {
  27200. builder.addFlowCode( '\n\n' );
  27201. }
  27202. return builder.format( nodeProperty, type, output );
  27203. }
  27204. }
  27205. const cond = nodeProxy( CondNode );
  27206. addNodeElement( 'cond', cond );
  27207. addNodeClass( 'CondNode', CondNode );
  27208. class StackNode extends Node {
  27209. constructor( parent = null ) {
  27210. super();
  27211. this.nodes = [];
  27212. this.outputNode = null;
  27213. this.parent = parent;
  27214. this._currentCond = null;
  27215. this.isStackNode = true;
  27216. }
  27217. getNodeType( builder ) {
  27218. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27219. }
  27220. add( node ) {
  27221. this.nodes.push( node );
  27222. return this;
  27223. }
  27224. if( boolNode, method ) {
  27225. const methodNode = new ShaderNode( method );
  27226. this._currentCond = cond( boolNode, methodNode );
  27227. return this.add( this._currentCond );
  27228. }
  27229. elseif( boolNode, method ) {
  27230. const methodNode = new ShaderNode( method );
  27231. const ifNode = cond( boolNode, methodNode );
  27232. this._currentCond.elseNode = ifNode;
  27233. this._currentCond = ifNode;
  27234. return this;
  27235. }
  27236. else( method ) {
  27237. this._currentCond.elseNode = new ShaderNode( method );
  27238. return this;
  27239. }
  27240. build( builder, ...params ) {
  27241. const previousStack = getCurrentStack();
  27242. setCurrentStack( this );
  27243. for ( const node of this.nodes ) {
  27244. node.build( builder, 'void' );
  27245. }
  27246. setCurrentStack( previousStack );
  27247. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27248. }
  27249. }
  27250. const stack = nodeProxy( StackNode );
  27251. addNodeClass( 'StackNode', StackNode );
  27252. class EquirectUVNode extends TempNode {
  27253. constructor( dirNode = positionWorldDirection ) {
  27254. super( 'vec2' );
  27255. this.dirNode = dirNode;
  27256. }
  27257. setup() {
  27258. const dir = this.dirNode;
  27259. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27260. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27261. return vec2( u, v );
  27262. }
  27263. }
  27264. const equirectUV = nodeProxy( EquirectUVNode );
  27265. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27266. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27267. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27268. constructor( size = 1, options = {} ) {
  27269. super( size, options );
  27270. this.isCubeRenderTarget = true;
  27271. }
  27272. fromEquirectangularTexture( renderer, texture$1 ) {
  27273. const currentMinFilter = texture$1.minFilter;
  27274. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27275. texture$1.generateMipmaps = true;
  27276. this.texture.type = texture$1.type;
  27277. this.texture.colorSpace = texture$1.colorSpace;
  27278. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27279. this.texture.minFilter = texture$1.minFilter;
  27280. this.texture.magFilter = texture$1.magFilter;
  27281. const geometry = new BoxGeometry( 5, 5, 5 );
  27282. const uvNode = equirectUV( positionWorldDirection );
  27283. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27284. material.colorNode = texture( texture$1, uvNode, 0 );
  27285. material.side = BackSide;
  27286. material.blending = NoBlending;
  27287. const mesh = new Mesh( geometry, material );
  27288. const scene = new Scene();
  27289. scene.add( mesh );
  27290. // Avoid blurred poles
  27291. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27292. const camera = new CubeCamera( 1, 10, this );
  27293. camera.update( renderer, scene );
  27294. texture$1.minFilter = currentMinFilter;
  27295. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27296. mesh.geometry.dispose();
  27297. mesh.material.dispose();
  27298. return this;
  27299. }
  27300. }
  27301. // These defines must match with PMREMGenerator
  27302. const cubeUV_r0 = float( 1.0 );
  27303. const cubeUV_m0 = float( - 2.0 );
  27304. const cubeUV_r1 = float( 0.8 );
  27305. const cubeUV_m1 = float( - 1.0 );
  27306. const cubeUV_r4 = float( 0.4 );
  27307. const cubeUV_m4 = float( 2.0 );
  27308. const cubeUV_r5 = float( 0.305 );
  27309. const cubeUV_m5 = float( 3.0 );
  27310. const cubeUV_r6 = float( 0.21 );
  27311. const cubeUV_m6 = float( 4.0 );
  27312. const cubeUV_minMipLevel = float( 4.0 );
  27313. const cubeUV_minTileSize = float( 16.0 );
  27314. // These shader functions convert between the UV coordinates of a single face of
  27315. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27316. // sampling a textureCube (not generally normalized ).
  27317. const getFace = tslFn( ( [ direction ] ) => {
  27318. const absDirection = vec3( abs( direction ) ).toVar();
  27319. const face = float( - 1.0 ).toVar();
  27320. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27321. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27322. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27323. } ).else( () => {
  27324. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27325. } );
  27326. } ).else( () => {
  27327. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27328. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27329. } ).else( () => {
  27330. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27331. } );
  27332. } );
  27333. return face;
  27334. } ).setLayout( {
  27335. name: 'getFace',
  27336. type: 'float',
  27337. inputs: [
  27338. { name: 'direction', type: 'vec3' }
  27339. ]
  27340. } );
  27341. // RH coordinate system; PMREM face-indexing convention
  27342. const getUV = tslFn( ( [ direction, face ] ) => {
  27343. const uv = vec2().toVar();
  27344. If( face.equal( 0.0 ), () => {
  27345. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27346. } ).elseif( face.equal( 1.0 ), () => {
  27347. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27348. } ).elseif( face.equal( 2.0 ), () => {
  27349. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27350. } ).elseif( face.equal( 3.0 ), () => {
  27351. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27352. } ).elseif( face.equal( 4.0 ), () => {
  27353. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27354. } ).else( () => {
  27355. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27356. } );
  27357. return mul( 0.5, uv.add( 1.0 ) );
  27358. } ).setLayout( {
  27359. name: 'getUV',
  27360. type: 'vec2',
  27361. inputs: [
  27362. { name: 'direction', type: 'vec3' },
  27363. { name: 'face', type: 'float' }
  27364. ]
  27365. } );
  27366. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  27367. const mip = float( 0.0 ).toVar();
  27368. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27369. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27370. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27371. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27372. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27373. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27374. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27375. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27376. } ).else( () => {
  27377. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27378. } );
  27379. return mip;
  27380. } ).setLayout( {
  27381. name: 'roughnessToMip',
  27382. type: 'float',
  27383. inputs: [
  27384. { name: 'roughness', type: 'float' }
  27385. ]
  27386. } );
  27387. // RH coordinate system; PMREM face-indexing convention
  27388. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  27389. const uv = uv_immutable.toVar();
  27390. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27391. const direction = vec3( uv, 1.0 ).toVar();
  27392. If( face.equal( 0.0 ), () => {
  27393. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27394. } ).elseif( face.equal( 1.0 ), () => {
  27395. direction.assign( direction.xzy );
  27396. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27397. } ).elseif( face.equal( 2.0 ), () => {
  27398. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27399. } ).elseif( face.equal( 3.0 ), () => {
  27400. direction.assign( direction.zyx );
  27401. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27402. } ).elseif( face.equal( 4.0 ), () => {
  27403. direction.assign( direction.xzy );
  27404. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27405. } ).elseif( face.equal( 5.0 ), () => {
  27406. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27407. } );
  27408. return direction;
  27409. } ).setLayout( {
  27410. name: 'getDirection',
  27411. type: 'vec3',
  27412. inputs: [
  27413. { name: 'uv', type: 'vec2' },
  27414. { name: 'face', type: 'float' }
  27415. ]
  27416. } );
  27417. //
  27418. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27419. const roughness = float( roughness_immutable );
  27420. const sampleDir = vec3( sampleDir_immutable );
  27421. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27422. const mipF = fract( mip );
  27423. const mipInt = floor( mip );
  27424. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27425. If( mipF.notEqual( 0.0 ), () => {
  27426. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27427. color0.assign( mix( color0, color1, mipF ) );
  27428. } );
  27429. return color0;
  27430. } );
  27431. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27432. const mipInt = float( mipInt_immutable ).toVar();
  27433. const direction = vec3( direction_immutable );
  27434. const face = float( getFace( direction ) ).toVar();
  27435. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27436. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27437. const faceSize = float( exp2( mipInt ) ).toVar();
  27438. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27439. If( face.greaterThan( 2.0 ), () => {
  27440. uv.y.addAssign( faceSize );
  27441. face.subAssign( 3.0 );
  27442. } );
  27443. uv.x.addAssign( face.mul( faceSize ) );
  27444. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27445. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27446. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27447. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27448. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27449. } );
  27450. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27451. const cosTheta = cos( theta );
  27452. // Rodrigues' axis-angle rotation
  27453. const sampleDirection = outputDirection.mul( cosTheta )
  27454. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27455. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27456. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27457. } );
  27458. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27459. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27460. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27461. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27462. } );
  27463. axis.assign( normalize( axis ) );
  27464. const gl_FragColor = vec3().toVar();
  27465. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27466. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27467. If( i.greaterThanEqual( samples ), () => {
  27468. Break();
  27469. } );
  27470. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27471. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27472. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27473. } );
  27474. return vec4( gl_FragColor, 1 );
  27475. } );
  27476. const LOD_MIN = 4;
  27477. // The standard deviations (radians) associated with the extra mips. These are
  27478. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27479. // geometric shadowing function. These sigma values squared must match the
  27480. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27481. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27482. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27483. // samples and exit early, but not recompile the shader.
  27484. const MAX_SAMPLES = 20;
  27485. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27486. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27487. const _clearColor$2 = /*@__PURE__*/ new Color();
  27488. let _oldTarget = null;
  27489. let _oldActiveCubeFace = 0;
  27490. let _oldActiveMipmapLevel = 0;
  27491. // Golden Ratio
  27492. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27493. const INV_PHI = 1 / PHI;
  27494. // Vertices of a dodecahedron (except the opposites, which represent the
  27495. // same axis), used as axis directions evenly spread on a sphere.
  27496. const _axisDirections = [
  27497. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27498. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27499. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27500. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27501. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27502. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27503. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27504. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27505. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27506. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27507. ];
  27508. //
  27509. // WebGPU Face indices
  27510. const _faceLib = [
  27511. 3, 1, 5,
  27512. 0, 4, 2
  27513. ];
  27514. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27515. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27516. /**
  27517. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27518. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27519. * blur to be quickly accessed based on material roughness. It is packed into a
  27520. * special CubeUV format that allows us to perform custom interpolation so that
  27521. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27522. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27523. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27524. * higher roughness levels. In this way we maintain resolution to smoothly
  27525. * interpolate diffuse lighting while limiting sampling computation.
  27526. *
  27527. * Paper: Fast, Accurate Image-Based Lighting
  27528. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27529. */
  27530. class PMREMGenerator {
  27531. constructor( renderer ) {
  27532. this._renderer = renderer;
  27533. this._pingPongRenderTarget = null;
  27534. this._lodMax = 0;
  27535. this._cubeSize = 0;
  27536. this._lodPlanes = [];
  27537. this._sizeLods = [];
  27538. this._sigmas = [];
  27539. this._lodMeshes = [];
  27540. this._blurMaterial = null;
  27541. this._cubemapMaterial = null;
  27542. this._equirectMaterial = null;
  27543. this._backgroundBox = null;
  27544. }
  27545. /**
  27546. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27547. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27548. * in radians to be applied to the scene before PMREM generation. Optional near
  27549. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27550. * is placed at the origin).
  27551. */
  27552. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27553. _oldTarget = this._renderer.getRenderTarget();
  27554. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27555. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27556. this._setSize( 256 );
  27557. const cubeUVRenderTarget = this._allocateTargets();
  27558. cubeUVRenderTarget.depthBuffer = true;
  27559. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27560. if ( sigma > 0 ) {
  27561. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27562. }
  27563. this._applyPMREM( cubeUVRenderTarget );
  27564. this._cleanup( cubeUVRenderTarget );
  27565. return cubeUVRenderTarget;
  27566. }
  27567. /**
  27568. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27569. * or HDR. The ideal input image size is 1k (1024 x 512),
  27570. * as this matches best with the 256 x 256 cubemap output.
  27571. */
  27572. fromEquirectangular( equirectangular, renderTarget = null ) {
  27573. return this._fromTexture( equirectangular, renderTarget );
  27574. }
  27575. /**
  27576. * Generates a PMREM from an cubemap texture, which can be either LDR
  27577. * or HDR. The ideal input cube size is 256 x 256,
  27578. * as this matches best with the 256 x 256 cubemap output.
  27579. */
  27580. fromCubemap( cubemap, renderTarget = null ) {
  27581. return this._fromTexture( cubemap, renderTarget );
  27582. }
  27583. /**
  27584. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27585. * your texture's network fetch for increased concurrency.
  27586. */
  27587. compileCubemapShader() {
  27588. if ( this._cubemapMaterial === null ) {
  27589. this._cubemapMaterial = _getCubemapMaterial();
  27590. this._compileMaterial( this._cubemapMaterial );
  27591. }
  27592. }
  27593. /**
  27594. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27595. * your texture's network fetch for increased concurrency.
  27596. */
  27597. compileEquirectangularShader() {
  27598. if ( this._equirectMaterial === null ) {
  27599. this._equirectMaterial = _getEquirectMaterial();
  27600. this._compileMaterial( this._equirectMaterial );
  27601. }
  27602. }
  27603. /**
  27604. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27605. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27606. * one of them will cause any others to also become unusable.
  27607. */
  27608. dispose() {
  27609. this._dispose();
  27610. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27611. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27612. if ( this._backgroundBox !== null ) {
  27613. this._backgroundBox.geometry.dispose();
  27614. this._backgroundBox.material.dispose();
  27615. }
  27616. }
  27617. // private interface
  27618. _setSize( cubeSize ) {
  27619. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27620. this._cubeSize = Math.pow( 2, this._lodMax );
  27621. }
  27622. _dispose() {
  27623. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27624. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27625. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27626. this._lodPlanes[ i ].dispose();
  27627. }
  27628. }
  27629. _cleanup( outputTarget ) {
  27630. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27631. outputTarget.scissorTest = false;
  27632. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27633. }
  27634. _fromTexture( texture, renderTarget ) {
  27635. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27636. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27637. } else { // Equirectangular
  27638. this._setSize( texture.image.width / 4 );
  27639. }
  27640. _oldTarget = this._renderer.getRenderTarget();
  27641. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27642. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27643. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27644. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27645. this._applyPMREM( cubeUVRenderTarget );
  27646. this._cleanup( cubeUVRenderTarget );
  27647. return cubeUVRenderTarget;
  27648. }
  27649. _allocateTargets() {
  27650. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27651. const height = 4 * this._cubeSize;
  27652. const params = {
  27653. magFilter: LinearFilter,
  27654. minFilter: LinearFilter,
  27655. generateMipmaps: false,
  27656. type: HalfFloatType,
  27657. format: RGBAFormat,
  27658. colorSpace: LinearSRGBColorSpace,
  27659. //depthBuffer: false
  27660. };
  27661. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27662. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27663. if ( this._pingPongRenderTarget !== null ) {
  27664. this._dispose();
  27665. }
  27666. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27667. const { _lodMax } = this;
  27668. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27669. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27670. }
  27671. return cubeUVRenderTarget;
  27672. }
  27673. _compileMaterial( material ) {
  27674. const tmpMesh = this._lodMeshes[ 0 ];
  27675. tmpMesh.material = material;
  27676. this._renderer.compile( tmpMesh, _flatCamera );
  27677. }
  27678. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27679. const cubeCamera = _cubeCamera;
  27680. cubeCamera.near = near;
  27681. cubeCamera.far = far;
  27682. // px, py, pz, nx, ny, nz
  27683. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27684. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27685. const renderer = this._renderer;
  27686. const originalAutoClear = renderer.autoClear;
  27687. renderer.getClearColor( _clearColor$2 );
  27688. renderer.autoClear = false;
  27689. let backgroundBox = this._backgroundBox;
  27690. if ( backgroundBox === null ) {
  27691. const backgroundMaterial = new MeshBasicMaterial( {
  27692. name: 'PMREM.Background',
  27693. side: BackSide,
  27694. depthWrite: false,
  27695. depthTest: false
  27696. } );
  27697. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27698. }
  27699. let useSolidColor = false;
  27700. const background = scene.background;
  27701. if ( background ) {
  27702. if ( background.isColor ) {
  27703. backgroundBox.material.color.copy( background );
  27704. scene.background = null;
  27705. useSolidColor = true;
  27706. }
  27707. } else {
  27708. backgroundBox.material.color.copy( _clearColor$2 );
  27709. useSolidColor = true;
  27710. }
  27711. renderer.setRenderTarget( cubeUVRenderTarget );
  27712. renderer.clear();
  27713. if ( useSolidColor ) {
  27714. renderer.render( backgroundBox, cubeCamera );
  27715. }
  27716. for ( let i = 0; i < 6; i ++ ) {
  27717. const col = i % 3;
  27718. if ( col === 0 ) {
  27719. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27720. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27721. } else if ( col === 1 ) {
  27722. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27723. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27724. } else {
  27725. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27726. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27727. }
  27728. const size = this._cubeSize;
  27729. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27730. renderer.render( scene, cubeCamera );
  27731. }
  27732. renderer.autoClear = originalAutoClear;
  27733. scene.background = background;
  27734. }
  27735. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27736. const renderer = this._renderer;
  27737. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27738. if ( isCubeTexture ) {
  27739. if ( this._cubemapMaterial === null ) {
  27740. this._cubemapMaterial = _getCubemapMaterial( texture );
  27741. }
  27742. } else {
  27743. if ( this._equirectMaterial === null ) {
  27744. this._equirectMaterial = _getEquirectMaterial( texture );
  27745. }
  27746. }
  27747. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27748. material.fragmentNode.value = texture;
  27749. const mesh = this._lodMeshes[ 0 ];
  27750. mesh.material = material;
  27751. const size = this._cubeSize;
  27752. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27753. renderer.setRenderTarget( cubeUVRenderTarget );
  27754. renderer.render( mesh, _flatCamera );
  27755. }
  27756. _applyPMREM( cubeUVRenderTarget ) {
  27757. const renderer = this._renderer;
  27758. const autoClear = renderer.autoClear;
  27759. renderer.autoClear = false;
  27760. const n = this._lodPlanes.length;
  27761. for ( let i = 1; i < n; i ++ ) {
  27762. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27763. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27764. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27765. }
  27766. renderer.autoClear = autoClear;
  27767. }
  27768. /**
  27769. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27770. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27771. * the blur latitudinally (around the poles), and then longitudinally (towards
  27772. * the poles) to approximate the orthogonally-separable blur. It is least
  27773. * accurate at the poles, but still does a decent job.
  27774. */
  27775. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27776. const pingPongRenderTarget = this._pingPongRenderTarget;
  27777. this._halfBlur(
  27778. cubeUVRenderTarget,
  27779. pingPongRenderTarget,
  27780. lodIn,
  27781. lodOut,
  27782. sigma,
  27783. 'latitudinal',
  27784. poleAxis );
  27785. this._halfBlur(
  27786. pingPongRenderTarget,
  27787. cubeUVRenderTarget,
  27788. lodOut,
  27789. lodOut,
  27790. sigma,
  27791. 'longitudinal',
  27792. poleAxis );
  27793. }
  27794. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27795. const renderer = this._renderer;
  27796. const blurMaterial = this._blurMaterial;
  27797. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27798. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27799. }
  27800. // Number of standard deviations at which to cut off the discrete approximation.
  27801. const STANDARD_DEVIATIONS = 3;
  27802. const blurMesh = this._lodMeshes[ lodOut ];
  27803. blurMesh.material = blurMaterial;
  27804. const blurUniforms = blurMaterial.uniforms;
  27805. const pixels = this._sizeLods[ lodIn ] - 1;
  27806. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27807. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27808. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27809. if ( samples > MAX_SAMPLES ) {
  27810. console.warn( `sigmaRadians, ${
  27811. sigmaRadians}, is too large and will clip, as it requested ${
  27812. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27813. }
  27814. const weights = [];
  27815. let sum = 0;
  27816. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27817. const x = i / sigmaPixels;
  27818. const weight = Math.exp( - x * x / 2 );
  27819. weights.push( weight );
  27820. if ( i === 0 ) {
  27821. sum += weight;
  27822. } else if ( i < samples ) {
  27823. sum += 2 * weight;
  27824. }
  27825. }
  27826. for ( let i = 0; i < weights.length; i ++ ) {
  27827. weights[ i ] = weights[ i ] / sum;
  27828. }
  27829. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27830. blurUniforms.envMap.value = targetIn.texture;
  27831. blurUniforms.samples.value = samples;
  27832. blurUniforms.weights.array = weights;
  27833. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27834. if ( poleAxis ) {
  27835. blurUniforms.poleAxis.value = poleAxis;
  27836. }
  27837. const { _lodMax } = this;
  27838. blurUniforms.dTheta.value = radiansPerPixel;
  27839. blurUniforms.mipInt.value = _lodMax - lodIn;
  27840. const outputSize = this._sizeLods[ lodOut ];
  27841. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27842. const y = 4 * ( this._cubeSize - outputSize );
  27843. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27844. renderer.setRenderTarget( targetOut );
  27845. renderer.render( blurMesh, _flatCamera );
  27846. }
  27847. }
  27848. function _createPlanes( lodMax ) {
  27849. const lodPlanes = [];
  27850. const sizeLods = [];
  27851. const sigmas = [];
  27852. const lodMeshes = [];
  27853. let lod = lodMax;
  27854. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27855. for ( let i = 0; i < totalLods; i ++ ) {
  27856. const sizeLod = Math.pow( 2, lod );
  27857. sizeLods.push( sizeLod );
  27858. let sigma = 1.0 / sizeLod;
  27859. if ( i > lodMax - LOD_MIN ) {
  27860. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27861. } else if ( i === 0 ) {
  27862. sigma = 0;
  27863. }
  27864. sigmas.push( sigma );
  27865. const texelSize = 1.0 / ( sizeLod - 2 );
  27866. const min = - texelSize;
  27867. const max = 1 + texelSize;
  27868. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27869. const cubeFaces = 6;
  27870. const vertices = 6;
  27871. const positionSize = 3;
  27872. const uvSize = 2;
  27873. const faceIndexSize = 1;
  27874. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27875. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27876. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27877. for ( let face = 0; face < cubeFaces; face ++ ) {
  27878. const x = ( face % 3 ) * 2 / 3 - 1;
  27879. const y = face > 2 ? 0 : - 1;
  27880. const coordinates = [
  27881. x, y, 0,
  27882. x + 2 / 3, y, 0,
  27883. x + 2 / 3, y + 1, 0,
  27884. x, y, 0,
  27885. x + 2 / 3, y + 1, 0,
  27886. x, y + 1, 0
  27887. ];
  27888. const faceIdx = _faceLib[ face ];
  27889. position.set( coordinates, positionSize * vertices * faceIdx );
  27890. uv.set( uv1, uvSize * vertices * faceIdx );
  27891. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27892. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27893. }
  27894. const planes = new BufferGeometry();
  27895. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27896. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27897. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27898. lodPlanes.push( planes );
  27899. lodMeshes.push( new Mesh( planes, null ) );
  27900. if ( lod > LOD_MIN ) {
  27901. lod --;
  27902. }
  27903. }
  27904. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27905. }
  27906. function _createRenderTarget( width, height, params ) {
  27907. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27908. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27909. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27910. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27911. cubeUVRenderTarget.scissorTest = true;
  27912. return cubeUVRenderTarget;
  27913. }
  27914. function _setViewport( target, x, y, width, height ) {
  27915. const viewY = target.height - height - y;
  27916. target.viewport.set( x, viewY, width, height );
  27917. target.scissor.set( x, viewY, width, height );
  27918. }
  27919. function _getMaterial() {
  27920. const material = new NodeMaterial();
  27921. material.depthTest = false;
  27922. material.depthWrite = false;
  27923. material.blending = NoBlending;
  27924. return material;
  27925. }
  27926. function _getBlurShader( lodMax, width, height ) {
  27927. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  27928. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27929. const dTheta = uniform( 0 );
  27930. const n = float( MAX_SAMPLES );
  27931. const latitudinal = uniform( 0 ); // false, bool
  27932. const samples = uniform( 1 ); // int
  27933. const envMap = texture( null );
  27934. const mipInt = uniform( 0 ); // int
  27935. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27936. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27937. const CUBEUV_MAX_MIP = float( lodMax );
  27938. const materialUniforms = {
  27939. n,
  27940. latitudinal,
  27941. weights,
  27942. poleAxis,
  27943. outputDirection,
  27944. dTheta,
  27945. samples,
  27946. envMap,
  27947. mipInt,
  27948. CUBEUV_TEXEL_WIDTH,
  27949. CUBEUV_TEXEL_HEIGHT,
  27950. CUBEUV_MAX_MIP
  27951. };
  27952. const material = _getMaterial();
  27953. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27954. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27955. return material;
  27956. }
  27957. function _getCubemapMaterial( envTexture ) {
  27958. const material = _getMaterial();
  27959. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27960. return material;
  27961. }
  27962. function _getEquirectMaterial( envTexture ) {
  27963. const material = _getMaterial();
  27964. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27965. return material;
  27966. }
  27967. let _id$5 = 0;
  27968. class BindGroup {
  27969. constructor( name = '', bindings = [], index = 0 ) {
  27970. this.name = name;
  27971. this.bindings = bindings;
  27972. this.index = index;
  27973. this.id = _id$5 ++;
  27974. }
  27975. }
  27976. const rendererCache = new WeakMap();
  27977. const typeFromLength = new Map( [
  27978. [ 2, 'vec2' ],
  27979. [ 3, 'vec3' ],
  27980. [ 4, 'vec4' ],
  27981. [ 9, 'mat3' ],
  27982. [ 16, 'mat4' ]
  27983. ] );
  27984. const typeFromArray = new Map( [
  27985. [ Int8Array, 'int' ],
  27986. [ Int16Array, 'int' ],
  27987. [ Int32Array, 'int' ],
  27988. [ Uint8Array, 'uint' ],
  27989. [ Uint16Array, 'uint' ],
  27990. [ Uint32Array, 'uint' ],
  27991. [ Float32Array, 'float' ]
  27992. ] );
  27993. const toFloat = ( value ) => {
  27994. value = Number( value );
  27995. return value + ( value % 1 ? '' : '.0' );
  27996. };
  27997. class NodeBuilder {
  27998. constructor( object, renderer, parser ) {
  27999. this.object = object;
  28000. this.material = ( object && object.material ) || null;
  28001. this.geometry = ( object && object.geometry ) || null;
  28002. this.renderer = renderer;
  28003. this.parser = parser;
  28004. this.scene = null;
  28005. this.camera = null;
  28006. this.nodes = [];
  28007. this.updateNodes = [];
  28008. this.updateBeforeNodes = [];
  28009. this.updateAfterNodes = [];
  28010. this.hashNodes = {};
  28011. this.lightsNode = null;
  28012. this.environmentNode = null;
  28013. this.fogNode = null;
  28014. this.clippingContext = null;
  28015. this.vertexShader = null;
  28016. this.fragmentShader = null;
  28017. this.computeShader = null;
  28018. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  28019. this.flowCode = { vertex: '', fragment: '', compute: '' };
  28020. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  28021. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  28022. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  28023. this.bindingsIndexes = {};
  28024. this.bindGroups = null;
  28025. this.attributes = [];
  28026. this.bufferAttributes = [];
  28027. this.varyings = [];
  28028. this.codes = {};
  28029. this.vars = {};
  28030. this.flow = { code: '' };
  28031. this.chaining = [];
  28032. this.stack = stack();
  28033. this.stacks = [];
  28034. this.tab = '\t';
  28035. this.instanceBindGroups = true;
  28036. this.currentFunctionNode = null;
  28037. this.context = {
  28038. keywords: new NodeKeywords(),
  28039. material: this.material
  28040. };
  28041. this.cache = new NodeCache();
  28042. this.globalCache = this.cache;
  28043. this.flowsData = new WeakMap();
  28044. this.shaderStage = null;
  28045. this.buildStage = null;
  28046. }
  28047. getBingGroupsCache() {
  28048. let bindGroupsCache = rendererCache.get( this.renderer );
  28049. if ( bindGroupsCache === undefined ) {
  28050. bindGroupsCache = new ChainMap();
  28051. rendererCache.set( this.renderer, bindGroupsCache );
  28052. }
  28053. return bindGroupsCache;
  28054. }
  28055. createRenderTarget( width, height, options ) {
  28056. return new RenderTarget( width, height, options );
  28057. }
  28058. createCubeRenderTarget( size, options ) {
  28059. return new CubeRenderTarget( size, options );
  28060. }
  28061. createPMREMGenerator() {
  28062. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28063. return new PMREMGenerator( this.renderer );
  28064. }
  28065. includes( node ) {
  28066. return this.nodes.includes( node );
  28067. }
  28068. _getBindGroup( groupName, bindings ) {
  28069. const bindGroupsCache = this.getBingGroupsCache();
  28070. //
  28071. const bindingsArray = [];
  28072. let sharedGroup = true;
  28073. for ( const binding of bindings ) {
  28074. bindingsArray.push( binding );
  28075. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  28076. }
  28077. //
  28078. let bindGroup;
  28079. if ( sharedGroup ) {
  28080. bindGroup = bindGroupsCache.get( bindingsArray );
  28081. if ( bindGroup === undefined ) {
  28082. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group );
  28083. bindGroupsCache.set( bindingsArray, bindGroup );
  28084. }
  28085. } else {
  28086. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group );
  28087. }
  28088. return bindGroup;
  28089. }
  28090. getBindGroupArray( groupName, shaderStage ) {
  28091. const bindings = this.bindings[ shaderStage ];
  28092. let bindGroup = bindings[ groupName ];
  28093. if ( bindGroup === undefined ) {
  28094. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28095. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28096. }
  28097. bindings[ groupName ] = bindGroup = [];
  28098. }
  28099. return bindGroup;
  28100. }
  28101. getBindings() {
  28102. let bindingsGroups = this.bindGroups;
  28103. if ( bindingsGroups === null ) {
  28104. const groups = {};
  28105. const bindings = this.bindings;
  28106. for ( const shaderStage of shaderStages ) {
  28107. for ( const groupName in bindings[ shaderStage ] ) {
  28108. const uniforms = bindings[ shaderStage ][ groupName ];
  28109. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28110. groupUniforms.push( ...uniforms );
  28111. }
  28112. }
  28113. bindingsGroups = [];
  28114. for ( const groupName in groups ) {
  28115. const group = groups[ groupName ];
  28116. const bindingsGroup = this._getBindGroup( groupName, group );
  28117. bindingsGroups.push( bindingsGroup );
  28118. }
  28119. this.bindGroups = bindingsGroups;
  28120. }
  28121. return bindingsGroups;
  28122. }
  28123. setHashNode( node, hash ) {
  28124. this.hashNodes[ hash ] = node;
  28125. }
  28126. addNode( node ) {
  28127. if ( this.nodes.includes( node ) === false ) {
  28128. this.nodes.push( node );
  28129. this.setHashNode( node, node.getHash( this ) );
  28130. }
  28131. }
  28132. buildUpdateNodes() {
  28133. for ( const node of this.nodes ) {
  28134. const updateType = node.getUpdateType();
  28135. const updateBeforeType = node.getUpdateBeforeType();
  28136. const updateAfterType = node.getUpdateAfterType();
  28137. if ( updateType !== NodeUpdateType.NONE ) {
  28138. this.updateNodes.push( node.getSelf() );
  28139. }
  28140. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28141. this.updateBeforeNodes.push( node );
  28142. }
  28143. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28144. this.updateAfterNodes.push( node );
  28145. }
  28146. }
  28147. }
  28148. get currentNode() {
  28149. return this.chaining[ this.chaining.length - 1 ];
  28150. }
  28151. isFilteredTexture( texture ) {
  28152. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28153. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28154. }
  28155. addChain( node ) {
  28156. /*
  28157. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28158. console.warn( 'Recursive node: ', node );
  28159. }
  28160. */
  28161. this.chaining.push( node );
  28162. }
  28163. removeChain( node ) {
  28164. const lastChain = this.chaining.pop();
  28165. if ( lastChain !== node ) {
  28166. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28167. }
  28168. }
  28169. getMethod( method ) {
  28170. return method;
  28171. }
  28172. getNodeFromHash( hash ) {
  28173. return this.hashNodes[ hash ];
  28174. }
  28175. addFlow( shaderStage, node ) {
  28176. this.flowNodes[ shaderStage ].push( node );
  28177. return node;
  28178. }
  28179. setContext( context ) {
  28180. this.context = context;
  28181. }
  28182. getContext() {
  28183. return this.context;
  28184. }
  28185. getSharedContext() {
  28186. ({ ...this.context });
  28187. return this.context;
  28188. }
  28189. setCache( cache ) {
  28190. this.cache = cache;
  28191. }
  28192. getCache() {
  28193. return this.cache;
  28194. }
  28195. getCacheFromNode( node, parent = true ) {
  28196. const data = this.getDataFromNode( node );
  28197. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28198. return data.cache;
  28199. }
  28200. isAvailable( /*name*/ ) {
  28201. return false;
  28202. }
  28203. getVertexIndex() {
  28204. console.warn( 'Abstract function.' );
  28205. }
  28206. getInstanceIndex() {
  28207. console.warn( 'Abstract function.' );
  28208. }
  28209. getDrawIndex() {
  28210. console.warn( 'Abstract function.' );
  28211. }
  28212. getFrontFacing() {
  28213. console.warn( 'Abstract function.' );
  28214. }
  28215. getFragCoord() {
  28216. console.warn( 'Abstract function.' );
  28217. }
  28218. isFlipY() {
  28219. return false;
  28220. }
  28221. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28222. console.warn( 'Abstract function.' );
  28223. }
  28224. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28225. console.warn( 'Abstract function.' );
  28226. }
  28227. generateConst( type, value = null ) {
  28228. if ( value === null ) {
  28229. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28230. else if ( type === 'bool' ) value = false;
  28231. else if ( type === 'color' ) value = new Color();
  28232. else if ( type === 'vec2' ) value = new Vector2();
  28233. else if ( type === 'vec3' ) value = new Vector3();
  28234. else if ( type === 'vec4' ) value = new Vector4();
  28235. }
  28236. if ( type === 'float' ) return toFloat( value );
  28237. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28238. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28239. if ( type === 'bool' ) return value ? 'true' : 'false';
  28240. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28241. const typeLength = this.getTypeLength( type );
  28242. const componentType = this.getComponentType( type );
  28243. const generateConst = value => this.generateConst( componentType, value );
  28244. if ( typeLength === 2 ) {
  28245. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28246. } else if ( typeLength === 3 ) {
  28247. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28248. } else if ( typeLength === 4 ) {
  28249. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28250. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28251. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28252. } else if ( typeLength > 4 ) {
  28253. return `${ this.getType( type ) }()`;
  28254. }
  28255. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28256. }
  28257. getType( type ) {
  28258. if ( type === 'color' ) return 'vec3';
  28259. return type;
  28260. }
  28261. hasGeometryAttribute( name ) {
  28262. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28263. }
  28264. getAttribute( name, type ) {
  28265. const attributes = this.attributes;
  28266. // find attribute
  28267. for ( const attribute of attributes ) {
  28268. if ( attribute.name === name ) {
  28269. return attribute;
  28270. }
  28271. }
  28272. // create a new if no exist
  28273. const attribute = new NodeAttribute( name, type );
  28274. attributes.push( attribute );
  28275. return attribute;
  28276. }
  28277. getPropertyName( node/*, shaderStage*/ ) {
  28278. return node.name;
  28279. }
  28280. isVector( type ) {
  28281. return /vec\d/.test( type );
  28282. }
  28283. isMatrix( type ) {
  28284. return /mat\d/.test( type );
  28285. }
  28286. isReference( type ) {
  28287. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28288. }
  28289. needsColorSpaceToLinear( /*texture*/ ) {
  28290. return false;
  28291. }
  28292. getComponentTypeFromTexture( texture ) {
  28293. const type = texture.type;
  28294. if ( texture.isDataTexture ) {
  28295. if ( type === IntType ) return 'int';
  28296. if ( type === UnsignedIntType ) return 'uint';
  28297. }
  28298. return 'float';
  28299. }
  28300. getElementType( type ) {
  28301. if ( type === 'mat2' ) return 'vec2';
  28302. if ( type === 'mat3' ) return 'vec3';
  28303. if ( type === 'mat4' ) return 'vec4';
  28304. return this.getComponentType( type );
  28305. }
  28306. getComponentType( type ) {
  28307. type = this.getVectorType( type );
  28308. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28309. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28310. if ( componentType === null ) return null;
  28311. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28312. if ( componentType[ 1 ] === 'i' ) return 'int';
  28313. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28314. return 'float';
  28315. }
  28316. getVectorType( type ) {
  28317. if ( type === 'color' ) return 'vec3';
  28318. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28319. return type;
  28320. }
  28321. getTypeFromLength( length, componentType = 'float' ) {
  28322. if ( length === 1 ) return componentType;
  28323. const baseType = typeFromLength.get( length );
  28324. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28325. return prefix + baseType;
  28326. }
  28327. getTypeFromArray( array ) {
  28328. return typeFromArray.get( array.constructor );
  28329. }
  28330. getTypeFromAttribute( attribute ) {
  28331. let dataAttribute = attribute;
  28332. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28333. const array = dataAttribute.array;
  28334. const itemSize = attribute.itemSize;
  28335. const normalized = attribute.normalized;
  28336. let arrayType;
  28337. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28338. arrayType = this.getTypeFromArray( array );
  28339. }
  28340. return this.getTypeFromLength( itemSize, arrayType );
  28341. }
  28342. getTypeLength( type ) {
  28343. const vecType = this.getVectorType( type );
  28344. const vecNum = /vec([2-4])/.exec( vecType );
  28345. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28346. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28347. if ( /mat2/.test( type ) === true ) return 4;
  28348. if ( /mat3/.test( type ) === true ) return 9;
  28349. if ( /mat4/.test( type ) === true ) return 16;
  28350. return 0;
  28351. }
  28352. getVectorFromMatrix( type ) {
  28353. return type.replace( 'mat', 'vec' );
  28354. }
  28355. changeComponentType( type, newComponentType ) {
  28356. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28357. }
  28358. getIntegerType( type ) {
  28359. const componentType = this.getComponentType( type );
  28360. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28361. return this.changeComponentType( type, 'int' );
  28362. }
  28363. addStack() {
  28364. this.stack = stack( this.stack );
  28365. this.stacks.push( getCurrentStack() || this.stack );
  28366. setCurrentStack( this.stack );
  28367. return this.stack;
  28368. }
  28369. removeStack() {
  28370. const lastStack = this.stack;
  28371. this.stack = lastStack.parent;
  28372. setCurrentStack( this.stacks.pop() );
  28373. return lastStack;
  28374. }
  28375. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28376. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28377. let nodeData = cache.getData( node );
  28378. if ( nodeData === undefined ) {
  28379. nodeData = {};
  28380. cache.setData( node, nodeData );
  28381. }
  28382. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28383. return nodeData[ shaderStage ];
  28384. }
  28385. getNodeProperties( node, shaderStage = 'any' ) {
  28386. const nodeData = this.getDataFromNode( node, shaderStage );
  28387. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28388. }
  28389. getBufferAttributeFromNode( node, type ) {
  28390. const nodeData = this.getDataFromNode( node );
  28391. let bufferAttribute = nodeData.bufferAttribute;
  28392. if ( bufferAttribute === undefined ) {
  28393. const index = this.uniforms.index ++;
  28394. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28395. this.bufferAttributes.push( bufferAttribute );
  28396. nodeData.bufferAttribute = bufferAttribute;
  28397. }
  28398. return bufferAttribute;
  28399. }
  28400. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28401. const nodeData = this.getDataFromNode( node, shaderStage );
  28402. if ( nodeData.structType === undefined ) {
  28403. const index = this.structs.index ++;
  28404. node.name = `StructType${ index }`;
  28405. this.structs[ shaderStage ].push( node );
  28406. nodeData.structType = node;
  28407. }
  28408. return node;
  28409. }
  28410. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28411. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28412. let nodeUniform = nodeData.uniform;
  28413. if ( nodeUniform === undefined ) {
  28414. const index = this.uniforms.index ++;
  28415. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28416. this.uniforms[ shaderStage ].push( nodeUniform );
  28417. nodeData.uniform = nodeUniform;
  28418. }
  28419. return nodeUniform;
  28420. }
  28421. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28422. const nodeData = this.getDataFromNode( node, shaderStage );
  28423. let nodeVar = nodeData.variable;
  28424. if ( nodeVar === undefined ) {
  28425. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28426. if ( name === null ) name = 'nodeVar' + vars.length;
  28427. nodeVar = new NodeVar( name, type );
  28428. vars.push( nodeVar );
  28429. nodeData.variable = nodeVar;
  28430. }
  28431. return nodeVar;
  28432. }
  28433. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28434. const nodeData = this.getDataFromNode( node, 'any' );
  28435. let nodeVarying = nodeData.varying;
  28436. if ( nodeVarying === undefined ) {
  28437. const varyings = this.varyings;
  28438. const index = varyings.length;
  28439. if ( name === null ) name = 'nodeVarying' + index;
  28440. nodeVarying = new NodeVarying( name, type );
  28441. varyings.push( nodeVarying );
  28442. nodeData.varying = nodeVarying;
  28443. }
  28444. return nodeVarying;
  28445. }
  28446. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28447. const nodeData = this.getDataFromNode( node );
  28448. let nodeCode = nodeData.code;
  28449. if ( nodeCode === undefined ) {
  28450. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28451. const index = codes.length;
  28452. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28453. codes.push( nodeCode );
  28454. nodeData.code = nodeCode;
  28455. }
  28456. return nodeCode;
  28457. }
  28458. addLineFlowCode( code ) {
  28459. if ( code === '' ) return this;
  28460. code = this.tab + code;
  28461. if ( ! /;\s*$/.test( code ) ) {
  28462. code = code + ';\n';
  28463. }
  28464. this.flow.code += code;
  28465. return this;
  28466. }
  28467. addFlowCode( code ) {
  28468. this.flow.code += code;
  28469. return this;
  28470. }
  28471. addFlowTab() {
  28472. this.tab += '\t';
  28473. return this;
  28474. }
  28475. removeFlowTab() {
  28476. this.tab = this.tab.slice( 0, - 1 );
  28477. return this;
  28478. }
  28479. getFlowData( node/*, shaderStage*/ ) {
  28480. return this.flowsData.get( node );
  28481. }
  28482. flowNode( node ) {
  28483. const output = node.getNodeType( this );
  28484. const flowData = this.flowChildNode( node, output );
  28485. this.flowsData.set( node, flowData );
  28486. return flowData;
  28487. }
  28488. buildFunctionNode( shaderNode ) {
  28489. const fn = new FunctionNode();
  28490. const previous = this.currentFunctionNode;
  28491. this.currentFunctionNode = fn;
  28492. fn.code = this.buildFunctionCode( shaderNode );
  28493. this.currentFunctionNode = previous;
  28494. return fn;
  28495. }
  28496. flowShaderNode( shaderNode ) {
  28497. const layout = shaderNode.layout;
  28498. let inputs;
  28499. if ( shaderNode.isArrayInput ) {
  28500. inputs = [];
  28501. for ( const input of layout.inputs ) {
  28502. inputs.push( new ParameterNode( input.type, input.name ) );
  28503. }
  28504. } else {
  28505. inputs = {};
  28506. for ( const input of layout.inputs ) {
  28507. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28508. }
  28509. }
  28510. //
  28511. shaderNode.layout = null;
  28512. const callNode = shaderNode.call( inputs );
  28513. const flowData = this.flowStagesNode( callNode, layout.type );
  28514. shaderNode.layout = layout;
  28515. return flowData;
  28516. }
  28517. flowStagesNode( node, output = null ) {
  28518. const previousFlow = this.flow;
  28519. const previousVars = this.vars;
  28520. const previousCache = this.cache;
  28521. const previousBuildStage = this.buildStage;
  28522. const previousStack = this.stack;
  28523. const flow = {
  28524. code: ''
  28525. };
  28526. this.flow = flow;
  28527. this.vars = {};
  28528. this.cache = new NodeCache();
  28529. this.stack = stack();
  28530. for ( const buildStage of defaultBuildStages ) {
  28531. this.setBuildStage( buildStage );
  28532. flow.result = node.build( this, output );
  28533. }
  28534. flow.vars = this.getVars( this.shaderStage );
  28535. this.flow = previousFlow;
  28536. this.vars = previousVars;
  28537. this.cache = previousCache;
  28538. this.stack = previousStack;
  28539. this.setBuildStage( previousBuildStage );
  28540. return flow;
  28541. }
  28542. getFunctionOperator() {
  28543. return null;
  28544. }
  28545. flowChildNode( node, output = null ) {
  28546. const previousFlow = this.flow;
  28547. const flow = {
  28548. code: ''
  28549. };
  28550. this.flow = flow;
  28551. flow.result = node.build( this, output );
  28552. this.flow = previousFlow;
  28553. return flow;
  28554. }
  28555. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28556. const previousShaderStage = this.shaderStage;
  28557. this.setShaderStage( shaderStage );
  28558. const flowData = this.flowChildNode( node, output );
  28559. if ( propertyName !== null ) {
  28560. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28561. }
  28562. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28563. this.setShaderStage( previousShaderStage );
  28564. return flowData;
  28565. }
  28566. getAttributesArray() {
  28567. return this.attributes.concat( this.bufferAttributes );
  28568. }
  28569. getAttributes( /*shaderStage*/ ) {
  28570. console.warn( 'Abstract function.' );
  28571. }
  28572. getVaryings( /*shaderStage*/ ) {
  28573. console.warn( 'Abstract function.' );
  28574. }
  28575. getVar( type, name ) {
  28576. return `${ this.getType( type ) } ${ name }`;
  28577. }
  28578. getVars( shaderStage ) {
  28579. let snippet = '';
  28580. const vars = this.vars[ shaderStage ];
  28581. if ( vars !== undefined ) {
  28582. for ( const variable of vars ) {
  28583. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28584. }
  28585. }
  28586. return snippet;
  28587. }
  28588. getUniforms( /*shaderStage*/ ) {
  28589. console.warn( 'Abstract function.' );
  28590. }
  28591. getCodes( shaderStage ) {
  28592. const codes = this.codes[ shaderStage ];
  28593. let code = '';
  28594. if ( codes !== undefined ) {
  28595. for ( const nodeCode of codes ) {
  28596. code += nodeCode.code + '\n';
  28597. }
  28598. }
  28599. return code;
  28600. }
  28601. getHash() {
  28602. return this.vertexShader + this.fragmentShader + this.computeShader;
  28603. }
  28604. setShaderStage( shaderStage ) {
  28605. this.shaderStage = shaderStage;
  28606. }
  28607. getShaderStage() {
  28608. return this.shaderStage;
  28609. }
  28610. setBuildStage( buildStage ) {
  28611. this.buildStage = buildStage;
  28612. }
  28613. getBuildStage() {
  28614. return this.buildStage;
  28615. }
  28616. buildCode() {
  28617. console.warn( 'Abstract function.' );
  28618. }
  28619. build() {
  28620. const { object, material } = this;
  28621. if ( material !== null ) {
  28622. NodeMaterial.fromMaterial( material ).build( this );
  28623. } else {
  28624. this.addFlow( 'compute', object );
  28625. }
  28626. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28627. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28628. // generate() -> stage 3: generate shader
  28629. for ( const buildStage of defaultBuildStages ) {
  28630. this.setBuildStage( buildStage );
  28631. if ( this.context.vertex && this.context.vertex.isNode ) {
  28632. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28633. }
  28634. for ( const shaderStage of shaderStages ) {
  28635. this.setShaderStage( shaderStage );
  28636. const flowNodes = this.flowNodes[ shaderStage ];
  28637. for ( const node of flowNodes ) {
  28638. if ( buildStage === 'generate' ) {
  28639. this.flowNode( node );
  28640. } else {
  28641. node.build( this );
  28642. }
  28643. }
  28644. }
  28645. }
  28646. this.setBuildStage( null );
  28647. this.setShaderStage( null );
  28648. // stage 4: build code for a specific output
  28649. this.buildCode();
  28650. this.buildUpdateNodes();
  28651. return this;
  28652. }
  28653. getNodeUniform( uniformNode, type ) {
  28654. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28655. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28656. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28657. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28658. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28659. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28660. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28661. throw new Error( `Uniform "${type}" not declared.` );
  28662. }
  28663. createNodeMaterial( type = 'NodeMaterial' ) {
  28664. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28665. return createNodeMaterialFromType( type );
  28666. }
  28667. format( snippet, fromType, toType ) {
  28668. fromType = this.getVectorType( fromType );
  28669. toType = this.getVectorType( toType );
  28670. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28671. return snippet;
  28672. }
  28673. const fromTypeLength = this.getTypeLength( fromType );
  28674. const toTypeLength = this.getTypeLength( toType );
  28675. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  28676. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  28677. }
  28678. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  28679. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  28680. }
  28681. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28682. // @TODO: ignore for now
  28683. return snippet;
  28684. }
  28685. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28686. // @TODO: ignore for now
  28687. return snippet;
  28688. }
  28689. if ( fromTypeLength === toTypeLength ) {
  28690. return `${ this.getType( toType ) }( ${ snippet } )`;
  28691. }
  28692. if ( fromTypeLength > toTypeLength ) {
  28693. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28694. }
  28695. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28696. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28697. }
  28698. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28699. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28700. }
  28701. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28702. // convert a number value to vector type, e.g:
  28703. // vec3( 1u ) -> vec3( float( 1u ) )
  28704. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28705. }
  28706. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28707. }
  28708. getSignature() {
  28709. return `// Three.js r${ REVISION } - Node System\n`;
  28710. }
  28711. }
  28712. class NodeFrame {
  28713. constructor() {
  28714. this.time = 0;
  28715. this.deltaTime = 0;
  28716. this.frameId = 0;
  28717. this.renderId = 0;
  28718. this.startTime = null;
  28719. this.updateMap = new WeakMap();
  28720. this.updateBeforeMap = new WeakMap();
  28721. this.updateAfterMap = new WeakMap();
  28722. this.renderer = null;
  28723. this.material = null;
  28724. this.camera = null;
  28725. this.object = null;
  28726. this.scene = null;
  28727. }
  28728. _getMaps( referenceMap, nodeRef ) {
  28729. let maps = referenceMap.get( nodeRef );
  28730. if ( maps === undefined ) {
  28731. maps = {
  28732. renderMap: new WeakMap(),
  28733. frameMap: new WeakMap()
  28734. };
  28735. referenceMap.set( nodeRef, maps );
  28736. }
  28737. return maps;
  28738. }
  28739. updateBeforeNode( node ) {
  28740. const updateType = node.getUpdateBeforeType();
  28741. const reference = node.updateReference( this );
  28742. if ( updateType === NodeUpdateType.FRAME ) {
  28743. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28744. if ( frameMap.get( reference ) !== this.frameId ) {
  28745. if ( node.updateBefore( this ) !== false ) {
  28746. frameMap.set( reference, this.frameId );
  28747. }
  28748. }
  28749. } else if ( updateType === NodeUpdateType.RENDER ) {
  28750. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28751. if ( renderMap.get( reference ) !== this.renderId ) {
  28752. if ( node.updateBefore( this ) !== false ) {
  28753. renderMap.set( reference, this.renderId );
  28754. }
  28755. }
  28756. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28757. node.updateBefore( this );
  28758. }
  28759. }
  28760. updateAfterNode( node ) {
  28761. const updateType = node.getUpdateAfterType();
  28762. const reference = node.updateReference( this );
  28763. if ( updateType === NodeUpdateType.FRAME ) {
  28764. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28765. if ( frameMap.get( reference ) !== this.frameId ) {
  28766. if ( node.updateAfter( this ) !== false ) {
  28767. frameMap.set( reference, this.frameId );
  28768. }
  28769. }
  28770. } else if ( updateType === NodeUpdateType.RENDER ) {
  28771. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28772. if ( renderMap.get( reference ) !== this.renderId ) {
  28773. if ( node.updateAfter( this ) !== false ) {
  28774. renderMap.set( reference, this.renderId );
  28775. }
  28776. }
  28777. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28778. node.updateAfter( this );
  28779. }
  28780. }
  28781. updateNode( node ) {
  28782. const updateType = node.getUpdateType();
  28783. const reference = node.updateReference( this );
  28784. if ( updateType === NodeUpdateType.FRAME ) {
  28785. const { frameMap } = this._getMaps( this.updateMap, reference );
  28786. if ( frameMap.get( reference ) !== this.frameId ) {
  28787. if ( node.update( this ) !== false ) {
  28788. frameMap.set( reference, this.frameId );
  28789. }
  28790. }
  28791. } else if ( updateType === NodeUpdateType.RENDER ) {
  28792. const { renderMap } = this._getMaps( this.updateMap, reference );
  28793. if ( renderMap.get( reference ) !== this.renderId ) {
  28794. if ( node.update( this ) !== false ) {
  28795. renderMap.set( reference, this.renderId );
  28796. }
  28797. }
  28798. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28799. node.update( this );
  28800. }
  28801. }
  28802. update() {
  28803. this.frameId ++;
  28804. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28805. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28806. this.lastTime = performance.now();
  28807. this.time += this.deltaTime;
  28808. }
  28809. }
  28810. class NodeFunctionInput {
  28811. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28812. this.type = type;
  28813. this.name = name;
  28814. this.count = count;
  28815. this.qualifier = qualifier;
  28816. this.isConst = isConst;
  28817. }
  28818. }
  28819. NodeFunctionInput.isNodeFunctionInput = true;
  28820. class StructTypeNode extends Node {
  28821. constructor( types ) {
  28822. super();
  28823. this.types = types;
  28824. this.isStructTypeNode = true;
  28825. }
  28826. getMemberTypes() {
  28827. return this.types;
  28828. }
  28829. }
  28830. addNodeClass( 'StructTypeNode', StructTypeNode );
  28831. class OutputStructNode extends Node {
  28832. constructor( ...members ) {
  28833. super();
  28834. this.members = members;
  28835. this.isOutputStructNode = true;
  28836. }
  28837. setup( builder ) {
  28838. super.setup( builder );
  28839. const members = this.members;
  28840. const types = [];
  28841. for ( let i = 0; i < members.length; i ++ ) {
  28842. types.push( members[ i ].getNodeType( builder ) );
  28843. }
  28844. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28845. }
  28846. generate( builder, output ) {
  28847. const propertyName = builder.getOutputStructName();
  28848. const members = this.members;
  28849. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28850. for ( let i = 0; i < members.length; i ++ ) {
  28851. const snippet = members[ i ].build( builder, output );
  28852. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28853. }
  28854. return propertyName;
  28855. }
  28856. }
  28857. const outputStruct = nodeProxy( OutputStructNode );
  28858. addNodeClass( 'OutputStructNode', OutputStructNode );
  28859. function getTextureIndex( textures, name ) {
  28860. for ( let i = 0; i < textures.length; i ++ ) {
  28861. if ( textures[ i ].name === name ) {
  28862. return i;
  28863. }
  28864. }
  28865. return - 1;
  28866. }
  28867. class MRTNode extends OutputStructNode {
  28868. constructor( outputNodes ) {
  28869. super();
  28870. this.outputNodes = outputNodes;
  28871. this.isMRTNode = true;
  28872. }
  28873. getNode( name ) {
  28874. return this.outputNodes[ name ];
  28875. }
  28876. merge( mrtNode ) {
  28877. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  28878. return mrt( outputs );
  28879. }
  28880. setup( builder ) {
  28881. const outputNodes = this.outputNodes;
  28882. const mrt = builder.renderer.getRenderTarget();
  28883. const members = [];
  28884. const textures = mrt.textures;
  28885. for ( const name in outputNodes ) {
  28886. const index = getTextureIndex( textures, name );
  28887. members[ index ] = vec4( outputNodes[ name ] );
  28888. }
  28889. this.members = members;
  28890. return super.setup( builder );
  28891. }
  28892. }
  28893. const mrt = nodeProxy( MRTNode );
  28894. addNodeClass( 'MRTNode', MRTNode );
  28895. class HashNode extends Node {
  28896. constructor( seedNode ) {
  28897. super();
  28898. this.seedNode = seedNode;
  28899. }
  28900. setup( /*builder*/ ) {
  28901. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28902. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28903. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28904. const result = word.shiftRight( 22 ).bitXor( word );
  28905. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28906. }
  28907. }
  28908. const hash = nodeProxy( HashNode );
  28909. addNodeElement( 'hash', hash );
  28910. addNodeClass( 'HashNode', HashNode );
  28911. // remapping functions https://iquilezles.org/articles/functions/
  28912. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28913. 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 ) );
  28914. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28915. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28916. addNodeElement( 'parabola', parabola );
  28917. addNodeElement( 'gain', gain );
  28918. addNodeElement( 'pcurve', pcurve );
  28919. addNodeElement( 'sinc', sinc );
  28920. // https://github.com/cabbibo/glsl-tri-noise-3d
  28921. const tri = tslFn( ( [ x ] ) => {
  28922. return x.fract().sub( .5 ).abs();
  28923. } );
  28924. const tri3 = tslFn( ( [ p ] ) => {
  28925. 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. ) ) ) ) );
  28926. } );
  28927. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28928. const p = vec3( p_immutable ).toVar();
  28929. const z = float( 1.4 ).toVar();
  28930. const rz = float( 0.0 ).toVar();
  28931. const bp = vec3( p ).toVar();
  28932. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28933. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28934. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28935. bp.mulAssign( 1.8 );
  28936. z.mulAssign( 1.5 );
  28937. p.mulAssign( 1.2 );
  28938. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28939. rz.addAssign( t.div( z ) );
  28940. bp.addAssign( 0.14 );
  28941. } );
  28942. return rz;
  28943. } );
  28944. // layouts
  28945. tri.setLayout( {
  28946. name: 'tri',
  28947. type: 'float',
  28948. inputs: [
  28949. { name: 'x', type: 'float' }
  28950. ]
  28951. } );
  28952. tri3.setLayout( {
  28953. name: 'tri3',
  28954. type: 'vec3',
  28955. inputs: [
  28956. { name: 'p', type: 'vec3' }
  28957. ]
  28958. } );
  28959. triNoise3D.setLayout( {
  28960. name: 'triNoise3D',
  28961. type: 'float',
  28962. inputs: [
  28963. { name: 'p', type: 'vec3' },
  28964. { name: 'spd', type: 'float' },
  28965. { name: 'time', type: 'float' }
  28966. ]
  28967. } );
  28968. let discardExpression;
  28969. class DiscardNode extends CondNode {
  28970. constructor( condNode ) {
  28971. discardExpression = discardExpression || expression( 'discard' );
  28972. super( condNode, discardExpression );
  28973. }
  28974. }
  28975. const inlineDiscard = nodeProxy( DiscardNode );
  28976. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28977. const Return = () => expression( 'return' ).append();
  28978. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28979. addNodeClass( 'DiscardNode', DiscardNode );
  28980. class FunctionOverloadingNode extends Node {
  28981. constructor( functionNodes = [], ...parametersNodes ) {
  28982. super();
  28983. this.functionNodes = functionNodes;
  28984. this.parametersNodes = parametersNodes;
  28985. this._candidateFnCall = null;
  28986. this.global = true;
  28987. }
  28988. getNodeType() {
  28989. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28990. }
  28991. setup( builder ) {
  28992. const params = this.parametersNodes;
  28993. let candidateFnCall = this._candidateFnCall;
  28994. if ( candidateFnCall === null ) {
  28995. let candidateFn = null;
  28996. let candidateScore = - 1;
  28997. for ( const functionNode of this.functionNodes ) {
  28998. const shaderNode = functionNode.shaderNode;
  28999. const layout = shaderNode.layout;
  29000. if ( layout === null ) {
  29001. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  29002. }
  29003. const inputs = layout.inputs;
  29004. if ( params.length === inputs.length ) {
  29005. let score = 0;
  29006. for ( let i = 0; i < params.length; i ++ ) {
  29007. const param = params[ i ];
  29008. const input = inputs[ i ];
  29009. if ( param.getNodeType( builder ) === input.type ) {
  29010. score ++;
  29011. } else {
  29012. score = 0;
  29013. }
  29014. }
  29015. if ( score > candidateScore ) {
  29016. candidateFn = functionNode;
  29017. candidateScore = score;
  29018. }
  29019. }
  29020. }
  29021. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  29022. }
  29023. return candidateFnCall;
  29024. }
  29025. }
  29026. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  29027. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  29028. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  29029. class MatcapUVNode extends TempNode {
  29030. constructor() {
  29031. super( 'vec2' );
  29032. }
  29033. setup() {
  29034. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29035. const y = positionViewDirection.cross( x );
  29036. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29037. }
  29038. }
  29039. const matcapUV = nodeImmutable( MatcapUVNode );
  29040. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  29041. class TimerNode extends UniformNode {
  29042. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  29043. super( value );
  29044. this.scope = scope;
  29045. this.scale = scale;
  29046. this.updateType = NodeUpdateType.FRAME;
  29047. }
  29048. /*
  29049. @TODO:
  29050. getNodeType( builder ) {
  29051. const scope = this.scope;
  29052. if ( scope === TimerNode.FRAME ) {
  29053. return 'uint';
  29054. }
  29055. return 'float';
  29056. }
  29057. */
  29058. update( frame ) {
  29059. const scope = this.scope;
  29060. const scale = this.scale;
  29061. if ( scope === TimerNode.LOCAL ) {
  29062. this.value += frame.deltaTime * scale;
  29063. } else if ( scope === TimerNode.DELTA ) {
  29064. this.value = frame.deltaTime * scale;
  29065. } else if ( scope === TimerNode.FRAME ) {
  29066. this.value = frame.frameId;
  29067. } else {
  29068. // global
  29069. this.value = frame.time * scale;
  29070. }
  29071. }
  29072. serialize( data ) {
  29073. super.serialize( data );
  29074. data.scope = this.scope;
  29075. data.scale = this.scale;
  29076. }
  29077. deserialize( data ) {
  29078. super.deserialize( data );
  29079. this.scope = data.scope;
  29080. this.scale = data.scale;
  29081. }
  29082. }
  29083. TimerNode.LOCAL = 'local';
  29084. TimerNode.GLOBAL = 'global';
  29085. TimerNode.DELTA = 'delta';
  29086. TimerNode.FRAME = 'frame';
  29087. // @TODO: add support to use node in timeScale
  29088. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29089. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29090. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29091. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29092. addNodeClass( 'TimerNode', TimerNode );
  29093. class OscNode extends Node {
  29094. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29095. super();
  29096. this.method = method;
  29097. this.timeNode = timeNode;
  29098. }
  29099. getNodeType( builder ) {
  29100. return this.timeNode.getNodeType( builder );
  29101. }
  29102. setup() {
  29103. const method = this.method;
  29104. const timeNode = nodeObject( this.timeNode );
  29105. let outputNode = null;
  29106. if ( method === OscNode.SINE ) {
  29107. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29108. } else if ( method === OscNode.SQUARE ) {
  29109. outputNode = timeNode.fract().round();
  29110. } else if ( method === OscNode.TRIANGLE ) {
  29111. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29112. } else if ( method === OscNode.SAWTOOTH ) {
  29113. outputNode = timeNode.fract();
  29114. }
  29115. return outputNode;
  29116. }
  29117. serialize( data ) {
  29118. super.serialize( data );
  29119. data.method = this.method;
  29120. }
  29121. deserialize( data ) {
  29122. super.deserialize( data );
  29123. this.method = data.method;
  29124. }
  29125. }
  29126. OscNode.SINE = 'sine';
  29127. OscNode.SQUARE = 'square';
  29128. OscNode.TRIANGLE = 'triangle';
  29129. OscNode.SAWTOOTH = 'sawtooth';
  29130. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29131. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29132. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29133. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29134. addNodeClass( 'OscNode', OscNode );
  29135. class PackingNode extends TempNode {
  29136. constructor( scope, node ) {
  29137. super();
  29138. this.scope = scope;
  29139. this.node = node;
  29140. }
  29141. getNodeType( builder ) {
  29142. return this.node.getNodeType( builder );
  29143. }
  29144. setup() {
  29145. const { scope, node } = this;
  29146. let result = null;
  29147. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29148. result = node.mul( 0.5 ).add( 0.5 );
  29149. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29150. result = node.mul( 2.0 ).sub( 1 );
  29151. }
  29152. return result;
  29153. }
  29154. }
  29155. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29156. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29157. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29158. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29159. addNodeElement( 'directionToColor', directionToColor );
  29160. addNodeElement( 'colorToDirection', colorToDirection );
  29161. addNodeClass( 'PackingNode', PackingNode );
  29162. class RemapNode extends Node {
  29163. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29164. super();
  29165. this.node = node;
  29166. this.inLowNode = inLowNode;
  29167. this.inHighNode = inHighNode;
  29168. this.outLowNode = outLowNode;
  29169. this.outHighNode = outHighNode;
  29170. this.doClamp = true;
  29171. }
  29172. setup() {
  29173. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29174. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29175. if ( doClamp === true ) t = t.clamp();
  29176. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29177. }
  29178. }
  29179. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29180. const remapClamp = nodeProxy( RemapNode );
  29181. addNodeElement( 'remap', remap );
  29182. addNodeElement( 'remapClamp', remapClamp );
  29183. addNodeClass( 'RemapNode', RemapNode );
  29184. const rotateUV = tslFn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  29185. return uv.sub( center ).rotate( rotation ).add( center );
  29186. } );
  29187. const spherizeUV = tslFn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  29188. const delta = uv.sub( center );
  29189. const delta2 = delta.dot( delta );
  29190. const delta4 = delta2.mul( delta2 );
  29191. const deltaOffset = delta4.mul( strength );
  29192. return uv.add( delta.mul( deltaOffset ) );
  29193. } );
  29194. addNodeElement( 'rotateUV', rotateUV );
  29195. addNodeElement( 'spherizeUV', spherizeUV );
  29196. const billboarding = tslFn( ( { position = null, horizontal = true, vertical = false } ) => {
  29197. let worldMatrix;
  29198. if ( position !== null ) {
  29199. worldMatrix = modelWorldMatrix.toVar();
  29200. worldMatrix[ 3 ][ 0 ] = position.x;
  29201. worldMatrix[ 3 ][ 1 ] = position.y;
  29202. worldMatrix[ 3 ][ 2 ] = position.z;
  29203. } else {
  29204. worldMatrix = modelWorldMatrix;
  29205. }
  29206. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  29207. if ( defined( horizontal ) ) {
  29208. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  29209. modelViewMatrix[ 0 ][ 1 ] = 0;
  29210. modelViewMatrix[ 0 ][ 2 ] = 0;
  29211. }
  29212. if ( defined( vertical ) ) {
  29213. modelViewMatrix[ 1 ][ 0 ] = 0;
  29214. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  29215. modelViewMatrix[ 1 ][ 2 ] = 0;
  29216. }
  29217. modelViewMatrix[ 2 ][ 0 ] = 0;
  29218. modelViewMatrix[ 2 ][ 1 ] = 0;
  29219. modelViewMatrix[ 2 ][ 2 ] = 1;
  29220. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  29221. } );
  29222. const viewportSafeUV = tslFn( ( [ uv = null ] ) => {
  29223. const depth = linearDepth();
  29224. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  29225. const finalUV = depthDiff.lessThan( 0 ).cond( viewportTopLeft, uv );
  29226. return finalUV;
  29227. } );
  29228. class RotateNode extends TempNode {
  29229. constructor( positionNode, rotationNode ) {
  29230. super();
  29231. this.positionNode = positionNode;
  29232. this.rotationNode = rotationNode;
  29233. }
  29234. getNodeType( builder ) {
  29235. return this.positionNode.getNodeType( builder );
  29236. }
  29237. setup( builder ) {
  29238. const { rotationNode, positionNode } = this;
  29239. const nodeType = this.getNodeType( builder );
  29240. if ( nodeType === 'vec2' ) {
  29241. const cosAngle = rotationNode.cos();
  29242. const sinAngle = rotationNode.sin();
  29243. const rotationMatrix = mat2(
  29244. cosAngle, sinAngle,
  29245. sinAngle.negate(), cosAngle
  29246. );
  29247. return rotationMatrix.mul( positionNode );
  29248. } else {
  29249. const rotation = rotationNode;
  29250. 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 ) );
  29251. 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 ) );
  29252. 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 ) );
  29253. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29254. }
  29255. }
  29256. }
  29257. const rotate = nodeProxy( RotateNode );
  29258. addNodeElement( 'rotate', rotate );
  29259. addNodeClass( 'RotateNode', RotateNode );
  29260. class SpriteSheetUVNode extends Node {
  29261. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29262. super( 'vec2' );
  29263. this.countNode = countNode;
  29264. this.uvNode = uvNode;
  29265. this.frameNode = frameNode;
  29266. }
  29267. setup() {
  29268. const { frameNode, uvNode, countNode } = this;
  29269. const { width, height } = countNode;
  29270. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29271. const column = frameNum.mod( width );
  29272. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29273. const scale = countNode.reciprocal();
  29274. const uvFrameOffset = vec2( column, row );
  29275. return uvNode.add( uvFrameOffset ).mul( scale );
  29276. }
  29277. }
  29278. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29279. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29280. class StorageArrayElementNode extends ArrayElementNode {
  29281. constructor( storageBufferNode, indexNode ) {
  29282. super( storageBufferNode, indexNode );
  29283. this.isStorageArrayElementNode = true;
  29284. }
  29285. set storageBufferNode( value ) {
  29286. this.node = value;
  29287. }
  29288. get storageBufferNode() {
  29289. return this.node;
  29290. }
  29291. setup( builder ) {
  29292. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29293. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29294. builder.setupPBO( this.node );
  29295. }
  29296. }
  29297. return super.setup( builder );
  29298. }
  29299. generate( builder, output ) {
  29300. let snippet;
  29301. const isAssignContext = builder.context.assign;
  29302. //
  29303. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29304. const { node } = this;
  29305. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29306. snippet = builder.generatePBO( this );
  29307. } else {
  29308. snippet = node.build( builder );
  29309. }
  29310. } else {
  29311. snippet = super.generate( builder );
  29312. }
  29313. if ( isAssignContext !== true ) {
  29314. const type = this.getNodeType( builder );
  29315. snippet = builder.format( snippet, type, output );
  29316. }
  29317. return snippet;
  29318. }
  29319. }
  29320. const storageElement = nodeProxy( StorageArrayElementNode );
  29321. addNodeElement( 'storageElement', storageElement );
  29322. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29323. class TriplanarTexturesNode extends Node {
  29324. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29325. super( 'vec4' );
  29326. this.textureXNode = textureXNode;
  29327. this.textureYNode = textureYNode;
  29328. this.textureZNode = textureZNode;
  29329. this.scaleNode = scaleNode;
  29330. this.positionNode = positionNode;
  29331. this.normalNode = normalNode;
  29332. }
  29333. setup() {
  29334. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29335. // Ref: https://github.com/keijiro/StandardTriplanar
  29336. // Blending factor of triplanar mapping
  29337. let bf = normalNode.abs().normalize();
  29338. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29339. // Triplanar mapping
  29340. const tx = positionNode.yz.mul( scaleNode );
  29341. const ty = positionNode.zx.mul( scaleNode );
  29342. const tz = positionNode.xy.mul( scaleNode );
  29343. // Base color
  29344. const textureX = textureXNode.value;
  29345. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29346. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29347. const cx = texture( textureX, tx ).mul( bf.x );
  29348. const cy = texture( textureY, ty ).mul( bf.y );
  29349. const cz = texture( textureZ, tz ).mul( bf.z );
  29350. return add( cx, cy, cz );
  29351. }
  29352. }
  29353. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29354. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29355. addNodeElement( 'triplanarTexture', triplanarTexture );
  29356. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29357. const _reflectorPlane = new Plane();
  29358. const _normal = new Vector3();
  29359. const _reflectorWorldPosition = new Vector3();
  29360. const _cameraWorldPosition = new Vector3();
  29361. const _rotationMatrix = new Matrix4();
  29362. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29363. const clipPlane = new Vector4();
  29364. const _view = new Vector3();
  29365. const _target = new Vector3();
  29366. const _q = new Vector4();
  29367. const _size$6 = new Vector2();
  29368. const _defaultRT = new RenderTarget();
  29369. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29370. let _inReflector = false;
  29371. class ReflectorNode extends TextureNode {
  29372. constructor( parameters = {} ) {
  29373. super( _defaultRT.texture, _defaultUV );
  29374. const {
  29375. target = new Object3D(),
  29376. resolution = 1,
  29377. generateMipmaps = false,
  29378. bounces = true
  29379. } = parameters;
  29380. //
  29381. this.target = target;
  29382. this.resolution = resolution;
  29383. this.generateMipmaps = generateMipmaps;
  29384. this.bounces = bounces;
  29385. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29386. this.virtualCameras = new WeakMap();
  29387. this.renderTargets = new WeakMap();
  29388. }
  29389. _updateResolution( renderTarget, renderer ) {
  29390. const resolution = this.resolution;
  29391. renderer.getDrawingBufferSize( _size$6 );
  29392. renderTarget.setSize( Math.round( _size$6.width * resolution ), Math.round( _size$6.height * resolution ) );
  29393. }
  29394. setup( builder ) {
  29395. this._updateResolution( _defaultRT, builder.renderer );
  29396. return super.setup( builder );
  29397. }
  29398. getTextureNode() {
  29399. return this.textureNode;
  29400. }
  29401. getVirtualCamera( camera ) {
  29402. let virtualCamera = this.virtualCameras.get( camera );
  29403. if ( virtualCamera === undefined ) {
  29404. virtualCamera = camera.clone();
  29405. this.virtualCameras.set( camera, virtualCamera );
  29406. }
  29407. return virtualCamera;
  29408. }
  29409. getRenderTarget( camera ) {
  29410. let renderTarget = this.renderTargets.get( camera );
  29411. if ( renderTarget === undefined ) {
  29412. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29413. if ( this.generateMipmaps === true ) {
  29414. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29415. renderTarget.texture.generateMipmaps = true;
  29416. }
  29417. this.renderTargets.set( camera, renderTarget );
  29418. }
  29419. return renderTarget;
  29420. }
  29421. updateBefore( frame ) {
  29422. if ( this.bounces === false && _inReflector ) return false;
  29423. _inReflector = true;
  29424. const { scene, camera, renderer, material } = frame;
  29425. const { target } = this;
  29426. const virtualCamera = this.getVirtualCamera( camera );
  29427. const renderTarget = this.getRenderTarget( virtualCamera );
  29428. renderer.getDrawingBufferSize( _size$6 );
  29429. this._updateResolution( renderTarget, renderer );
  29430. //
  29431. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29432. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29433. _rotationMatrix.extractRotation( target.matrixWorld );
  29434. _normal.set( 0, 0, 1 );
  29435. _normal.applyMatrix4( _rotationMatrix );
  29436. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29437. // Avoid rendering when reflector is facing away
  29438. if ( _view.dot( _normal ) > 0 ) return;
  29439. _view.reflect( _normal ).negate();
  29440. _view.add( _reflectorWorldPosition );
  29441. _rotationMatrix.extractRotation( camera.matrixWorld );
  29442. _lookAtPosition.set( 0, 0, - 1 );
  29443. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29444. _lookAtPosition.add( _cameraWorldPosition );
  29445. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29446. _target.reflect( _normal ).negate();
  29447. _target.add( _reflectorWorldPosition );
  29448. //
  29449. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29450. virtualCamera.position.copy( _view );
  29451. virtualCamera.up.set( 0, 1, 0 );
  29452. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29453. virtualCamera.up.reflect( _normal );
  29454. virtualCamera.lookAt( _target );
  29455. virtualCamera.near = camera.near;
  29456. virtualCamera.far = camera.far;
  29457. virtualCamera.updateMatrixWorld();
  29458. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29459. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29460. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29461. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29462. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29463. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29464. const projectionMatrix = virtualCamera.projectionMatrix;
  29465. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29466. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29467. _q.z = - 1.0;
  29468. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29469. // Calculate the scaled plane vector
  29470. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29471. const clipBias = 0;
  29472. // Replacing the third row of the projection matrix
  29473. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29474. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29475. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29476. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29477. //
  29478. this.value = renderTarget.texture;
  29479. material.visible = false;
  29480. const currentRenderTarget = renderer.getRenderTarget();
  29481. renderer.setRenderTarget( renderTarget );
  29482. renderer.render( scene, virtualCamera );
  29483. renderer.setRenderTarget( currentRenderTarget );
  29484. material.visible = true;
  29485. _inReflector = false;
  29486. }
  29487. }
  29488. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29489. // Helper for passes that need to fill the viewport with a single quad.
  29490. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29491. // https://github.com/mrdoob/three.js/pull/21358
  29492. class QuadGeometry extends BufferGeometry {
  29493. constructor( flipY = false ) {
  29494. super();
  29495. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29496. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29497. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29498. }
  29499. }
  29500. const _geometry = /*@__PURE__*/ new QuadGeometry();
  29501. class QuadMesh extends Mesh {
  29502. constructor( material = null ) {
  29503. super( _geometry, material );
  29504. this.camera = _camera;
  29505. }
  29506. renderAsync( renderer ) {
  29507. return renderer.renderAsync( this, _camera );
  29508. }
  29509. render( renderer ) {
  29510. renderer.render( this, _camera );
  29511. }
  29512. }
  29513. const _size$5 = /*@__PURE__*/ new Vector2();
  29514. class RTTNode extends TextureNode {
  29515. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29516. const renderTarget = new RenderTarget( width, height, options );
  29517. super( renderTarget.texture, uv() );
  29518. this.node = node;
  29519. this.width = width;
  29520. this.height = height;
  29521. this.renderTarget = renderTarget;
  29522. this.textureNeedsUpdate = true;
  29523. this.autoUpdate = true;
  29524. this.updateMap = new WeakMap();
  29525. this._rttNode = null;
  29526. this._quadMesh = new QuadMesh( new NodeMaterial() );
  29527. this.updateBeforeType = NodeUpdateType.RENDER;
  29528. }
  29529. get autoSize() {
  29530. return this.width === null;
  29531. }
  29532. setup( builder ) {
  29533. this._rttNode = this.node.context( builder.getSharedContext() );
  29534. this._quadMesh.material.needsUpdate = true;
  29535. return super.setup( builder );
  29536. }
  29537. setSize( width, height ) {
  29538. this.width = width;
  29539. this.height = height;
  29540. const effectiveWidth = width * this.pixelRatio;
  29541. const effectiveHeight = height * this.pixelRatio;
  29542. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29543. this.textureNeedsUpdate = true;
  29544. }
  29545. setPixelRatio( pixelRatio ) {
  29546. this.pixelRatio = pixelRatio;
  29547. this.setSize( this.width, this.height );
  29548. }
  29549. updateBefore( { renderer } ) {
  29550. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29551. this.textureNeedsUpdate = false;
  29552. //
  29553. if ( this.autoSize === true ) {
  29554. this.pixelRatio = renderer.getPixelRatio();
  29555. const size = renderer.getSize( _size$5 );
  29556. this.setSize( size.width, size.height );
  29557. }
  29558. //
  29559. this._quadMesh.material.fragmentNode = this._rttNode;
  29560. //
  29561. const currentRenderTarget = renderer.getRenderTarget();
  29562. renderer.setRenderTarget( this.renderTarget );
  29563. this._quadMesh.render( renderer );
  29564. renderer.setRenderTarget( currentRenderTarget );
  29565. }
  29566. clone() {
  29567. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29568. newNode.sampler = this.sampler;
  29569. newNode.referenceNode = this;
  29570. return newNode;
  29571. }
  29572. }
  29573. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29574. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29575. addNodeClass( 'RTTNode', RTTNode );
  29576. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  29577. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  29578. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  29579. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  29580. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  29581. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  29582. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  29583. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  29584. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  29585. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  29586. const transformedBentNormalView = ( () => {
  29587. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  29588. let bentNormal = anisotropyB.cross( positionViewDirection );
  29589. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  29590. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  29591. return bentNormal;
  29592. } )();
  29593. class VertexColorNode extends AttributeNode {
  29594. constructor( index = 0 ) {
  29595. super( null, 'vec4' );
  29596. this.isVertexColorNode = true;
  29597. this.index = index;
  29598. }
  29599. getAttributeName( /*builder*/ ) {
  29600. const index = this.index;
  29601. return 'color' + ( index > 0 ? index : '' );
  29602. }
  29603. generate( builder ) {
  29604. const attributeName = this.getAttributeName( builder );
  29605. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29606. let result;
  29607. if ( geometryAttribute === true ) {
  29608. result = super.generate( builder );
  29609. } else {
  29610. // Vertex color fallback should be white
  29611. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29612. }
  29613. return result;
  29614. }
  29615. serialize( data ) {
  29616. super.serialize( data );
  29617. data.index = this.index;
  29618. }
  29619. deserialize( data ) {
  29620. super.deserialize( data );
  29621. this.index = data.index;
  29622. }
  29623. }
  29624. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29625. addNodeClass( 'VertexColorNode', VertexColorNode );
  29626. class RendererReferenceNode extends ReferenceNode {
  29627. constructor( property, inputType, renderer = null ) {
  29628. super( property, inputType, renderer );
  29629. this.renderer = renderer;
  29630. }
  29631. updateReference( state ) {
  29632. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29633. return this.reference;
  29634. }
  29635. }
  29636. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29637. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29638. // Mipped Bicubic Texture Filtering by N8
  29639. // https://www.shadertoy.com/view/Dl2SDW
  29640. const bC = 1.0 / 6.0;
  29641. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29642. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29643. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29644. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29645. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29646. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29647. // h0 and h1 are the two offset functions
  29648. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29649. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29650. const bicubic = ( textureNode, texelSize, lod ) => {
  29651. const uv = textureNode.uvNode;
  29652. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29653. const iuv = floor( uvScaled );
  29654. const fuv = fract( uvScaled );
  29655. const g0x = g0( fuv.x );
  29656. const g1x = g1( fuv.x );
  29657. const h0x = h0( fuv.x );
  29658. const h1x = h1( fuv.x );
  29659. const h0y = h0( fuv.y );
  29660. const h1y = h1( fuv.y );
  29661. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29662. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29663. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29664. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29665. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29666. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29667. return a.add( b );
  29668. };
  29669. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29670. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29671. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29672. const fLodSizeInv = div( 1.0, fLodSize );
  29673. const cLodSizeInv = div( 1.0, cLodSize );
  29674. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29675. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29676. return fract( lodNode ).mix( fSample, cSample );
  29677. };
  29678. class TextureBicubicNode extends TempNode {
  29679. constructor( textureNode, blurNode = float( 3 ) ) {
  29680. super( 'vec4' );
  29681. this.textureNode = textureNode;
  29682. this.blurNode = blurNode;
  29683. }
  29684. setup() {
  29685. return textureBicubicMethod( this.textureNode, this.blurNode );
  29686. }
  29687. }
  29688. const textureBicubic = nodeProxy( TextureBicubicNode );
  29689. addNodeElement( 'bicubic', textureBicubic );
  29690. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29691. class PointUVNode extends Node {
  29692. constructor() {
  29693. super( 'vec2' );
  29694. this.isPointUVNode = true;
  29695. }
  29696. generate( /*builder*/ ) {
  29697. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29698. }
  29699. }
  29700. const pointUV = nodeImmutable( PointUVNode );
  29701. addNodeClass( 'PointUVNode', PointUVNode );
  29702. class SceneNode extends Node {
  29703. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29704. super();
  29705. this.scope = scope;
  29706. this.scene = scene;
  29707. }
  29708. setup( builder ) {
  29709. const scope = this.scope;
  29710. const scene = this.scene !== null ? this.scene : builder.scene;
  29711. let output;
  29712. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29713. output = reference( 'backgroundBlurriness', 'float', scene );
  29714. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29715. output = reference( 'backgroundIntensity', 'float', scene );
  29716. } else {
  29717. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29718. }
  29719. return output;
  29720. }
  29721. }
  29722. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29723. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29724. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29725. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29726. addNodeClass( 'SceneNode', SceneNode );
  29727. const GPUPrimitiveTopology = {
  29728. PointList: 'point-list',
  29729. LineList: 'line-list',
  29730. LineStrip: 'line-strip',
  29731. TriangleList: 'triangle-list',
  29732. TriangleStrip: 'triangle-strip',
  29733. };
  29734. const GPUCompareFunction = {
  29735. Never: 'never',
  29736. Less: 'less',
  29737. Equal: 'equal',
  29738. LessEqual: 'less-equal',
  29739. Greater: 'greater',
  29740. NotEqual: 'not-equal',
  29741. GreaterEqual: 'greater-equal',
  29742. Always: 'always'
  29743. };
  29744. const GPUStoreOp = {
  29745. Store: 'store',
  29746. Discard: 'discard'
  29747. };
  29748. const GPULoadOp = {
  29749. Load: 'load',
  29750. Clear: 'clear'
  29751. };
  29752. const GPUFrontFace = {
  29753. CCW: 'ccw',
  29754. CW: 'cw'
  29755. };
  29756. const GPUCullMode = {
  29757. None: 'none',
  29758. Front: 'front',
  29759. Back: 'back'
  29760. };
  29761. const GPUIndexFormat = {
  29762. Uint16: 'uint16',
  29763. Uint32: 'uint32'
  29764. };
  29765. const GPUTextureFormat = {
  29766. // 8-bit formats
  29767. R8Unorm: 'r8unorm',
  29768. R8Snorm: 'r8snorm',
  29769. R8Uint: 'r8uint',
  29770. R8Sint: 'r8sint',
  29771. // 16-bit formats
  29772. R16Uint: 'r16uint',
  29773. R16Sint: 'r16sint',
  29774. R16Float: 'r16float',
  29775. RG8Unorm: 'rg8unorm',
  29776. RG8Snorm: 'rg8snorm',
  29777. RG8Uint: 'rg8uint',
  29778. RG8Sint: 'rg8sint',
  29779. // 32-bit formats
  29780. R32Uint: 'r32uint',
  29781. R32Sint: 'r32sint',
  29782. R32Float: 'r32float',
  29783. RG16Uint: 'rg16uint',
  29784. RG16Sint: 'rg16sint',
  29785. RG16Float: 'rg16float',
  29786. RGBA8Unorm: 'rgba8unorm',
  29787. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29788. RGBA8Snorm: 'rgba8snorm',
  29789. RGBA8Uint: 'rgba8uint',
  29790. RGBA8Sint: 'rgba8sint',
  29791. BGRA8Unorm: 'bgra8unorm',
  29792. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29793. // Packed 32-bit formats
  29794. RGB9E5UFloat: 'rgb9e5ufloat',
  29795. RGB10A2Unorm: 'rgb10a2unorm',
  29796. RG11B10uFloat: 'rgb10a2unorm',
  29797. // 64-bit formats
  29798. RG32Uint: 'rg32uint',
  29799. RG32Sint: 'rg32sint',
  29800. RG32Float: 'rg32float',
  29801. RGBA16Uint: 'rgba16uint',
  29802. RGBA16Sint: 'rgba16sint',
  29803. RGBA16Float: 'rgba16float',
  29804. // 128-bit formats
  29805. RGBA32Uint: 'rgba32uint',
  29806. RGBA32Sint: 'rgba32sint',
  29807. RGBA32Float: 'rgba32float',
  29808. // Depth and stencil formats
  29809. Stencil8: 'stencil8',
  29810. Depth16Unorm: 'depth16unorm',
  29811. Depth24Plus: 'depth24plus',
  29812. Depth24PlusStencil8: 'depth24plus-stencil8',
  29813. Depth32Float: 'depth32float',
  29814. // 'depth32float-stencil8' extension
  29815. Depth32FloatStencil8: 'depth32float-stencil8',
  29816. // BC compressed formats usable if 'texture-compression-bc' is both
  29817. // supported by the device/user agent and enabled in requestDevice.
  29818. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29819. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29820. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29821. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29822. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29823. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29824. BC4RUnorm: 'bc4-r-unorm',
  29825. BC4RSnorm: 'bc4-r-snorm',
  29826. BC5RGUnorm: 'bc5-rg-unorm',
  29827. BC5RGSnorm: 'bc5-rg-snorm',
  29828. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29829. BC6HRGBFloat: 'bc6h-rgb-float',
  29830. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29831. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29832. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29833. // supported by the device/user agent and enabled in requestDevice.
  29834. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29835. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29836. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29837. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29838. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29839. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29840. EACR11Unorm: 'eac-r11unorm',
  29841. EACR11Snorm: 'eac-r11snorm',
  29842. EACRG11Unorm: 'eac-rg11unorm',
  29843. EACRG11Snorm: 'eac-rg11snorm',
  29844. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29845. // supported by the device/user agent and enabled in requestDevice.
  29846. ASTC4x4Unorm: 'astc-4x4-unorm',
  29847. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29848. ASTC5x4Unorm: 'astc-5x4-unorm',
  29849. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29850. ASTC5x5Unorm: 'astc-5x5-unorm',
  29851. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29852. ASTC6x5Unorm: 'astc-6x5-unorm',
  29853. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29854. ASTC6x6Unorm: 'astc-6x6-unorm',
  29855. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29856. ASTC8x5Unorm: 'astc-8x5-unorm',
  29857. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29858. ASTC8x6Unorm: 'astc-8x6-unorm',
  29859. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29860. ASTC8x8Unorm: 'astc-8x8-unorm',
  29861. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29862. ASTC10x5Unorm: 'astc-10x5-unorm',
  29863. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29864. ASTC10x6Unorm: 'astc-10x6-unorm',
  29865. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29866. ASTC10x8Unorm: 'astc-10x8-unorm',
  29867. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29868. ASTC10x10Unorm: 'astc-10x10-unorm',
  29869. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29870. ASTC12x10Unorm: 'astc-12x10-unorm',
  29871. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29872. ASTC12x12Unorm: 'astc-12x12-unorm',
  29873. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29874. };
  29875. const GPUAddressMode = {
  29876. ClampToEdge: 'clamp-to-edge',
  29877. Repeat: 'repeat',
  29878. MirrorRepeat: 'mirror-repeat'
  29879. };
  29880. const GPUFilterMode = {
  29881. Linear: 'linear',
  29882. Nearest: 'nearest'
  29883. };
  29884. const GPUBlendFactor = {
  29885. Zero: 'zero',
  29886. One: 'one',
  29887. Src: 'src',
  29888. OneMinusSrc: 'one-minus-src',
  29889. SrcAlpha: 'src-alpha',
  29890. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29891. Dst: 'dst',
  29892. OneMinusDstColor: 'one-minus-dst',
  29893. DstAlpha: 'dst-alpha',
  29894. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29895. SrcAlphaSaturated: 'src-alpha-saturated',
  29896. Constant: 'constant',
  29897. OneMinusConstant: 'one-minus-constant'
  29898. };
  29899. const GPUBlendOperation = {
  29900. Add: 'add',
  29901. Subtract: 'subtract',
  29902. ReverseSubtract: 'reverse-subtract',
  29903. Min: 'min',
  29904. Max: 'max'
  29905. };
  29906. const GPUColorWriteFlags = {
  29907. None: 0,
  29908. Red: 0x1,
  29909. Green: 0x2,
  29910. Blue: 0x4,
  29911. Alpha: 0x8,
  29912. All: 0xF
  29913. };
  29914. const GPUStencilOperation = {
  29915. Keep: 'keep',
  29916. Zero: 'zero',
  29917. Replace: 'replace',
  29918. Invert: 'invert',
  29919. IncrementClamp: 'increment-clamp',
  29920. DecrementClamp: 'decrement-clamp',
  29921. IncrementWrap: 'increment-wrap',
  29922. DecrementWrap: 'decrement-wrap'
  29923. };
  29924. const GPUBufferBindingType = {
  29925. Uniform: 'uniform',
  29926. Storage: 'storage',
  29927. ReadOnlyStorage: 'read-only-storage'
  29928. };
  29929. const GPUStorageTextureAccess = {
  29930. WriteOnly: 'write-only',
  29931. ReadOnly: 'read-only',
  29932. ReadWrite: 'read-write',
  29933. };
  29934. const GPUTextureSampleType = {
  29935. Float: 'float',
  29936. UnfilterableFloat: 'unfilterable-float',
  29937. Depth: 'depth',
  29938. SInt: 'sint',
  29939. UInt: 'uint'
  29940. };
  29941. const GPUTextureDimension = {
  29942. OneD: '1d',
  29943. TwoD: '2d',
  29944. ThreeD: '3d'
  29945. };
  29946. const GPUTextureViewDimension = {
  29947. OneD: '1d',
  29948. TwoD: '2d',
  29949. TwoDArray: '2d-array',
  29950. Cube: 'cube',
  29951. CubeArray: 'cube-array',
  29952. ThreeD: '3d'
  29953. };
  29954. const GPUTextureAspect = {
  29955. All: 'all',
  29956. StencilOnly: 'stencil-only',
  29957. DepthOnly: 'depth-only'
  29958. };
  29959. const GPUInputStepMode = {
  29960. Vertex: 'vertex',
  29961. Instance: 'instance'
  29962. };
  29963. const GPUFeatureName = {
  29964. DepthClipControl: 'depth-clip-control',
  29965. Depth32FloatStencil8: 'depth32float-stencil8',
  29966. TextureCompressionBC: 'texture-compression-bc',
  29967. TextureCompressionETC2: 'texture-compression-etc2',
  29968. TextureCompressionASTC: 'texture-compression-astc',
  29969. TimestampQuery: 'timestamp-query',
  29970. IndirectFirstInstance: 'indirect-first-instance',
  29971. ShaderF16: 'shader-f16',
  29972. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29973. BGRA8UNormStorage: 'bgra8unorm-storage',
  29974. Float32Filterable: 'float32-filterable',
  29975. ClipDistances: 'clip-distances',
  29976. DualSourceBlending: 'dual-source-blending'
  29977. };
  29978. class StorageBufferNode extends BufferNode {
  29979. constructor( value, bufferType, bufferCount = 0 ) {
  29980. super( value, bufferType, bufferCount );
  29981. this.isStorageBufferNode = true;
  29982. this.access = GPUBufferBindingType.Storage;
  29983. this.bufferObject = false;
  29984. this.bufferCount = bufferCount;
  29985. this._attribute = null;
  29986. this._varying = null;
  29987. this.global = true;
  29988. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29989. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29990. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29991. else value.isStorageBufferAttribute = true;
  29992. }
  29993. }
  29994. getHash( builder ) {
  29995. if ( this.bufferCount === 0 ) {
  29996. let bufferData = builder.globalCache.getData( this.value );
  29997. if ( bufferData === undefined ) {
  29998. bufferData = {
  29999. node: this
  30000. };
  30001. builder.globalCache.setData( this.value, bufferData );
  30002. }
  30003. return bufferData.node.uuid;
  30004. }
  30005. return this.uuid;
  30006. }
  30007. getInputType( /*builder*/ ) {
  30008. return 'storageBuffer';
  30009. }
  30010. element( indexNode ) {
  30011. return storageElement( this, indexNode );
  30012. }
  30013. setBufferObject( value ) {
  30014. this.bufferObject = value;
  30015. return this;
  30016. }
  30017. setAccess( value ) {
  30018. this.access = value;
  30019. return this;
  30020. }
  30021. toReadOnly() {
  30022. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  30023. }
  30024. generate( builder ) {
  30025. if ( builder.isAvailable( 'storageBuffer' ) ) {
  30026. return super.generate( builder );
  30027. }
  30028. const nodeType = this.getNodeType( builder );
  30029. if ( this._attribute === null ) {
  30030. this._attribute = bufferAttribute( this.value );
  30031. this._varying = varying( this._attribute );
  30032. }
  30033. const output = this._varying.build( builder, nodeType );
  30034. builder.registerTransform( output, this._attribute );
  30035. return output;
  30036. }
  30037. }
  30038. // Read-Write Storage
  30039. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  30040. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  30041. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  30042. class StorageTextureNode extends TextureNode {
  30043. constructor( value, uvNode, storeNode = null ) {
  30044. super( value, uvNode );
  30045. this.storeNode = storeNode;
  30046. this.isStorageTextureNode = true;
  30047. this.access = GPUStorageTextureAccess.WriteOnly;
  30048. }
  30049. getInputType( /*builder*/ ) {
  30050. return 'storageTexture';
  30051. }
  30052. setup( builder ) {
  30053. super.setup( builder );
  30054. const properties = builder.getNodeProperties( this );
  30055. properties.storeNode = this.storeNode;
  30056. }
  30057. setAccess( value ) {
  30058. this.access = value;
  30059. return this;
  30060. }
  30061. generate( builder, output ) {
  30062. let snippet;
  30063. if ( this.storeNode !== null ) {
  30064. snippet = this.generateStore( builder );
  30065. } else {
  30066. snippet = super.generate( builder, output );
  30067. }
  30068. return snippet;
  30069. }
  30070. toReadOnly() {
  30071. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  30072. }
  30073. toWriteOnly() {
  30074. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  30075. }
  30076. generateStore( builder ) {
  30077. const properties = builder.getNodeProperties( this );
  30078. const { uvNode, storeNode } = properties;
  30079. const textureProperty = super.generate( builder, 'property' );
  30080. const uvSnippet = uvNode.build( builder, 'uvec2' );
  30081. const storeSnippet = storeNode.build( builder, 'vec4' );
  30082. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  30083. builder.addLineFlowCode( snippet );
  30084. }
  30085. }
  30086. const storageTexture = nodeProxy( StorageTextureNode );
  30087. const textureStore = ( value, uvNode, storeNode ) => {
  30088. const node = storageTexture( value, uvNode, storeNode );
  30089. if ( storeNode !== null ) node.append();
  30090. return node;
  30091. };
  30092. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  30093. const normal = tslFn( ( { texture, uv } ) => {
  30094. const epsilon = 0.0001;
  30095. const ret = vec3().temp();
  30096. If( uv.x.lessThan( epsilon ), () => {
  30097. ret.assign( vec3( 1, 0, 0 ) );
  30098. } ).elseif( uv.y.lessThan( epsilon ), () => {
  30099. ret.assign( vec3( 0, 1, 0 ) );
  30100. } ).elseif( uv.z.lessThan( epsilon ), () => {
  30101. ret.assign( vec3( 0, 0, 1 ) );
  30102. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  30103. ret.assign( vec3( - 1, 0, 0 ) );
  30104. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  30105. ret.assign( vec3( 0, - 1, 0 ) );
  30106. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  30107. ret.assign( vec3( 0, 0, - 1 ) );
  30108. } ).else( () => {
  30109. const step = 0.01;
  30110. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  30111. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  30112. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  30113. ret.assign( vec3( x, y, z ) );
  30114. } );
  30115. return ret.normalize();
  30116. } );
  30117. class Texture3DNode extends TextureNode {
  30118. constructor( value, uvNode = null, levelNode = null ) {
  30119. super( value, uvNode, levelNode );
  30120. this.isTexture3DNode = true;
  30121. }
  30122. getInputType( /*builder*/ ) {
  30123. return 'texture3D';
  30124. }
  30125. getDefaultUV() {
  30126. return vec3( 0.5, 0.5, 0.5 );
  30127. }
  30128. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  30129. setupUV( builder, uvNode ) {
  30130. return uvNode;
  30131. }
  30132. generateUV( builder, uvNode ) {
  30133. return uvNode.build( builder, 'vec3' );
  30134. }
  30135. normal( uvNode ) {
  30136. return normal( { texture: this, uv: uvNode } );
  30137. }
  30138. }
  30139. const texture3D = nodeProxy( Texture3DNode );
  30140. addNodeClass( 'Texture3DNode', Texture3DNode );
  30141. class UserDataNode extends ReferenceNode {
  30142. constructor( property, inputType, userData = null ) {
  30143. super( property, inputType, userData );
  30144. this.userData = userData;
  30145. }
  30146. update( frame ) {
  30147. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  30148. super.update( frame );
  30149. }
  30150. }
  30151. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  30152. addNodeClass( 'UserDataNode', UserDataNode );
  30153. const BurnNode = tslFn( ( { base, blend } ) => {
  30154. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  30155. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30156. } ).setLayout( {
  30157. name: 'burnColor',
  30158. type: 'vec3',
  30159. inputs: [
  30160. { name: 'base', type: 'vec3' },
  30161. { name: 'blend', type: 'vec3' }
  30162. ]
  30163. } );
  30164. const DodgeNode = tslFn( ( { base, blend } ) => {
  30165. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30166. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30167. } ).setLayout( {
  30168. name: 'dodgeColor',
  30169. type: 'vec3',
  30170. inputs: [
  30171. { name: 'base', type: 'vec3' },
  30172. { name: 'blend', type: 'vec3' }
  30173. ]
  30174. } );
  30175. const ScreenNode = tslFn( ( { base, blend } ) => {
  30176. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30177. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30178. } ).setLayout( {
  30179. name: 'screenColor',
  30180. type: 'vec3',
  30181. inputs: [
  30182. { name: 'base', type: 'vec3' },
  30183. { name: 'blend', type: 'vec3' }
  30184. ]
  30185. } );
  30186. const OverlayNode = tslFn( ( { base, blend } ) => {
  30187. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30188. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30189. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30190. } ).setLayout( {
  30191. name: 'overlayColor',
  30192. type: 'vec3',
  30193. inputs: [
  30194. { name: 'base', type: 'vec3' },
  30195. { name: 'blend', type: 'vec3' }
  30196. ]
  30197. } );
  30198. class BlendModeNode extends TempNode {
  30199. constructor( blendMode, baseNode, blendNode ) {
  30200. super();
  30201. this.blendMode = blendMode;
  30202. this.baseNode = baseNode;
  30203. this.blendNode = blendNode;
  30204. }
  30205. setup() {
  30206. const { blendMode, baseNode, blendNode } = this;
  30207. const params = { base: baseNode, blend: blendNode };
  30208. let outputNode = null;
  30209. if ( blendMode === BlendModeNode.BURN ) {
  30210. outputNode = BurnNode( params );
  30211. } else if ( blendMode === BlendModeNode.DODGE ) {
  30212. outputNode = DodgeNode( params );
  30213. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30214. outputNode = ScreenNode( params );
  30215. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30216. outputNode = OverlayNode( params );
  30217. }
  30218. return outputNode;
  30219. }
  30220. }
  30221. BlendModeNode.BURN = 'burn';
  30222. BlendModeNode.DODGE = 'dodge';
  30223. BlendModeNode.SCREEN = 'screen';
  30224. BlendModeNode.OVERLAY = 'overlay';
  30225. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30226. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30227. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30228. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30229. addNodeElement( 'burn', burn );
  30230. addNodeElement( 'dodge', dodge );
  30231. addNodeElement( 'overlay', overlay );
  30232. addNodeElement( 'screen', screen );
  30233. addNodeClass( 'BlendModeNode', BlendModeNode );
  30234. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30235. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30236. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30237. // It's used to preserve the same TextureNode instance
  30238. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30239. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30240. return vec2(
  30241. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30242. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30243. ).mul( bumpScale );
  30244. } );
  30245. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30246. const perturbNormalArb = tslFn( ( inputs ) => {
  30247. const { surf_pos, surf_norm, dHdxy } = inputs;
  30248. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30249. const vSigmaX = surf_pos.dFdx().normalize();
  30250. const vSigmaY = surf_pos.dFdy().normalize();
  30251. const vN = surf_norm; // normalized
  30252. const R1 = vSigmaY.cross( vN );
  30253. const R2 = vN.cross( vSigmaX );
  30254. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30255. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30256. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30257. } );
  30258. class BumpMapNode extends TempNode {
  30259. constructor( textureNode, scaleNode = null ) {
  30260. super( 'vec3' );
  30261. this.textureNode = textureNode;
  30262. this.scaleNode = scaleNode;
  30263. }
  30264. setup() {
  30265. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30266. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30267. return perturbNormalArb( {
  30268. surf_pos: positionView,
  30269. surf_norm: normalView,
  30270. dHdxy
  30271. } );
  30272. }
  30273. }
  30274. const bumpMap = nodeProxy( BumpMapNode );
  30275. addNodeElement( 'bumpMap', bumpMap );
  30276. addNodeClass( 'BumpMapNode', BumpMapNode );
  30277. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30278. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30279. } );
  30280. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30281. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30282. const mx = color.r.max( color.g.max( color.b ) );
  30283. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30284. return mix( color.rgb, mx, amt );
  30285. } );
  30286. const hueNode = tslFn( ( { color, adjustment } ) => {
  30287. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30288. const cosAngle = adjustment.cos();
  30289. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30290. } );
  30291. class ColorAdjustmentNode extends TempNode {
  30292. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30293. super( 'vec3' );
  30294. this.method = method;
  30295. this.colorNode = colorNode;
  30296. this.adjustmentNode = adjustmentNode;
  30297. }
  30298. setup() {
  30299. const { method, colorNode, adjustmentNode } = this;
  30300. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30301. let outputNode = null;
  30302. if ( method === ColorAdjustmentNode.SATURATION ) {
  30303. outputNode = saturationNode( callParams );
  30304. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30305. outputNode = vibranceNode( callParams );
  30306. } else if ( method === ColorAdjustmentNode.HUE ) {
  30307. outputNode = hueNode( callParams );
  30308. } else {
  30309. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30310. }
  30311. return outputNode;
  30312. }
  30313. }
  30314. ColorAdjustmentNode.SATURATION = 'saturation';
  30315. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30316. ColorAdjustmentNode.HUE = 'hue';
  30317. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30318. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30319. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30320. const _luminanceCoefficients = /*#__PURE__*/ new Vector3();
  30321. const luminance = (
  30322. color,
  30323. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  30324. ) => dot( color, luminanceCoefficients );
  30325. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30326. addNodeElement( 'saturation', saturation );
  30327. addNodeElement( 'vibrance', vibrance );
  30328. addNodeElement( 'hue', hue );
  30329. addNodeElement( 'threshold', threshold );
  30330. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30331. // Normal Mapping Without Precomputed Tangents
  30332. // http://www.thetenthplanet.de/archives/1180
  30333. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30334. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30335. const q0 = eye_pos.dFdx();
  30336. const q1 = eye_pos.dFdy();
  30337. const st0 = uv.dFdx();
  30338. const st1 = uv.dFdy();
  30339. const N = surf_norm; // normalized
  30340. const q1perp = q1.cross( N );
  30341. const q0perp = N.cross( q0 );
  30342. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30343. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30344. const det = T.dot( T ).max( B.dot( B ) );
  30345. const scale = faceDirection.mul( det.inverseSqrt() );
  30346. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30347. } );
  30348. class NormalMapNode extends TempNode {
  30349. constructor( node, scaleNode = null ) {
  30350. super( 'vec3' );
  30351. this.node = node;
  30352. this.scaleNode = scaleNode;
  30353. this.normalMapType = TangentSpaceNormalMap;
  30354. }
  30355. setup( builder ) {
  30356. const { normalMapType, scaleNode } = this;
  30357. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30358. if ( scaleNode !== null ) {
  30359. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30360. }
  30361. let outputNode = null;
  30362. if ( normalMapType === ObjectSpaceNormalMap ) {
  30363. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30364. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30365. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30366. if ( tangent === true ) {
  30367. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30368. } else {
  30369. outputNode = perturbNormal2Arb( {
  30370. eye_pos: positionView,
  30371. surf_norm: normalView,
  30372. mapN: normalMap,
  30373. uv: uv()
  30374. } );
  30375. }
  30376. }
  30377. return outputNode;
  30378. }
  30379. }
  30380. const normalMap = nodeProxy( NormalMapNode );
  30381. addNodeElement( 'normalMap', normalMap );
  30382. addNodeClass( 'NormalMapNode', NormalMapNode );
  30383. class PosterizeNode extends TempNode {
  30384. constructor( sourceNode, stepsNode ) {
  30385. super();
  30386. this.sourceNode = sourceNode;
  30387. this.stepsNode = stepsNode;
  30388. }
  30389. setup() {
  30390. const { sourceNode, stepsNode } = this;
  30391. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30392. }
  30393. }
  30394. const posterize = nodeProxy( PosterizeNode );
  30395. addNodeElement( 'posterize', posterize );
  30396. addNodeClass( 'PosterizeNode', PosterizeNode );
  30397. // exposure only
  30398. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30399. return color.mul( exposure ).clamp();
  30400. } );
  30401. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30402. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30403. color = color.mul( exposure );
  30404. return color.div( color.add( 1.0 ) ).clamp();
  30405. } );
  30406. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30407. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30408. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30409. color = color.mul( exposure );
  30410. color = color.sub( 0.004 ).max( 0.0 );
  30411. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30412. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30413. return a.div( b ).pow( 2.2 );
  30414. } );
  30415. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30416. const RRTAndODTFit = tslFn( ( { color } ) => {
  30417. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30418. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30419. return a.div( b );
  30420. } );
  30421. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30422. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30423. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30424. const ACESInputMat = mat3(
  30425. 0.59719, 0.35458, 0.04823,
  30426. 0.07600, 0.90834, 0.01566,
  30427. 0.02840, 0.13383, 0.83777
  30428. );
  30429. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30430. const ACESOutputMat = mat3(
  30431. 1.60475, - 0.53108, - 0.07367,
  30432. - 0.10208, 1.10813, - 0.00605,
  30433. - 0.00327, - 0.07276, 1.07602
  30434. );
  30435. color = color.mul( exposure ).div( 0.6 );
  30436. color = ACESInputMat.mul( color );
  30437. // Apply RRT and ODT
  30438. color = RRTAndODTFit( { color } );
  30439. color = ACESOutputMat.mul( color );
  30440. // Clamp to [0, 1]
  30441. return color.clamp();
  30442. } );
  30443. const LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  30444. const LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  30445. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30446. const x = vec3( x_immutable ).toVar();
  30447. const x2 = vec3( x.mul( x ) ).toVar();
  30448. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30449. 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 ) ) ) );
  30450. } );
  30451. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30452. const colortone = vec3( color ).toVar();
  30453. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30454. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30455. const AgxMinEv = float( - 12.47393 );
  30456. const AgxMaxEv = float( 4.026069 );
  30457. colortone.mulAssign( exposure );
  30458. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30459. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30460. colortone.assign( max$1( colortone, 1e-10 ) );
  30461. colortone.assign( log2( colortone ) );
  30462. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30463. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30464. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30465. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30466. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30467. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30468. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30469. return colortone;
  30470. } );
  30471. // https://modelviewer.dev/examples/tone-mapping
  30472. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30473. const StartCompression = float( 0.8 - 0.04 );
  30474. const Desaturation = float( 0.15 );
  30475. color = color.mul( exposure );
  30476. const x = min$1( color.r, min$1( color.g, color.b ) );
  30477. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30478. color.subAssign( offset );
  30479. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30480. If( peak.lessThan( StartCompression ), () => {
  30481. return color;
  30482. } );
  30483. const d = sub( 1, StartCompression );
  30484. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30485. color.mulAssign( newPeak.div( peak ) );
  30486. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30487. return mix( color, vec3( newPeak ), g );
  30488. } ).setLayout( {
  30489. name: 'NeutralToneMapping',
  30490. type: 'vec3',
  30491. inputs: [
  30492. { name: 'color', type: 'vec3' },
  30493. { name: 'exposure', type: 'float' }
  30494. ]
  30495. } );
  30496. const toneMappingLib = {
  30497. [ LinearToneMapping ]: LinearToneMappingNode,
  30498. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30499. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30500. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30501. [ AgXToneMapping ]: AGXToneMappingNode,
  30502. [ NeutralToneMapping ]: NeutralToneMappingNode
  30503. };
  30504. class ToneMappingNode extends TempNode {
  30505. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30506. super( 'vec3' );
  30507. this.toneMapping = toneMapping;
  30508. this.exposureNode = exposureNode;
  30509. this.colorNode = colorNode;
  30510. }
  30511. getCacheKey() {
  30512. let cacheKey = super.getCacheKey();
  30513. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30514. return cacheKey;
  30515. }
  30516. setup( builder ) {
  30517. const colorNode = this.colorNode || builder.context.color;
  30518. const toneMapping = this.toneMapping;
  30519. if ( toneMapping === NoToneMapping ) return colorNode;
  30520. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30521. const toneMappingNode = toneMappingLib[ toneMapping ];
  30522. let outputNode = null;
  30523. if ( toneMappingNode ) {
  30524. outputNode = toneMappingNode( toneMappingParams );
  30525. } else {
  30526. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30527. outputNode = colorNode;
  30528. }
  30529. return outputNode;
  30530. }
  30531. }
  30532. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30533. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30534. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30535. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30536. let _sharedFramebuffer = null;
  30537. class ViewportSharedTextureNode extends ViewportTextureNode {
  30538. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30539. if ( _sharedFramebuffer === null ) {
  30540. _sharedFramebuffer = new FramebufferTexture();
  30541. }
  30542. super( uvNode, levelNode, _sharedFramebuffer );
  30543. }
  30544. updateReference() {
  30545. return this;
  30546. }
  30547. }
  30548. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30549. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30550. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30551. const _size$4 = /*@__PURE__*/ new Vector2();
  30552. class PassTextureNode extends TextureNode {
  30553. constructor( passNode, texture ) {
  30554. super( texture );
  30555. this.passNode = passNode;
  30556. this.setUpdateMatrix( false );
  30557. }
  30558. setup( builder ) {
  30559. this.passNode.build( builder );
  30560. return super.setup( builder );
  30561. }
  30562. clone() {
  30563. return new this.constructor( this.passNode, this.value );
  30564. }
  30565. }
  30566. class PassMultipleTextureNode extends PassTextureNode {
  30567. constructor( passNode, textureName ) {
  30568. super( passNode, null );
  30569. this.textureName = textureName;
  30570. }
  30571. setup( builder ) {
  30572. this.value = this.passNode.getTexture( this.textureName );
  30573. return super.setup( builder );
  30574. }
  30575. clone() {
  30576. return new this.constructor( this.passNode, this.textureName );
  30577. }
  30578. }
  30579. class PassNode extends TempNode {
  30580. constructor( scope, scene, camera, options = {} ) {
  30581. super( 'vec4' );
  30582. this.scope = scope;
  30583. this.scene = scene;
  30584. this.camera = camera;
  30585. this.options = options;
  30586. this._pixelRatio = 1;
  30587. this._width = 1;
  30588. this._height = 1;
  30589. const depthTexture = new DepthTexture();
  30590. depthTexture.isRenderTargetTexture = true;
  30591. //depthTexture.type = FloatType;
  30592. depthTexture.name = 'depth';
  30593. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  30594. renderTarget.texture.name = 'output';
  30595. renderTarget.depthTexture = depthTexture;
  30596. this.renderTarget = renderTarget;
  30597. this.updateBeforeType = NodeUpdateType.FRAME;
  30598. this._textures = {
  30599. output: renderTarget.texture,
  30600. depth: depthTexture
  30601. };
  30602. this._textureNodes = {};
  30603. this._linearDepthNodes = {};
  30604. this._viewZNodes = {};
  30605. this._cameraNear = uniform( 0 );
  30606. this._cameraFar = uniform( 0 );
  30607. this._mrt = null;
  30608. this.isPassNode = true;
  30609. }
  30610. setMRT( mrt ) {
  30611. this._mrt = mrt;
  30612. return this;
  30613. }
  30614. getMRT() {
  30615. return this._mrt;
  30616. }
  30617. isGlobal() {
  30618. return true;
  30619. }
  30620. getTexture( name ) {
  30621. let texture = this._textures[ name ];
  30622. if ( texture === undefined ) {
  30623. const refTexture = this.renderTarget.texture;
  30624. texture = refTexture.clone();
  30625. texture.isRenderTargetTexture = true;
  30626. texture.name = name;
  30627. this._textures[ name ] = texture;
  30628. this.renderTarget.textures.push( texture );
  30629. }
  30630. return texture;
  30631. }
  30632. getTextureNode( name = 'output' ) {
  30633. let textureNode = this._textureNodes[ name ];
  30634. if ( textureNode === undefined ) {
  30635. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  30636. }
  30637. return textureNode;
  30638. }
  30639. getViewZNode( name = 'depth' ) {
  30640. let viewZNode = this._viewZNodes[ name ];
  30641. if ( viewZNode === undefined ) {
  30642. const cameraNear = this._cameraNear;
  30643. const cameraFar = this._cameraFar;
  30644. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  30645. }
  30646. return viewZNode;
  30647. }
  30648. getLinearDepthNode( name = 'depth' ) {
  30649. let linearDepthNode = this._linearDepthNodes[ name ];
  30650. if ( linearDepthNode === undefined ) {
  30651. const cameraNear = this._cameraNear;
  30652. const cameraFar = this._cameraFar;
  30653. const viewZNode = this.getViewZNode( name );
  30654. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30655. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  30656. }
  30657. return linearDepthNode;
  30658. }
  30659. setup( { renderer } ) {
  30660. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  30661. // Disable MSAA for WebGL backend for now
  30662. if ( renderer.backend.isWebGLBackend === true ) {
  30663. this.renderTarget.samples = 0;
  30664. }
  30665. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  30666. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30667. }
  30668. updateBefore( frame ) {
  30669. const { renderer } = frame;
  30670. const { scene, camera } = this;
  30671. this._pixelRatio = renderer.getPixelRatio();
  30672. const size = renderer.getSize( _size$4 );
  30673. this.setSize( size.width, size.height );
  30674. const currentRenderTarget = renderer.getRenderTarget();
  30675. const currentMRT = renderer.getMRT();
  30676. this._cameraNear.value = camera.near;
  30677. this._cameraFar.value = camera.far;
  30678. renderer.setRenderTarget( this.renderTarget );
  30679. renderer.setMRT( this._mrt );
  30680. renderer.render( scene, camera );
  30681. renderer.setRenderTarget( currentRenderTarget );
  30682. renderer.setMRT( currentMRT );
  30683. }
  30684. setSize( width, height ) {
  30685. this._width = width;
  30686. this._height = height;
  30687. const effectiveWidth = this._width * this._pixelRatio;
  30688. const effectiveHeight = this._height * this._pixelRatio;
  30689. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30690. }
  30691. setPixelRatio( pixelRatio ) {
  30692. this._pixelRatio = pixelRatio;
  30693. this.setSize( this._width, this._height );
  30694. }
  30695. dispose() {
  30696. this.renderTarget.dispose();
  30697. }
  30698. }
  30699. PassNode.COLOR = 'color';
  30700. PassNode.DEPTH = 'depth';
  30701. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  30702. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30703. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30704. addNodeClass( 'PassNode', PassNode );
  30705. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30706. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30707. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  30708. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  30709. class GaussianBlurNode extends TempNode {
  30710. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30711. super( 'vec4' );
  30712. this.textureNode = textureNode;
  30713. this.directionNode = directionNode;
  30714. this.sigma = sigma;
  30715. this._invSize = uniform( new Vector2() );
  30716. this._passDirection = uniform( new Vector2() );
  30717. this._horizontalRT = new RenderTarget();
  30718. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30719. this._verticalRT = new RenderTarget();
  30720. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30721. this._textureNode = passTexture( this, this._verticalRT.texture );
  30722. this.updateBeforeType = NodeUpdateType.RENDER;
  30723. this.resolution = new Vector2( 1, 1 );
  30724. }
  30725. setSize( width, height ) {
  30726. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30727. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30728. this._invSize.value.set( 1 / width, 1 / height );
  30729. this._horizontalRT.setSize( width, height );
  30730. this._verticalRT.setSize( width, height );
  30731. }
  30732. updateBefore( frame ) {
  30733. const { renderer } = frame;
  30734. const textureNode = this.textureNode;
  30735. const map = textureNode.value;
  30736. const currentRenderTarget = renderer.getRenderTarget();
  30737. const currentMRT = renderer.getMRT();
  30738. const currentTexture = textureNode.value;
  30739. _quadMesh1.material = this._material;
  30740. _quadMesh2.material = this._material;
  30741. this.setSize( map.image.width, map.image.height );
  30742. const textureType = map.type;
  30743. this._horizontalRT.texture.type = textureType;
  30744. this._verticalRT.texture.type = textureType;
  30745. // clear
  30746. renderer.setMRT( null );
  30747. // horizontal
  30748. renderer.setRenderTarget( this._horizontalRT );
  30749. this._passDirection.value.set( 1, 0 );
  30750. _quadMesh1.render( renderer );
  30751. // vertical
  30752. textureNode.value = this._horizontalRT.texture;
  30753. renderer.setRenderTarget( this._verticalRT );
  30754. this._passDirection.value.set( 0, 1 );
  30755. _quadMesh2.render( renderer );
  30756. // restore
  30757. renderer.setRenderTarget( currentRenderTarget );
  30758. renderer.setMRT( currentMRT );
  30759. textureNode.value = currentTexture;
  30760. }
  30761. getTextureNode() {
  30762. return this._textureNode;
  30763. }
  30764. setup( builder ) {
  30765. const textureNode = this.textureNode;
  30766. if ( textureNode.isTextureNode !== true ) {
  30767. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30768. return vec4();
  30769. }
  30770. //
  30771. const uvNode = textureNode.uvNode || uv();
  30772. const directionNode = vec2( this.directionNode || 1 );
  30773. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30774. const blur = tslFn( () => {
  30775. const kernelSize = 3 + ( 2 * this.sigma );
  30776. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30777. const invSize = this._invSize;
  30778. const direction = directionNode.mul( this._passDirection );
  30779. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30780. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30781. for ( let i = 1; i < kernelSize; i ++ ) {
  30782. const x = float( i );
  30783. const w = float( gaussianCoefficients[ i ] );
  30784. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30785. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30786. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30787. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30788. weightSum.addAssign( mul( 2.0, w ) );
  30789. }
  30790. return diffuseSum.div( weightSum );
  30791. } );
  30792. //
  30793. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30794. material.fragmentNode = blur().context( builder.getSharedContext() );
  30795. material.needsUpdate = true;
  30796. //
  30797. const properties = builder.getNodeProperties( this );
  30798. properties.textureNode = textureNode;
  30799. //
  30800. return this._textureNode;
  30801. }
  30802. dispose() {
  30803. this._horizontalRT.dispose();
  30804. this._verticalRT.dispose();
  30805. }
  30806. _getCoefficients( kernelRadius ) {
  30807. const coefficients = [];
  30808. for ( let i = 0; i < kernelRadius; i ++ ) {
  30809. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30810. }
  30811. return coefficients;
  30812. }
  30813. }
  30814. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30815. addNodeElement( 'gaussianBlur', gaussianBlur );
  30816. const _size$3 = /*@__PURE__*/ new Vector2();
  30817. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  30818. class AfterImageNode extends TempNode {
  30819. constructor( textureNode, damp = 0.96 ) {
  30820. super( textureNode );
  30821. this.textureNode = textureNode;
  30822. this.textureNodeOld = texture();
  30823. this.damp = uniform( damp );
  30824. this._compRT = new RenderTarget();
  30825. this._compRT.texture.name = 'AfterImageNode.comp';
  30826. this._oldRT = new RenderTarget();
  30827. this._oldRT.texture.name = 'AfterImageNode.old';
  30828. this._textureNode = passTexture( this, this._compRT.texture );
  30829. this.updateBeforeType = NodeUpdateType.RENDER;
  30830. }
  30831. getTextureNode() {
  30832. return this._textureNode;
  30833. }
  30834. setSize( width, height ) {
  30835. this._compRT.setSize( width, height );
  30836. this._oldRT.setSize( width, height );
  30837. }
  30838. updateBefore( frame ) {
  30839. const { renderer } = frame;
  30840. const textureNode = this.textureNode;
  30841. const map = textureNode.value;
  30842. const textureType = map.type;
  30843. this._compRT.texture.type = textureType;
  30844. this._oldRT.texture.type = textureType;
  30845. renderer.getDrawingBufferSize( _size$3 );
  30846. this.setSize( _size$3.x, _size$3.y );
  30847. const currentRenderTarget = renderer.getRenderTarget();
  30848. const currentTexture = textureNode.value;
  30849. this.textureNodeOld.value = this._oldRT.texture;
  30850. // comp
  30851. renderer.setRenderTarget( this._compRT );
  30852. _quadMeshComp.render( renderer );
  30853. // Swap the textures
  30854. const temp = this._oldRT;
  30855. this._oldRT = this._compRT;
  30856. this._compRT = temp;
  30857. renderer.setRenderTarget( currentRenderTarget );
  30858. textureNode.value = currentTexture;
  30859. }
  30860. setup( builder ) {
  30861. const textureNode = this.textureNode;
  30862. const textureNodeOld = this.textureNodeOld;
  30863. //
  30864. const uvNode = textureNode.uvNode || uv();
  30865. textureNodeOld.uvNode = uvNode;
  30866. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30867. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30868. const y = float( y_immutable ).toVar();
  30869. const x = vec4( x_immutable ).toVar();
  30870. return max$1( sign( x.sub( y ) ), 0.0 );
  30871. } );
  30872. const afterImg = tslFn( () => {
  30873. const texelOld = vec4( textureNodeOld );
  30874. const texelNew = vec4( sampleTexture( uvNode ) );
  30875. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30876. return max$1( texelNew, texelOld );
  30877. } );
  30878. //
  30879. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30880. materialComposed.fragmentNode = afterImg();
  30881. _quadMeshComp.material = materialComposed;
  30882. //
  30883. const properties = builder.getNodeProperties( this );
  30884. properties.textureNode = textureNode;
  30885. //
  30886. return this._textureNode;
  30887. }
  30888. dispose() {
  30889. this._compRT.dispose();
  30890. this._oldRT.dispose();
  30891. }
  30892. }
  30893. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30894. addNodeElement( 'afterImage', afterImage );
  30895. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  30896. class AnamorphicNode extends TempNode {
  30897. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30898. super( 'vec4' );
  30899. this.textureNode = textureNode;
  30900. this.tresholdNode = tresholdNode;
  30901. this.scaleNode = scaleNode;
  30902. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30903. this.samples = samples;
  30904. this.resolution = new Vector2( 1, 1 );
  30905. this._renderTarget = new RenderTarget();
  30906. this._renderTarget.texture.name = 'anamorphic';
  30907. this._invSize = uniform( new Vector2() );
  30908. this._textureNode = passTexture( this, this._renderTarget.texture );
  30909. this.updateBeforeType = NodeUpdateType.RENDER;
  30910. }
  30911. getTextureNode() {
  30912. return this._textureNode;
  30913. }
  30914. setSize( width, height ) {
  30915. this._invSize.value.set( 1 / width, 1 / height );
  30916. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30917. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30918. this._renderTarget.setSize( width, height );
  30919. }
  30920. updateBefore( frame ) {
  30921. const { renderer } = frame;
  30922. const textureNode = this.textureNode;
  30923. const map = textureNode.value;
  30924. this._renderTarget.texture.type = map.type;
  30925. const currentRenderTarget = renderer.getRenderTarget();
  30926. const currentTexture = textureNode.value;
  30927. _quadMesh$3.material = this._material;
  30928. this.setSize( map.image.width, map.image.height );
  30929. // render
  30930. renderer.setRenderTarget( this._renderTarget );
  30931. _quadMesh$3.render( renderer );
  30932. // restore
  30933. renderer.setRenderTarget( currentRenderTarget );
  30934. textureNode.value = currentTexture;
  30935. }
  30936. setup( builder ) {
  30937. const textureNode = this.textureNode;
  30938. const uvNode = textureNode.uvNode || uv();
  30939. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30940. const anamorph = tslFn( () => {
  30941. const samples = this.samples;
  30942. const halfSamples = Math.floor( samples / 2 );
  30943. const total = vec3( 0 ).toVar();
  30944. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30945. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30946. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30947. const color = sampleTexture( uv );
  30948. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30949. total.addAssign( pass );
  30950. } );
  30951. return total.mul( this.colorNode );
  30952. } );
  30953. //
  30954. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30955. material.fragmentNode = anamorph();
  30956. //
  30957. const properties = builder.getNodeProperties( this );
  30958. properties.textureNode = textureNode;
  30959. //
  30960. return this._textureNode;
  30961. }
  30962. dispose() {
  30963. this._renderTarget.dispose();
  30964. }
  30965. }
  30966. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30967. addNodeElement( 'anamorphic', anamorphic );
  30968. class SobelOperatorNode extends TempNode {
  30969. constructor( textureNode ) {
  30970. super();
  30971. this.textureNode = textureNode;
  30972. this.updateBeforeType = NodeUpdateType.RENDER;
  30973. this._invSize = uniform( new Vector2() );
  30974. }
  30975. updateBefore() {
  30976. const map = this.textureNode.value;
  30977. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30978. }
  30979. setup() {
  30980. const { textureNode } = this;
  30981. const uvNode = textureNode.uvNode || uv();
  30982. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30983. const sobel = tslFn( () => {
  30984. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30985. const texel = this._invSize;
  30986. // kernel definition (in glsl matrices are filled in column-major order)
  30987. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30988. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30989. // fetch the 3x3 neighbourhood of a fragment
  30990. // first column
  30991. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30992. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30993. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30994. // second column
  30995. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30996. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30997. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30998. // third column
  30999. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  31000. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  31001. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  31002. // gradient value in x direction
  31003. const valueGx = add(
  31004. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  31005. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  31006. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  31007. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  31008. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  31009. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  31010. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  31011. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  31012. Gx[ 2 ][ 2 ].mul( tx2y2 )
  31013. );
  31014. // gradient value in y direction
  31015. const valueGy = add(
  31016. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  31017. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  31018. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  31019. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  31020. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  31021. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  31022. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  31023. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  31024. Gy[ 2 ][ 2 ].mul( tx2y2 )
  31025. );
  31026. // magnitute of the total gradient
  31027. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  31028. return vec4( vec3( G ), 1 );
  31029. } );
  31030. const outputNode = sobel();
  31031. return outputNode;
  31032. }
  31033. }
  31034. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  31035. addNodeElement( 'sobel', sobel );
  31036. class DepthOfFieldNode extends TempNode {
  31037. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  31038. super();
  31039. this.textureNode = textureNode;
  31040. this.viewZNode = viewZNode;
  31041. this.focusNode = focusNode;
  31042. this.apertureNode = apertureNode;
  31043. this.maxblurNode = maxblurNode;
  31044. this._aspect = uniform( 0 );
  31045. this.updateBeforeType = NodeUpdateType.RENDER;
  31046. }
  31047. updateBefore() {
  31048. const map = this.textureNode.value;
  31049. this._aspect.value = map.image.width / map.image.height;
  31050. }
  31051. setup() {
  31052. const textureNode = this.textureNode;
  31053. const uvNode = textureNode.uvNode || uv();
  31054. const sampleTexture = ( uv ) => textureNode.uv( uv );
  31055. const dof = tslFn( () => {
  31056. const aspectcorrect = vec2( 1.0, this._aspect );
  31057. const factor = this.focusNode.add( this.viewZNode );
  31058. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  31059. const dofblur9 = dofblur.mul( 0.9 );
  31060. const dofblur7 = dofblur.mul( 0.7 );
  31061. const dofblur4 = dofblur.mul( 0.4 );
  31062. let col = vec4( 0.0 );
  31063. col = col.add( sampleTexture( uvNode ) );
  31064. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31065. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31066. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31067. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31068. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31069. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31070. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31071. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31072. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31073. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31074. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31075. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31076. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31077. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31078. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31079. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31080. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31081. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31082. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31083. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31084. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31085. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31086. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31087. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31088. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31089. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31090. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31091. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31092. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31093. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31094. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31095. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31096. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31097. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31098. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31099. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31100. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31101. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31102. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31103. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31104. col = col.div( 41 );
  31105. col.a = 1;
  31106. return vec4( col );
  31107. } );
  31108. const outputNode = dof();
  31109. return outputNode;
  31110. }
  31111. }
  31112. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( nodeObject( node ).toTexture(), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  31113. addNodeElement( 'dof', dof );
  31114. class DotScreenNode extends TempNode {
  31115. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  31116. super( 'vec4' );
  31117. this.inputNode = inputNode;
  31118. this.center = uniform( center );
  31119. this.angle = uniform( angle );
  31120. this.scale = uniform( scale );
  31121. this._size = uniform( new Vector2() );
  31122. this.updateBeforeType = NodeUpdateType.RENDER;
  31123. }
  31124. updateBefore( frame ) {
  31125. const { renderer } = frame;
  31126. renderer.getDrawingBufferSize( this._size.value );
  31127. }
  31128. setup() {
  31129. const inputNode = this.inputNode;
  31130. const pattern = tslFn( () => {
  31131. const s = sin( this.angle );
  31132. const c = cos( this.angle );
  31133. const tex = uv().mul( this._size ).sub( this.center );
  31134. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  31135. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  31136. } );
  31137. const dotScreen = tslFn( () => {
  31138. const color = inputNode;
  31139. const average = add( color.r, color.g, color.b ).div( 3 );
  31140. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  31141. } );
  31142. const outputNode = dotScreen();
  31143. return outputNode;
  31144. }
  31145. }
  31146. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  31147. addNodeElement( 'dotScreen', dotScreen );
  31148. class RGBShiftNode extends TempNode {
  31149. constructor( textureNode, amount = 0.005, angle = 0 ) {
  31150. super( 'vec4' );
  31151. this.textureNode = textureNode;
  31152. this.amount = uniform( amount );
  31153. this.angle = uniform( angle );
  31154. }
  31155. setup() {
  31156. const { textureNode } = this;
  31157. const uvNode = textureNode.uvNode || uv();
  31158. const sampleTexture = ( uv ) => textureNode.uv( uv );
  31159. const rgbShift = tslFn( () => {
  31160. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  31161. const cr = sampleTexture( uvNode.add( offset ) );
  31162. const cga = sampleTexture( uvNode );
  31163. const cb = sampleTexture( uvNode.sub( offset ) );
  31164. return vec4( cr.r, cga.g, cb.b, cga.a );
  31165. } );
  31166. return rgbShift();
  31167. }
  31168. }
  31169. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  31170. addNodeElement( 'rgbShift', rgbShift );
  31171. class FilmNode extends TempNode {
  31172. constructor( inputNode, intensityNode = null, uvNode = null ) {
  31173. super();
  31174. this.inputNode = inputNode;
  31175. this.intensityNode = intensityNode;
  31176. this.uvNode = uvNode;
  31177. }
  31178. setup() {
  31179. const uvNode = this.uvNode || uv();
  31180. const film = tslFn( () => {
  31181. const base = this.inputNode.rgb;
  31182. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31183. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31184. if ( this.intensityNode !== null ) {
  31185. color = mix( base, color, this.intensityNode );
  31186. }
  31187. return vec4( color, this.inputNode.a );
  31188. } );
  31189. const outputNode = film();
  31190. return outputNode;
  31191. }
  31192. }
  31193. const film = nodeProxy( FilmNode );
  31194. addNodeElement( 'film', film );
  31195. class Lut3DNode extends TempNode {
  31196. constructor( inputNode, lutNode, size, intensityNode ) {
  31197. super();
  31198. this.inputNode = inputNode;
  31199. this.lutNode = lutNode;
  31200. this.size = uniform( size );
  31201. this.intensityNode = intensityNode;
  31202. }
  31203. setup() {
  31204. const { inputNode, lutNode } = this;
  31205. const sampleLut = ( uv ) => lutNode.uv( uv );
  31206. const lut3D = tslFn( () => {
  31207. const base = inputNode;
  31208. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31209. const pixelWidth = float( 1.0 ).div( this.size );
  31210. const halfPixelWidth = float( 0.5 ).div( this.size );
  31211. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31212. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31213. return vec4( mix( base, lutValue, this.intensityNode ) );
  31214. } );
  31215. const outputNode = lut3D();
  31216. return outputNode;
  31217. }
  31218. }
  31219. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31220. addNodeElement( 'lut3D', lut3D );
  31221. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  31222. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  31223. const _size$2 = /*@__PURE__*/ new Vector2();
  31224. class GTAONode extends TempNode {
  31225. constructor( depthNode, normalNode, camera ) {
  31226. super();
  31227. this.depthNode = depthNode;
  31228. this.normalNode = normalNode;
  31229. this.radius = uniform( 0.25 );
  31230. this.resolution = uniform( new Vector2() );
  31231. this.thickness = uniform( 1 );
  31232. this.distanceExponent = uniform( 1 );
  31233. this.distanceFallOff = uniform( 1 );
  31234. this.scale = uniform( 1 );
  31235. this.noiseNode = texture( generateMagicSquareNoise() );
  31236. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  31237. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31238. this.SAMPLES = uniform( 16 );
  31239. this._aoRenderTarget = new RenderTarget();
  31240. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  31241. this._material = null;
  31242. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  31243. this.updateBeforeType = NodeUpdateType.FRAME;
  31244. }
  31245. getTextureNode() {
  31246. return this._textureNode;
  31247. }
  31248. setSize( width, height ) {
  31249. this.resolution.value.set( width, height );
  31250. this._aoRenderTarget.setSize( width, height );
  31251. }
  31252. updateBefore( frame ) {
  31253. const { renderer } = frame;
  31254. const size = renderer.getDrawingBufferSize( _size$2 );
  31255. const currentRenderTarget = renderer.getRenderTarget();
  31256. const currentMRT = renderer.getMRT();
  31257. renderer.getClearColor( _currentClearColor$1 );
  31258. const currentClearAlpha = renderer.getClearAlpha();
  31259. _quadMesh$2.material = this._material;
  31260. this.setSize( size.width, size.height );
  31261. // clear
  31262. renderer.setMRT( null );
  31263. renderer.setClearColor( 0xffffff, 1 );
  31264. // ao
  31265. renderer.setRenderTarget( this._aoRenderTarget );
  31266. _quadMesh$2.render( renderer );
  31267. // restore
  31268. renderer.setRenderTarget( currentRenderTarget );
  31269. renderer.setMRT( currentMRT );
  31270. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  31271. }
  31272. setup( builder ) {
  31273. const uvNode = uv();
  31274. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31275. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31276. const getSceneUvAndDepth = tslFn( ( [ sampleViewPos ] )=> {
  31277. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  31278. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31279. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31280. const sampleSceneDepth = sampleDepth( sampleUv );
  31281. return vec3( sampleUv, sampleSceneDepth );
  31282. } );
  31283. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31284. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31285. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31286. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31287. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31288. } );
  31289. const ao = tslFn( () => {
  31290. const depth = sampleDepth( uvNode );
  31291. depth.greaterThanEqual( 1.0 ).discard();
  31292. const viewPosition = getViewPosition( uvNode, depth );
  31293. const viewNormal = this.normalNode.rgb.normalize();
  31294. const radiusToUse = this.radius;
  31295. const noiseResolution = textureSize( this.noiseNode, 0 );
  31296. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31297. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  31298. const noiseTexel = sampleNoise( noiseUv );
  31299. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  31300. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  31301. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  31302. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  31303. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).cond( 3, 5 );
  31304. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  31305. const ao = float( 0 ).toVar();
  31306. loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  31307. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  31308. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  31309. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  31310. const viewDir = normalize( viewPosition.xyz.negate() );
  31311. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  31312. const sliceTangent = cross( sliceBitangent, viewDir );
  31313. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  31314. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  31315. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  31316. loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  31317. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  31318. // x
  31319. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  31320. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  31321. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  31322. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  31323. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  31324. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31325. } );
  31326. // y
  31327. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  31328. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  31329. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  31330. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  31331. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  31332. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31333. } );
  31334. } );
  31335. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  31336. const nx = dot( normalInSlice, sliceTangent );
  31337. const ny = dot( normalInSlice, viewDir );
  31338. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  31339. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  31340. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  31341. ao.addAssign( occlusion );
  31342. } );
  31343. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  31344. ao.assign( pow( ao, this.scale ) );
  31345. return vec4( vec3( ao ), 1.0 );
  31346. } );
  31347. const material = this._material || ( this._material = builder.createNodeMaterial() );
  31348. material.fragmentNode = ao().context( builder.getSharedContext() );
  31349. material.needsUpdate = true;
  31350. //
  31351. return this._textureNode;
  31352. }
  31353. dispose() {
  31354. this._aoRenderTarget.dispose();
  31355. }
  31356. }
  31357. function generateMagicSquareNoise( size = 5 ) {
  31358. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31359. const magicSquare = generateMagicSquare( noiseSize );
  31360. const noiseSquareSize = magicSquare.length;
  31361. const data = new Uint8Array( noiseSquareSize * 4 );
  31362. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  31363. const iAng = magicSquare[ inx ];
  31364. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  31365. const randomVec = new Vector3(
  31366. Math.cos( angle ),
  31367. Math.sin( angle ),
  31368. 0
  31369. ).normalize();
  31370. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  31371. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  31372. data[ inx * 4 + 2 ] = 127;
  31373. data[ inx * 4 + 3 ] = 255;
  31374. }
  31375. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  31376. noiseTexture.wrapS = RepeatWrapping;
  31377. noiseTexture.wrapT = RepeatWrapping;
  31378. noiseTexture.needsUpdate = true;
  31379. return noiseTexture;
  31380. }
  31381. function generateMagicSquare( size ) {
  31382. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31383. const noiseSquareSize = noiseSize * noiseSize;
  31384. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  31385. let i = Math.floor( noiseSize / 2 );
  31386. let j = noiseSize - 1;
  31387. for ( let num = 1; num <= noiseSquareSize; ) {
  31388. if ( i === - 1 && j === noiseSize ) {
  31389. j = noiseSize - 2;
  31390. i = 0;
  31391. } else {
  31392. if ( j === noiseSize ) {
  31393. j = 0;
  31394. }
  31395. if ( i < 0 ) {
  31396. i = noiseSize - 1;
  31397. }
  31398. }
  31399. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  31400. j -= 2;
  31401. i ++;
  31402. continue;
  31403. } else {
  31404. magicSquare[ i * noiseSize + j ] = num ++;
  31405. }
  31406. j ++;
  31407. i --;
  31408. }
  31409. return magicSquare;
  31410. }
  31411. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  31412. addNodeElement( 'ao', ao );
  31413. class DenoiseNode extends TempNode {
  31414. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  31415. super();
  31416. this.textureNode = textureNode;
  31417. this.depthNode = depthNode;
  31418. this.normalNode = normalNode;
  31419. this.noiseNode = noiseNode;
  31420. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31421. this.lumaPhi = uniform( 5 );
  31422. this.depthPhi = uniform( 5 );
  31423. this.normalPhi = uniform( 5 );
  31424. this.radius = uniform( 5 );
  31425. this.index = uniform( 0 );
  31426. this._resolution = uniform( new Vector2() );
  31427. this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
  31428. this.updateBeforeType = NodeUpdateType.RENDER;
  31429. }
  31430. updateBefore() {
  31431. const map = this.textureNode.value;
  31432. this._resolution.value.set( map.image.width, map.image.height );
  31433. }
  31434. setup() {
  31435. const uvNode = uv();
  31436. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  31437. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31438. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  31439. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31440. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31441. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31442. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31443. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31444. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31445. } );
  31446. const denoiseSample = tslFn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  31447. const texel = sampleTexture( sampleUv );
  31448. const depth = sampleDepth( sampleUv );
  31449. const normal = sampleNormal( sampleUv ).rgb.normalize();
  31450. const neighborColor = texel.rgb;
  31451. const viewPos = getViewPosition( sampleUv, depth );
  31452. const normalDiff = dot( viewNormal, normal ).toVar();
  31453. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  31454. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  31455. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  31456. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  31457. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  31458. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  31459. return vec4( neighborColor.mul( w ), w );
  31460. } );
  31461. const denoise = tslFn( ( [ uvNode ] ) => {
  31462. const depth = sampleDepth( uvNode );
  31463. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  31464. const texel = sampleTexture( uvNode );
  31465. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  31466. return texel;
  31467. } );
  31468. const center = vec3( texel.rgb );
  31469. const viewPosition = getViewPosition( uvNode, depth );
  31470. const noiseResolution = textureSize( this.noiseNode, 0 );
  31471. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31472. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  31473. const noiseTexel = sampleNoise( noiseUv );
  31474. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31475. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31476. const noiseVec = vec2( x, y );
  31477. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  31478. const totalWeight = float( 1.0 ).toVar();
  31479. const denoised = vec3( texel.rgb ).toVar();
  31480. loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  31481. const sampleDir = this._sampleVectors.element( i ).toVar();
  31482. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  31483. const sampleUv = uvNode.add( offset ).toVar();
  31484. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  31485. denoised.addAssign( result.xyz );
  31486. totalWeight.addAssign( result.w );
  31487. } );
  31488. If( totalWeight.greaterThan( float( 0 ) ), () => {
  31489. denoised.divAssign( totalWeight );
  31490. } );
  31491. return vec4( denoised, texel.a );
  31492. } ).setLayout( {
  31493. name: 'denoise',
  31494. type: 'vec4',
  31495. inputs: [
  31496. { name: 'uv', type: 'vec2' }
  31497. ]
  31498. } );
  31499. const output = tslFn( () => {
  31500. return denoise( uvNode );
  31501. } );
  31502. const outputNode = output();
  31503. return outputNode;
  31504. }
  31505. }
  31506. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  31507. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  31508. const array = [];
  31509. for ( let i = 0; i < samples; i ++ ) {
  31510. const sample = poissonDisk[ i ];
  31511. array.push( sample );
  31512. }
  31513. return array;
  31514. }
  31515. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  31516. const samples = [];
  31517. for ( let i = 0; i < numSamples; i ++ ) {
  31518. const angle = 2 * Math.PI * numRings * i / numSamples;
  31519. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  31520. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  31521. }
  31522. return samples;
  31523. }
  31524. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( nodeObject( node ).toTexture(), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  31525. addNodeElement( 'denoise', denoise );
  31526. class FXAANode extends TempNode {
  31527. constructor( textureNode ) {
  31528. super();
  31529. this.textureNode = textureNode;
  31530. this.updateBeforeType = NodeUpdateType.RENDER;
  31531. this._invSize = uniform( new Vector2() );
  31532. }
  31533. updateBefore() {
  31534. const map = this.textureNode.value;
  31535. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  31536. }
  31537. setup() {
  31538. const textureNode = this.textureNode.bias( - 100 );
  31539. const uvNode = textureNode.uvNode || uv();
  31540. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  31541. //----------------------------------------------------------------------------------
  31542. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  31543. // SDK Version: v3.00
  31544. // Email: gameworks@nvidia.com
  31545. // Site: http://developer.nvidia.com/
  31546. //
  31547. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  31548. //
  31549. // Redistribution and use in source and binary forms, with or without
  31550. // modification, are permitted provided that the following conditions
  31551. // are met:
  31552. // * Redistributions of source code must retain the above copyright
  31553. // notice, this list of conditions and the following disclaimer.
  31554. // * Redistributions in binary form must reproduce the above copyright
  31555. // notice, this list of conditions and the following disclaimer in the
  31556. // documentation and/or other materials provided with the distribution.
  31557. // * Neither the name of NVIDIA CORPORATION nor the names of its
  31558. // contributors may be used to endorse or promote products derived
  31559. // from this software without specific prior written permission.
  31560. //
  31561. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  31562. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  31563. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  31564. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31565. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  31566. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  31567. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  31568. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  31569. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31570. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31571. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31572. //
  31573. //----------------------------------------------------------------------------------
  31574. const FxaaTexTop = ( p ) => textureNode.uv( p );
  31575. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  31576. const NUM_SAMPLES = int( 5 );
  31577. const contrast = tslFn( ( [ a_immutable, b_immutable ] ) => {
  31578. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  31579. const b = vec4( b_immutable ).toVar();
  31580. const a = vec4( a_immutable ).toVar();
  31581. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  31582. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  31583. } );
  31584. // FXAA3 QUALITY - PC
  31585. const FxaaPixelShader = tslFn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  31586. const rgbaM = FxaaTexTop( uv ).toVar();
  31587. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31588. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31589. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31590. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31591. // . S .
  31592. // W M E
  31593. // . N .
  31594. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  31595. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  31596. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  31597. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  31598. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  31599. // . 0 .
  31600. // 0 0 0
  31601. // . 0 .
  31602. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  31603. return rgbaM; // assuming define FXAA_DISCARD is always 0
  31604. } );
  31605. //
  31606. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  31607. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31608. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  31609. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  31610. // locate the edge
  31611. const x = contrastE.greaterThan( contrastW ).cond( 1, - 1 ).toVar();
  31612. const y = contrastS.greaterThan( contrastN ).cond( 1, - 1 ).toVar();
  31613. const dirToEdge = vec2( x, y ).toVar();
  31614. // . 2 . . 1 .
  31615. // 1 0 2 ~= 0 0 1
  31616. // . 1 . . 0 .
  31617. // tap 2 pixels and see which ones are "outside" the edge, to
  31618. // determine if the edge is vertical or horizontal
  31619. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  31620. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  31621. // . 1 .
  31622. // 0 0 1
  31623. // . 0 H
  31624. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  31625. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  31626. // V 1 .
  31627. // 0 0 1
  31628. // . 0 .
  31629. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  31630. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31631. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  31632. // 1 1 .
  31633. // 0 0 1
  31634. // . 0 1
  31635. // do a simple blur
  31636. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  31637. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  31638. } );
  31639. } );
  31640. const offNP = vec2().toVar();
  31641. If( relativeVContrast.lessThanEqual( 0 ), () => {
  31642. rgbaN.assign( rgbaW );
  31643. rgbaS.assign( rgbaE );
  31644. // . 0 . 1
  31645. // 1 0 1 -> 0
  31646. // . 0 . 1
  31647. offNP.x.assign( 0 );
  31648. offNP.y.assign( fxaaQualityRcpFrame.y );
  31649. } ).else( () => {
  31650. offNP.x.assign( fxaaQualityRcpFrame.x );
  31651. offNP.y.assign( 0 );
  31652. } );
  31653. const mn = contrast( rgbaM, rgbaN ).toVar();
  31654. const ms = contrast( rgbaM, rgbaS ).toVar();
  31655. If( mn.lessThanEqual( ms ), () => {
  31656. rgbaN.assign( rgbaS );
  31657. } );
  31658. const doneN = int( 0 ).toVar();
  31659. const doneP = int( 0 ).toVar();
  31660. const nDist = float( 0 ).toVar();
  31661. const pDist = float( 0 ).toVar();
  31662. const posN = vec2( uv ).toVar();
  31663. const posP = vec2( uv ).toVar();
  31664. const iterationsUsedN = int( 0 ).toVar();
  31665. const iterationsUsedP = int( 0 ).toVar();
  31666. loop( NUM_SAMPLES, ( { i } ) => {
  31667. const increment = i.add( 1 ).toVar();
  31668. If( doneN.equal( 0 ), () => {
  31669. nDist.addAssign( increment );
  31670. posN.assign( uv.add( offNP.mul( nDist ) ) );
  31671. const rgbaEndN = FxaaTexTop( posN.xy );
  31672. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  31673. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  31674. If( nm.greaterThan( nn ), () => {
  31675. doneN.assign( 1 );
  31676. } );
  31677. iterationsUsedN.assign( i );
  31678. } );
  31679. If( doneP.equal( 0 ), () => {
  31680. pDist.addAssign( increment );
  31681. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  31682. const rgbaEndP = FxaaTexTop( posP.xy );
  31683. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  31684. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  31685. If( pm.greaterThan( pn ), () => {
  31686. doneP.assign( 1 );
  31687. } );
  31688. iterationsUsedP.assign( i );
  31689. } );
  31690. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  31691. Break();
  31692. } );
  31693. } );
  31694. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  31695. return rgbaM; // failed to find end of edge
  31696. } );
  31697. const distN = float( 1 ).toVar();
  31698. const distP = float( 1 ).toVar();
  31699. If( doneN.equal( 1 ), () => {
  31700. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31701. } );
  31702. If( doneP.equal( 1 ), () => {
  31703. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31704. } );
  31705. const dist = min$1( distN, distP );
  31706. // hacky way of reduces blurriness of mostly diagonal edges
  31707. // but reduces AA quality
  31708. dist.assign( pow( dist, 0.5 ) );
  31709. dist.assign( float( 1 ).sub( dist ) );
  31710. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  31711. } ).setLayout( {
  31712. name: 'FxaaPixelShader',
  31713. type: 'vec4',
  31714. inputs: [
  31715. { name: 'uv', type: 'vec2' },
  31716. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  31717. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  31718. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  31719. ]
  31720. } );
  31721. const fxaa = tslFn( () => {
  31722. const edgeDetectionQuality = float( 0.2 );
  31723. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  31724. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  31725. } );
  31726. const outputNode = fxaa();
  31727. return outputNode;
  31728. }
  31729. }
  31730. const fxaa = ( node ) => nodeObject( new FXAANode( nodeObject( node ).toTexture() ) );
  31731. addNodeElement( 'fxaa', fxaa );
  31732. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  31733. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  31734. const _currentClearColor = /*@__PURE__*/ new Color();
  31735. const _size$1 = /*@__PURE__*/ new Vector2();
  31736. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  31737. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  31738. class BloomNode extends TempNode {
  31739. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  31740. super();
  31741. this.inputNode = inputNode;
  31742. this.strength = uniform( strength );
  31743. this.radius = uniform( radius );
  31744. this.threshold = uniform( threshold );
  31745. this.smoothWidth = uniform( 0.01 );
  31746. //
  31747. this._renderTargetsHorizontal = [];
  31748. this._renderTargetsVertical = [];
  31749. this._nMips = 5;
  31750. // render targets
  31751. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31752. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  31753. this._renderTargetBright.texture.generateMipmaps = false;
  31754. for ( let i = 0; i < this._nMips; i ++ ) {
  31755. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31756. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  31757. renderTargetHorizontal.texture.generateMipmaps = false;
  31758. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  31759. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31760. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  31761. renderTargetVertical.texture.generateMipmaps = false;
  31762. this._renderTargetsVertical.push( renderTargetVertical );
  31763. }
  31764. // materials
  31765. this._compositeMaterial = null;
  31766. this._highPassFilterMaterial = null;
  31767. this._separableBlurMaterials = [];
  31768. // pass and texture nodes
  31769. this._textureNodeBright = texture( this._renderTargetBright.texture );
  31770. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  31771. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  31772. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  31773. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  31774. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  31775. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  31776. this.updateBeforeType = NodeUpdateType.FRAME;
  31777. }
  31778. getTextureNode() {
  31779. return this._textureOutput;
  31780. }
  31781. setSize( width, height ) {
  31782. let resx = Math.round( width / 2 );
  31783. let resy = Math.round( height / 2 );
  31784. this._renderTargetBright.setSize( resx, resy );
  31785. for ( let i = 0; i < this._nMips; i ++ ) {
  31786. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  31787. this._renderTargetsVertical[ i ].setSize( resx, resy );
  31788. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  31789. resx = Math.round( resx / 2 );
  31790. resy = Math.round( resy / 2 );
  31791. }
  31792. }
  31793. updateBefore( frame ) {
  31794. const { renderer } = frame;
  31795. const size = renderer.getDrawingBufferSize( _size$1 );
  31796. this.setSize( size.width, size.height );
  31797. const currentRenderTarget = renderer.getRenderTarget();
  31798. const currentMRT = renderer.getMRT();
  31799. renderer.getClearColor( _currentClearColor );
  31800. const currentClearAlpha = renderer.getClearAlpha();
  31801. this.setSize( size.width, size.height );
  31802. renderer.setMRT( null );
  31803. renderer.setClearColor( _clearColor$1, 0 );
  31804. // 1. Extract Bright Areas
  31805. renderer.setRenderTarget( this._renderTargetBright );
  31806. _quadMesh$1.material = this._highPassFilterMaterial;
  31807. _quadMesh$1.render( renderer );
  31808. // 2. Blur All the mips progressively
  31809. let inputRenderTarget = this._renderTargetBright;
  31810. for ( let i = 0; i < this._nMips; i ++ ) {
  31811. _quadMesh$1.material = this._separableBlurMaterials[ i ];
  31812. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  31813. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  31814. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  31815. renderer.clear();
  31816. _quadMesh$1.render( renderer );
  31817. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  31818. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  31819. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  31820. renderer.clear();
  31821. _quadMesh$1.render( renderer );
  31822. inputRenderTarget = this._renderTargetsVertical[ i ];
  31823. }
  31824. // 3. Composite All the mips
  31825. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  31826. renderer.clear();
  31827. _quadMesh$1.material = this._compositeMaterial;
  31828. _quadMesh$1.render( renderer );
  31829. // restore
  31830. renderer.setRenderTarget( currentRenderTarget );
  31831. renderer.setMRT( currentMRT );
  31832. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  31833. }
  31834. setup( builder ) {
  31835. // luminosity high pass material
  31836. const luminosityHighPass = tslFn( () => {
  31837. const texel = this.inputNode;
  31838. const v = luminance( texel.rgb );
  31839. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  31840. return mix( vec4( 0 ), texel, alpha );
  31841. } );
  31842. this._highPassFilterMaterial = this._highPassFilterMaterial || builder.createNodeMaterial();
  31843. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  31844. this._highPassFilterMaterial.needsUpdate = true;
  31845. // gaussian blur materials
  31846. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  31847. for ( let i = 0; i < this._nMips; i ++ ) {
  31848. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  31849. }
  31850. // composite material
  31851. const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  31852. const bloomTintColors = uniformArray( [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ] );
  31853. const lerpBloomFactor = tslFn( ( [ factor, radius ] ) => {
  31854. const mirrorFactor = float( 1.2 ).sub( factor );
  31855. return mix( factor, mirrorFactor, radius );
  31856. } ).setLayout( {
  31857. name: 'lerpBloomFactor',
  31858. type: 'float',
  31859. inputs: [
  31860. { name: 'factor', type: 'float' },
  31861. { name: 'radius', type: 'float' },
  31862. ]
  31863. } );
  31864. const compositePass = tslFn( () => {
  31865. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  31866. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  31867. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  31868. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  31869. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  31870. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  31871. return sum.mul( this.strength );
  31872. } );
  31873. this._compositeMaterial = this._compositeMaterial || builder.createNodeMaterial();
  31874. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  31875. this._compositeMaterial.needsUpdate = true;
  31876. //
  31877. return this._textureOutput;
  31878. }
  31879. dispose() {
  31880. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  31881. this._renderTargetsHorizontal[ i ].dispose();
  31882. }
  31883. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  31884. this._renderTargetsVertical[ i ].dispose();
  31885. }
  31886. this._renderTargetBright.dispose();
  31887. }
  31888. _getSeperableBlurMaterial( builder, kernelRadius ) {
  31889. const coefficients = [];
  31890. for ( let i = 0; i < kernelRadius; i ++ ) {
  31891. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  31892. }
  31893. //
  31894. const colorTexture = texture();
  31895. const gaussianCoefficients = uniformArray( coefficients );
  31896. const invSize = uniform( new Vector2() );
  31897. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  31898. const uvNode = uv();
  31899. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  31900. const seperableBlurPass = tslFn( () => {
  31901. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  31902. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  31903. loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  31904. const x = float( i );
  31905. const w = gaussianCoefficients.element( i );
  31906. const uvOffset = direction.mul( invSize ).mul( x );
  31907. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  31908. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  31909. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  31910. weightSum.addAssign( float( 2.0 ).mul( w ) );
  31911. } );
  31912. return vec4( diffuseSum.div( weightSum ), 1.0 );
  31913. } );
  31914. const seperableBlurMaterial = builder.createNodeMaterial();
  31915. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  31916. seperableBlurMaterial.needsUpdate = true;
  31917. // uniforms
  31918. seperableBlurMaterial.colorTexture = colorTexture;
  31919. seperableBlurMaterial.direction = direction;
  31920. seperableBlurMaterial.invSize = invSize;
  31921. return seperableBlurMaterial;
  31922. }
  31923. }
  31924. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  31925. addNodeElement( 'bloom', bloom );
  31926. class TransitionNode extends TempNode {
  31927. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  31928. super();
  31929. // Input textures
  31930. this.textureNodeA = textureNodeA;
  31931. this.textureNodeB = textureNodeB;
  31932. this.mixTextureNode = mixTextureNode;
  31933. // Uniforms
  31934. this.mixRatioNode = mixRatioNode;
  31935. this.thresholdNode = thresholdNode;
  31936. this.useTextureNode = useTextureNode;
  31937. }
  31938. setup() {
  31939. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  31940. const sampleTexture = ( textureNode ) => {
  31941. const uvNodeTexture = textureNode.uvNode || uv();
  31942. return textureNode.uv( uvNodeTexture );
  31943. };
  31944. const transition = tslFn( () => {
  31945. const texelOne = sampleTexture( textureNodeA );
  31946. const texelTwo = sampleTexture( textureNodeB );
  31947. const color = vec4().toVar();
  31948. If( useTextureNode.equal( int( 1 ) ), () => {
  31949. const transitionTexel = sampleTexture( mixTextureNode );
  31950. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  31951. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  31952. color.assign( mix( texelOne, texelTwo, mixf ) );
  31953. } ).else( () => {
  31954. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  31955. } );
  31956. return color;
  31957. } );
  31958. const outputNode = transition();
  31959. return outputNode;
  31960. }
  31961. }
  31962. const transition = ( nodeA, nodeB, mixTexture, mixRatio = 0.0, threshold = 0.1, useTexture = 0 ) => nodeObject( new TransitionNode( nodeObject( nodeA ).toTexture(), nodeObject( nodeB ).toTexture(), nodeObject( mixTexture ).toTexture(), nodeObject( mixRatio ), nodeObject( threshold ), nodeObject( useTexture ) ) );
  31963. addNodeElement( 'transition', transition );
  31964. class RenderOutputNode extends TempNode {
  31965. constructor( colorNode, toneMapping, outputColorSpace ) {
  31966. super( 'vec4' );
  31967. this.colorNode = colorNode;
  31968. this.toneMapping = toneMapping;
  31969. this.outputColorSpace = outputColorSpace;
  31970. this.isRenderOutput = true;
  31971. }
  31972. setup( { context } ) {
  31973. let outputNode = this.colorNode || context.color;
  31974. // tone mapping
  31975. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  31976. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  31977. if ( toneMapping !== NoToneMapping ) {
  31978. outputNode = outputNode.toneMapping( toneMapping );
  31979. }
  31980. // output color space
  31981. if ( outputColorSpace === SRGBColorSpace ) {
  31982. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  31983. }
  31984. return outputNode;
  31985. }
  31986. }
  31987. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  31988. addNodeElement( 'renderOutput', renderOutput );
  31989. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  31990. class PixelationNode extends TempNode {
  31991. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  31992. super();
  31993. // Input textures
  31994. this.textureNode = textureNode;
  31995. this.depthNode = depthNode;
  31996. this.normalNode = normalNode;
  31997. // Input uniforms
  31998. this.pixelSize = pixelSize;
  31999. this.normalEdgeStrength = normalEdgeStrength;
  32000. this.depthEdgeStrength = depthEdgeStrength;
  32001. // Private uniforms
  32002. this._resolution = uniform( new Vector4() );
  32003. this.updateBeforeType = NodeUpdateType.RENDER;
  32004. }
  32005. updateBefore() {
  32006. const map = this.textureNode.value;
  32007. const width = map.image.width;
  32008. const height = map.image.height;
  32009. this._resolution.value.set( width, height, 1 / width, 1 / height );
  32010. }
  32011. setup() {
  32012. const { textureNode, depthNode, normalNode } = this;
  32013. const uvNodeTexture = textureNode.uvNode || uv();
  32014. const uvNodeDepth = depthNode.uvNode || uv();
  32015. const uvNodeNormal = normalNode.uvNode || uv();
  32016. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  32017. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  32018. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  32019. const depthEdgeIndicator = ( depth ) => {
  32020. const diff = property( 'float', 'diff' );
  32021. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  32022. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  32023. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  32024. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  32025. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  32026. };
  32027. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  32028. const depthDiff = sampleDepth( x, y ).sub( depth );
  32029. const neighborNormal = sampleNormal( x, y );
  32030. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  32031. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  32032. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  32033. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  32034. // Only the shallower pixel should detect the normal edge.
  32035. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  32036. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  32037. };
  32038. const normalEdgeIndicator = ( depth, normal ) => {
  32039. const indicator = property( 'float', 'indicator' );
  32040. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  32041. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  32042. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  32043. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  32044. return step( 0.1, indicator );
  32045. };
  32046. const pixelation = tslFn( () => {
  32047. const texel = sampleTexture();
  32048. const depth = property( 'float', 'depth' );
  32049. const normal = property( 'vec3', 'normal' );
  32050. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  32051. depth.assign( sampleDepth( 0, 0 ) );
  32052. normal.assign( sampleNormal( 0, 0 ) );
  32053. } );
  32054. const dei = property( 'float', 'dei' );
  32055. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  32056. dei.assign( depthEdgeIndicator( depth ) );
  32057. } );
  32058. const nei = property( 'float', 'nei' );
  32059. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  32060. nei.assign( normalEdgeIndicator( depth, normal ) );
  32061. } );
  32062. const strength = dei.greaterThan( 0 ).cond( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  32063. return texel.mul( strength );
  32064. } );
  32065. const outputNode = pixelation();
  32066. return outputNode;
  32067. }
  32068. }
  32069. const pixelation = ( node, depthNode, normalNode, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) => nodeObject( new PixelationNode( nodeObject( node ).toTexture(), nodeObject( depthNode ).toTexture(), nodeObject( normalNode ).toTexture(), nodeObject( pixelSize ), nodeObject( normalEdgeStrength ), nodeObject( depthEdgeStrength ) ) );
  32070. addNodeElement( 'pixelation', pixelation );
  32071. class PixelationPassNode extends PassNode {
  32072. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  32073. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  32074. this.pixelSize = pixelSize;
  32075. this.normalEdgeStrength = normalEdgeStrength;
  32076. this.depthEdgeStrength = depthEdgeStrength;
  32077. this.isPixelationPassNode = true;
  32078. this._mrt = mrt( {
  32079. output: output,
  32080. normal: normalView
  32081. } );
  32082. }
  32083. setSize( width, height ) {
  32084. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  32085. const adjustedWidth = Math.floor( width / pixelSize );
  32086. const adjustedHeight = Math.floor( height / pixelSize );
  32087. super.setSize( adjustedWidth, adjustedHeight );
  32088. }
  32089. setup() {
  32090. const color = super.getTextureNode( 'output' );
  32091. const depth = super.getTextureNode( 'depth' );
  32092. const normal = super.getTextureNode( 'normal' );
  32093. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  32094. }
  32095. }
  32096. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  32097. const sepia = /*@__PURE__*/ tslFn( ( [ color ] ) => {
  32098. const c = vec3( color );
  32099. // https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
  32100. return vec3(
  32101. dot( c, vec3( 0.393, 0.769, 0.189 ) ),
  32102. dot( c, vec3( 0.349, 0.686, 0.168 ) ),
  32103. dot( c, vec3( 0.272, 0.534, 0.131 ) )
  32104. );
  32105. } );
  32106. addNodeElement( 'sepia', sepia );
  32107. class FunctionCallNode extends TempNode {
  32108. constructor( functionNode = null, parameters = {} ) {
  32109. super();
  32110. this.functionNode = functionNode;
  32111. this.parameters = parameters;
  32112. }
  32113. setParameters( parameters ) {
  32114. this.parameters = parameters;
  32115. return this;
  32116. }
  32117. getParameters() {
  32118. return this.parameters;
  32119. }
  32120. getNodeType( builder ) {
  32121. return this.functionNode.getNodeType( builder );
  32122. }
  32123. generate( builder ) {
  32124. const params = [];
  32125. const functionNode = this.functionNode;
  32126. const inputs = functionNode.getInputs( builder );
  32127. const parameters = this.parameters;
  32128. if ( Array.isArray( parameters ) ) {
  32129. for ( let i = 0; i < parameters.length; i ++ ) {
  32130. const inputNode = inputs[ i ];
  32131. const node = parameters[ i ];
  32132. params.push( node.build( builder, inputNode.type ) );
  32133. }
  32134. } else {
  32135. for ( const inputNode of inputs ) {
  32136. const node = parameters[ inputNode.name ];
  32137. if ( node !== undefined ) {
  32138. params.push( node.build( builder, inputNode.type ) );
  32139. } else {
  32140. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  32141. }
  32142. }
  32143. }
  32144. const functionName = functionNode.build( builder, 'property' );
  32145. return `${functionName}( ${params.join( ', ' )} )`;
  32146. }
  32147. }
  32148. const call = ( func, ...params ) => {
  32149. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  32150. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  32151. };
  32152. addNodeElement( 'call', call );
  32153. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  32154. class ScriptableValueNode extends Node {
  32155. constructor( value = null ) {
  32156. super();
  32157. this._value = value;
  32158. this._cache = null;
  32159. this.inputType = null;
  32160. this.outpuType = null;
  32161. this.events = new EventDispatcher();
  32162. this.isScriptableValueNode = true;
  32163. }
  32164. get isScriptableOutputNode() {
  32165. return this.outputType !== null;
  32166. }
  32167. set value( val ) {
  32168. if ( this._value === val ) return;
  32169. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32170. URL.revokeObjectURL( this._cache );
  32171. this._cache = null;
  32172. }
  32173. this._value = val;
  32174. this.events.dispatchEvent( { type: 'change' } );
  32175. this.refresh();
  32176. }
  32177. get value() {
  32178. return this._value;
  32179. }
  32180. refresh() {
  32181. this.events.dispatchEvent( { type: 'refresh' } );
  32182. }
  32183. getValue() {
  32184. const value = this.value;
  32185. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32186. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32187. } else if ( value && value.value !== null && value.value !== undefined && (
  32188. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32189. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32190. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32191. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32192. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32193. ( this.inputType === 'Color' && value.value.isColor ) ||
  32194. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32195. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32196. ) ) {
  32197. return value.value;
  32198. }
  32199. return this._cache || value;
  32200. }
  32201. getNodeType( builder ) {
  32202. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32203. }
  32204. setup() {
  32205. return this.value && this.value.isNode ? this.value : float();
  32206. }
  32207. serialize( data ) {
  32208. super.serialize( data );
  32209. if ( this.value !== null ) {
  32210. if ( this.inputType === 'ArrayBuffer' ) {
  32211. data.value = arrayBufferToBase64( this.value );
  32212. } else {
  32213. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32214. }
  32215. } else {
  32216. data.value = null;
  32217. }
  32218. data.inputType = this.inputType;
  32219. data.outputType = this.outputType;
  32220. }
  32221. deserialize( data ) {
  32222. super.deserialize( data );
  32223. let value = null;
  32224. if ( data.value !== null ) {
  32225. if ( data.inputType === 'ArrayBuffer' ) {
  32226. value = base64ToArrayBuffer( data.value );
  32227. } else if ( data.inputType === 'Texture' ) {
  32228. value = data.meta.textures[ data.value ];
  32229. } else {
  32230. value = data.meta.nodes[ data.value ] || null;
  32231. }
  32232. }
  32233. this.value = value;
  32234. this.inputType = data.inputType;
  32235. this.outputType = data.outputType;
  32236. }
  32237. }
  32238. const scriptableValue = nodeProxy( ScriptableValueNode );
  32239. addNodeElement( 'scriptableValue', scriptableValue );
  32240. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  32241. class Resources extends Map {
  32242. get( key, callback = null, ...params ) {
  32243. if ( this.has( key ) ) return super.get( key );
  32244. if ( callback !== null ) {
  32245. const value = callback( ...params );
  32246. this.set( key, value );
  32247. return value;
  32248. }
  32249. }
  32250. }
  32251. class Parameters {
  32252. constructor( scriptableNode ) {
  32253. this.scriptableNode = scriptableNode;
  32254. }
  32255. get parameters() {
  32256. return this.scriptableNode.parameters;
  32257. }
  32258. get layout() {
  32259. return this.scriptableNode.getLayout();
  32260. }
  32261. getInputLayout( id ) {
  32262. return this.scriptableNode.getInputLayout( id );
  32263. }
  32264. get( name ) {
  32265. const param = this.parameters[ name ];
  32266. const value = param ? param.getValue() : null;
  32267. return value;
  32268. }
  32269. }
  32270. const global = new Resources();
  32271. class ScriptableNode extends Node {
  32272. constructor( codeNode = null, parameters = {} ) {
  32273. super();
  32274. this.codeNode = codeNode;
  32275. this.parameters = parameters;
  32276. this._local = new Resources();
  32277. this._output = scriptableValue();
  32278. this._outputs = {};
  32279. this._source = this.source;
  32280. this._method = null;
  32281. this._object = null;
  32282. this._value = null;
  32283. this._needsOutputUpdate = true;
  32284. this.onRefresh = this.onRefresh.bind( this );
  32285. this.isScriptableNode = true;
  32286. }
  32287. get source() {
  32288. return this.codeNode ? this.codeNode.code : '';
  32289. }
  32290. setLocal( name, value ) {
  32291. return this._local.set( name, value );
  32292. }
  32293. getLocal( name ) {
  32294. return this._local.get( name );
  32295. }
  32296. onRefresh() {
  32297. this._refresh();
  32298. }
  32299. getInputLayout( id ) {
  32300. for ( const element of this.getLayout() ) {
  32301. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32302. return element;
  32303. }
  32304. }
  32305. }
  32306. getOutputLayout( id ) {
  32307. for ( const element of this.getLayout() ) {
  32308. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32309. return element;
  32310. }
  32311. }
  32312. }
  32313. setOutput( name, value ) {
  32314. const outputs = this._outputs;
  32315. if ( outputs[ name ] === undefined ) {
  32316. outputs[ name ] = scriptableValue( value );
  32317. } else {
  32318. outputs[ name ].value = value;
  32319. }
  32320. return this;
  32321. }
  32322. getOutput( name ) {
  32323. return this._outputs[ name ];
  32324. }
  32325. getParameter( name ) {
  32326. return this.parameters[ name ];
  32327. }
  32328. setParameter( name, value ) {
  32329. const parameters = this.parameters;
  32330. if ( value && value.isScriptableNode ) {
  32331. this.deleteParameter( name );
  32332. parameters[ name ] = value;
  32333. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32334. } else if ( value && value.isScriptableValueNode ) {
  32335. this.deleteParameter( name );
  32336. parameters[ name ] = value;
  32337. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32338. } else if ( parameters[ name ] === undefined ) {
  32339. parameters[ name ] = scriptableValue( value );
  32340. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32341. } else {
  32342. parameters[ name ].value = value;
  32343. }
  32344. return this;
  32345. }
  32346. getValue() {
  32347. return this.getDefaultOutput().getValue();
  32348. }
  32349. deleteParameter( name ) {
  32350. let valueNode = this.parameters[ name ];
  32351. if ( valueNode ) {
  32352. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32353. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32354. }
  32355. return this;
  32356. }
  32357. clearParameters() {
  32358. for ( const name of Object.keys( this.parameters ) ) {
  32359. this.deleteParameter( name );
  32360. }
  32361. this.needsUpdate = true;
  32362. return this;
  32363. }
  32364. call( name, ...params ) {
  32365. const object = this.getObject();
  32366. const method = object[ name ];
  32367. if ( typeof method === 'function' ) {
  32368. return method( ...params );
  32369. }
  32370. }
  32371. async callAsync( name, ...params ) {
  32372. const object = this.getObject();
  32373. const method = object[ name ];
  32374. if ( typeof method === 'function' ) {
  32375. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32376. }
  32377. }
  32378. getNodeType( builder ) {
  32379. return this.getDefaultOutputNode().getNodeType( builder );
  32380. }
  32381. refresh( output = null ) {
  32382. if ( output !== null ) {
  32383. this.getOutput( output ).refresh();
  32384. } else {
  32385. this._refresh();
  32386. }
  32387. }
  32388. getObject() {
  32389. if ( this.needsUpdate ) this.dispose();
  32390. if ( this._object !== null ) return this._object;
  32391. //
  32392. const refresh = () => this.refresh();
  32393. const setOutput = ( id, value ) => this.setOutput( id, value );
  32394. const parameters = new Parameters( this );
  32395. const THREE = global.get( 'THREE' );
  32396. const TSL = global.get( 'TSL' );
  32397. const method = this.getMethod( this.codeNode );
  32398. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  32399. this._object = method( ...params );
  32400. const layout = this._object.layout;
  32401. if ( layout ) {
  32402. if ( layout.cache === false ) {
  32403. this._local.clear();
  32404. }
  32405. // default output
  32406. this._output.outputType = layout.outputType || null;
  32407. if ( Array.isArray( layout.elements ) ) {
  32408. for ( const element of layout.elements ) {
  32409. const id = element.id || element.name;
  32410. if ( element.inputType ) {
  32411. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32412. this.getParameter( id ).inputType = element.inputType;
  32413. }
  32414. if ( element.outputType ) {
  32415. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32416. this.getOutput( id ).outputType = element.outputType;
  32417. }
  32418. }
  32419. }
  32420. }
  32421. return this._object;
  32422. }
  32423. deserialize( data ) {
  32424. super.deserialize( data );
  32425. for ( const name in this.parameters ) {
  32426. let valueNode = this.parameters[ name ];
  32427. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32428. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32429. }
  32430. }
  32431. getLayout() {
  32432. return this.getObject().layout;
  32433. }
  32434. getDefaultOutputNode() {
  32435. const output = this.getDefaultOutput().value;
  32436. if ( output && output.isNode ) {
  32437. return output;
  32438. }
  32439. return float();
  32440. }
  32441. getDefaultOutput() {
  32442. return this._exec()._output;
  32443. }
  32444. getMethod() {
  32445. if ( this.needsUpdate ) this.dispose();
  32446. if ( this._method !== null ) return this._method;
  32447. //
  32448. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  32449. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  32450. const properties = interfaceProps.join( ', ' );
  32451. const declarations = 'var ' + properties + '; var output = {};\n';
  32452. const returns = '\nreturn { ...output, ' + properties + ' };';
  32453. const code = declarations + this.codeNode.code + returns;
  32454. //
  32455. this._method = new Function( ...parametersProps, code );
  32456. return this._method;
  32457. }
  32458. dispose() {
  32459. if ( this._method === null ) return;
  32460. if ( this._object && typeof this._object.dispose === 'function' ) {
  32461. this._object.dispose();
  32462. }
  32463. this._method = null;
  32464. this._object = null;
  32465. this._source = null;
  32466. this._value = null;
  32467. this._needsOutputUpdate = true;
  32468. this._output.value = null;
  32469. this._outputs = {};
  32470. }
  32471. setup() {
  32472. return this.getDefaultOutputNode();
  32473. }
  32474. getCacheKey( force ) {
  32475. const cacheKey = [ this.source, this.getDefaultOutputNode().getCacheKey( force ) ];
  32476. for ( const param in this.parameters ) {
  32477. cacheKey.push( this.parameters[ param ].getCacheKey( force ) );
  32478. }
  32479. return cacheKey.join( ',' );
  32480. }
  32481. set needsUpdate( value ) {
  32482. if ( value === true ) this.dispose();
  32483. }
  32484. get needsUpdate() {
  32485. return this.source !== this._source;
  32486. }
  32487. _exec() {
  32488. if ( this.codeNode === null ) return this;
  32489. if ( this._needsOutputUpdate === true ) {
  32490. this._value = this.call( 'main' );
  32491. this._needsOutputUpdate = false;
  32492. }
  32493. this._output.value = this._value;
  32494. return this;
  32495. }
  32496. _refresh() {
  32497. this.needsUpdate = true;
  32498. this._exec();
  32499. this._output.refresh();
  32500. }
  32501. }
  32502. const scriptable = nodeProxy( ScriptableNode );
  32503. addNodeElement( 'scriptable', scriptable );
  32504. addNodeClass( 'ScriptableNode', ScriptableNode );
  32505. class FogNode extends Node {
  32506. constructor( colorNode, factorNode ) {
  32507. super( 'float' );
  32508. this.isFogNode = true;
  32509. this.colorNode = colorNode;
  32510. this.factorNode = factorNode;
  32511. }
  32512. getViewZNode( builder ) {
  32513. let viewZ;
  32514. const getViewZ = builder.context.getViewZ;
  32515. if ( getViewZ !== undefined ) {
  32516. viewZ = getViewZ( this );
  32517. }
  32518. return ( viewZ || positionView.z ).negate();
  32519. }
  32520. setup() {
  32521. return this.factorNode;
  32522. }
  32523. }
  32524. const fog = nodeProxy( FogNode );
  32525. addNodeElement( 'fog', fog );
  32526. addNodeClass( 'FogNode', FogNode );
  32527. class FogRangeNode extends FogNode {
  32528. constructor( colorNode, nearNode, farNode ) {
  32529. super( colorNode );
  32530. this.isFogRangeNode = true;
  32531. this.nearNode = nearNode;
  32532. this.farNode = farNode;
  32533. }
  32534. setup( builder ) {
  32535. const viewZ = this.getViewZNode( builder );
  32536. return smoothstep( this.nearNode, this.farNode, viewZ );
  32537. }
  32538. }
  32539. const rangeFog = nodeProxy( FogRangeNode );
  32540. addNodeElement( 'rangeFog', rangeFog );
  32541. addNodeClass( 'FogRangeNode', FogRangeNode );
  32542. class FogExp2Node extends FogNode {
  32543. constructor( colorNode, densityNode ) {
  32544. super( colorNode );
  32545. this.isFogExp2Node = true;
  32546. this.densityNode = densityNode;
  32547. }
  32548. setup( builder ) {
  32549. const viewZ = this.getViewZNode( builder );
  32550. const density = this.densityNode;
  32551. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  32552. }
  32553. }
  32554. const densityFog = nodeProxy( FogExp2Node );
  32555. addNodeElement( 'densityFog', densityFog );
  32556. addNodeClass( 'FogExp2Node', FogExp2Node );
  32557. let min = null;
  32558. let max = null;
  32559. class RangeNode extends Node {
  32560. constructor( minNode = float(), maxNode = float() ) {
  32561. super();
  32562. this.minNode = minNode;
  32563. this.maxNode = maxNode;
  32564. }
  32565. getVectorLength( builder ) {
  32566. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  32567. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  32568. return minLength > maxLength ? minLength : maxLength;
  32569. }
  32570. getNodeType( builder ) {
  32571. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  32572. }
  32573. setup( builder ) {
  32574. const object = builder.object;
  32575. let output = null;
  32576. if ( object.count > 1 ) {
  32577. const minValue = this.minNode.value;
  32578. const maxValue = this.maxNode.value;
  32579. const minLength = builder.getTypeLength( getValueType( minValue ) );
  32580. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  32581. min = min || new Vector4();
  32582. max = max || new Vector4();
  32583. min.setScalar( 0 );
  32584. max.setScalar( 0 );
  32585. if ( minLength === 1 ) min.setScalar( minValue );
  32586. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  32587. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  32588. if ( maxLength === 1 ) max.setScalar( maxValue );
  32589. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  32590. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  32591. const stride = 4;
  32592. const length = stride * object.count;
  32593. const array = new Float32Array( length );
  32594. for ( let i = 0; i < length; i ++ ) {
  32595. const index = i % stride;
  32596. const minElementValue = min.getComponent( index );
  32597. const maxElementValue = max.getComponent( index );
  32598. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  32599. }
  32600. const nodeType = this.getNodeType( builder );
  32601. if ( object.count <= 4096 ) {
  32602. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  32603. } else {
  32604. // TODO: Improve anonymous buffer attribute creation removing this part
  32605. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  32606. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  32607. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  32608. }
  32609. } else {
  32610. output = float( 0 );
  32611. }
  32612. return output;
  32613. }
  32614. }
  32615. const range = nodeProxy( RangeNode );
  32616. addNodeClass( 'RangeNode', RangeNode );
  32617. class ComputeNode extends Node {
  32618. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  32619. super( 'void' );
  32620. this.isComputeNode = true;
  32621. this.computeNode = computeNode;
  32622. this.count = count;
  32623. this.workgroupSize = workgroupSize;
  32624. this.dispatchCount = 0;
  32625. this.version = 1;
  32626. this.updateBeforeType = NodeUpdateType.OBJECT;
  32627. this.updateDispatchCount();
  32628. }
  32629. dispose() {
  32630. this.dispatchEvent( { type: 'dispose' } );
  32631. }
  32632. set needsUpdate( value ) {
  32633. if ( value === true ) this.version ++;
  32634. }
  32635. updateDispatchCount() {
  32636. const { count, workgroupSize } = this;
  32637. let size = workgroupSize[ 0 ];
  32638. for ( let i = 1; i < workgroupSize.length; i ++ )
  32639. size *= workgroupSize[ i ];
  32640. this.dispatchCount = Math.ceil( count / size );
  32641. }
  32642. onInit() { }
  32643. updateBefore( { renderer } ) {
  32644. renderer.compute( this );
  32645. }
  32646. generate( builder ) {
  32647. const { shaderStage } = builder;
  32648. if ( shaderStage === 'compute' ) {
  32649. const snippet = this.computeNode.build( builder, 'void' );
  32650. if ( snippet !== '' ) {
  32651. builder.addLineFlowCode( snippet );
  32652. }
  32653. }
  32654. }
  32655. }
  32656. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  32657. addNodeElement( 'compute', compute );
  32658. addNodeClass( 'ComputeNode', ComputeNode );
  32659. class LightNode extends Node {
  32660. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  32661. super();
  32662. this.scope = scope;
  32663. this.light = light;
  32664. }
  32665. setup() {
  32666. const { scope, light } = this;
  32667. let output = null;
  32668. if ( scope === LightNode.TARGET_DIRECTION ) {
  32669. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  32670. }
  32671. return output;
  32672. }
  32673. serialize( data ) {
  32674. super.serialize( data );
  32675. data.scope = this.scope;
  32676. }
  32677. deserialize( data ) {
  32678. super.deserialize( data );
  32679. this.scope = data.scope;
  32680. }
  32681. }
  32682. LightNode.TARGET_DIRECTION = 'targetDirection';
  32683. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  32684. addNodeClass( 'LightNode', LightNode );
  32685. const getDistanceAttenuation = tslFn( ( inputs ) => {
  32686. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  32687. // based upon Frostbite 3 Moving to Physically-based Rendering
  32688. // page 32, equation 26: E[window1]
  32689. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32690. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32691. return cutoffDistance.greaterThan( 0 ).cond(
  32692. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32693. distanceFalloff
  32694. );
  32695. } ); // validated
  32696. class PointLightNode extends AnalyticLightNode {
  32697. constructor( light = null ) {
  32698. super( light );
  32699. this.cutoffDistanceNode = uniform( 0 );
  32700. this.decayExponentNode = uniform( 0 );
  32701. }
  32702. update( frame ) {
  32703. const { light } = this;
  32704. super.update( frame );
  32705. this.cutoffDistanceNode.value = light.distance;
  32706. this.decayExponentNode.value = light.decay;
  32707. }
  32708. setup( builder ) {
  32709. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32710. const lightingModel = builder.context.lightingModel;
  32711. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32712. const lightDirection = lVector.normalize();
  32713. const lightDistance = lVector.length();
  32714. const lightAttenuation = getDistanceAttenuation( {
  32715. lightDistance,
  32716. cutoffDistance: cutoffDistanceNode,
  32717. decayExponent: decayExponentNode
  32718. } );
  32719. const lightColor = colorNode.mul( lightAttenuation );
  32720. const reflectedLight = builder.context.reflectedLight;
  32721. lightingModel.direct( {
  32722. lightDirection,
  32723. lightColor,
  32724. reflectedLight
  32725. }, builder.stack, builder );
  32726. }
  32727. }
  32728. addNodeClass( 'PointLightNode', PointLightNode );
  32729. addLightNode( PointLight, PointLightNode );
  32730. class DirectionalLightNode extends AnalyticLightNode {
  32731. constructor( light = null ) {
  32732. super( light );
  32733. }
  32734. setup( builder ) {
  32735. super.setup( builder );
  32736. const lightingModel = builder.context.lightingModel;
  32737. const lightColor = this.colorNode;
  32738. const lightDirection = lightTargetDirection( this.light );
  32739. const reflectedLight = builder.context.reflectedLight;
  32740. lightingModel.direct( {
  32741. lightDirection,
  32742. lightColor,
  32743. reflectedLight
  32744. }, builder.stack, builder );
  32745. }
  32746. }
  32747. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  32748. addLightNode( DirectionalLight, DirectionalLightNode );
  32749. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32750. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32751. let ltcLib = null;
  32752. class RectAreaLightNode extends AnalyticLightNode {
  32753. constructor( light = null ) {
  32754. super( light );
  32755. this.halfHeight = uniform( new Vector3() );
  32756. this.halfWidth = uniform( new Vector3() );
  32757. }
  32758. update( frame ) {
  32759. super.update( frame );
  32760. const { light } = this;
  32761. const viewMatrix = frame.camera.matrixWorldInverse;
  32762. _matrix42.identity();
  32763. _matrix41.copy( light.matrixWorld );
  32764. _matrix41.premultiply( viewMatrix );
  32765. _matrix42.extractRotation( _matrix41 );
  32766. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32767. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32768. this.halfWidth.value.applyMatrix4( _matrix42 );
  32769. this.halfHeight.value.applyMatrix4( _matrix42 );
  32770. }
  32771. setup( builder ) {
  32772. super.setup( builder );
  32773. let ltc_1, ltc_2;
  32774. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32775. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  32776. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  32777. } else {
  32778. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  32779. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  32780. }
  32781. const { colorNode, light } = this;
  32782. const lightingModel = builder.context.lightingModel;
  32783. const lightPosition = objectViewPosition( light );
  32784. const reflectedLight = builder.context.reflectedLight;
  32785. lightingModel.directRectArea( {
  32786. lightColor: colorNode,
  32787. lightPosition,
  32788. halfWidth: this.halfWidth,
  32789. halfHeight: this.halfHeight,
  32790. reflectedLight,
  32791. ltc_1,
  32792. ltc_2
  32793. }, builder.stack, builder );
  32794. }
  32795. static setLTC( ltc ) {
  32796. ltcLib = ltc;
  32797. }
  32798. }
  32799. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  32800. addLightNode( RectAreaLight, RectAreaLightNode );
  32801. class SpotLightNode extends AnalyticLightNode {
  32802. constructor( light = null ) {
  32803. super( light );
  32804. this.coneCosNode = uniform( 0 );
  32805. this.penumbraCosNode = uniform( 0 );
  32806. this.cutoffDistanceNode = uniform( 0 );
  32807. this.decayExponentNode = uniform( 0 );
  32808. }
  32809. update( frame ) {
  32810. super.update( frame );
  32811. const { light } = this;
  32812. this.coneCosNode.value = Math.cos( light.angle );
  32813. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32814. this.cutoffDistanceNode.value = light.distance;
  32815. this.decayExponentNode.value = light.decay;
  32816. }
  32817. getSpotAttenuation( angleCosine ) {
  32818. const { coneCosNode, penumbraCosNode } = this;
  32819. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32820. }
  32821. setup( builder ) {
  32822. super.setup( builder );
  32823. const lightingModel = builder.context.lightingModel;
  32824. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32825. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32826. const lightDirection = lVector.normalize();
  32827. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32828. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32829. const lightDistance = lVector.length();
  32830. const lightAttenuation = getDistanceAttenuation( {
  32831. lightDistance,
  32832. cutoffDistance: cutoffDistanceNode,
  32833. decayExponent: decayExponentNode
  32834. } );
  32835. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32836. const reflectedLight = builder.context.reflectedLight;
  32837. lightingModel.direct( {
  32838. lightDirection,
  32839. lightColor,
  32840. reflectedLight
  32841. }, builder.stack, builder );
  32842. }
  32843. }
  32844. addNodeClass( 'SpotLightNode', SpotLightNode );
  32845. addLightNode( SpotLight, SpotLightNode );
  32846. class IESSpotLight extends SpotLight {
  32847. constructor( color, intensity, distance, angle, penumbra, decay ) {
  32848. super( color, intensity, distance, angle, penumbra, decay );
  32849. this.iesMap = null;
  32850. }
  32851. copy( source, recursive ) {
  32852. super.copy( source, recursive );
  32853. this.iesMap = source.iesMap;
  32854. return this;
  32855. }
  32856. }
  32857. class IESSpotLightNode extends SpotLightNode {
  32858. getSpotAttenuation( angleCosine ) {
  32859. const iesMap = this.light.iesMap;
  32860. let spotAttenuation = null;
  32861. if ( iesMap && iesMap.isTexture === true ) {
  32862. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32863. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32864. } else {
  32865. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32866. }
  32867. return spotAttenuation;
  32868. }
  32869. }
  32870. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  32871. addLightNode( IESSpotLight, IESSpotLightNode );
  32872. class AmbientLightNode extends AnalyticLightNode {
  32873. constructor( light = null ) {
  32874. super( light );
  32875. }
  32876. setup( { context } ) {
  32877. context.irradiance.addAssign( this.colorNode );
  32878. }
  32879. }
  32880. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  32881. addLightNode( AmbientLight, AmbientLightNode );
  32882. class HemisphereLightNode extends AnalyticLightNode {
  32883. constructor( light = null ) {
  32884. super( light );
  32885. this.lightPositionNode = objectPosition( light );
  32886. this.lightDirectionNode = this.lightPositionNode.normalize();
  32887. this.groundColorNode = uniform( new Color() );
  32888. }
  32889. update( frame ) {
  32890. const { light } = this;
  32891. super.update( frame );
  32892. this.lightPositionNode.object3d = light;
  32893. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32894. }
  32895. setup( builder ) {
  32896. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32897. const dotNL = normalView.dot( lightDirectionNode );
  32898. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32899. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32900. builder.context.irradiance.addAssign( irradiance );
  32901. }
  32902. }
  32903. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  32904. addLightNode( HemisphereLight, HemisphereLightNode );
  32905. let _generator = null;
  32906. const _cache = new WeakMap();
  32907. function _generateCubeUVSize( imageHeight ) {
  32908. const maxMip = Math.log2( imageHeight ) - 2;
  32909. const texelHeight = 1.0 / imageHeight;
  32910. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  32911. return { texelWidth, texelHeight, maxMip };
  32912. }
  32913. function _getPMREMFromTexture( texture ) {
  32914. let cacheTexture = _cache.get( texture );
  32915. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  32916. if ( pmremVersion !== texture.pmremVersion ) {
  32917. const image = texture.image;
  32918. if ( texture.isCubeTexture ) {
  32919. if ( isCubeMapReady( image ) ) {
  32920. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  32921. } else {
  32922. return null;
  32923. }
  32924. } else {
  32925. if ( isEquirectangularMapReady( image ) ) {
  32926. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  32927. } else {
  32928. return null;
  32929. }
  32930. }
  32931. cacheTexture.pmremVersion = texture.pmremVersion;
  32932. _cache.set( texture, cacheTexture );
  32933. }
  32934. return cacheTexture.texture;
  32935. }
  32936. class PMREMNode extends TempNode {
  32937. constructor( value, uvNode = null, levelNode = null ) {
  32938. super( 'vec3' );
  32939. this._value = value;
  32940. this._pmrem = null;
  32941. this.uvNode = uvNode;
  32942. this.levelNode = levelNode;
  32943. this._generator = null;
  32944. this._texture = texture( new Texture() );
  32945. this._width = uniform( 0 );
  32946. this._height = uniform( 0 );
  32947. this._maxMip = uniform( 0 );
  32948. this.updateBeforeType = NodeUpdateType.RENDER;
  32949. }
  32950. set value( value ) {
  32951. this._value = value;
  32952. this._pmrem = null;
  32953. }
  32954. get value() {
  32955. return this._value;
  32956. }
  32957. updateFromTexture( texture ) {
  32958. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  32959. this._texture.value = texture;
  32960. this._width.value = cubeUVSize.texelWidth;
  32961. this._height.value = cubeUVSize.texelHeight;
  32962. this._maxMip.value = cubeUVSize.maxMip;
  32963. }
  32964. updateBefore() {
  32965. let pmrem = this._pmrem;
  32966. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  32967. const texture = this._value;
  32968. if ( pmremVersion !== texture.pmremVersion ) {
  32969. if ( texture.isPMREMTexture === true ) {
  32970. pmrem = texture;
  32971. } else {
  32972. pmrem = _getPMREMFromTexture( texture );
  32973. }
  32974. if ( pmrem !== null ) {
  32975. this._pmrem = pmrem;
  32976. this.updateFromTexture( pmrem );
  32977. }
  32978. }
  32979. }
  32980. setup( builder ) {
  32981. if ( _generator === null ) {
  32982. _generator = builder.createPMREMGenerator();
  32983. }
  32984. //
  32985. this.updateBefore( builder );
  32986. //
  32987. let uvNode = this.uvNode;
  32988. if ( uvNode === null && builder.context.getUV ) {
  32989. uvNode = builder.context.getUV( this );
  32990. }
  32991. //
  32992. const texture = this.value;
  32993. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  32994. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  32995. }
  32996. //
  32997. let levelNode = this.levelNode;
  32998. if ( levelNode === null && builder.context.getTextureLevel ) {
  32999. levelNode = builder.context.getTextureLevel( this );
  33000. }
  33001. //
  33002. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  33003. }
  33004. }
  33005. function isCubeMapReady( image ) {
  33006. if ( image === null || image === undefined ) return false;
  33007. let count = 0;
  33008. const length = 6;
  33009. for ( let i = 0; i < length; i ++ ) {
  33010. if ( image[ i ] !== undefined ) count ++;
  33011. }
  33012. return count === length;
  33013. }
  33014. function isEquirectangularMapReady( image ) {
  33015. if ( image === null || image === undefined ) return false;
  33016. return image.height > 0;
  33017. }
  33018. const pmremTexture = nodeProxy( PMREMNode );
  33019. addNodeClass( 'PMREMNode', PMREMNode );
  33020. const _envNodeCache = new WeakMap();
  33021. class EnvironmentNode extends LightingNode {
  33022. constructor( envNode = null ) {
  33023. super();
  33024. this.envNode = envNode;
  33025. }
  33026. setup( builder ) {
  33027. let envNode = this.envNode;
  33028. if ( envNode.isTextureNode ) {
  33029. let cacheEnvNode = _envNodeCache.get( envNode.value );
  33030. if ( cacheEnvNode === undefined ) {
  33031. cacheEnvNode = pmremTexture( envNode.value );
  33032. _envNodeCache.set( envNode.value, cacheEnvNode );
  33033. }
  33034. envNode = cacheEnvNode;
  33035. }
  33036. //
  33037. const { material } = builder;
  33038. const envMap = material.envMap;
  33039. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  33040. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  33041. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  33042. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  33043. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  33044. const isolateRadiance = cache( radiance );
  33045. const isolateIrradiance = cache( irradiance );
  33046. //
  33047. builder.context.radiance.addAssign( isolateRadiance );
  33048. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  33049. //
  33050. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  33051. if ( clearcoatRadiance ) {
  33052. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  33053. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  33054. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  33055. }
  33056. }
  33057. }
  33058. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  33059. let reflectVec = null;
  33060. return {
  33061. getUV: () => {
  33062. if ( reflectVec === null ) {
  33063. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  33064. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  33065. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  33066. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  33067. }
  33068. return reflectVec;
  33069. },
  33070. getTextureLevel: () => {
  33071. return roughnessNode;
  33072. }
  33073. };
  33074. };
  33075. const createIrradianceContext = ( normalWorldNode ) => {
  33076. return {
  33077. getUV: () => {
  33078. return normalWorldNode;
  33079. },
  33080. getTextureLevel: () => {
  33081. return float( 1.0 );
  33082. }
  33083. };
  33084. };
  33085. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  33086. class BasicEnvironmentNode extends LightingNode {
  33087. constructor( envNode = null ) {
  33088. super();
  33089. this.envNode = envNode;
  33090. }
  33091. setup( builder ) {
  33092. // environment property is used in the finish() method of BasicLightingModel
  33093. builder.context.environment = this.envNode;
  33094. }
  33095. }
  33096. addNodeClass( 'BasicEnvironmentNode', BasicEnvironmentNode );
  33097. const checkerShaderNode = tslFn( ( inputs ) => {
  33098. const uv = inputs.uv.mul( 2.0 );
  33099. const cx = uv.x.floor();
  33100. const cy = uv.y.floor();
  33101. const result = cx.add( cy ).mod( 2.0 );
  33102. return result.sign();
  33103. } );
  33104. class CheckerNode extends TempNode {
  33105. constructor( uvNode = uv() ) {
  33106. super( 'float' );
  33107. this.uvNode = uvNode;
  33108. }
  33109. setup() {
  33110. return checkerShaderNode( { uv: this.uvNode } );
  33111. }
  33112. }
  33113. const checker = nodeProxy( CheckerNode );
  33114. addNodeElement( 'checker', checker );
  33115. addNodeClass( 'CheckerNode', CheckerNode );
  33116. class NodeLoader extends Loader {
  33117. constructor( manager ) {
  33118. super( manager );
  33119. this.textures = {};
  33120. }
  33121. load( url, onLoad, onProgress, onError ) {
  33122. const loader = new FileLoader( this.manager );
  33123. loader.setPath( this.path );
  33124. loader.setRequestHeader( this.requestHeader );
  33125. loader.setWithCredentials( this.withCredentials );
  33126. loader.load( url, ( text ) => {
  33127. try {
  33128. onLoad( this.parse( JSON.parse( text ) ) );
  33129. } catch ( e ) {
  33130. if ( onError ) {
  33131. onError( e );
  33132. } else {
  33133. console.error( e );
  33134. }
  33135. this.manager.itemError( url );
  33136. }
  33137. }, onProgress, onError );
  33138. }
  33139. parseNodes( json ) {
  33140. const nodes = {};
  33141. if ( json !== undefined ) {
  33142. for ( const nodeJSON of json ) {
  33143. const { uuid, type } = nodeJSON;
  33144. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  33145. nodes[ uuid ].uuid = uuid;
  33146. }
  33147. const meta = { nodes, textures: this.textures };
  33148. for ( const nodeJSON of json ) {
  33149. nodeJSON.meta = meta;
  33150. const node = nodes[ nodeJSON.uuid ];
  33151. node.deserialize( nodeJSON );
  33152. delete nodeJSON.meta;
  33153. }
  33154. }
  33155. return nodes;
  33156. }
  33157. parse( json ) {
  33158. const node = nodeObject( createNodeFromType( json.type ) );
  33159. node.uuid = json.uuid;
  33160. const nodes = this.parseNodes( json.nodes );
  33161. const meta = { nodes, textures: this.textures };
  33162. json.meta = meta;
  33163. node.deserialize( json );
  33164. delete json.meta;
  33165. return node;
  33166. }
  33167. setTextures( value ) {
  33168. this.textures = value;
  33169. return this;
  33170. }
  33171. }
  33172. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  33173. class InstancedPointsNodeMaterial extends NodeMaterial {
  33174. constructor( params = {} ) {
  33175. super();
  33176. this.normals = false;
  33177. this.lights = false;
  33178. this.useAlphaToCoverage = true;
  33179. this.useColor = params.vertexColors;
  33180. this.pointWidth = 1;
  33181. this.pointColorNode = null;
  33182. this.setDefaultValues( _defaultValues$e );
  33183. this.setupShaders();
  33184. this.setValues( params );
  33185. }
  33186. setupShaders() {
  33187. const useAlphaToCoverage = this.alphaToCoverage;
  33188. const useColor = this.useColor;
  33189. this.vertexNode = tslFn( () => {
  33190. //vUv = uv;
  33191. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  33192. const instancePosition = attribute( 'instancePosition' );
  33193. // camera space
  33194. const mvPos = property( 'vec4', 'mvPos' );
  33195. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  33196. const aspect = viewport.z.div( viewport.w );
  33197. // clip space
  33198. const clipPos = cameraProjectionMatrix.mul( mvPos );
  33199. // offset in ndc space
  33200. const offset = property( 'vec2', 'offset' );
  33201. offset.assign( positionGeometry.xy );
  33202. offset.assign( offset.mul( materialPointWidth ) );
  33203. offset.assign( offset.div( viewport.z ) );
  33204. offset.y.assign( offset.y.mul( aspect ) );
  33205. // back to clip space
  33206. offset.assign( offset.mul( clipPos.w ) );
  33207. //clipPos.xy += offset;
  33208. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  33209. return clipPos;
  33210. //vec4 mvPosition = mvPos; // this was used for somethihng...
  33211. } )();
  33212. this.fragmentNode = tslFn( () => {
  33213. const vUv = varying( vec2(), 'vUv' );
  33214. // force assignment into correct place in flow
  33215. const alpha = property( 'float', 'alpha' );
  33216. alpha.assign( 1 );
  33217. const a = vUv.x;
  33218. const b = vUv.y;
  33219. const len2 = a.mul( a ).add( b.mul( b ) );
  33220. if ( useAlphaToCoverage ) {
  33221. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33222. const dlen = property( 'float', 'dlen' );
  33223. dlen.assign( len2.fwidth() );
  33224. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33225. } else {
  33226. len2.greaterThan( 1.0 ).discard();
  33227. }
  33228. let pointColorNode;
  33229. if ( this.pointColorNode ) {
  33230. pointColorNode = this.pointColorNode;
  33231. } else {
  33232. if ( useColor ) {
  33233. const instanceColor = attribute( 'instanceColor' );
  33234. pointColorNode = instanceColor.mul( materialColor );
  33235. } else {
  33236. pointColorNode = materialColor;
  33237. }
  33238. }
  33239. return vec4( pointColorNode, alpha );
  33240. } )();
  33241. this.needsUpdate = true;
  33242. }
  33243. get alphaToCoverage() {
  33244. return this.useAlphaToCoverage;
  33245. }
  33246. set alphaToCoverage( value ) {
  33247. if ( this.useAlphaToCoverage !== value ) {
  33248. this.useAlphaToCoverage = value;
  33249. this.setupShaders();
  33250. }
  33251. }
  33252. }
  33253. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  33254. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  33255. class LineBasicNodeMaterial extends NodeMaterial {
  33256. constructor( parameters ) {
  33257. super();
  33258. this.isLineBasicNodeMaterial = true;
  33259. this.lights = false;
  33260. this.normals = false;
  33261. this.setDefaultValues( _defaultValues$d );
  33262. this.setValues( parameters );
  33263. }
  33264. }
  33265. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  33266. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  33267. class LineDashedNodeMaterial extends NodeMaterial {
  33268. constructor( parameters ) {
  33269. super();
  33270. this.isLineDashedNodeMaterial = true;
  33271. this.lights = false;
  33272. this.normals = false;
  33273. this.setDefaultValues( _defaultValues$c );
  33274. this.offsetNode = null;
  33275. this.dashScaleNode = null;
  33276. this.dashSizeNode = null;
  33277. this.gapSizeNode = null;
  33278. this.setValues( parameters );
  33279. }
  33280. setupVariants() {
  33281. const offsetNode = this.offsetNode;
  33282. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33283. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33284. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33285. dashSize.assign( dashSizeNode );
  33286. gapSize.assign( gapSizeNode );
  33287. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  33288. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33289. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  33290. }
  33291. }
  33292. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  33293. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  33294. class Line2NodeMaterial extends NodeMaterial {
  33295. constructor( params = {} ) {
  33296. super();
  33297. this.normals = false;
  33298. this.lights = false;
  33299. this.setDefaultValues( _defaultValues$b );
  33300. this.useAlphaToCoverage = true;
  33301. this.useColor = params.vertexColors;
  33302. this.useDash = params.dashed;
  33303. this.useWorldUnits = false;
  33304. this.dashOffset = 0;
  33305. this.lineWidth = 1;
  33306. this.lineColorNode = null;
  33307. this.offsetNode = null;
  33308. this.dashScaleNode = null;
  33309. this.dashSizeNode = null;
  33310. this.gapSizeNode = null;
  33311. this.setValues( params );
  33312. }
  33313. setup( builder ) {
  33314. this.setupShaders();
  33315. super.setup( builder );
  33316. }
  33317. setupShaders() {
  33318. const useAlphaToCoverage = this.alphaToCoverage;
  33319. const useColor = this.useColor;
  33320. const useDash = this.dashed;
  33321. const useWorldUnits = this.worldUnits;
  33322. const trimSegment = tslFn( ( { start, end } ) => {
  33323. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  33324. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  33325. const nearEstimate = b.mul( - 0.5 ).div( a );
  33326. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  33327. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  33328. } );
  33329. this.vertexNode = tslFn( () => {
  33330. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  33331. const instanceStart = attribute( 'instanceStart' );
  33332. const instanceEnd = attribute( 'instanceEnd' );
  33333. // camera space
  33334. const start = property( 'vec4', 'start' );
  33335. const end = property( 'vec4', 'end' );
  33336. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  33337. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  33338. if ( useWorldUnits ) {
  33339. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  33340. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  33341. }
  33342. const aspect = viewport.z.div( viewport.w );
  33343. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  33344. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  33345. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  33346. // perhaps there is a more elegant solution -- WestLangley
  33347. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  33348. If( perspective, () => {
  33349. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  33350. end.assign( trimSegment( { start: start, end: end } ) );
  33351. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  33352. start.assign( trimSegment( { start: end, end: start } ) );
  33353. } );
  33354. } );
  33355. // clip space
  33356. const clipStart = cameraProjectionMatrix.mul( start );
  33357. const clipEnd = cameraProjectionMatrix.mul( end );
  33358. // ndc space
  33359. const ndcStart = clipStart.xyz.div( clipStart.w );
  33360. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  33361. // direction
  33362. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  33363. // account for clip-space aspect ratio
  33364. dir.x.assign( dir.x.mul( aspect ) );
  33365. dir.assign( dir.normalize() );
  33366. const clip = temp( vec4() );
  33367. if ( useWorldUnits ) {
  33368. // get the offset direction as perpendicular to the view vector
  33369. const worldDir = end.xyz.sub( start.xyz ).normalize();
  33370. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  33371. const worldUp = worldDir.cross( tmpFwd ).normalize();
  33372. const worldFwd = worldDir.cross( worldUp );
  33373. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  33374. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  33375. // height offset
  33376. const hw = materialLineWidth.mul( 0.5 );
  33377. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  33378. // don't extend the line if we're rendering dashes because we
  33379. // won't be rendering the endcaps
  33380. if ( ! useDash ) {
  33381. // cap extension
  33382. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  33383. // add width to the box
  33384. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  33385. // endcaps
  33386. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  33387. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  33388. } );
  33389. }
  33390. // project the worldpos
  33391. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  33392. // shift the depth of the projected points so the line
  33393. // segments overlap neatly
  33394. const clipPose = temp( vec3() );
  33395. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  33396. clip.z.assign( clipPose.z.mul( clip.w ) );
  33397. } else {
  33398. const offset = property( 'vec2', 'offset' );
  33399. offset.assign( vec2( dir.y, dir.x.negate() ) );
  33400. // undo aspect ratio adjustment
  33401. dir.x.assign( dir.x.div( aspect ) );
  33402. offset.x.assign( offset.x.div( aspect ) );
  33403. // sign flip
  33404. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  33405. // endcaps
  33406. If( positionGeometry.y.lessThan( 0.0 ), () => {
  33407. offset.assign( offset.sub( dir ) );
  33408. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  33409. offset.assign( offset.add( dir ) );
  33410. } );
  33411. // adjust for linewidth
  33412. offset.assign( offset.mul( materialLineWidth ) );
  33413. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  33414. offset.assign( offset.div( viewport.w ) );
  33415. // select end
  33416. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  33417. // back to clip space
  33418. offset.assign( offset.mul( clip.w ) );
  33419. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  33420. }
  33421. return clip;
  33422. } )();
  33423. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  33424. const p13 = p1.sub( p3 );
  33425. const p43 = p4.sub( p3 );
  33426. const p21 = p2.sub( p1 );
  33427. const d1343 = p13.dot( p43 );
  33428. const d4321 = p43.dot( p21 );
  33429. const d1321 = p13.dot( p21 );
  33430. const d4343 = p43.dot( p43 );
  33431. const d2121 = p21.dot( p21 );
  33432. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  33433. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  33434. const mua = numer.div( denom ).clamp();
  33435. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  33436. return vec2( mua, mub );
  33437. } );
  33438. this.fragmentNode = tslFn( () => {
  33439. const vUv = varyingProperty( 'vec2', 'vUv' );
  33440. if ( useDash ) {
  33441. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  33442. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33443. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33444. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33445. dashSize.assign( dashSizeNode );
  33446. gapSize.assign( gapSizeNode );
  33447. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  33448. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  33449. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  33450. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  33451. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33452. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  33453. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  33454. }
  33455. // force assignment into correct place in flow
  33456. const alpha = property( 'float', 'alpha' );
  33457. alpha.assign( 1 );
  33458. if ( useWorldUnits ) {
  33459. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  33460. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  33461. // Find the closest points on the view ray and the line segment
  33462. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  33463. const lineDir = worldEnd.sub( worldStart );
  33464. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  33465. const p1 = worldStart.add( lineDir.mul( params.x ) );
  33466. const p2 = rayEnd.mul( params.y );
  33467. const delta = p1.sub( p2 );
  33468. const len = delta.length();
  33469. const norm = len.div( materialLineWidth );
  33470. if ( ! useDash ) {
  33471. if ( useAlphaToCoverage ) {
  33472. const dnorm = norm.fwidth();
  33473. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  33474. } else {
  33475. norm.greaterThan( 0.5 ).discard();
  33476. }
  33477. }
  33478. } else {
  33479. // round endcaps
  33480. if ( useAlphaToCoverage ) {
  33481. const a = vUv.x;
  33482. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33483. const len2 = a.mul( a ).add( b.mul( b ) );
  33484. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33485. const dlen = property( 'float', 'dlen' );
  33486. dlen.assign( len2.fwidth() );
  33487. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33488. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33489. } );
  33490. } else {
  33491. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33492. const a = vUv.x;
  33493. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33494. const len2 = a.mul( a ).add( b.mul( b ) );
  33495. len2.greaterThan( 1.0 ).discard();
  33496. } );
  33497. }
  33498. }
  33499. let lineColorNode;
  33500. if ( this.lineColorNode ) {
  33501. lineColorNode = this.lineColorNode;
  33502. } else {
  33503. if ( useColor ) {
  33504. const instanceColorStart = attribute( 'instanceColorStart' );
  33505. const instanceColorEnd = attribute( 'instanceColorEnd' );
  33506. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  33507. lineColorNode = instanceColor.mul( materialColor );
  33508. } else {
  33509. lineColorNode = materialColor;
  33510. }
  33511. }
  33512. return vec4( lineColorNode, alpha );
  33513. } )();
  33514. }
  33515. get worldUnits() {
  33516. return this.useWorldUnits;
  33517. }
  33518. set worldUnits( value ) {
  33519. if ( this.useWorldUnits !== value ) {
  33520. this.useWorldUnits = value;
  33521. this.needsUpdate = true;
  33522. }
  33523. }
  33524. get dashed() {
  33525. return this.useDash;
  33526. }
  33527. set dashed( value ) {
  33528. if ( this.useDash !== value ) {
  33529. this.useDash = value;
  33530. this.needsUpdate = true;
  33531. }
  33532. }
  33533. get alphaToCoverage() {
  33534. return this.useAlphaToCoverage;
  33535. }
  33536. set alphaToCoverage( value ) {
  33537. if ( this.useAlphaToCoverage !== value ) {
  33538. this.useAlphaToCoverage = value;
  33539. this.needsUpdate = true;
  33540. }
  33541. }
  33542. }
  33543. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  33544. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  33545. class MeshNormalNodeMaterial extends NodeMaterial {
  33546. constructor( parameters ) {
  33547. super();
  33548. this.lights = false;
  33549. this.isMeshNormalNodeMaterial = true;
  33550. this.setDefaultValues( _defaultValues$a );
  33551. this.setValues( parameters );
  33552. }
  33553. setupDiffuseColor() {
  33554. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  33555. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  33556. }
  33557. }
  33558. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  33559. class BasicLightMapNode extends LightingNode {
  33560. constructor( lightMapNode = null ) {
  33561. super();
  33562. this.lightMapNode = lightMapNode;
  33563. }
  33564. setup( builder ) {
  33565. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  33566. const RECIPROCAL_PI = float( 1 / Math.PI );
  33567. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  33568. }
  33569. }
  33570. addNodeClass( 'BasicLightMapNode', BasicLightMapNode );
  33571. class BasicLightingModel extends LightingModel {
  33572. constructor() {
  33573. super();
  33574. }
  33575. indirect( context, stack, builder ) {
  33576. const ambientOcclusion = context.ambientOcclusion;
  33577. const reflectedLight = context.reflectedLight;
  33578. const irradianceLightMap = builder.context.irradianceLightMap;
  33579. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  33580. // accumulation (baked indirect lighting only)
  33581. if ( irradianceLightMap ) {
  33582. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  33583. } else {
  33584. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  33585. }
  33586. // modulation
  33587. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33588. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  33589. }
  33590. finish( context, stack, builder ) {
  33591. const material = builder.material;
  33592. const outgoingLight = context.outgoingLight;
  33593. const envNode = builder.context.environment;
  33594. if ( envNode ) {
  33595. switch ( material.combine ) {
  33596. case MultiplyOperation:
  33597. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  33598. break;
  33599. case MixOperation:
  33600. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  33601. break;
  33602. case AddOperation:
  33603. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  33604. break;
  33605. default:
  33606. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  33607. break;
  33608. }
  33609. }
  33610. }
  33611. }
  33612. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  33613. class MeshBasicNodeMaterial extends NodeMaterial {
  33614. constructor( parameters ) {
  33615. super();
  33616. this.isMeshBasicNodeMaterial = true;
  33617. this.lights = true;
  33618. //this.normals = false; @TODO: normals usage by context
  33619. this.setDefaultValues( _defaultValues$9 );
  33620. this.setValues( parameters );
  33621. }
  33622. setupNormal() {
  33623. transformedNormalView.assign( normalView ); // see #28839
  33624. }
  33625. setupEnvironment( builder ) {
  33626. const envNode = super.setupEnvironment( builder );
  33627. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33628. }
  33629. setupLightMap( builder ) {
  33630. let node = null;
  33631. if ( builder.material.lightMap ) {
  33632. node = new BasicLightMapNode( materialLightMap );
  33633. }
  33634. return node;
  33635. }
  33636. setupOutgoingLight() {
  33637. return diffuseColor.rgb;
  33638. }
  33639. setupLightingModel() {
  33640. return new BasicLightingModel();
  33641. }
  33642. }
  33643. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  33644. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  33645. // Original approximation by Christophe Schlick '94
  33646. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  33647. // Optimized variant (presented by Epic at SIGGRAPH '13)
  33648. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  33649. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  33650. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  33651. } ); // validated
  33652. const BRDF_Lambert = tslFn( ( inputs ) => {
  33653. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  33654. } ); // validated
  33655. const G_BlinnPhong_Implicit = () => float( 0.25 );
  33656. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  33657. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  33658. } );
  33659. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  33660. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33661. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33662. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33663. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  33664. const G = G_BlinnPhong_Implicit();
  33665. const D = D_BlinnPhong( { dotNH } );
  33666. return F.mul( G ).mul( D );
  33667. } );
  33668. class PhongLightingModel extends BasicLightingModel {
  33669. constructor( specular = true ) {
  33670. super();
  33671. this.specular = specular;
  33672. }
  33673. direct( { lightDirection, lightColor, reflectedLight } ) {
  33674. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33675. const irradiance = dotNL.mul( lightColor );
  33676. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33677. if ( this.specular === true ) {
  33678. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  33679. }
  33680. }
  33681. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  33682. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33683. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33684. }
  33685. }
  33686. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  33687. class MeshLambertNodeMaterial extends NodeMaterial {
  33688. constructor( parameters ) {
  33689. super();
  33690. this.isMeshLambertNodeMaterial = true;
  33691. this.lights = true;
  33692. this.setDefaultValues( _defaultValues$8 );
  33693. this.setValues( parameters );
  33694. }
  33695. setupEnvironment( builder ) {
  33696. const envNode = super.setupEnvironment( builder );
  33697. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33698. }
  33699. setupLightingModel( /*builder*/ ) {
  33700. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  33701. }
  33702. }
  33703. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  33704. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  33705. class MeshPhongNodeMaterial extends NodeMaterial {
  33706. constructor( parameters ) {
  33707. super();
  33708. this.isMeshPhongNodeMaterial = true;
  33709. this.lights = true;
  33710. this.shininessNode = null;
  33711. this.specularNode = null;
  33712. this.setDefaultValues( _defaultValues$7 );
  33713. this.setValues( parameters );
  33714. }
  33715. setupEnvironment( builder ) {
  33716. const envNode = super.setupEnvironment( builder );
  33717. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33718. }
  33719. setupLightingModel( /*builder*/ ) {
  33720. return new PhongLightingModel();
  33721. }
  33722. setupVariants() {
  33723. // SHININESS
  33724. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  33725. shininess.assign( shininessNode );
  33726. // SPECULAR COLOR
  33727. const specularNode = this.specularNode || materialSpecular;
  33728. specularColor.assign( specularNode );
  33729. }
  33730. copy( source ) {
  33731. this.shininessNode = source.shininessNode;
  33732. this.specularNode = source.specularNode;
  33733. return super.copy( source );
  33734. }
  33735. }
  33736. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  33737. const getGeometryRoughness = tslFn( () => {
  33738. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  33739. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  33740. return geometryRoughness;
  33741. } );
  33742. const getRoughness = tslFn( ( inputs ) => {
  33743. const { roughness } = inputs;
  33744. const geometryRoughness = getGeometryRoughness();
  33745. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  33746. roughnessFactor = roughnessFactor.add( geometryRoughness );
  33747. roughnessFactor = roughnessFactor.min( 1.0 );
  33748. return roughnessFactor;
  33749. } );
  33750. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  33751. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33752. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  33753. const a2 = alpha.pow2();
  33754. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  33755. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  33756. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  33757. } ).setLayout( {
  33758. name: 'V_GGX_SmithCorrelated',
  33759. type: 'float',
  33760. inputs: [
  33761. { name: 'alpha', type: 'float' },
  33762. { name: 'dotNL', type: 'float' },
  33763. { name: 'dotNV', type: 'float' }
  33764. ]
  33765. } ); // validated
  33766. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33767. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  33768. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  33769. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  33770. const v = div( 0.5, gv.add( gl ) );
  33771. return v.saturate();
  33772. } ).setLayout( {
  33773. name: 'V_GGX_SmithCorrelated_Anisotropic',
  33774. type: 'float',
  33775. inputs: [
  33776. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33777. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33778. { name: 'dotTV', type: 'float', qualifier: 'in' },
  33779. { name: 'dotBV', type: 'float', qualifier: 'in' },
  33780. { name: 'dotTL', type: 'float', qualifier: 'in' },
  33781. { name: 'dotBL', type: 'float', qualifier: 'in' },
  33782. { name: 'dotNV', type: 'float', qualifier: 'in' },
  33783. { name: 'dotNL', type: 'float', qualifier: 'in' }
  33784. ]
  33785. } );
  33786. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  33787. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  33788. // alpha is "roughness squared" in Disney’s reparameterization
  33789. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  33790. const a2 = alpha.pow2();
  33791. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  33792. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  33793. } ).setLayout( {
  33794. name: 'D_GGX',
  33795. type: 'float',
  33796. inputs: [
  33797. { name: 'alpha', type: 'float' },
  33798. { name: 'dotNH', type: 'float' }
  33799. ]
  33800. } ); // validated
  33801. const RECIPROCAL_PI = float( 1 / Math.PI );
  33802. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33803. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  33804. const a2 = alphaT.mul( alphaB );
  33805. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  33806. const v2 = v.dot( v );
  33807. const w2 = a2.div( v2 );
  33808. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  33809. } ).setLayout( {
  33810. name: 'D_GGX_Anisotropic',
  33811. type: 'float',
  33812. inputs: [
  33813. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33814. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33815. { name: 'dotNH', type: 'float', qualifier: 'in' },
  33816. { name: 'dotTH', type: 'float', qualifier: 'in' },
  33817. { name: 'dotBH', type: 'float', qualifier: 'in' }
  33818. ]
  33819. } );
  33820. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  33821. const BRDF_GGX = tslFn( ( inputs ) => {
  33822. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  33823. const normalView = inputs.normalView || transformedNormalView;
  33824. const alpha = roughness.pow2(); // UE4's roughness
  33825. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33826. const dotNL = normalView.dot( lightDirection ).clamp();
  33827. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33828. const dotNH = normalView.dot( halfDir ).clamp();
  33829. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33830. let F = F_Schlick( { f0, f90, dotVH } );
  33831. let V, D;
  33832. if ( defined( USE_IRIDESCENCE ) ) {
  33833. F = iridescence.mix( F, f );
  33834. }
  33835. if ( defined( USE_ANISOTROPY ) ) {
  33836. const dotTL = anisotropyT.dot( lightDirection );
  33837. const dotTV = anisotropyT.dot( positionViewDirection );
  33838. const dotTH = anisotropyT.dot( halfDir );
  33839. const dotBL = anisotropyB.dot( lightDirection );
  33840. const dotBV = anisotropyB.dot( positionViewDirection );
  33841. const dotBH = anisotropyB.dot( halfDir );
  33842. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  33843. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  33844. } else {
  33845. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  33846. D = D_GGX( { alpha, dotNH } );
  33847. }
  33848. return F.mul( V ).mul( D );
  33849. } ); // validated
  33850. // Analytical approximation of the DFG LUT, one half of the
  33851. // split-sum approximation used in indirect specular lighting.
  33852. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  33853. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  33854. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  33855. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  33856. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  33857. const r = roughness.mul( c0 ).add( c1 );
  33858. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  33859. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  33860. return fab;
  33861. } ).setLayout( {
  33862. name: 'DFGApprox',
  33863. type: 'vec2',
  33864. inputs: [
  33865. { name: 'roughness', type: 'float' },
  33866. { name: 'dotNV', type: 'vec3' }
  33867. ]
  33868. } );
  33869. const EnvironmentBRDF = tslFn( ( inputs ) => {
  33870. const { dotNV, specularColor, specularF90, roughness } = inputs;
  33871. const fab = DFGApprox( { dotNV, roughness } );
  33872. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33873. } );
  33874. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  33875. const x = dotVH.oneMinus().saturate();
  33876. const x2 = x.mul( x );
  33877. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  33878. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  33879. } ).setLayout( {
  33880. name: 'Schlick_to_F0',
  33881. type: 'vec3',
  33882. inputs: [
  33883. { name: 'f', type: 'vec3' },
  33884. { name: 'f90', type: 'float' },
  33885. { name: 'dotVH', type: 'float' }
  33886. ]
  33887. } );
  33888. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33889. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  33890. const alpha = roughness.pow2();
  33891. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  33892. const invAlpha = float( 1.0 ).div( alpha );
  33893. const cos2h = dotNH.pow2();
  33894. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  33895. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  33896. } ).setLayout( {
  33897. name: 'D_Charlie',
  33898. type: 'float',
  33899. inputs: [
  33900. { name: 'roughness', type: 'float' },
  33901. { name: 'dotNH', type: 'float' }
  33902. ]
  33903. } );
  33904. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33905. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  33906. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  33907. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  33908. } ).setLayout( {
  33909. name: 'V_Neubelt',
  33910. type: 'float',
  33911. inputs: [
  33912. { name: 'dotNV', type: 'float' },
  33913. { name: 'dotNL', type: 'float' }
  33914. ]
  33915. } );
  33916. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  33917. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33918. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33919. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  33920. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33921. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  33922. const V = V_Neubelt( { dotNV, dotNL } );
  33923. return sheen.mul( D ).mul( V );
  33924. } );
  33925. // Rect Area Light
  33926. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  33927. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  33928. // code: https://github.com/selfshadow/ltc_code/
  33929. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  33930. const LUT_SIZE = 64.0;
  33931. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  33932. const LUT_BIAS = 0.5 / LUT_SIZE;
  33933. const dotNV = N.dot( V ).saturate();
  33934. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  33935. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  33936. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  33937. return uv;
  33938. } ).setLayout( {
  33939. name: 'LTC_Uv',
  33940. type: 'vec2',
  33941. inputs: [
  33942. { name: 'N', type: 'vec3' },
  33943. { name: 'V', type: 'vec3' },
  33944. { name: 'roughness', type: 'float' }
  33945. ]
  33946. } );
  33947. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  33948. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  33949. // An approximation of the form factor of a horizon-clipped rectangle.
  33950. const l = f.length();
  33951. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  33952. } ).setLayout( {
  33953. name: 'LTC_ClippedSphereFormFactor',
  33954. type: 'float',
  33955. inputs: [
  33956. { name: 'f', type: 'vec3' }
  33957. ]
  33958. } );
  33959. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  33960. const x = v1.dot( v2 );
  33961. const y = x.abs().toVar();
  33962. // rational polynomial approximation to theta / sin( theta ) / 2PI
  33963. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  33964. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  33965. const v = a.div( b );
  33966. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  33967. return v1.cross( v2 ).mul( theta_sintheta );
  33968. } ).setLayout( {
  33969. name: 'LTC_EdgeVectorFormFactor',
  33970. type: 'vec3',
  33971. inputs: [
  33972. { name: 'v1', type: 'vec3' },
  33973. { name: 'v2', type: 'vec3' }
  33974. ]
  33975. } );
  33976. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  33977. // bail if point is on back side of plane of light
  33978. // assumes ccw winding order of light vertices
  33979. const v1 = p1.sub( p0 ).toVar();
  33980. const v2 = p3.sub( p0 ).toVar();
  33981. const lightNormal = v1.cross( v2 );
  33982. const result = vec3().toVar();
  33983. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  33984. // construct orthonormal basis around N
  33985. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  33986. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  33987. // compute transform
  33988. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  33989. // transform rect
  33990. // & project rect onto sphere
  33991. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  33992. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  33993. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  33994. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  33995. // calculate vector form factor
  33996. const vectorFormFactor = vec3( 0 ).toVar();
  33997. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  33998. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  33999. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  34000. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  34001. // adjust for horizon clipping
  34002. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  34003. } );
  34004. return result;
  34005. } ).setLayout( {
  34006. name: 'LTC_Evaluate',
  34007. type: 'vec3',
  34008. inputs: [
  34009. { name: 'N', type: 'vec3' },
  34010. { name: 'V', type: 'vec3' },
  34011. { name: 'P', type: 'vec3' },
  34012. { name: 'mInv', type: 'mat3' },
  34013. { name: 'p0', type: 'vec3' },
  34014. { name: 'p1', type: 'vec3' },
  34015. { name: 'p2', type: 'vec3' },
  34016. { name: 'p3', type: 'vec3' }
  34017. ]
  34018. } );
  34019. //
  34020. // Transmission
  34021. //
  34022. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  34023. // Direction of refracted light.
  34024. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  34025. // Compute rotation-independant scaling of the model matrix.
  34026. const modelScale = vec3(
  34027. length( modelMatrix[ 0 ].xyz ),
  34028. length( modelMatrix[ 1 ].xyz ),
  34029. length( modelMatrix[ 2 ].xyz )
  34030. );
  34031. // The thickness is specified in local space.
  34032. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  34033. } ).setLayout( {
  34034. name: 'getVolumeTransmissionRay',
  34035. type: 'vec3',
  34036. inputs: [
  34037. { name: 'n', type: 'vec3' },
  34038. { name: 'v', type: 'vec3' },
  34039. { name: 'thickness', type: 'float' },
  34040. { name: 'ior', type: 'float' },
  34041. { name: 'modelMatrix', type: 'mat4' }
  34042. ]
  34043. } );
  34044. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  34045. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  34046. // an IOR of 1.5 results in the default amount of microfacet refraction.
  34047. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  34048. } ).setLayout( {
  34049. name: 'applyIorToRoughness',
  34050. type: 'float',
  34051. inputs: [
  34052. { name: 'roughness', type: 'float' },
  34053. { name: 'ior', type: 'float' }
  34054. ]
  34055. } );
  34056. const singleViewportMipTexture = viewportMipTexture();
  34057. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  34058. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  34059. //const transmissionSample = viewportMipTexture( fragCoord );
  34060. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  34061. return transmissionSample.bicubic( lod );
  34062. } );
  34063. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  34064. If( attenuationDistance.notEqual( 0 ), () => {
  34065. // Compute light attenuation using Beer's law.
  34066. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  34067. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  34068. return transmittance;
  34069. } );
  34070. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  34071. return vec3( 1.0 );
  34072. } ).setLayout( {
  34073. name: 'volumeAttenuation',
  34074. type: 'vec3',
  34075. inputs: [
  34076. { name: 'transmissionDistance', type: 'float' },
  34077. { name: 'attenuationColor', type: 'vec3' },
  34078. { name: 'attenuationDistance', type: 'float' }
  34079. ]
  34080. } );
  34081. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  34082. let transmittedLight, transmittance;
  34083. if ( dispersion ) {
  34084. transmittedLight = vec4().toVar();
  34085. transmittance = vec3().toVar();
  34086. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  34087. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  34088. loop( { start: 0, end: 3 }, ( { i } ) => {
  34089. const ior = iors.element( i );
  34090. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  34091. const refractedRayExit = position.add( transmissionRay );
  34092. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  34093. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  34094. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  34095. refractionCoords.addAssign( 1.0 );
  34096. refractionCoords.divAssign( 2.0 );
  34097. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  34098. // Sample framebuffer to get pixel the refracted ray hits.
  34099. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  34100. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  34101. transmittedLight.a.addAssign( transmissionSample.a );
  34102. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  34103. } );
  34104. transmittedLight.a.divAssign( 3.0 );
  34105. } else {
  34106. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  34107. const refractedRayExit = position.add( transmissionRay );
  34108. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  34109. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  34110. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  34111. refractionCoords.addAssign( 1.0 );
  34112. refractionCoords.divAssign( 2.0 );
  34113. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  34114. // Sample framebuffer to get pixel the refracted ray hits.
  34115. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  34116. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  34117. }
  34118. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  34119. const dotNV = n.dot( v ).clamp();
  34120. // Get the specular component.
  34121. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  34122. dotNV,
  34123. specularColor,
  34124. specularF90,
  34125. roughness
  34126. } ) );
  34127. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  34128. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  34129. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  34130. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  34131. } );
  34132. //
  34133. // Iridescence
  34134. //
  34135. // XYZ to linear-sRGB color space
  34136. const XYZ_TO_REC709 = mat3(
  34137. 3.2404542, - 0.9692660, 0.0556434,
  34138. - 1.5371385, 1.8760108, - 0.2040259,
  34139. - 0.4985314, 0.0415560, 1.0572252
  34140. );
  34141. // Assume air interface for top
  34142. // Note: We don't handle the case fresnel0 == 1
  34143. const Fresnel0ToIor = ( fresnel0 ) => {
  34144. const sqrtF0 = fresnel0.sqrt();
  34145. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  34146. };
  34147. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  34148. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  34149. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  34150. };
  34151. // Fresnel equations for dielectric/dielectric interfaces.
  34152. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  34153. // Evaluation XYZ sensitivity curves in Fourier space
  34154. const evalSensitivity = ( OPD, shift ) => {
  34155. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  34156. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  34157. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  34158. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  34159. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  34160. 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() );
  34161. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  34162. const rgb = XYZ_TO_REC709.mul( xyz );
  34163. return rgb;
  34164. };
  34165. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  34166. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  34167. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  34168. // Evaluate the cosTheta on the base layer (Snell law)
  34169. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  34170. // Handle TIR:
  34171. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  34172. /*if ( cosTheta2Sq < 0.0 ) {
  34173. return vec3( 1.0 );
  34174. }*/
  34175. const cosTheta2 = cosTheta2Sq.sqrt();
  34176. // First interface
  34177. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  34178. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  34179. //const R21 = R12;
  34180. const T121 = R12.oneMinus();
  34181. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  34182. const phi21 = float( Math.PI ).sub( phi12 );
  34183. // Second interface
  34184. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  34185. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  34186. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  34187. const phi23 = vec3(
  34188. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34189. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34190. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  34191. );
  34192. // Phase shift
  34193. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  34194. const phi = vec3( phi21 ).add( phi23 );
  34195. // Compound terms
  34196. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  34197. const r123 = R123.sqrt();
  34198. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  34199. // Reflectance term for m = 0 (DC term amplitude)
  34200. const C0 = R12.add( Rs );
  34201. let I = C0;
  34202. // Reflectance term for m > 0 (pairs of diracs)
  34203. let Cm = Rs.sub( T121 );
  34204. for ( let m = 1; m <= 2; ++ m ) {
  34205. Cm = Cm.mul( r123 );
  34206. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  34207. I = I.add( Cm.mul( Sm ) );
  34208. }
  34209. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  34210. return I.max( vec3( 0.0 ) );
  34211. } ).setLayout( {
  34212. name: 'evalIridescence',
  34213. type: 'vec3',
  34214. inputs: [
  34215. { name: 'outsideIOR', type: 'float' },
  34216. { name: 'eta2', type: 'float' },
  34217. { name: 'cosTheta1', type: 'float' },
  34218. { name: 'thinFilmThickness', type: 'float' },
  34219. { name: 'baseF0', type: 'vec3' }
  34220. ]
  34221. } );
  34222. //
  34223. // Sheen
  34224. //
  34225. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  34226. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  34227. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  34228. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  34229. const dotNV = normal.dot( viewDir ).saturate();
  34230. const r2 = roughness.pow2();
  34231. const a = cond(
  34232. roughness.lessThan( 0.25 ),
  34233. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  34234. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  34235. );
  34236. const b = cond(
  34237. roughness.lessThan( 0.25 ),
  34238. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  34239. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  34240. );
  34241. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  34242. return DG.mul( 1.0 / Math.PI ).saturate();
  34243. } );
  34244. const clearcoatF0 = vec3( 0.04 );
  34245. const clearcoatF90 = float( 1 );
  34246. //
  34247. class PhysicalLightingModel extends LightingModel {
  34248. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  34249. super();
  34250. this.clearcoat = clearcoat;
  34251. this.sheen = sheen;
  34252. this.iridescence = iridescence;
  34253. this.anisotropy = anisotropy;
  34254. this.transmission = transmission;
  34255. this.dispersion = dispersion;
  34256. this.clearcoatRadiance = null;
  34257. this.clearcoatSpecularDirect = null;
  34258. this.clearcoatSpecularIndirect = null;
  34259. this.sheenSpecularDirect = null;
  34260. this.sheenSpecularIndirect = null;
  34261. this.iridescenceFresnel = null;
  34262. this.iridescenceF0 = null;
  34263. }
  34264. start( context ) {
  34265. if ( this.clearcoat === true ) {
  34266. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  34267. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  34268. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  34269. }
  34270. if ( this.sheen === true ) {
  34271. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  34272. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  34273. }
  34274. if ( this.iridescence === true ) {
  34275. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  34276. this.iridescenceFresnel = evalIridescence( {
  34277. outsideIOR: float( 1.0 ),
  34278. eta2: iridescenceIOR,
  34279. cosTheta1: dotNVi,
  34280. thinFilmThickness: iridescenceThickness,
  34281. baseF0: specularColor
  34282. } );
  34283. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  34284. }
  34285. if ( this.transmission === true ) {
  34286. const position = positionWorld;
  34287. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  34288. const n = transformedNormalWorld;
  34289. context.backdrop = getIBLVolumeRefraction(
  34290. n,
  34291. v,
  34292. roughness,
  34293. diffuseColor,
  34294. specularColor,
  34295. specularF90, // specularF90
  34296. position, // positionWorld
  34297. modelWorldMatrix, // modelMatrix
  34298. cameraViewMatrix, // viewMatrix
  34299. cameraProjectionMatrix, // projMatrix
  34300. ior,
  34301. thickness,
  34302. attenuationColor,
  34303. attenuationDistance,
  34304. this.dispersion ? dispersion : null
  34305. );
  34306. context.backdropAlpha = transmission;
  34307. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  34308. }
  34309. }
  34310. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  34311. // Approximates multiscattering in order to preserve energy.
  34312. // http://www.jcgt.org/published/0008/01/03/
  34313. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  34314. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34315. const fab = DFGApprox( { roughness, dotNV } );
  34316. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  34317. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  34318. const Ess = fab.x.add( fab.y );
  34319. const Ems = Ess.oneMinus();
  34320. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  34321. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  34322. singleScatter.addAssign( FssEss );
  34323. multiScatter.addAssign( Fms.mul( Ems ) );
  34324. }
  34325. direct( { lightDirection, lightColor, reflectedLight } ) {
  34326. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  34327. const irradiance = dotNL.mul( lightColor );
  34328. if ( this.sheen === true ) {
  34329. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  34330. }
  34331. if ( this.clearcoat === true ) {
  34332. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  34333. const ccIrradiance = dotNLcc.mul( lightColor );
  34334. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  34335. }
  34336. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34337. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  34338. }
  34339. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  34340. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  34341. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  34342. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  34343. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  34344. const N = transformedNormalView;
  34345. const V = positionViewDirection;
  34346. const P = positionView.toVar();
  34347. const uv = LTC_Uv( { N, V, roughness } );
  34348. const t1 = ltc_1.uv( uv ).toVar();
  34349. const t2 = ltc_2.uv( uv ).toVar();
  34350. const mInv = mat3(
  34351. vec3( t1.x, 0, t1.y ),
  34352. vec3( 0, 1, 0 ),
  34353. vec3( t1.z, 0, t1.w )
  34354. ).toVar();
  34355. // LTC Fresnel Approximation by Stephen Hill
  34356. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  34357. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  34358. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  34359. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  34360. }
  34361. indirect( context, stack, builder ) {
  34362. this.indirectDiffuse( context, stack, builder );
  34363. this.indirectSpecular( context, stack, builder );
  34364. this.ambientOcclusion( context, stack, builder );
  34365. }
  34366. indirectDiffuse( { irradiance, reflectedLight } ) {
  34367. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34368. }
  34369. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  34370. if ( this.sheen === true ) {
  34371. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  34372. sheen,
  34373. IBLSheenBRDF( {
  34374. normal: transformedNormalView,
  34375. viewDir: positionViewDirection,
  34376. roughness: sheenRoughness
  34377. } )
  34378. ) );
  34379. }
  34380. if ( this.clearcoat === true ) {
  34381. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34382. const clearcoatEnv = EnvironmentBRDF( {
  34383. dotNV: dotNVcc,
  34384. specularColor: clearcoatF0,
  34385. specularF90: clearcoatF90,
  34386. roughness: clearcoatRoughness
  34387. } );
  34388. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  34389. }
  34390. // Both indirect specular and indirect diffuse light accumulate here
  34391. const singleScattering = vec3().temp( 'singleScattering' );
  34392. const multiScattering = vec3().temp( 'multiScattering' );
  34393. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  34394. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  34395. const totalScattering = singleScattering.add( multiScattering );
  34396. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  34397. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  34398. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  34399. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  34400. }
  34401. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  34402. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34403. const aoNV = dotNV.add( ambientOcclusion );
  34404. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  34405. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  34406. if ( this.clearcoat === true ) {
  34407. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  34408. }
  34409. if ( this.sheen === true ) {
  34410. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  34411. }
  34412. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34413. reflectedLight.indirectSpecular.mulAssign( aoNode );
  34414. }
  34415. finish( context ) {
  34416. const { outgoingLight } = context;
  34417. if ( this.clearcoat === true ) {
  34418. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34419. const Fcc = F_Schlick( {
  34420. dotVH: dotNVcc,
  34421. f0: clearcoatF0,
  34422. f90: clearcoatF90
  34423. } );
  34424. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  34425. outgoingLight.assign( clearcoatLight );
  34426. }
  34427. if ( this.sheen === true ) {
  34428. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  34429. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  34430. outgoingLight.assign( sheenLight );
  34431. }
  34432. }
  34433. }
  34434. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  34435. class MeshStandardNodeMaterial extends NodeMaterial {
  34436. constructor( parameters ) {
  34437. super();
  34438. this.isMeshStandardNodeMaterial = true;
  34439. this.lights = true;
  34440. this.emissiveNode = null;
  34441. this.metalnessNode = null;
  34442. this.roughnessNode = null;
  34443. this.setDefaultValues( _defaultValues$6 );
  34444. this.setValues( parameters );
  34445. }
  34446. setupEnvironment( builder ) {
  34447. let envNode = super.setupEnvironment( builder );
  34448. if ( envNode === null && builder.environmentNode ) {
  34449. envNode = builder.environmentNode;
  34450. }
  34451. return envNode ? new EnvironmentNode( envNode ) : null;
  34452. }
  34453. setupLightingModel( /*builder*/ ) {
  34454. return new PhysicalLightingModel();
  34455. }
  34456. setupSpecular() {
  34457. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  34458. specularColor.assign( specularColorNode );
  34459. specularF90.assign( 1.0 );
  34460. }
  34461. setupVariants() {
  34462. // METALNESS
  34463. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  34464. metalness.assign( metalnessNode );
  34465. // ROUGHNESS
  34466. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  34467. roughnessNode = getRoughness( { roughness: roughnessNode } );
  34468. roughness.assign( roughnessNode );
  34469. // SPECULAR COLOR
  34470. this.setupSpecular();
  34471. // DIFFUSE COLOR
  34472. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  34473. }
  34474. copy( source ) {
  34475. this.emissiveNode = source.emissiveNode;
  34476. this.metalnessNode = source.metalnessNode;
  34477. this.roughnessNode = source.roughnessNode;
  34478. return super.copy( source );
  34479. }
  34480. }
  34481. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  34482. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  34483. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  34484. constructor( parameters ) {
  34485. super();
  34486. this.isMeshPhysicalNodeMaterial = true;
  34487. this.clearcoatNode = null;
  34488. this.clearcoatRoughnessNode = null;
  34489. this.clearcoatNormalNode = null;
  34490. this.sheenNode = null;
  34491. this.sheenRoughnessNode = null;
  34492. this.iridescenceNode = null;
  34493. this.iridescenceIORNode = null;
  34494. this.iridescenceThicknessNode = null;
  34495. this.specularIntensityNode = null;
  34496. this.specularColorNode = null;
  34497. this.iorNode = null;
  34498. this.transmissionNode = null;
  34499. this.thicknessNode = null;
  34500. this.attenuationDistanceNode = null;
  34501. this.attenuationColorNode = null;
  34502. this.dispersionNode = null;
  34503. this.anisotropyNode = null;
  34504. this.setDefaultValues( _defaultValues$5 );
  34505. this.setValues( parameters );
  34506. }
  34507. get useClearcoat() {
  34508. return this.clearcoat > 0 || this.clearcoatNode !== null;
  34509. }
  34510. get useIridescence() {
  34511. return this.iridescence > 0 || this.iridescenceNode !== null;
  34512. }
  34513. get useSheen() {
  34514. return this.sheen > 0 || this.sheenNode !== null;
  34515. }
  34516. get useAnisotropy() {
  34517. return this.anisotropy > 0 || this.anisotropyNode !== null;
  34518. }
  34519. get useTransmission() {
  34520. return this.transmission > 0 || this.transmissionNode !== null;
  34521. }
  34522. get useDispersion() {
  34523. return this.dispersion > 0 || this.dispersionNode !== null;
  34524. }
  34525. setupSpecular() {
  34526. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  34527. ior.assign( iorNode );
  34528. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  34529. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  34530. }
  34531. setupLightingModel( /*builder*/ ) {
  34532. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  34533. }
  34534. setupVariants( builder ) {
  34535. super.setupVariants( builder );
  34536. // CLEARCOAT
  34537. if ( this.useClearcoat ) {
  34538. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  34539. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  34540. clearcoat.assign( clearcoatNode );
  34541. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  34542. }
  34543. // SHEEN
  34544. if ( this.useSheen ) {
  34545. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  34546. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  34547. sheen.assign( sheenNode );
  34548. sheenRoughness.assign( sheenRoughnessNode );
  34549. }
  34550. // IRIDESCENCE
  34551. if ( this.useIridescence ) {
  34552. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  34553. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  34554. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  34555. iridescence.assign( iridescenceNode );
  34556. iridescenceIOR.assign( iridescenceIORNode );
  34557. iridescenceThickness.assign( iridescenceThicknessNode );
  34558. }
  34559. // ANISOTROPY
  34560. if ( this.useAnisotropy ) {
  34561. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  34562. anisotropy.assign( anisotropyV.length() );
  34563. If( anisotropy.equal( 0.0 ), () => {
  34564. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  34565. } ).else( () => {
  34566. anisotropyV.divAssign( vec2( anisotropy ) );
  34567. anisotropy.assign( anisotropy.saturate() );
  34568. } );
  34569. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  34570. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  34571. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  34572. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  34573. }
  34574. // TRANSMISSION
  34575. if ( this.useTransmission ) {
  34576. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  34577. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  34578. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  34579. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  34580. transmission.assign( transmissionNode );
  34581. thickness.assign( thicknessNode );
  34582. attenuationDistance.assign( attenuationDistanceNode );
  34583. attenuationColor.assign( attenuationColorNode );
  34584. if ( this.useDispersion ) {
  34585. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  34586. dispersion.assign( dispersionNode );
  34587. }
  34588. }
  34589. }
  34590. setupNormal( builder ) {
  34591. super.setupNormal( builder );
  34592. // CLEARCOAT NORMAL
  34593. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  34594. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  34595. }
  34596. copy( source ) {
  34597. this.clearcoatNode = source.clearcoatNode;
  34598. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  34599. this.clearcoatNormalNode = source.clearcoatNormalNode;
  34600. this.sheenNode = source.sheenNode;
  34601. this.sheenRoughnessNode = source.sheenRoughnessNode;
  34602. this.iridescenceNode = source.iridescenceNode;
  34603. this.iridescenceIORNode = source.iridescenceIORNode;
  34604. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  34605. this.specularIntensityNode = source.specularIntensityNode;
  34606. this.specularColorNode = source.specularColorNode;
  34607. this.transmissionNode = source.transmissionNode;
  34608. this.thicknessNode = source.thicknessNode;
  34609. this.attenuationDistanceNode = source.attenuationDistanceNode;
  34610. this.attenuationColorNode = source.attenuationColorNode;
  34611. this.dispersionNode = source.dispersionNode;
  34612. this.anisotropyNode = source.anisotropyNode;
  34613. return super.copy( source );
  34614. }
  34615. }
  34616. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  34617. class SSSLightingModel extends PhysicalLightingModel {
  34618. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  34619. super( useClearcoat, useSheen, useIridescence );
  34620. this.useSSS = useSSS;
  34621. }
  34622. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34623. if ( this.useSSS === true ) {
  34624. const material = builder.material;
  34625. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  34626. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  34627. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  34628. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  34629. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  34630. }
  34631. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  34632. }
  34633. }
  34634. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  34635. constructor( parameters ) {
  34636. super( parameters );
  34637. this.thicknessColorNode = null;
  34638. this.thicknessDistortionNode = float( 0.1 );
  34639. this.thicknessAmbientNode = float( 0.0 );
  34640. this.thicknessAttenuationNode = float( .1 );
  34641. this.thicknessPowerNode = float( 2.0 );
  34642. this.thicknessScaleNode = float( 10.0 );
  34643. }
  34644. get useSSS() {
  34645. return this.thicknessColorNode !== null;
  34646. }
  34647. setupLightingModel( /*builder*/ ) {
  34648. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  34649. }
  34650. copy( source ) {
  34651. this.thicknessColorNode = source.thicknessColorNode;
  34652. this.thicknessDistortionNode = source.thicknessDistortionNode;
  34653. this.thicknessAmbientNode = source.thicknessAmbientNode;
  34654. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  34655. this.thicknessPowerNode = source.thicknessPowerNode;
  34656. this.thicknessScaleNode = source.thicknessScaleNode;
  34657. return super.copy( source );
  34658. }
  34659. }
  34660. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  34661. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  34662. // dotNL will be from -1.0 to 1.0
  34663. const dotNL = normal.dot( lightDirection );
  34664. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  34665. if ( builder.material.gradientMap ) {
  34666. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  34667. return vec3( gradientMap.r );
  34668. } else {
  34669. const fw = coord.fwidth().mul( 0.5 );
  34670. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  34671. }
  34672. } );
  34673. class ToonLightingModel extends LightingModel {
  34674. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34675. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  34676. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34677. }
  34678. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  34679. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34680. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34681. }
  34682. }
  34683. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  34684. class MeshToonNodeMaterial extends NodeMaterial {
  34685. constructor( parameters ) {
  34686. super();
  34687. this.isMeshToonNodeMaterial = true;
  34688. this.lights = true;
  34689. this.setDefaultValues( _defaultValues$4 );
  34690. this.setValues( parameters );
  34691. }
  34692. setupLightingModel( /*builder*/ ) {
  34693. return new ToonLightingModel();
  34694. }
  34695. }
  34696. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  34697. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  34698. class MeshMatcapNodeMaterial extends NodeMaterial {
  34699. constructor( parameters ) {
  34700. super();
  34701. this.lights = false;
  34702. this.isMeshMatcapNodeMaterial = true;
  34703. this.setDefaultValues( _defaultValues$3 );
  34704. this.setValues( parameters );
  34705. }
  34706. setupVariants( builder ) {
  34707. const uv = matcapUV;
  34708. let matcapColor;
  34709. if ( builder.material.matcap ) {
  34710. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  34711. } else {
  34712. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  34713. }
  34714. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  34715. }
  34716. }
  34717. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  34718. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  34719. class PointsNodeMaterial extends NodeMaterial {
  34720. constructor( parameters ) {
  34721. super();
  34722. this.isPointsNodeMaterial = true;
  34723. this.lights = false;
  34724. this.normals = false;
  34725. this.transparent = true;
  34726. this.sizeNode = null;
  34727. this.setDefaultValues( _defaultValues$2 );
  34728. this.setValues( parameters );
  34729. }
  34730. copy( source ) {
  34731. this.sizeNode = source.sizeNode;
  34732. return super.copy( source );
  34733. }
  34734. }
  34735. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  34736. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  34737. class SpriteNodeMaterial extends NodeMaterial {
  34738. constructor( parameters ) {
  34739. super();
  34740. this.isSpriteNodeMaterial = true;
  34741. this.lights = false;
  34742. this.normals = false;
  34743. this.positionNode = null;
  34744. this.rotationNode = null;
  34745. this.scaleNode = null;
  34746. this.setDefaultValues( _defaultValues$1 );
  34747. this.setValues( parameters );
  34748. }
  34749. setupPosition( { object, context } ) {
  34750. // < VERTEX STAGE >
  34751. const { positionNode, rotationNode, scaleNode } = this;
  34752. const vertex = positionLocal;
  34753. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  34754. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  34755. if ( scaleNode !== null ) {
  34756. scale = scale.mul( scaleNode );
  34757. }
  34758. let alignedPosition = vertex.xy;
  34759. if ( object.center && object.center.isVector2 === true ) {
  34760. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  34761. }
  34762. alignedPosition = alignedPosition.mul( scale );
  34763. const rotation = float( rotationNode || materialRotation );
  34764. const rotatedPosition = alignedPosition.rotate( rotation );
  34765. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  34766. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  34767. context.vertex = vertex;
  34768. return modelViewProjection;
  34769. }
  34770. copy( source ) {
  34771. this.positionNode = source.positionNode;
  34772. this.rotationNode = source.rotationNode;
  34773. this.scaleNode = source.scaleNode;
  34774. return super.copy( source );
  34775. }
  34776. }
  34777. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  34778. class ShadowMaskModel extends LightingModel {
  34779. constructor() {
  34780. super();
  34781. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  34782. }
  34783. direct( { shadowMask } ) {
  34784. this.shadowNode.mulAssign( shadowMask );
  34785. }
  34786. finish( context ) {
  34787. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  34788. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  34789. }
  34790. }
  34791. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  34792. class ShadowNodeMaterial extends NodeMaterial {
  34793. constructor( parameters ) {
  34794. super();
  34795. this.isShadowNodeMaterial = true;
  34796. this.lights = true;
  34797. this.setDefaultValues( _defaultValues );
  34798. this.setValues( parameters );
  34799. }
  34800. setupLightingModel( /*builder*/ ) {
  34801. return new ShadowMaskModel();
  34802. }
  34803. }
  34804. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  34805. class VolumeNodeMaterial extends NodeMaterial {
  34806. constructor( params = {} ) {
  34807. super();
  34808. this.normals = false;
  34809. this.lights = false;
  34810. this.isVolumeNodeMaterial = true;
  34811. this.testNode = null;
  34812. this.setValues( params );
  34813. }
  34814. setup( builder ) {
  34815. const map = texture3D( this.map, null, 0 );
  34816. const hitBox = tslFn( ( { orig, dir } ) => {
  34817. const box_min = vec3( - 0.5 );
  34818. const box_max = vec3( 0.5 );
  34819. const inv_dir = dir.reciprocal();
  34820. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  34821. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  34822. const tmin = min$1( tmin_tmp, tmax_tmp );
  34823. const tmax = max$1( tmin_tmp, tmax_tmp );
  34824. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  34825. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  34826. return vec2( t0, t1 );
  34827. } );
  34828. this.fragmentNode = tslFn( () => {
  34829. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  34830. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  34831. const rayDir = vDirection.normalize();
  34832. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  34833. bounds.x.greaterThan( bounds.y ).discard();
  34834. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  34835. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  34836. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  34837. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  34838. delta.divAssign( materialReference( 'steps', 'float' ) );
  34839. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  34840. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  34841. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  34842. if ( this.testNode !== null ) {
  34843. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  34844. } else {
  34845. // default to show surface of mesh
  34846. ac.a.assign( 1 );
  34847. Break();
  34848. }
  34849. p.addAssign( rayDir.mul( delta ) );
  34850. } );
  34851. ac.a.equal( 0 ).discard();
  34852. return vec4( ac );
  34853. } )();
  34854. super.setup( builder );
  34855. }
  34856. }
  34857. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  34858. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  34859. MaterialLoader.createMaterialFromType = function ( type ) {
  34860. const material = createNodeMaterialFromType( type );
  34861. if ( material !== undefined ) {
  34862. return material;
  34863. }
  34864. return superFromTypeFunction.call( this, type );
  34865. };
  34866. class NodeMaterialLoader extends MaterialLoader {
  34867. constructor( manager ) {
  34868. super( manager );
  34869. this.nodes = {};
  34870. }
  34871. parse( json ) {
  34872. const material = super.parse( json );
  34873. const nodes = this.nodes;
  34874. const inputNodes = json.inputNodes;
  34875. for ( const property in inputNodes ) {
  34876. const uuid = inputNodes[ property ];
  34877. material[ property ] = nodes[ uuid ];
  34878. }
  34879. return material;
  34880. }
  34881. setNodes( value ) {
  34882. this.nodes = value;
  34883. return this;
  34884. }
  34885. }
  34886. class NodeObjectLoader extends ObjectLoader {
  34887. constructor( manager ) {
  34888. super( manager );
  34889. this._nodesJSON = null;
  34890. }
  34891. parse( json, onLoad ) {
  34892. this._nodesJSON = json.nodes;
  34893. const data = super.parse( json, onLoad );
  34894. this._nodesJSON = null; // dispose
  34895. return data;
  34896. }
  34897. parseNodes( json, textures ) {
  34898. if ( json !== undefined ) {
  34899. const loader = new NodeLoader();
  34900. loader.setTextures( textures );
  34901. return loader.parseNodes( json );
  34902. }
  34903. return {};
  34904. }
  34905. parseMaterials( json, textures ) {
  34906. const materials = {};
  34907. if ( json !== undefined ) {
  34908. const nodes = this.parseNodes( this._nodesJSON, textures );
  34909. const loader = new NodeMaterialLoader();
  34910. loader.setTextures( textures );
  34911. loader.setNodes( nodes );
  34912. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34913. const data = json[ i ];
  34914. materials[ data.uuid ] = loader.parse( data );
  34915. }
  34916. }
  34917. return materials;
  34918. }
  34919. }
  34920. class NodeParser {
  34921. parseFunction( /*source*/ ) {
  34922. console.warn( 'Abstract function.' );
  34923. }
  34924. }
  34925. class NodeFunction {
  34926. constructor( type, inputs, name = '', precision = '' ) {
  34927. this.type = type;
  34928. this.inputs = inputs;
  34929. this.name = name;
  34930. this.precision = precision;
  34931. }
  34932. getCode( /*name = this.name*/ ) {
  34933. console.warn( 'Abstract function.' );
  34934. }
  34935. }
  34936. NodeFunction.isNodeFunction = true;
  34937. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34938. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34939. const pragmaMain = '#pragma main';
  34940. const parse$1 = ( source ) => {
  34941. source = source.trim();
  34942. const pragmaMainIndex = source.indexOf( pragmaMain );
  34943. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34944. const declaration = mainCode.match( declarationRegexp$1 );
  34945. if ( declaration !== null && declaration.length === 5 ) {
  34946. // tokenizer
  34947. const inputsCode = declaration[ 4 ];
  34948. const propsMatches = [];
  34949. let nameMatch = null;
  34950. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34951. propsMatches.push( nameMatch );
  34952. }
  34953. // parser
  34954. const inputs = [];
  34955. let i = 0;
  34956. while ( i < propsMatches.length ) {
  34957. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34958. if ( isConst === true ) {
  34959. i ++;
  34960. }
  34961. let qualifier = propsMatches[ i ][ 0 ];
  34962. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34963. i ++;
  34964. } else {
  34965. qualifier = '';
  34966. }
  34967. const type = propsMatches[ i ++ ][ 0 ];
  34968. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34969. if ( Number.isNaN( count ) === false ) i ++;
  34970. else count = null;
  34971. const name = propsMatches[ i ++ ][ 0 ];
  34972. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34973. }
  34974. //
  34975. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34976. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34977. const type = declaration[ 2 ];
  34978. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34979. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  34980. return {
  34981. type,
  34982. inputs,
  34983. name,
  34984. precision,
  34985. inputsCode,
  34986. blockCode,
  34987. headerCode
  34988. };
  34989. } else {
  34990. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34991. }
  34992. };
  34993. class GLSLNodeFunction extends NodeFunction {
  34994. constructor( source ) {
  34995. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34996. super( type, inputs, name, precision );
  34997. this.inputsCode = inputsCode;
  34998. this.blockCode = blockCode;
  34999. this.headerCode = headerCode;
  35000. }
  35001. getCode( name = this.name ) {
  35002. let code;
  35003. const blockCode = this.blockCode;
  35004. if ( blockCode !== '' ) {
  35005. const { type, inputsCode, headerCode, precision } = this;
  35006. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35007. if ( precision !== '' ) {
  35008. declarationCode = `${ precision } ${ declarationCode }`;
  35009. }
  35010. code = headerCode + declarationCode + blockCode;
  35011. } else {
  35012. // interface function
  35013. code = '';
  35014. }
  35015. return code;
  35016. }
  35017. }
  35018. class GLSLNodeParser extends NodeParser {
  35019. parseFunction( source ) {
  35020. return new GLSLNodeFunction( source );
  35021. }
  35022. }
  35023. // Three.js Transpiler
  35024. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  35025. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  35026. const f = float( f_immutable ).toVar();
  35027. const t = float( t_immutable ).toVar();
  35028. const b = bool( b_immutable ).toVar();
  35029. return cond( b, t, f );
  35030. } ).setLayout( {
  35031. name: 'mx_select',
  35032. type: 'float',
  35033. inputs: [
  35034. { name: 'b', type: 'bool' },
  35035. { name: 't', type: 'float' },
  35036. { name: 'f', type: 'float' }
  35037. ]
  35038. } );
  35039. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  35040. const b = bool( b_immutable ).toVar();
  35041. const val = float( val_immutable ).toVar();
  35042. return cond( b, val.negate(), val );
  35043. } ).setLayout( {
  35044. name: 'mx_negate_if',
  35045. type: 'float',
  35046. inputs: [
  35047. { name: 'val', type: 'float' },
  35048. { name: 'b', type: 'bool' }
  35049. ]
  35050. } );
  35051. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  35052. const x = float( x_immutable ).toVar();
  35053. return int( floor( x ) );
  35054. } ).setLayout( {
  35055. name: 'mx_floor',
  35056. type: 'int',
  35057. inputs: [
  35058. { name: 'x', type: 'float' }
  35059. ]
  35060. } );
  35061. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  35062. const x = float( x_immutable ).toVar();
  35063. i.assign( mx_floor( x ) );
  35064. return x.sub( float( i ) );
  35065. } );
  35066. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  35067. const t = float( t_immutable ).toVar();
  35068. const s = float( s_immutable ).toVar();
  35069. const v3 = float( v3_immutable ).toVar();
  35070. const v2 = float( v2_immutable ).toVar();
  35071. const v1 = float( v1_immutable ).toVar();
  35072. const v0 = float( v0_immutable ).toVar();
  35073. const s1 = float( sub( 1.0, s ) ).toVar();
  35074. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  35075. } ).setLayout( {
  35076. name: 'mx_bilerp_0',
  35077. type: 'float',
  35078. inputs: [
  35079. { name: 'v0', type: 'float' },
  35080. { name: 'v1', type: 'float' },
  35081. { name: 'v2', type: 'float' },
  35082. { name: 'v3', type: 'float' },
  35083. { name: 's', type: 'float' },
  35084. { name: 't', type: 'float' }
  35085. ]
  35086. } );
  35087. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  35088. const t = float( t_immutable ).toVar();
  35089. const s = float( s_immutable ).toVar();
  35090. const v3 = vec3( v3_immutable ).toVar();
  35091. const v2 = vec3( v2_immutable ).toVar();
  35092. const v1 = vec3( v1_immutable ).toVar();
  35093. const v0 = vec3( v0_immutable ).toVar();
  35094. const s1 = float( sub( 1.0, s ) ).toVar();
  35095. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  35096. } ).setLayout( {
  35097. name: 'mx_bilerp_1',
  35098. type: 'vec3',
  35099. inputs: [
  35100. { name: 'v0', type: 'vec3' },
  35101. { name: 'v1', type: 'vec3' },
  35102. { name: 'v2', type: 'vec3' },
  35103. { name: 'v3', type: 'vec3' },
  35104. { name: 's', type: 'float' },
  35105. { name: 't', type: 'float' }
  35106. ]
  35107. } );
  35108. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  35109. const mx_trilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  35110. const r = float( r_immutable ).toVar();
  35111. const t = float( t_immutable ).toVar();
  35112. const s = float( s_immutable ).toVar();
  35113. const v7 = float( v7_immutable ).toVar();
  35114. const v6 = float( v6_immutable ).toVar();
  35115. const v5 = float( v5_immutable ).toVar();
  35116. const v4 = float( v4_immutable ).toVar();
  35117. const v3 = float( v3_immutable ).toVar();
  35118. const v2 = float( v2_immutable ).toVar();
  35119. const v1 = float( v1_immutable ).toVar();
  35120. const v0 = float( v0_immutable ).toVar();
  35121. const s1 = float( sub( 1.0, s ) ).toVar();
  35122. const t1 = float( sub( 1.0, t ) ).toVar();
  35123. const r1 = float( sub( 1.0, r ) ).toVar();
  35124. 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 ) ) ) ) ) );
  35125. } ).setLayout( {
  35126. name: 'mx_trilerp_0',
  35127. type: 'float',
  35128. inputs: [
  35129. { name: 'v0', type: 'float' },
  35130. { name: 'v1', type: 'float' },
  35131. { name: 'v2', type: 'float' },
  35132. { name: 'v3', type: 'float' },
  35133. { name: 'v4', type: 'float' },
  35134. { name: 'v5', type: 'float' },
  35135. { name: 'v6', type: 'float' },
  35136. { name: 'v7', type: 'float' },
  35137. { name: 's', type: 'float' },
  35138. { name: 't', type: 'float' },
  35139. { name: 'r', type: 'float' }
  35140. ]
  35141. } );
  35142. const mx_trilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  35143. const r = float( r_immutable ).toVar();
  35144. const t = float( t_immutable ).toVar();
  35145. const s = float( s_immutable ).toVar();
  35146. const v7 = vec3( v7_immutable ).toVar();
  35147. const v6 = vec3( v6_immutable ).toVar();
  35148. const v5 = vec3( v5_immutable ).toVar();
  35149. const v4 = vec3( v4_immutable ).toVar();
  35150. const v3 = vec3( v3_immutable ).toVar();
  35151. const v2 = vec3( v2_immutable ).toVar();
  35152. const v1 = vec3( v1_immutable ).toVar();
  35153. const v0 = vec3( v0_immutable ).toVar();
  35154. const s1 = float( sub( 1.0, s ) ).toVar();
  35155. const t1 = float( sub( 1.0, t ) ).toVar();
  35156. const r1 = float( sub( 1.0, r ) ).toVar();
  35157. 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 ) ) ) ) ) );
  35158. } ).setLayout( {
  35159. name: 'mx_trilerp_1',
  35160. type: 'vec3',
  35161. inputs: [
  35162. { name: 'v0', type: 'vec3' },
  35163. { name: 'v1', type: 'vec3' },
  35164. { name: 'v2', type: 'vec3' },
  35165. { name: 'v3', type: 'vec3' },
  35166. { name: 'v4', type: 'vec3' },
  35167. { name: 'v5', type: 'vec3' },
  35168. { name: 'v6', type: 'vec3' },
  35169. { name: 'v7', type: 'vec3' },
  35170. { name: 's', type: 'float' },
  35171. { name: 't', type: 'float' },
  35172. { name: 'r', type: 'float' }
  35173. ]
  35174. } );
  35175. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  35176. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35177. const y = float( y_immutable ).toVar();
  35178. const x = float( x_immutable ).toVar();
  35179. const hash = uint( hash_immutable ).toVar();
  35180. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  35181. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  35182. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  35183. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35184. } ).setLayout( {
  35185. name: 'mx_gradient_float_0',
  35186. type: 'float',
  35187. inputs: [
  35188. { name: 'hash', type: 'uint' },
  35189. { name: 'x', type: 'float' },
  35190. { name: 'y', type: 'float' }
  35191. ]
  35192. } );
  35193. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35194. const z = float( z_immutable ).toVar();
  35195. const y = float( y_immutable ).toVar();
  35196. const x = float( x_immutable ).toVar();
  35197. const hash = uint( hash_immutable ).toVar();
  35198. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  35199. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  35200. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  35201. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35202. } ).setLayout( {
  35203. name: 'mx_gradient_float_1',
  35204. type: 'float',
  35205. inputs: [
  35206. { name: 'hash', type: 'uint' },
  35207. { name: 'x', type: 'float' },
  35208. { name: 'y', type: 'float' },
  35209. { name: 'z', type: 'float' }
  35210. ]
  35211. } );
  35212. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  35213. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35214. const y = float( y_immutable ).toVar();
  35215. const x = float( x_immutable ).toVar();
  35216. const hash = uvec3( hash_immutable ).toVar();
  35217. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  35218. } ).setLayout( {
  35219. name: 'mx_gradient_vec3_0',
  35220. type: 'vec3',
  35221. inputs: [
  35222. { name: 'hash', type: 'uvec3' },
  35223. { name: 'x', type: 'float' },
  35224. { name: 'y', type: 'float' }
  35225. ]
  35226. } );
  35227. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35228. const z = float( z_immutable ).toVar();
  35229. const y = float( y_immutable ).toVar();
  35230. const x = float( x_immutable ).toVar();
  35231. const hash = uvec3( hash_immutable ).toVar();
  35232. 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 ) );
  35233. } ).setLayout( {
  35234. name: 'mx_gradient_vec3_1',
  35235. type: 'vec3',
  35236. inputs: [
  35237. { name: 'hash', type: 'uvec3' },
  35238. { name: 'x', type: 'float' },
  35239. { name: 'y', type: 'float' },
  35240. { name: 'z', type: 'float' }
  35241. ]
  35242. } );
  35243. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  35244. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35245. const v = float( v_immutable ).toVar();
  35246. return mul( 0.6616, v );
  35247. } ).setLayout( {
  35248. name: 'mx_gradient_scale2d_0',
  35249. type: 'float',
  35250. inputs: [
  35251. { name: 'v', type: 'float' }
  35252. ]
  35253. } );
  35254. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35255. const v = float( v_immutable ).toVar();
  35256. return mul( 0.9820, v );
  35257. } ).setLayout( {
  35258. name: 'mx_gradient_scale3d_0',
  35259. type: 'float',
  35260. inputs: [
  35261. { name: 'v', type: 'float' }
  35262. ]
  35263. } );
  35264. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35265. const v = vec3( v_immutable ).toVar();
  35266. return mul( 0.6616, v );
  35267. } ).setLayout( {
  35268. name: 'mx_gradient_scale2d_1',
  35269. type: 'vec3',
  35270. inputs: [
  35271. { name: 'v', type: 'vec3' }
  35272. ]
  35273. } );
  35274. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  35275. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35276. const v = vec3( v_immutable ).toVar();
  35277. return mul( 0.9820, v );
  35278. } ).setLayout( {
  35279. name: 'mx_gradient_scale3d_1',
  35280. type: 'vec3',
  35281. inputs: [
  35282. { name: 'v', type: 'vec3' }
  35283. ]
  35284. } );
  35285. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  35286. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  35287. const k = int( k_immutable ).toVar();
  35288. const x = uint( x_immutable ).toVar();
  35289. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  35290. } ).setLayout( {
  35291. name: 'mx_rotl32',
  35292. type: 'uint',
  35293. inputs: [
  35294. { name: 'x', type: 'uint' },
  35295. { name: 'k', type: 'int' }
  35296. ]
  35297. } );
  35298. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  35299. a.subAssign( c );
  35300. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  35301. c.addAssign( b );
  35302. b.subAssign( a );
  35303. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  35304. a.addAssign( c );
  35305. c.subAssign( b );
  35306. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  35307. b.addAssign( a );
  35308. a.subAssign( c );
  35309. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  35310. c.addAssign( b );
  35311. b.subAssign( a );
  35312. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  35313. a.addAssign( c );
  35314. c.subAssign( b );
  35315. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  35316. b.addAssign( a );
  35317. } );
  35318. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  35319. const c = uint( c_immutable ).toVar();
  35320. const b = uint( b_immutable ).toVar();
  35321. const a = uint( a_immutable ).toVar();
  35322. c.bitXorAssign( b );
  35323. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  35324. a.bitXorAssign( c );
  35325. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  35326. b.bitXorAssign( a );
  35327. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  35328. c.bitXorAssign( b );
  35329. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  35330. a.bitXorAssign( c );
  35331. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  35332. b.bitXorAssign( a );
  35333. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  35334. c.bitXorAssign( b );
  35335. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  35336. return c;
  35337. } ).setLayout( {
  35338. name: 'mx_bjfinal',
  35339. type: 'uint',
  35340. inputs: [
  35341. { name: 'a', type: 'uint' },
  35342. { name: 'b', type: 'uint' },
  35343. { name: 'c', type: 'uint' }
  35344. ]
  35345. } );
  35346. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  35347. const bits = uint( bits_immutable ).toVar();
  35348. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  35349. } ).setLayout( {
  35350. name: 'mx_bits_to_01',
  35351. type: 'float',
  35352. inputs: [
  35353. { name: 'bits', type: 'uint' }
  35354. ]
  35355. } );
  35356. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  35357. const t = float( t_immutable ).toVar();
  35358. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  35359. } ).setLayout( {
  35360. name: 'mx_fade',
  35361. type: 'float',
  35362. inputs: [
  35363. { name: 't', type: 'float' }
  35364. ]
  35365. } );
  35366. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  35367. const x = int( x_immutable ).toVar();
  35368. const len = uint( uint( 1 ) ).toVar();
  35369. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  35370. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  35371. } ).setLayout( {
  35372. name: 'mx_hash_int_0',
  35373. type: 'uint',
  35374. inputs: [
  35375. { name: 'x', type: 'int' }
  35376. ]
  35377. } );
  35378. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35379. const y = int( y_immutable ).toVar();
  35380. const x = int( x_immutable ).toVar();
  35381. const len = uint( uint( 2 ) ).toVar();
  35382. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35383. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35384. a.addAssign( uint( x ) );
  35385. b.addAssign( uint( y ) );
  35386. return mx_bjfinal( a, b, c );
  35387. } ).setLayout( {
  35388. name: 'mx_hash_int_1',
  35389. type: 'uint',
  35390. inputs: [
  35391. { name: 'x', type: 'int' },
  35392. { name: 'y', type: 'int' }
  35393. ]
  35394. } );
  35395. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35396. const z = int( z_immutable ).toVar();
  35397. const y = int( y_immutable ).toVar();
  35398. const x = int( x_immutable ).toVar();
  35399. const len = uint( uint( 3 ) ).toVar();
  35400. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35401. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35402. a.addAssign( uint( x ) );
  35403. b.addAssign( uint( y ) );
  35404. c.addAssign( uint( z ) );
  35405. return mx_bjfinal( a, b, c );
  35406. } ).setLayout( {
  35407. name: 'mx_hash_int_2',
  35408. type: 'uint',
  35409. inputs: [
  35410. { name: 'x', type: 'int' },
  35411. { name: 'y', type: 'int' },
  35412. { name: 'z', type: 'int' }
  35413. ]
  35414. } );
  35415. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  35416. const xx = int( xx_immutable ).toVar();
  35417. const z = int( z_immutable ).toVar();
  35418. const y = int( y_immutable ).toVar();
  35419. const x = int( x_immutable ).toVar();
  35420. const len = uint( uint( 4 ) ).toVar();
  35421. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35422. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35423. a.addAssign( uint( x ) );
  35424. b.addAssign( uint( y ) );
  35425. c.addAssign( uint( z ) );
  35426. mx_bjmix( a, b, c );
  35427. a.addAssign( uint( xx ) );
  35428. return mx_bjfinal( a, b, c );
  35429. } ).setLayout( {
  35430. name: 'mx_hash_int_3',
  35431. type: 'uint',
  35432. inputs: [
  35433. { name: 'x', type: 'int' },
  35434. { name: 'y', type: 'int' },
  35435. { name: 'z', type: 'int' },
  35436. { name: 'xx', type: 'int' }
  35437. ]
  35438. } );
  35439. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  35440. const yy = int( yy_immutable ).toVar();
  35441. const xx = int( xx_immutable ).toVar();
  35442. const z = int( z_immutable ).toVar();
  35443. const y = int( y_immutable ).toVar();
  35444. const x = int( x_immutable ).toVar();
  35445. const len = uint( uint( 5 ) ).toVar();
  35446. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35447. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35448. a.addAssign( uint( x ) );
  35449. b.addAssign( uint( y ) );
  35450. c.addAssign( uint( z ) );
  35451. mx_bjmix( a, b, c );
  35452. a.addAssign( uint( xx ) );
  35453. b.addAssign( uint( yy ) );
  35454. return mx_bjfinal( a, b, c );
  35455. } ).setLayout( {
  35456. name: 'mx_hash_int_4',
  35457. type: 'uint',
  35458. inputs: [
  35459. { name: 'x', type: 'int' },
  35460. { name: 'y', type: 'int' },
  35461. { name: 'z', type: 'int' },
  35462. { name: 'xx', type: 'int' },
  35463. { name: 'yy', type: 'int' }
  35464. ]
  35465. } );
  35466. 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 ] );
  35467. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35468. const y = int( y_immutable ).toVar();
  35469. const x = int( x_immutable ).toVar();
  35470. const h = uint( mx_hash_int( x, y ) ).toVar();
  35471. const result = uvec3().toVar();
  35472. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35473. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35474. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35475. return result;
  35476. } ).setLayout( {
  35477. name: 'mx_hash_vec3_0',
  35478. type: 'uvec3',
  35479. inputs: [
  35480. { name: 'x', type: 'int' },
  35481. { name: 'y', type: 'int' }
  35482. ]
  35483. } );
  35484. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35485. const z = int( z_immutable ).toVar();
  35486. const y = int( y_immutable ).toVar();
  35487. const x = int( x_immutable ).toVar();
  35488. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  35489. const result = uvec3().toVar();
  35490. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35491. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35492. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35493. return result;
  35494. } ).setLayout( {
  35495. name: 'mx_hash_vec3_1',
  35496. type: 'uvec3',
  35497. inputs: [
  35498. { name: 'x', type: 'int' },
  35499. { name: 'y', type: 'int' },
  35500. { name: 'z', type: 'int' }
  35501. ]
  35502. } );
  35503. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  35504. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35505. const p = vec2( p_immutable ).toVar();
  35506. const X = int().toVar(), Y = int().toVar();
  35507. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35508. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35509. const u = float( mx_fade( fx ) ).toVar();
  35510. const v = float( mx_fade( fy ) ).toVar();
  35511. 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();
  35512. return mx_gradient_scale2d( result );
  35513. } ).setLayout( {
  35514. name: 'mx_perlin_noise_float_0',
  35515. type: 'float',
  35516. inputs: [
  35517. { name: 'p', type: 'vec2' }
  35518. ]
  35519. } );
  35520. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35521. const p = vec3( p_immutable ).toVar();
  35522. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35523. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35524. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35525. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35526. const u = float( mx_fade( fx ) ).toVar();
  35527. const v = float( mx_fade( fy ) ).toVar();
  35528. const w = float( mx_fade( fz ) ).toVar();
  35529. 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();
  35530. return mx_gradient_scale3d( result );
  35531. } ).setLayout( {
  35532. name: 'mx_perlin_noise_float_1',
  35533. type: 'float',
  35534. inputs: [
  35535. { name: 'p', type: 'vec3' }
  35536. ]
  35537. } );
  35538. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  35539. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35540. const p = vec2( p_immutable ).toVar();
  35541. const X = int().toVar(), Y = int().toVar();
  35542. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35543. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35544. const u = float( mx_fade( fx ) ).toVar();
  35545. const v = float( mx_fade( fy ) ).toVar();
  35546. 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();
  35547. return mx_gradient_scale2d( result );
  35548. } ).setLayout( {
  35549. name: 'mx_perlin_noise_vec3_0',
  35550. type: 'vec3',
  35551. inputs: [
  35552. { name: 'p', type: 'vec2' }
  35553. ]
  35554. } );
  35555. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35556. const p = vec3( p_immutable ).toVar();
  35557. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35558. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35559. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35560. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35561. const u = float( mx_fade( fx ) ).toVar();
  35562. const v = float( mx_fade( fy ) ).toVar();
  35563. const w = float( mx_fade( fz ) ).toVar();
  35564. 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();
  35565. return mx_gradient_scale3d( result );
  35566. } ).setLayout( {
  35567. name: 'mx_perlin_noise_vec3_1',
  35568. type: 'vec3',
  35569. inputs: [
  35570. { name: 'p', type: 'vec3' }
  35571. ]
  35572. } );
  35573. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  35574. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35575. const p = float( p_immutable ).toVar();
  35576. const ix = int( mx_floor( p ) ).toVar();
  35577. return mx_bits_to_01( mx_hash_int( ix ) );
  35578. } ).setLayout( {
  35579. name: 'mx_cell_noise_float_0',
  35580. type: 'float',
  35581. inputs: [
  35582. { name: 'p', type: 'float' }
  35583. ]
  35584. } );
  35585. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35586. const p = vec2( p_immutable ).toVar();
  35587. const ix = int( mx_floor( p.x ) ).toVar();
  35588. const iy = int( mx_floor( p.y ) ).toVar();
  35589. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  35590. } ).setLayout( {
  35591. name: 'mx_cell_noise_float_1',
  35592. type: 'float',
  35593. inputs: [
  35594. { name: 'p', type: 'vec2' }
  35595. ]
  35596. } );
  35597. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35598. const p = vec3( p_immutable ).toVar();
  35599. const ix = int( mx_floor( p.x ) ).toVar();
  35600. const iy = int( mx_floor( p.y ) ).toVar();
  35601. const iz = int( mx_floor( p.z ) ).toVar();
  35602. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  35603. } ).setLayout( {
  35604. name: 'mx_cell_noise_float_2',
  35605. type: 'float',
  35606. inputs: [
  35607. { name: 'p', type: 'vec3' }
  35608. ]
  35609. } );
  35610. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35611. const p = vec4( p_immutable ).toVar();
  35612. const ix = int( mx_floor( p.x ) ).toVar();
  35613. const iy = int( mx_floor( p.y ) ).toVar();
  35614. const iz = int( mx_floor( p.z ) ).toVar();
  35615. const iw = int( mx_floor( p.w ) ).toVar();
  35616. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  35617. } ).setLayout( {
  35618. name: 'mx_cell_noise_float_3',
  35619. type: 'float',
  35620. inputs: [
  35621. { name: 'p', type: 'vec4' }
  35622. ]
  35623. } );
  35624. 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 ] );
  35625. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35626. const p = float( p_immutable ).toVar();
  35627. const ix = int( mx_floor( p ) ).toVar();
  35628. 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 ) ) ) );
  35629. } ).setLayout( {
  35630. name: 'mx_cell_noise_vec3_0',
  35631. type: 'vec3',
  35632. inputs: [
  35633. { name: 'p', type: 'float' }
  35634. ]
  35635. } );
  35636. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35637. const p = vec2( p_immutable ).toVar();
  35638. const ix = int( mx_floor( p.x ) ).toVar();
  35639. const iy = int( mx_floor( p.y ) ).toVar();
  35640. 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 ) ) ) );
  35641. } ).setLayout( {
  35642. name: 'mx_cell_noise_vec3_1',
  35643. type: 'vec3',
  35644. inputs: [
  35645. { name: 'p', type: 'vec2' }
  35646. ]
  35647. } );
  35648. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35649. const p = vec3( p_immutable ).toVar();
  35650. const ix = int( mx_floor( p.x ) ).toVar();
  35651. const iy = int( mx_floor( p.y ) ).toVar();
  35652. const iz = int( mx_floor( p.z ) ).toVar();
  35653. 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 ) ) ) );
  35654. } ).setLayout( {
  35655. name: 'mx_cell_noise_vec3_2',
  35656. type: 'vec3',
  35657. inputs: [
  35658. { name: 'p', type: 'vec3' }
  35659. ]
  35660. } );
  35661. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35662. const p = vec4( p_immutable ).toVar();
  35663. const ix = int( mx_floor( p.x ) ).toVar();
  35664. const iy = int( mx_floor( p.y ) ).toVar();
  35665. const iz = int( mx_floor( p.z ) ).toVar();
  35666. const iw = int( mx_floor( p.w ) ).toVar();
  35667. 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 ) ) ) );
  35668. } ).setLayout( {
  35669. name: 'mx_cell_noise_vec3_3',
  35670. type: 'vec3',
  35671. inputs: [
  35672. { name: 'p', type: 'vec4' }
  35673. ]
  35674. } );
  35675. 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 ] );
  35676. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35677. const diminish = float( diminish_immutable ).toVar();
  35678. const lacunarity = float( lacunarity_immutable ).toVar();
  35679. const octaves = int( octaves_immutable ).toVar();
  35680. const p = vec3( p_immutable ).toVar();
  35681. const result = float( 0.0 ).toVar();
  35682. const amplitude = float( 1.0 ).toVar();
  35683. loop( octaves, () => {
  35684. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  35685. amplitude.mulAssign( diminish );
  35686. p.mulAssign( lacunarity );
  35687. } );
  35688. return result;
  35689. } ).setLayout( {
  35690. name: 'mx_fractal_noise_float',
  35691. type: 'float',
  35692. inputs: [
  35693. { name: 'p', type: 'vec3' },
  35694. { name: 'octaves', type: 'int' },
  35695. { name: 'lacunarity', type: 'float' },
  35696. { name: 'diminish', type: 'float' }
  35697. ]
  35698. } );
  35699. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35700. const diminish = float( diminish_immutable ).toVar();
  35701. const lacunarity = float( lacunarity_immutable ).toVar();
  35702. const octaves = int( octaves_immutable ).toVar();
  35703. const p = vec3( p_immutable ).toVar();
  35704. const result = vec3( 0.0 ).toVar();
  35705. const amplitude = float( 1.0 ).toVar();
  35706. loop( octaves, () => {
  35707. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  35708. amplitude.mulAssign( diminish );
  35709. p.mulAssign( lacunarity );
  35710. } );
  35711. return result;
  35712. } ).setLayout( {
  35713. name: 'mx_fractal_noise_vec3',
  35714. type: 'vec3',
  35715. inputs: [
  35716. { name: 'p', type: 'vec3' },
  35717. { name: 'octaves', type: 'int' },
  35718. { name: 'lacunarity', type: 'float' },
  35719. { name: 'diminish', type: 'float' }
  35720. ]
  35721. } );
  35722. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35723. const diminish = float( diminish_immutable ).toVar();
  35724. const lacunarity = float( lacunarity_immutable ).toVar();
  35725. const octaves = int( octaves_immutable ).toVar();
  35726. const p = vec3( p_immutable ).toVar();
  35727. 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 ) );
  35728. } ).setLayout( {
  35729. name: 'mx_fractal_noise_vec2',
  35730. type: 'vec2',
  35731. inputs: [
  35732. { name: 'p', type: 'vec3' },
  35733. { name: 'octaves', type: 'int' },
  35734. { name: 'lacunarity', type: 'float' },
  35735. { name: 'diminish', type: 'float' }
  35736. ]
  35737. } );
  35738. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35739. const diminish = float( diminish_immutable ).toVar();
  35740. const lacunarity = float( lacunarity_immutable ).toVar();
  35741. const octaves = int( octaves_immutable ).toVar();
  35742. const p = vec3( p_immutable ).toVar();
  35743. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  35744. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  35745. return vec4( c, f );
  35746. } ).setLayout( {
  35747. name: 'mx_fractal_noise_vec4',
  35748. type: 'vec4',
  35749. inputs: [
  35750. { name: 'p', type: 'vec3' },
  35751. { name: 'octaves', type: 'int' },
  35752. { name: 'lacunarity', type: 'float' },
  35753. { name: 'diminish', type: 'float' }
  35754. ]
  35755. } );
  35756. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35757. const metric = int( metric_immutable ).toVar();
  35758. const jitter = float( jitter_immutable ).toVar();
  35759. const yoff = int( yoff_immutable ).toVar();
  35760. const xoff = int( xoff_immutable ).toVar();
  35761. const y = int( y_immutable ).toVar();
  35762. const x = int( x_immutable ).toVar();
  35763. const p = vec2( p_immutable ).toVar();
  35764. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  35765. const off = vec2( tmp.x, tmp.y ).toVar();
  35766. off.subAssign( 0.5 );
  35767. off.mulAssign( jitter );
  35768. off.addAssign( 0.5 );
  35769. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  35770. const diff = vec2( cellpos.sub( p ) ).toVar();
  35771. If( metric.equal( int( 2 ) ), () => {
  35772. return abs( diff.x ).add( abs( diff.y ) );
  35773. } );
  35774. If( metric.equal( int( 3 ) ), () => {
  35775. return max$1( abs( diff.x ), abs( diff.y ) );
  35776. } );
  35777. return dot( diff, diff );
  35778. } ).setLayout( {
  35779. name: 'mx_worley_distance_0',
  35780. type: 'float',
  35781. inputs: [
  35782. { name: 'p', type: 'vec2' },
  35783. { name: 'x', type: 'int' },
  35784. { name: 'y', type: 'int' },
  35785. { name: 'xoff', type: 'int' },
  35786. { name: 'yoff', type: 'int' },
  35787. { name: 'jitter', type: 'float' },
  35788. { name: 'metric', type: 'int' }
  35789. ]
  35790. } );
  35791. const mx_worley_distance_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35792. const metric = int( metric_immutable ).toVar();
  35793. const jitter = float( jitter_immutable ).toVar();
  35794. const zoff = int( zoff_immutable ).toVar();
  35795. const yoff = int( yoff_immutable ).toVar();
  35796. const xoff = int( xoff_immutable ).toVar();
  35797. const z = int( z_immutable ).toVar();
  35798. const y = int( y_immutable ).toVar();
  35799. const x = int( x_immutable ).toVar();
  35800. const p = vec3( p_immutable ).toVar();
  35801. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  35802. off.subAssign( 0.5 );
  35803. off.mulAssign( jitter );
  35804. off.addAssign( 0.5 );
  35805. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  35806. const diff = vec3( cellpos.sub( p ) ).toVar();
  35807. If( metric.equal( int( 2 ) ), () => {
  35808. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  35809. } );
  35810. If( metric.equal( int( 3 ) ), () => {
  35811. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  35812. } );
  35813. return dot( diff, diff );
  35814. } ).setLayout( {
  35815. name: 'mx_worley_distance_1',
  35816. type: 'float',
  35817. inputs: [
  35818. { name: 'p', type: 'vec3' },
  35819. { name: 'x', type: 'int' },
  35820. { name: 'y', type: 'int' },
  35821. { name: 'z', type: 'int' },
  35822. { name: 'xoff', type: 'int' },
  35823. { name: 'yoff', type: 'int' },
  35824. { name: 'zoff', type: 'int' },
  35825. { name: 'jitter', type: 'float' },
  35826. { name: 'metric', type: 'int' }
  35827. ]
  35828. } );
  35829. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  35830. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35831. const metric = int( metric_immutable ).toVar();
  35832. const jitter = float( jitter_immutable ).toVar();
  35833. const p = vec2( p_immutable ).toVar();
  35834. const X = int().toVar(), Y = int().toVar();
  35835. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35836. const sqdist = float( 1e6 ).toVar();
  35837. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35838. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35839. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35840. sqdist.assign( min$1( sqdist, dist ) );
  35841. } );
  35842. } );
  35843. If( metric.equal( int( 0 ) ), () => {
  35844. sqdist.assign( sqrt( sqdist ) );
  35845. } );
  35846. return sqdist;
  35847. } ).setLayout( {
  35848. name: 'mx_worley_noise_float_0',
  35849. type: 'float',
  35850. inputs: [
  35851. { name: 'p', type: 'vec2' },
  35852. { name: 'jitter', type: 'float' },
  35853. { name: 'metric', type: 'int' }
  35854. ]
  35855. } );
  35856. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35857. const metric = int( metric_immutable ).toVar();
  35858. const jitter = float( jitter_immutable ).toVar();
  35859. const p = vec2( p_immutable ).toVar();
  35860. const X = int().toVar(), Y = int().toVar();
  35861. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35862. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35863. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35864. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35865. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35866. If( dist.lessThan( sqdist.x ), () => {
  35867. sqdist.y.assign( sqdist.x );
  35868. sqdist.x.assign( dist );
  35869. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35870. sqdist.y.assign( dist );
  35871. } );
  35872. } );
  35873. } );
  35874. If( metric.equal( int( 0 ) ), () => {
  35875. sqdist.assign( sqrt( sqdist ) );
  35876. } );
  35877. return sqdist;
  35878. } ).setLayout( {
  35879. name: 'mx_worley_noise_vec2_0',
  35880. type: 'vec2',
  35881. inputs: [
  35882. { name: 'p', type: 'vec2' },
  35883. { name: 'jitter', type: 'float' },
  35884. { name: 'metric', type: 'int' }
  35885. ]
  35886. } );
  35887. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35888. const metric = int( metric_immutable ).toVar();
  35889. const jitter = float( jitter_immutable ).toVar();
  35890. const p = vec2( p_immutable ).toVar();
  35891. const X = int().toVar(), Y = int().toVar();
  35892. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35893. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35894. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35895. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35896. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35897. If( dist.lessThan( sqdist.x ), () => {
  35898. sqdist.z.assign( sqdist.y );
  35899. sqdist.y.assign( sqdist.x );
  35900. sqdist.x.assign( dist );
  35901. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35902. sqdist.z.assign( sqdist.y );
  35903. sqdist.y.assign( dist );
  35904. } ).elseif( dist.lessThan( sqdist.z ), () => {
  35905. sqdist.z.assign( dist );
  35906. } );
  35907. } );
  35908. } );
  35909. If( metric.equal( int( 0 ) ), () => {
  35910. sqdist.assign( sqrt( sqdist ) );
  35911. } );
  35912. return sqdist;
  35913. } ).setLayout( {
  35914. name: 'mx_worley_noise_vec3_0',
  35915. type: 'vec3',
  35916. inputs: [
  35917. { name: 'p', type: 'vec2' },
  35918. { name: 'jitter', type: 'float' },
  35919. { name: 'metric', type: 'int' }
  35920. ]
  35921. } );
  35922. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35923. const metric = int( metric_immutable ).toVar();
  35924. const jitter = float( jitter_immutable ).toVar();
  35925. const p = vec3( p_immutable ).toVar();
  35926. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35927. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35928. const sqdist = float( 1e6 ).toVar();
  35929. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35930. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35931. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35932. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35933. sqdist.assign( min$1( sqdist, dist ) );
  35934. } );
  35935. } );
  35936. } );
  35937. If( metric.equal( int( 0 ) ), () => {
  35938. sqdist.assign( sqrt( sqdist ) );
  35939. } );
  35940. return sqdist;
  35941. } ).setLayout( {
  35942. name: 'mx_worley_noise_float_1',
  35943. type: 'float',
  35944. inputs: [
  35945. { name: 'p', type: 'vec3' },
  35946. { name: 'jitter', type: 'float' },
  35947. { name: 'metric', type: 'int' }
  35948. ]
  35949. } );
  35950. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  35951. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35952. const metric = int( metric_immutable ).toVar();
  35953. const jitter = float( jitter_immutable ).toVar();
  35954. const p = vec3( p_immutable ).toVar();
  35955. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35956. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35957. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35958. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35959. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35960. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35961. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35962. If( dist.lessThan( sqdist.x ), () => {
  35963. sqdist.y.assign( sqdist.x );
  35964. sqdist.x.assign( dist );
  35965. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35966. sqdist.y.assign( dist );
  35967. } );
  35968. } );
  35969. } );
  35970. } );
  35971. If( metric.equal( int( 0 ) ), () => {
  35972. sqdist.assign( sqrt( sqdist ) );
  35973. } );
  35974. return sqdist;
  35975. } ).setLayout( {
  35976. name: 'mx_worley_noise_vec2_1',
  35977. type: 'vec2',
  35978. inputs: [
  35979. { name: 'p', type: 'vec3' },
  35980. { name: 'jitter', type: 'float' },
  35981. { name: 'metric', type: 'int' }
  35982. ]
  35983. } );
  35984. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  35985. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35986. const metric = int( metric_immutable ).toVar();
  35987. const jitter = float( jitter_immutable ).toVar();
  35988. const p = vec3( p_immutable ).toVar();
  35989. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35990. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35991. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35992. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35993. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35994. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35995. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35996. If( dist.lessThan( sqdist.x ), () => {
  35997. sqdist.z.assign( sqdist.y );
  35998. sqdist.y.assign( sqdist.x );
  35999. sqdist.x.assign( dist );
  36000. } ).elseif( dist.lessThan( sqdist.y ), () => {
  36001. sqdist.z.assign( sqdist.y );
  36002. sqdist.y.assign( dist );
  36003. } ).elseif( dist.lessThan( sqdist.z ), () => {
  36004. sqdist.z.assign( dist );
  36005. } );
  36006. } );
  36007. } );
  36008. } );
  36009. If( metric.equal( int( 0 ) ), () => {
  36010. sqdist.assign( sqrt( sqdist ) );
  36011. } );
  36012. return sqdist;
  36013. } ).setLayout( {
  36014. name: 'mx_worley_noise_vec3_1',
  36015. type: 'vec3',
  36016. inputs: [
  36017. { name: 'p', type: 'vec3' },
  36018. { name: 'jitter', type: 'float' },
  36019. { name: 'metric', type: 'int' }
  36020. ]
  36021. } );
  36022. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  36023. // Three.js Transpiler
  36024. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  36025. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  36026. const hsv = vec3( hsv_immutable ).toVar();
  36027. const h = float( hsv.x ).toVar();
  36028. const s = float( hsv.y ).toVar();
  36029. const v = float( hsv.z ).toVar();
  36030. If( s.lessThan( 0.0001 ), () => {
  36031. return vec3( v, v, v );
  36032. } ).else( () => {
  36033. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  36034. const hi = int( trunc( h ) ).toVar();
  36035. const f = float( h.sub( float( hi ) ) ).toVar();
  36036. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  36037. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  36038. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  36039. If( hi.equal( int( 0 ) ), () => {
  36040. return vec3( v, t, p );
  36041. } ).elseif( hi.equal( int( 1 ) ), () => {
  36042. return vec3( q, v, p );
  36043. } ).elseif( hi.equal( int( 2 ) ), () => {
  36044. return vec3( p, v, t );
  36045. } ).elseif( hi.equal( int( 3 ) ), () => {
  36046. return vec3( p, q, v );
  36047. } ).elseif( hi.equal( int( 4 ) ), () => {
  36048. return vec3( t, p, v );
  36049. } );
  36050. return vec3( v, p, q );
  36051. } );
  36052. } ).setLayout( {
  36053. name: 'mx_hsvtorgb',
  36054. type: 'vec3',
  36055. inputs: [
  36056. { name: 'hsv', type: 'vec3' }
  36057. ]
  36058. } );
  36059. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  36060. const c = vec3( c_immutable ).toVar();
  36061. const r = float( c.x ).toVar();
  36062. const g = float( c.y ).toVar();
  36063. const b = float( c.z ).toVar();
  36064. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  36065. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  36066. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  36067. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  36068. v.assign( maxcomp );
  36069. If( maxcomp.greaterThan( 0.0 ), () => {
  36070. s.assign( delta.div( maxcomp ) );
  36071. } ).else( () => {
  36072. s.assign( 0.0 );
  36073. } );
  36074. If( s.lessThanEqual( 0.0 ), () => {
  36075. h.assign( 0.0 );
  36076. } ).else( () => {
  36077. If( r.greaterThanEqual( maxcomp ), () => {
  36078. h.assign( g.sub( b ).div( delta ) );
  36079. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  36080. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  36081. } ).else( () => {
  36082. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  36083. } );
  36084. h.mulAssign( 1.0 / 6.0 );
  36085. If( h.lessThan( 0.0 ), () => {
  36086. h.addAssign( 1.0 );
  36087. } );
  36088. } );
  36089. return vec3( h, s, v );
  36090. } ).setLayout( {
  36091. name: 'mx_rgbtohsv',
  36092. type: 'vec3',
  36093. inputs: [
  36094. { name: 'c', type: 'vec3' }
  36095. ]
  36096. } );
  36097. // Three.js Transpiler
  36098. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  36099. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  36100. const color = vec3( color_immutable ).toVar();
  36101. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  36102. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  36103. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  36104. return mix( linSeg, powSeg, isAbove );
  36105. } ).setLayout( {
  36106. name: 'mx_srgb_texture_to_lin_rec709',
  36107. type: 'vec3',
  36108. inputs: [
  36109. { name: 'color', type: 'vec3' }
  36110. ]
  36111. } );
  36112. const mx_aastep = ( threshold, value ) => {
  36113. threshold = float( threshold );
  36114. value = float( value );
  36115. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  36116. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  36117. };
  36118. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  36119. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  36120. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  36121. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  36122. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  36123. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  36124. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  36125. const mx_safepower = ( in1, in2 = 1 ) => {
  36126. in1 = float( in1 );
  36127. return in1.abs().pow( in2 ).mul( in1.sign() );
  36128. };
  36129. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  36130. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36131. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36132. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36133. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  36134. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  36135. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  36136. return noise_vec4.mul( amplitude ).add( pivot );
  36137. };
  36138. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36139. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36140. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36141. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  36142. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36143. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36144. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36145. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36146. function painterSortStable( a, b ) {
  36147. if ( a.groupOrder !== b.groupOrder ) {
  36148. return a.groupOrder - b.groupOrder;
  36149. } else if ( a.renderOrder !== b.renderOrder ) {
  36150. return a.renderOrder - b.renderOrder;
  36151. } else if ( a.material.id !== b.material.id ) {
  36152. return a.material.id - b.material.id;
  36153. } else if ( a.z !== b.z ) {
  36154. return a.z - b.z;
  36155. } else {
  36156. return a.id - b.id;
  36157. }
  36158. }
  36159. function reversePainterSortStable( a, b ) {
  36160. if ( a.groupOrder !== b.groupOrder ) {
  36161. return a.groupOrder - b.groupOrder;
  36162. } else if ( a.renderOrder !== b.renderOrder ) {
  36163. return a.renderOrder - b.renderOrder;
  36164. } else if ( a.z !== b.z ) {
  36165. return b.z - a.z;
  36166. } else {
  36167. return a.id - b.id;
  36168. }
  36169. }
  36170. class RenderList {
  36171. constructor() {
  36172. this.renderItems = [];
  36173. this.renderItemsIndex = 0;
  36174. this.opaque = [];
  36175. this.transparent = [];
  36176. this.bundles = [];
  36177. this.lightsNode = new LightsNode( [] );
  36178. this.lightsArray = [];
  36179. this.occlusionQueryCount = 0;
  36180. }
  36181. begin() {
  36182. this.renderItemsIndex = 0;
  36183. this.opaque.length = 0;
  36184. this.transparent.length = 0;
  36185. this.bundles.length = 0;
  36186. this.lightsArray.length = 0;
  36187. this.occlusionQueryCount = 0;
  36188. return this;
  36189. }
  36190. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  36191. let renderItem = this.renderItems[ this.renderItemsIndex ];
  36192. if ( renderItem === undefined ) {
  36193. renderItem = {
  36194. id: object.id,
  36195. object: object,
  36196. geometry: geometry,
  36197. material: material,
  36198. groupOrder: groupOrder,
  36199. renderOrder: object.renderOrder,
  36200. z: z,
  36201. group: group
  36202. };
  36203. this.renderItems[ this.renderItemsIndex ] = renderItem;
  36204. } else {
  36205. renderItem.id = object.id;
  36206. renderItem.object = object;
  36207. renderItem.geometry = geometry;
  36208. renderItem.material = material;
  36209. renderItem.groupOrder = groupOrder;
  36210. renderItem.renderOrder = object.renderOrder;
  36211. renderItem.z = z;
  36212. renderItem.group = group;
  36213. }
  36214. this.renderItemsIndex ++;
  36215. return renderItem;
  36216. }
  36217. push( object, geometry, material, groupOrder, z, group ) {
  36218. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36219. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  36220. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  36221. }
  36222. unshift( object, geometry, material, groupOrder, z, group ) {
  36223. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36224. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  36225. }
  36226. pushBundle( group ) {
  36227. this.bundles.push( group );
  36228. }
  36229. pushLight( light ) {
  36230. this.lightsArray.push( light );
  36231. }
  36232. getLightsNode() {
  36233. return this.lightsNode.fromLights( this.lightsArray );
  36234. }
  36235. sort( customOpaqueSort, customTransparentSort ) {
  36236. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  36237. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  36238. }
  36239. finish() {
  36240. // update lights
  36241. this.lightsNode.fromLights( this.lightsArray );
  36242. // Clear references from inactive renderItems in the list
  36243. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  36244. const renderItem = this.renderItems[ i ];
  36245. if ( renderItem.id === null ) break;
  36246. renderItem.id = null;
  36247. renderItem.object = null;
  36248. renderItem.geometry = null;
  36249. renderItem.material = null;
  36250. renderItem.groupOrder = null;
  36251. renderItem.renderOrder = null;
  36252. renderItem.z = null;
  36253. renderItem.group = null;
  36254. }
  36255. }
  36256. }
  36257. class RenderLists {
  36258. constructor() {
  36259. this.lists = new ChainMap();
  36260. }
  36261. get( scene, camera ) {
  36262. const lists = this.lists;
  36263. const keys = [ scene, camera ];
  36264. let list = lists.get( keys );
  36265. if ( list === undefined ) {
  36266. list = new RenderList();
  36267. lists.set( keys, list );
  36268. }
  36269. return list;
  36270. }
  36271. dispose() {
  36272. this.lists = new ChainMap();
  36273. }
  36274. }
  36275. let id = 0;
  36276. class RenderContext {
  36277. constructor() {
  36278. this.id = id ++;
  36279. this.color = true;
  36280. this.clearColor = true;
  36281. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  36282. this.depth = true;
  36283. this.clearDepth = true;
  36284. this.clearDepthValue = 1;
  36285. this.stencil = false;
  36286. this.clearStencil = true;
  36287. this.clearStencilValue = 1;
  36288. this.viewport = false;
  36289. this.viewportValue = new Vector4();
  36290. this.scissor = false;
  36291. this.scissorValue = new Vector4();
  36292. this.textures = null;
  36293. this.depthTexture = null;
  36294. this.activeCubeFace = 0;
  36295. this.sampleCount = 1;
  36296. this.width = 0;
  36297. this.height = 0;
  36298. this.isRenderContext = true;
  36299. }
  36300. }
  36301. class RenderContexts {
  36302. constructor() {
  36303. this.chainMaps = {};
  36304. }
  36305. get( scene, camera, renderTarget = null ) {
  36306. const chainKey = [ scene, camera ];
  36307. let attachmentState;
  36308. if ( renderTarget === null ) {
  36309. attachmentState = 'default';
  36310. } else {
  36311. const format = renderTarget.texture.format;
  36312. const count = renderTarget.textures.length;
  36313. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  36314. }
  36315. const chainMap = this.getChainMap( attachmentState );
  36316. let renderState = chainMap.get( chainKey );
  36317. if ( renderState === undefined ) {
  36318. renderState = new RenderContext();
  36319. chainMap.set( chainKey, renderState );
  36320. }
  36321. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36322. return renderState;
  36323. }
  36324. getChainMap( attachmentState ) {
  36325. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  36326. }
  36327. dispose() {
  36328. this.chainMaps = {};
  36329. }
  36330. }
  36331. const _size = /*@__PURE__*/ new Vector3();
  36332. class Textures extends DataMap {
  36333. constructor( renderer, backend, info ) {
  36334. super();
  36335. this.renderer = renderer;
  36336. this.backend = backend;
  36337. this.info = info;
  36338. }
  36339. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  36340. const renderTargetData = this.get( renderTarget );
  36341. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36342. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  36343. const texture = renderTarget.texture;
  36344. const textures = renderTarget.textures;
  36345. const size = this.getSize( texture );
  36346. const mipWidth = size.width >> activeMipmapLevel;
  36347. const mipHeight = size.height >> activeMipmapLevel;
  36348. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  36349. let textureNeedsUpdate = false;
  36350. if ( depthTexture === undefined ) {
  36351. depthTexture = new DepthTexture();
  36352. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  36353. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  36354. depthTexture.image.width = mipWidth;
  36355. depthTexture.image.height = mipHeight;
  36356. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  36357. }
  36358. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  36359. textureNeedsUpdate = true;
  36360. depthTexture.needsUpdate = true;
  36361. depthTexture.image.width = mipWidth;
  36362. depthTexture.image.height = mipHeight;
  36363. }
  36364. renderTargetData.width = size.width;
  36365. renderTargetData.height = size.height;
  36366. renderTargetData.textures = textures;
  36367. renderTargetData.depthTexture = depthTexture;
  36368. renderTargetData.depth = renderTarget.depthBuffer;
  36369. renderTargetData.stencil = renderTarget.stencilBuffer;
  36370. renderTargetData.renderTarget = renderTarget;
  36371. if ( renderTargetData.sampleCount !== sampleCount ) {
  36372. textureNeedsUpdate = true;
  36373. depthTexture.needsUpdate = true;
  36374. renderTargetData.sampleCount = sampleCount;
  36375. }
  36376. //
  36377. const options = { sampleCount };
  36378. for ( let i = 0; i < textures.length; i ++ ) {
  36379. const texture = textures[ i ];
  36380. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  36381. this.updateTexture( texture, options );
  36382. }
  36383. this.updateTexture( depthTexture, options );
  36384. // dispose handler
  36385. if ( renderTargetData.initialized !== true ) {
  36386. renderTargetData.initialized = true;
  36387. // dispose
  36388. const onDispose = () => {
  36389. renderTarget.removeEventListener( 'dispose', onDispose );
  36390. if ( textures !== undefined ) {
  36391. for ( let i = 0; i < textures.length; i ++ ) {
  36392. this._destroyTexture( textures[ i ] );
  36393. }
  36394. } else {
  36395. this._destroyTexture( texture );
  36396. }
  36397. this._destroyTexture( depthTexture );
  36398. this.delete( renderTarget );
  36399. };
  36400. renderTarget.addEventListener( 'dispose', onDispose );
  36401. }
  36402. }
  36403. updateTexture( texture, options = {} ) {
  36404. const textureData = this.get( texture );
  36405. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  36406. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  36407. const backend = this.backend;
  36408. if ( isRenderTarget && textureData.initialized === true ) {
  36409. // it's an update
  36410. backend.destroySampler( texture );
  36411. backend.destroyTexture( texture );
  36412. }
  36413. //
  36414. if ( texture.isFramebufferTexture ) {
  36415. const renderer = this.renderer;
  36416. const renderTarget = renderer.getRenderTarget();
  36417. if ( renderTarget ) {
  36418. texture.type = renderTarget.texture.type;
  36419. } else {
  36420. texture.type = UnsignedByteType;
  36421. }
  36422. }
  36423. //
  36424. const { width, height, depth } = this.getSize( texture );
  36425. options.width = width;
  36426. options.height = height;
  36427. options.depth = depth;
  36428. options.needsMipmaps = this.needsMipmaps( texture );
  36429. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  36430. //
  36431. if ( isRenderTarget || texture.isStorageTexture === true ) {
  36432. backend.createSampler( texture );
  36433. backend.createTexture( texture, options );
  36434. } else {
  36435. const needsCreate = textureData.initialized !== true;
  36436. if ( needsCreate ) backend.createSampler( texture );
  36437. if ( texture.version > 0 ) {
  36438. const image = texture.image;
  36439. if ( image === undefined ) {
  36440. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  36441. } else if ( image.complete === false ) {
  36442. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  36443. } else {
  36444. if ( texture.images ) {
  36445. const images = [];
  36446. for ( const image of texture.images ) {
  36447. images.push( image );
  36448. }
  36449. options.images = images;
  36450. } else {
  36451. options.image = image;
  36452. }
  36453. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  36454. backend.createTexture( texture, options );
  36455. textureData.isDefaultTexture = false;
  36456. }
  36457. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  36458. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  36459. }
  36460. } else {
  36461. // async update
  36462. backend.createDefaultTexture( texture );
  36463. textureData.isDefaultTexture = true;
  36464. }
  36465. }
  36466. // dispose handler
  36467. if ( textureData.initialized !== true ) {
  36468. textureData.initialized = true;
  36469. //
  36470. this.info.memory.textures ++;
  36471. // dispose
  36472. const onDispose = () => {
  36473. texture.removeEventListener( 'dispose', onDispose );
  36474. this._destroyTexture( texture );
  36475. this.info.memory.textures --;
  36476. };
  36477. texture.addEventListener( 'dispose', onDispose );
  36478. }
  36479. //
  36480. textureData.version = texture.version;
  36481. }
  36482. getSize( texture, target = _size ) {
  36483. let image = texture.images ? texture.images[ 0 ] : texture.image;
  36484. if ( image ) {
  36485. if ( image.image !== undefined ) image = image.image;
  36486. target.width = image.width;
  36487. target.height = image.height;
  36488. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  36489. } else {
  36490. target.width = target.height = target.depth = 1;
  36491. }
  36492. return target;
  36493. }
  36494. getMipLevels( texture, width, height ) {
  36495. let mipLevelCount;
  36496. if ( texture.isCompressedTexture ) {
  36497. mipLevelCount = texture.mipmaps.length;
  36498. } else {
  36499. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  36500. }
  36501. return mipLevelCount;
  36502. }
  36503. needsMipmaps( texture ) {
  36504. if ( this.isEnvironmentTexture( texture ) ) return true;
  36505. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  36506. }
  36507. isEnvironmentTexture( texture ) {
  36508. const mapping = texture.mapping;
  36509. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  36510. }
  36511. _destroyTexture( texture ) {
  36512. this.backend.destroySampler( texture );
  36513. this.backend.destroyTexture( texture );
  36514. this.delete( texture );
  36515. }
  36516. }
  36517. class Color4 extends Color {
  36518. constructor( r, g, b, a = 1 ) {
  36519. super( r, g, b );
  36520. this.a = a;
  36521. }
  36522. set( r, g, b, a = 1 ) {
  36523. this.a = a;
  36524. return super.set( r, g, b );
  36525. }
  36526. copy( color ) {
  36527. if ( color.a !== undefined ) this.a = color.a;
  36528. return super.copy( color );
  36529. }
  36530. clone() {
  36531. return new this.constructor( this.r, this.g, this.b, this.a );
  36532. }
  36533. }
  36534. const _clearColor = /*@__PURE__*/ new Color4();
  36535. class Background extends DataMap {
  36536. constructor( renderer, nodes ) {
  36537. super();
  36538. this.renderer = renderer;
  36539. this.nodes = nodes;
  36540. }
  36541. update( scene, renderList, renderContext ) {
  36542. const renderer = this.renderer;
  36543. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  36544. let forceClear = false;
  36545. if ( background === null ) {
  36546. // no background settings, use clear color configuration from the renderer
  36547. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  36548. _clearColor.a = renderer._clearColor.a;
  36549. } else if ( background.isColor === true ) {
  36550. // background is an opaque color
  36551. background.getRGB( _clearColor, LinearSRGBColorSpace );
  36552. _clearColor.a = 1;
  36553. forceClear = true;
  36554. } else if ( background.isNode === true ) {
  36555. const sceneData = this.get( scene );
  36556. const backgroundNode = background;
  36557. _clearColor.copy( renderer._clearColor );
  36558. let backgroundMesh = sceneData.backgroundMesh;
  36559. if ( backgroundMesh === undefined ) {
  36560. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  36561. // @TODO: Add Texture2D support using node context
  36562. getUV: () => normalWorld,
  36563. getTextureLevel: () => backgroundBlurriness
  36564. } );
  36565. let viewProj = modelViewProjection();
  36566. viewProj = viewProj.setZ( viewProj.w );
  36567. const nodeMaterial = new NodeMaterial();
  36568. nodeMaterial.name = 'Background.material';
  36569. nodeMaterial.side = BackSide;
  36570. nodeMaterial.depthTest = false;
  36571. nodeMaterial.depthWrite = false;
  36572. nodeMaterial.fog = false;
  36573. nodeMaterial.lights = false;
  36574. nodeMaterial.vertexNode = viewProj;
  36575. nodeMaterial.colorNode = backgroundMeshNode;
  36576. sceneData.backgroundMeshNode = backgroundMeshNode;
  36577. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  36578. backgroundMesh.frustumCulled = false;
  36579. backgroundMesh.name = 'Background.mesh';
  36580. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  36581. this.matrixWorld.copyPosition( camera.matrixWorld );
  36582. };
  36583. }
  36584. const backgroundCacheKey = backgroundNode.getCacheKey();
  36585. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  36586. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  36587. sceneData.backgroundMeshNode.needsUpdate = true;
  36588. backgroundMesh.material.needsUpdate = true;
  36589. sceneData.backgroundCacheKey = backgroundCacheKey;
  36590. }
  36591. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  36592. } else {
  36593. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  36594. }
  36595. //
  36596. if ( renderer.autoClear === true || forceClear === true ) {
  36597. _clearColor.multiplyScalar( _clearColor.a );
  36598. const clearColorValue = renderContext.clearColorValue;
  36599. clearColorValue.r = _clearColor.r;
  36600. clearColorValue.g = _clearColor.g;
  36601. clearColorValue.b = _clearColor.b;
  36602. clearColorValue.a = _clearColor.a;
  36603. renderContext.depthClearValue = renderer._clearDepth;
  36604. renderContext.stencilClearValue = renderer._clearStencil;
  36605. renderContext.clearColor = renderer.autoClearColor === true;
  36606. renderContext.clearDepth = renderer.autoClearDepth === true;
  36607. renderContext.clearStencil = renderer.autoClearStencil === true;
  36608. } else {
  36609. renderContext.clearColor = false;
  36610. renderContext.clearDepth = false;
  36611. renderContext.clearStencil = false;
  36612. }
  36613. }
  36614. }
  36615. class NodeBuilderState {
  36616. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  36617. this.vertexShader = vertexShader;
  36618. this.fragmentShader = fragmentShader;
  36619. this.computeShader = computeShader;
  36620. this.transforms = transforms;
  36621. this.nodeAttributes = nodeAttributes;
  36622. this.bindings = bindings;
  36623. this.updateNodes = updateNodes;
  36624. this.updateBeforeNodes = updateBeforeNodes;
  36625. this.updateAfterNodes = updateAfterNodes;
  36626. this.instanceBindGroups = instanceBindGroups;
  36627. this.usedTimes = 0;
  36628. }
  36629. createBindings() {
  36630. const bindings = [];
  36631. for ( const instanceGroup of this.bindings ) {
  36632. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  36633. if ( shared !== true ) {
  36634. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index );
  36635. bindings.push( bindingsGroup );
  36636. for ( const instanceBinding of instanceGroup.bindings ) {
  36637. bindingsGroup.bindings.push( instanceBinding.clone() );
  36638. }
  36639. } else {
  36640. bindings.push( instanceGroup );
  36641. }
  36642. }
  36643. return bindings;
  36644. }
  36645. }
  36646. const outputNodeMap = new WeakMap();
  36647. class Nodes extends DataMap {
  36648. constructor( renderer, backend ) {
  36649. super();
  36650. this.renderer = renderer;
  36651. this.backend = backend;
  36652. this.nodeFrame = new NodeFrame();
  36653. this.nodeBuilderCache = new Map();
  36654. this.callHashCache = new ChainMap();
  36655. this.groupsData = new ChainMap();
  36656. }
  36657. updateGroup( nodeUniformsGroup ) {
  36658. const groupNode = nodeUniformsGroup.groupNode;
  36659. const name = groupNode.name;
  36660. // objectGroup is every updated
  36661. if ( name === objectGroup.name ) return true;
  36662. // renderGroup is updated once per render/compute call
  36663. if ( name === renderGroup.name ) {
  36664. const uniformsGroupData = this.get( nodeUniformsGroup );
  36665. const renderId = this.nodeFrame.renderId;
  36666. if ( uniformsGroupData.renderId !== renderId ) {
  36667. uniformsGroupData.renderId = renderId;
  36668. return true;
  36669. }
  36670. return false;
  36671. }
  36672. // frameGroup is updated once per frame
  36673. if ( name === frameGroup.name ) {
  36674. const uniformsGroupData = this.get( nodeUniformsGroup );
  36675. const frameId = this.nodeFrame.frameId;
  36676. if ( uniformsGroupData.frameId !== frameId ) {
  36677. uniformsGroupData.frameId = frameId;
  36678. return true;
  36679. }
  36680. return false;
  36681. }
  36682. // other groups are updated just when groupNode.needsUpdate is true
  36683. const groupChain = [ groupNode, nodeUniformsGroup ];
  36684. let groupData = this.groupsData.get( groupChain );
  36685. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36686. if ( groupData.version !== groupNode.version ) {
  36687. groupData.version = groupNode.version;
  36688. return true;
  36689. }
  36690. return false;
  36691. }
  36692. getForRenderCacheKey( renderObject ) {
  36693. return renderObject.initialCacheKey;
  36694. }
  36695. getForRender( renderObject ) {
  36696. const renderObjectData = this.get( renderObject );
  36697. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36698. if ( nodeBuilderState === undefined ) {
  36699. const { nodeBuilderCache } = this;
  36700. const cacheKey = this.getForRenderCacheKey( renderObject );
  36701. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36702. if ( nodeBuilderState === undefined ) {
  36703. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36704. nodeBuilder.scene = renderObject.scene;
  36705. nodeBuilder.material = renderObject.material;
  36706. nodeBuilder.camera = renderObject.camera;
  36707. nodeBuilder.context.material = renderObject.material;
  36708. nodeBuilder.lightsNode = renderObject.lightsNode;
  36709. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36710. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36711. nodeBuilder.clippingContext = renderObject.clippingContext;
  36712. nodeBuilder.build();
  36713. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36714. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36715. }
  36716. nodeBuilderState.usedTimes ++;
  36717. renderObjectData.nodeBuilderState = nodeBuilderState;
  36718. }
  36719. return nodeBuilderState;
  36720. }
  36721. delete( object ) {
  36722. if ( object.isRenderObject ) {
  36723. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36724. nodeBuilderState.usedTimes --;
  36725. if ( nodeBuilderState.usedTimes === 0 ) {
  36726. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36727. }
  36728. }
  36729. return super.delete( object );
  36730. }
  36731. getForCompute( computeNode ) {
  36732. const computeData = this.get( computeNode );
  36733. let nodeBuilderState = computeData.nodeBuilderState;
  36734. if ( nodeBuilderState === undefined ) {
  36735. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36736. nodeBuilder.build();
  36737. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36738. computeData.nodeBuilderState = nodeBuilderState;
  36739. }
  36740. return nodeBuilderState;
  36741. }
  36742. _createNodeBuilderState( nodeBuilder ) {
  36743. return new NodeBuilderState(
  36744. nodeBuilder.vertexShader,
  36745. nodeBuilder.fragmentShader,
  36746. nodeBuilder.computeShader,
  36747. nodeBuilder.getAttributesArray(),
  36748. nodeBuilder.getBindings(),
  36749. nodeBuilder.updateNodes,
  36750. nodeBuilder.updateBeforeNodes,
  36751. nodeBuilder.updateAfterNodes,
  36752. nodeBuilder.instanceBindGroups,
  36753. nodeBuilder.transforms
  36754. );
  36755. }
  36756. getEnvironmentNode( scene ) {
  36757. return scene.environmentNode || this.get( scene ).environmentNode || null;
  36758. }
  36759. getBackgroundNode( scene ) {
  36760. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  36761. }
  36762. getFogNode( scene ) {
  36763. return scene.fogNode || this.get( scene ).fogNode || null;
  36764. }
  36765. getCacheKey( scene, lightsNode ) {
  36766. const chain = [ scene, lightsNode ];
  36767. const callId = this.renderer.info.calls;
  36768. let cacheKeyData = this.callHashCache.get( chain );
  36769. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  36770. const environmentNode = this.getEnvironmentNode( scene );
  36771. const fogNode = this.getFogNode( scene );
  36772. const cacheKey = [];
  36773. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey( true ) );
  36774. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  36775. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  36776. cacheKeyData = {
  36777. callId,
  36778. cacheKey: cacheKey.join( ',' )
  36779. };
  36780. this.callHashCache.set( chain, cacheKeyData );
  36781. }
  36782. return cacheKeyData.cacheKey;
  36783. }
  36784. updateScene( scene ) {
  36785. this.updateEnvironment( scene );
  36786. this.updateFog( scene );
  36787. this.updateBackground( scene );
  36788. }
  36789. get isToneMappingState() {
  36790. return this.renderer.getRenderTarget() ? false : true;
  36791. }
  36792. updateBackground( scene ) {
  36793. const sceneData = this.get( scene );
  36794. const background = scene.background;
  36795. if ( background ) {
  36796. if ( sceneData.background !== background ) {
  36797. let backgroundNode = null;
  36798. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  36799. backgroundNode = pmremTexture( background, normalWorld );
  36800. } else if ( background.isTexture === true ) {
  36801. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  36802. } else if ( background.isColor !== true ) {
  36803. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36804. }
  36805. sceneData.backgroundNode = backgroundNode;
  36806. sceneData.background = background;
  36807. }
  36808. } else if ( sceneData.backgroundNode ) {
  36809. delete sceneData.backgroundNode;
  36810. delete sceneData.background;
  36811. }
  36812. }
  36813. updateFog( scene ) {
  36814. const sceneData = this.get( scene );
  36815. const fog = scene.fog;
  36816. if ( fog ) {
  36817. if ( sceneData.fog !== fog ) {
  36818. let fogNode = null;
  36819. if ( fog.isFogExp2 ) {
  36820. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  36821. } else if ( fog.isFog ) {
  36822. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  36823. } else {
  36824. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  36825. }
  36826. sceneData.fogNode = fogNode;
  36827. sceneData.fog = fog;
  36828. }
  36829. } else {
  36830. delete sceneData.fogNode;
  36831. delete sceneData.fog;
  36832. }
  36833. }
  36834. updateEnvironment( scene ) {
  36835. const sceneData = this.get( scene );
  36836. const environment = scene.environment;
  36837. if ( environment ) {
  36838. if ( sceneData.environment !== environment ) {
  36839. let environmentNode = null;
  36840. if ( environment.isCubeTexture === true ) {
  36841. environmentNode = cubeTexture( environment );
  36842. } else if ( environment.isTexture === true ) {
  36843. environmentNode = texture( environment );
  36844. } else {
  36845. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36846. }
  36847. sceneData.environmentNode = environmentNode;
  36848. sceneData.environment = environment;
  36849. }
  36850. } else if ( sceneData.environmentNode ) {
  36851. delete sceneData.environmentNode;
  36852. delete sceneData.environment;
  36853. }
  36854. }
  36855. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36856. const nodeFrame = this.nodeFrame;
  36857. nodeFrame.renderer = renderer;
  36858. nodeFrame.scene = scene;
  36859. nodeFrame.object = object;
  36860. nodeFrame.camera = camera;
  36861. nodeFrame.material = material;
  36862. return nodeFrame;
  36863. }
  36864. getNodeFrameForRender( renderObject ) {
  36865. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36866. }
  36867. getOutputCacheKey() {
  36868. const renderer = this.renderer;
  36869. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  36870. }
  36871. hasOutputChange( outputTarget ) {
  36872. const cacheKey = outputNodeMap.get( outputTarget );
  36873. return cacheKey !== this.getOutputCacheKey();
  36874. }
  36875. getOutputNode( outputTexture ) {
  36876. const renderer = this.renderer;
  36877. const cacheKey = this.getOutputCacheKey();
  36878. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36879. outputNodeMap.set( outputTexture, cacheKey );
  36880. return output;
  36881. }
  36882. updateBefore( renderObject ) {
  36883. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36884. const nodeBuilder = renderObject.getNodeBuilderState();
  36885. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36886. nodeFrame.updateBeforeNode( node );
  36887. }
  36888. }
  36889. updateAfter( renderObject ) {
  36890. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36891. const nodeBuilder = renderObject.getNodeBuilderState();
  36892. for ( const node of nodeBuilder.updateAfterNodes ) {
  36893. nodeFrame.updateAfterNode( node );
  36894. }
  36895. }
  36896. updateForCompute( computeNode ) {
  36897. const nodeFrame = this.getNodeFrame();
  36898. const nodeBuilder = this.getForCompute( computeNode );
  36899. for ( const node of nodeBuilder.updateNodes ) {
  36900. nodeFrame.updateNode( node );
  36901. }
  36902. }
  36903. updateForRender( renderObject ) {
  36904. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36905. const nodeBuilder = renderObject.getNodeBuilderState();
  36906. for ( const node of nodeBuilder.updateNodes ) {
  36907. nodeFrame.updateNode( node );
  36908. }
  36909. }
  36910. dispose() {
  36911. super.dispose();
  36912. this.nodeFrame = new NodeFrame();
  36913. this.nodeBuilderCache = new Map();
  36914. }
  36915. }
  36916. class RenderBundle {
  36917. constructor( scene, camera ) {
  36918. this.scene = scene;
  36919. this.camera = camera;
  36920. }
  36921. clone() {
  36922. return Object.assign( new this.constructor(), this );
  36923. }
  36924. }
  36925. class RenderBundles {
  36926. constructor() {
  36927. this.lists = new ChainMap();
  36928. }
  36929. get( scene, camera ) {
  36930. const lists = this.lists;
  36931. const keys = [ scene, camera ];
  36932. let list = lists.get( keys );
  36933. if ( list === undefined ) {
  36934. list = new RenderBundle( scene, camera );
  36935. lists.set( keys, list );
  36936. }
  36937. return list;
  36938. }
  36939. dispose() {
  36940. this.lists = new ChainMap();
  36941. }
  36942. }
  36943. const _scene = /*@__PURE__*/ new Scene();
  36944. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36945. const _screen = /*@__PURE__*/ new Vector4();
  36946. const _frustum = /*@__PURE__*/ new Frustum();
  36947. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36948. const _vector3 = /*@__PURE__*/ new Vector3();
  36949. class Renderer {
  36950. constructor( backend, parameters = {} ) {
  36951. this.isRenderer = true;
  36952. //
  36953. const {
  36954. logarithmicDepthBuffer = false,
  36955. alpha = true,
  36956. antialias = false,
  36957. samples = 0
  36958. } = parameters;
  36959. // public
  36960. this.domElement = backend.getDomElement();
  36961. this.backend = backend;
  36962. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36963. this.autoClear = true;
  36964. this.autoClearColor = true;
  36965. this.autoClearDepth = true;
  36966. this.autoClearStencil = true;
  36967. this.alpha = alpha;
  36968. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36969. this.outputColorSpace = SRGBColorSpace;
  36970. this.toneMapping = NoToneMapping;
  36971. this.toneMappingExposure = 1.0;
  36972. this.sortObjects = true;
  36973. this.depth = true;
  36974. this.stencil = false;
  36975. this.clippingPlanes = [];
  36976. this.info = new Info();
  36977. // internals
  36978. this._pixelRatio = 1;
  36979. this._width = this.domElement.width;
  36980. this._height = this.domElement.height;
  36981. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36982. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36983. this._scissorTest = false;
  36984. this._attributes = null;
  36985. this._geometries = null;
  36986. this._nodes = null;
  36987. this._animation = null;
  36988. this._bindings = null;
  36989. this._objects = null;
  36990. this._pipelines = null;
  36991. this._bundles = null;
  36992. this._renderLists = null;
  36993. this._renderContexts = null;
  36994. this._textures = null;
  36995. this._background = null;
  36996. this._quad = new QuadMesh( new NodeMaterial() );
  36997. this._currentRenderContext = null;
  36998. this._opaqueSort = null;
  36999. this._transparentSort = null;
  37000. this._frameBufferTarget = null;
  37001. const alphaClear = this.alpha === true ? 0 : 1;
  37002. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37003. this._clearDepth = 1;
  37004. this._clearStencil = 0;
  37005. this._renderTarget = null;
  37006. this._activeCubeFace = 0;
  37007. this._activeMipmapLevel = 0;
  37008. this._mrt = null;
  37009. this._renderObjectFunction = null;
  37010. this._currentRenderObjectFunction = null;
  37011. this._currentRenderBundle = null;
  37012. this._handleObjectFunction = this._renderObjectDirect;
  37013. this._initialized = false;
  37014. this._initPromise = null;
  37015. this._compilationPromises = null;
  37016. this.transparent = true;
  37017. this.opaque = true;
  37018. this.shadowMap = {
  37019. enabled: false,
  37020. type: PCFShadowMap$1
  37021. };
  37022. this.xr = {
  37023. enabled: false
  37024. };
  37025. this.debug = {
  37026. checkShaderErrors: true,
  37027. onShaderError: null,
  37028. getShaderAsync: async ( scene, camera, object ) => {
  37029. await this.compileAsync( scene, camera );
  37030. const renderList = this._renderLists.get( scene, camera );
  37031. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37032. const material = scene.overrideMaterial || object.material;
  37033. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37034. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37035. return { fragmentShader, vertexShader };
  37036. }
  37037. };
  37038. }
  37039. async init() {
  37040. if ( this._initialized ) {
  37041. throw new Error( 'Renderer: Backend has already been initialized.' );
  37042. }
  37043. if ( this._initPromise !== null ) {
  37044. return this._initPromise;
  37045. }
  37046. this._initPromise = new Promise( async ( resolve, reject ) => {
  37047. const backend = this.backend;
  37048. try {
  37049. await backend.init( this );
  37050. } catch ( error ) {
  37051. reject( error );
  37052. return;
  37053. }
  37054. this._nodes = new Nodes( this, backend );
  37055. this._animation = new Animation( this._nodes, this.info );
  37056. this._attributes = new Attributes( backend );
  37057. this._background = new Background( this, this._nodes );
  37058. this._geometries = new Geometries( this._attributes, this.info );
  37059. this._textures = new Textures( this, backend, this.info );
  37060. this._pipelines = new Pipelines( backend, this._nodes );
  37061. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37062. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37063. this._renderLists = new RenderLists();
  37064. this._bundles = new RenderBundles();
  37065. this._renderContexts = new RenderContexts();
  37066. //
  37067. this._initialized = true;
  37068. resolve();
  37069. } );
  37070. return this._initPromise;
  37071. }
  37072. get coordinateSystem() {
  37073. return this.backend.coordinateSystem;
  37074. }
  37075. async compileAsync( scene, camera, targetScene = null ) {
  37076. if ( this._initialized === false ) await this.init();
  37077. // preserve render tree
  37078. const nodeFrame = this._nodes.nodeFrame;
  37079. const previousRenderId = nodeFrame.renderId;
  37080. const previousRenderContext = this._currentRenderContext;
  37081. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37082. const previousCompilationPromises = this._compilationPromises;
  37083. //
  37084. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37085. if ( targetScene === null ) targetScene = scene;
  37086. const renderTarget = this._renderTarget;
  37087. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37088. const activeMipmapLevel = this._activeMipmapLevel;
  37089. const compilationPromises = [];
  37090. this._currentRenderContext = renderContext;
  37091. this._currentRenderObjectFunction = this.renderObject;
  37092. this._handleObjectFunction = this._createObjectPipeline;
  37093. this._compilationPromises = compilationPromises;
  37094. nodeFrame.renderId ++;
  37095. //
  37096. nodeFrame.update();
  37097. //
  37098. renderContext.depth = this.depth;
  37099. renderContext.stencil = this.stencil;
  37100. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37101. renderContext.clippingContext.updateGlobal( this, camera );
  37102. //
  37103. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37104. //
  37105. const renderList = this._renderLists.get( scene, camera );
  37106. renderList.begin();
  37107. this._projectObject( scene, camera, 0, renderList );
  37108. // include lights from target scene
  37109. if ( targetScene !== scene ) {
  37110. targetScene.traverseVisible( function ( object ) {
  37111. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37112. renderList.pushLight( object );
  37113. }
  37114. } );
  37115. }
  37116. renderList.finish();
  37117. //
  37118. if ( renderTarget !== null ) {
  37119. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37120. const renderTargetData = this._textures.get( renderTarget );
  37121. renderContext.textures = renderTargetData.textures;
  37122. renderContext.depthTexture = renderTargetData.depthTexture;
  37123. } else {
  37124. renderContext.textures = null;
  37125. renderContext.depthTexture = null;
  37126. }
  37127. //
  37128. this._nodes.updateScene( sceneRef );
  37129. //
  37130. this._background.update( sceneRef, renderList, renderContext );
  37131. // process render lists
  37132. const opaqueObjects = renderList.opaque;
  37133. const transparentObjects = renderList.transparent;
  37134. const lightsNode = renderList.lightsNode;
  37135. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37136. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37137. // restore render tree
  37138. nodeFrame.renderId = previousRenderId;
  37139. this._currentRenderContext = previousRenderContext;
  37140. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37141. this._compilationPromises = previousCompilationPromises;
  37142. this._handleObjectFunction = this._renderObjectDirect;
  37143. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37144. await Promise.all( compilationPromises );
  37145. }
  37146. async renderAsync( scene, camera ) {
  37147. if ( this._initialized === false ) await this.init();
  37148. const renderContext = this._renderScene( scene, camera );
  37149. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37150. }
  37151. setMRT( mrt ) {
  37152. this._mrt = mrt;
  37153. return this;
  37154. }
  37155. getMRT() {
  37156. return this._mrt;
  37157. }
  37158. _renderBundle( bundle, sceneRef, lightsNode ) {
  37159. const { object, camera, renderList } = bundle;
  37160. const renderContext = this._currentRenderContext;
  37161. const renderContextData = this.backend.get( renderContext );
  37162. //
  37163. const renderBundle = this._bundles.get( object, camera );
  37164. const renderBundleData = this.backend.get( renderBundle );
  37165. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37166. //
  37167. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  37168. renderBundleData.renderContexts.add( renderContext );
  37169. if ( renderBundleNeedsUpdate ) {
  37170. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  37171. const nodeFrame = this._nodes.nodeFrame;
  37172. renderContextData.renderObjects = [];
  37173. renderContextData.renderBundles = [];
  37174. renderContextData.scene = sceneRef;
  37175. renderContextData.camera = camera;
  37176. renderContextData.renderId = nodeFrame.renderId;
  37177. renderContextData.registerBundlesPhase = true;
  37178. }
  37179. this._currentRenderBundle = renderBundle;
  37180. const opaqueObjects = renderList.opaque;
  37181. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37182. this._currentRenderBundle = null;
  37183. //
  37184. object.needsUpdate = false;
  37185. } else {
  37186. const renderContext = this._currentRenderContext;
  37187. const renderContextData = this.backend.get( renderContext );
  37188. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  37189. const renderObject = renderContextData.renderObjects[ i ];
  37190. this._nodes.updateBefore( renderObject );
  37191. //
  37192. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  37193. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  37194. this._nodes.updateForRender( renderObject );
  37195. this._bindings.updateForRender( renderObject );
  37196. this.backend.draw( renderObject, this.info );
  37197. this._nodes.updateAfter( renderObject );
  37198. }
  37199. }
  37200. }
  37201. render( scene, camera ) {
  37202. if ( this._initialized === false ) {
  37203. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37204. return this.renderAsync( scene, camera );
  37205. }
  37206. this._renderScene( scene, camera );
  37207. }
  37208. _getFrameBufferTarget() {
  37209. const { currentColorSpace } = this;
  37210. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  37211. const useColorSpace = this._renderTarget === null && ( currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace );
  37212. if ( useToneMapping === false && useColorSpace === false ) return null;
  37213. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37214. const { depth, stencil } = this;
  37215. let frameBufferTarget = this._frameBufferTarget;
  37216. if ( frameBufferTarget === null ) {
  37217. frameBufferTarget = new RenderTarget( width, height, {
  37218. depthBuffer: depth,
  37219. stencilBuffer: stencil,
  37220. type: HalfFloatType, // FloatType
  37221. format: RGBAFormat,
  37222. colorSpace: LinearSRGBColorSpace,
  37223. generateMipmaps: false,
  37224. minFilter: LinearFilter,
  37225. magFilter: LinearFilter,
  37226. samples: this.samples
  37227. } );
  37228. frameBufferTarget.isPostProcessingRenderTarget = true;
  37229. this._frameBufferTarget = frameBufferTarget;
  37230. }
  37231. frameBufferTarget.depthBuffer = depth;
  37232. frameBufferTarget.stencilBuffer = stencil;
  37233. frameBufferTarget.setSize( width, height );
  37234. frameBufferTarget.viewport.copy( this._viewport );
  37235. frameBufferTarget.scissor.copy( this._scissor );
  37236. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37237. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37238. frameBufferTarget.scissorTest = this._scissorTest;
  37239. return frameBufferTarget;
  37240. }
  37241. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37242. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37243. // preserve render tree
  37244. const nodeFrame = this._nodes.nodeFrame;
  37245. const previousRenderId = nodeFrame.renderId;
  37246. const previousRenderContext = this._currentRenderContext;
  37247. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37248. //
  37249. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37250. const outputRenderTarget = this._renderTarget;
  37251. const activeCubeFace = this._activeCubeFace;
  37252. const activeMipmapLevel = this._activeMipmapLevel;
  37253. //
  37254. let renderTarget;
  37255. if ( frameBufferTarget !== null ) {
  37256. renderTarget = frameBufferTarget;
  37257. this.setRenderTarget( renderTarget );
  37258. } else {
  37259. renderTarget = outputRenderTarget;
  37260. }
  37261. //
  37262. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37263. this._currentRenderContext = renderContext;
  37264. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37265. //
  37266. this.info.calls ++;
  37267. this.info.render.calls ++;
  37268. this.info.render.frameCalls ++;
  37269. nodeFrame.renderId = this.info.calls;
  37270. //
  37271. const coordinateSystem = this.coordinateSystem;
  37272. if ( camera.coordinateSystem !== coordinateSystem ) {
  37273. camera.coordinateSystem = coordinateSystem;
  37274. camera.updateProjectionMatrix();
  37275. }
  37276. //
  37277. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37278. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37279. //
  37280. let viewport = this._viewport;
  37281. let scissor = this._scissor;
  37282. let pixelRatio = this._pixelRatio;
  37283. if ( renderTarget !== null ) {
  37284. viewport = renderTarget.viewport;
  37285. scissor = renderTarget.scissor;
  37286. pixelRatio = 1;
  37287. }
  37288. this.getDrawingBufferSize( _drawingBufferSize );
  37289. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37290. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37291. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37292. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37293. renderContext.viewportValue.width >>= activeMipmapLevel;
  37294. renderContext.viewportValue.height >>= activeMipmapLevel;
  37295. renderContext.viewportValue.minDepth = minDepth;
  37296. renderContext.viewportValue.maxDepth = maxDepth;
  37297. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37298. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37299. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37300. renderContext.scissorValue.width >>= activeMipmapLevel;
  37301. renderContext.scissorValue.height >>= activeMipmapLevel;
  37302. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37303. renderContext.clippingContext.updateGlobal( this, camera );
  37304. //
  37305. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37306. //
  37307. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37308. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37309. const renderList = this._renderLists.get( scene, camera );
  37310. renderList.begin();
  37311. this._projectObject( scene, camera, 0, renderList );
  37312. renderList.finish();
  37313. if ( this.sortObjects === true ) {
  37314. renderList.sort( this._opaqueSort, this._transparentSort );
  37315. }
  37316. //
  37317. if ( renderTarget !== null ) {
  37318. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37319. const renderTargetData = this._textures.get( renderTarget );
  37320. renderContext.textures = renderTargetData.textures;
  37321. renderContext.depthTexture = renderTargetData.depthTexture;
  37322. renderContext.width = renderTargetData.width;
  37323. renderContext.height = renderTargetData.height;
  37324. renderContext.renderTarget = renderTarget;
  37325. renderContext.depth = renderTarget.depthBuffer;
  37326. renderContext.stencil = renderTarget.stencilBuffer;
  37327. } else {
  37328. renderContext.textures = null;
  37329. renderContext.depthTexture = null;
  37330. renderContext.width = this.domElement.width;
  37331. renderContext.height = this.domElement.height;
  37332. renderContext.depth = this.depth;
  37333. renderContext.stencil = this.stencil;
  37334. }
  37335. renderContext.width >>= activeMipmapLevel;
  37336. renderContext.height >>= activeMipmapLevel;
  37337. renderContext.activeCubeFace = activeCubeFace;
  37338. renderContext.activeMipmapLevel = activeMipmapLevel;
  37339. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37340. //
  37341. this._nodes.updateScene( sceneRef );
  37342. //
  37343. this._background.update( sceneRef, renderList, renderContext );
  37344. //
  37345. this.backend.beginRender( renderContext );
  37346. // process render lists
  37347. const opaqueObjects = renderList.opaque;
  37348. const transparentObjects = renderList.transparent;
  37349. const bundles = renderList.bundles;
  37350. const lightsNode = renderList.lightsNode;
  37351. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37352. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37353. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37354. // finish render pass
  37355. this.backend.finishRender( renderContext );
  37356. // restore render tree
  37357. nodeFrame.renderId = previousRenderId;
  37358. this._currentRenderContext = previousRenderContext;
  37359. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37360. //
  37361. if ( frameBufferTarget !== null ) {
  37362. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37363. const quad = this._quad;
  37364. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37365. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37366. quad.material.needsUpdate = true;
  37367. }
  37368. this._renderScene( quad, quad.camera, false );
  37369. }
  37370. //
  37371. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37372. //
  37373. return renderContext;
  37374. }
  37375. getMaxAnisotropy() {
  37376. return this.backend.getMaxAnisotropy();
  37377. }
  37378. getActiveCubeFace() {
  37379. return this._activeCubeFace;
  37380. }
  37381. getActiveMipmapLevel() {
  37382. return this._activeMipmapLevel;
  37383. }
  37384. async setAnimationLoop( callback ) {
  37385. if ( this._initialized === false ) await this.init();
  37386. this._animation.setAnimationLoop( callback );
  37387. }
  37388. async getArrayBufferAsync( attribute ) {
  37389. return await this.backend.getArrayBufferAsync( attribute );
  37390. }
  37391. getContext() {
  37392. return this.backend.getContext();
  37393. }
  37394. getPixelRatio() {
  37395. return this._pixelRatio;
  37396. }
  37397. getDrawingBufferSize( target ) {
  37398. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37399. }
  37400. getSize( target ) {
  37401. return target.set( this._width, this._height );
  37402. }
  37403. setPixelRatio( value = 1 ) {
  37404. this._pixelRatio = value;
  37405. this.setSize( this._width, this._height, false );
  37406. }
  37407. setDrawingBufferSize( width, height, pixelRatio ) {
  37408. this._width = width;
  37409. this._height = height;
  37410. this._pixelRatio = pixelRatio;
  37411. this.domElement.width = Math.floor( width * pixelRatio );
  37412. this.domElement.height = Math.floor( height * pixelRatio );
  37413. this.setViewport( 0, 0, width, height );
  37414. if ( this._initialized ) this.backend.updateSize();
  37415. }
  37416. setSize( width, height, updateStyle = true ) {
  37417. this._width = width;
  37418. this._height = height;
  37419. this.domElement.width = Math.floor( width * this._pixelRatio );
  37420. this.domElement.height = Math.floor( height * this._pixelRatio );
  37421. if ( updateStyle === true ) {
  37422. this.domElement.style.width = width + 'px';
  37423. this.domElement.style.height = height + 'px';
  37424. }
  37425. this.setViewport( 0, 0, width, height );
  37426. if ( this._initialized ) this.backend.updateSize();
  37427. }
  37428. setOpaqueSort( method ) {
  37429. this._opaqueSort = method;
  37430. }
  37431. setTransparentSort( method ) {
  37432. this._transparentSort = method;
  37433. }
  37434. getScissor( target ) {
  37435. const scissor = this._scissor;
  37436. target.x = scissor.x;
  37437. target.y = scissor.y;
  37438. target.width = scissor.width;
  37439. target.height = scissor.height;
  37440. return target;
  37441. }
  37442. setScissor( x, y, width, height ) {
  37443. const scissor = this._scissor;
  37444. if ( x.isVector4 ) {
  37445. scissor.copy( x );
  37446. } else {
  37447. scissor.set( x, y, width, height );
  37448. }
  37449. }
  37450. getScissorTest() {
  37451. return this._scissorTest;
  37452. }
  37453. setScissorTest( boolean ) {
  37454. this._scissorTest = boolean;
  37455. this.backend.setScissorTest( boolean );
  37456. }
  37457. getViewport( target ) {
  37458. return target.copy( this._viewport );
  37459. }
  37460. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37461. const viewport = this._viewport;
  37462. if ( x.isVector4 ) {
  37463. viewport.copy( x );
  37464. } else {
  37465. viewport.set( x, y, width, height );
  37466. }
  37467. viewport.minDepth = minDepth;
  37468. viewport.maxDepth = maxDepth;
  37469. }
  37470. getClearColor( target ) {
  37471. return target.copy( this._clearColor );
  37472. }
  37473. setClearColor( color, alpha = 1 ) {
  37474. this._clearColor.set( color );
  37475. this._clearColor.a = alpha;
  37476. }
  37477. getClearAlpha() {
  37478. return this._clearColor.a;
  37479. }
  37480. setClearAlpha( alpha ) {
  37481. this._clearColor.a = alpha;
  37482. }
  37483. getClearDepth() {
  37484. return this._clearDepth;
  37485. }
  37486. setClearDepth( depth ) {
  37487. this._clearDepth = depth;
  37488. }
  37489. getClearStencil() {
  37490. return this._clearStencil;
  37491. }
  37492. setClearStencil( stencil ) {
  37493. this._clearStencil = stencil;
  37494. }
  37495. isOccluded( object ) {
  37496. const renderContext = this._currentRenderContext;
  37497. return renderContext && this.backend.isOccluded( renderContext, object );
  37498. }
  37499. clear( color = true, depth = true, stencil = true ) {
  37500. if ( this._initialized === false ) {
  37501. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37502. return this.clearAsync( color, depth, stencil );
  37503. }
  37504. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37505. let renderTargetData = null;
  37506. if ( renderTarget !== null ) {
  37507. this._textures.updateRenderTarget( renderTarget );
  37508. renderTargetData = this._textures.get( renderTarget );
  37509. }
  37510. this.backend.clear( color, depth, stencil, renderTargetData );
  37511. if ( renderTarget !== null && this._renderTarget === null ) {
  37512. // If a color space transform or tone mapping is required,
  37513. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37514. const quad = this._quad;
  37515. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37516. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37517. quad.material.needsUpdate = true;
  37518. }
  37519. this._renderScene( quad, quad.camera, false );
  37520. }
  37521. }
  37522. clearColor() {
  37523. return this.clear( true, false, false );
  37524. }
  37525. clearDepth() {
  37526. return this.clear( false, true, false );
  37527. }
  37528. clearStencil() {
  37529. return this.clear( false, false, true );
  37530. }
  37531. async clearAsync( color = true, depth = true, stencil = true ) {
  37532. if ( this._initialized === false ) await this.init();
  37533. this.clear( color, depth, stencil );
  37534. }
  37535. clearColorAsync() {
  37536. return this.clearAsync( true, false, false );
  37537. }
  37538. clearDepthAsync() {
  37539. return this.clearAsync( false, true, false );
  37540. }
  37541. clearStencilAsync() {
  37542. return this.clearAsync( false, false, true );
  37543. }
  37544. get currentColorSpace() {
  37545. const renderTarget = this._renderTarget;
  37546. if ( renderTarget !== null ) {
  37547. const texture = renderTarget.texture;
  37548. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  37549. }
  37550. return this.outputColorSpace;
  37551. }
  37552. dispose() {
  37553. this.info.dispose();
  37554. this._animation.dispose();
  37555. this._objects.dispose();
  37556. this._pipelines.dispose();
  37557. this._nodes.dispose();
  37558. this._bindings.dispose();
  37559. this._renderLists.dispose();
  37560. this._renderContexts.dispose();
  37561. this._textures.dispose();
  37562. this.setRenderTarget( null );
  37563. this.setAnimationLoop( null );
  37564. }
  37565. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37566. this._renderTarget = renderTarget;
  37567. this._activeCubeFace = activeCubeFace;
  37568. this._activeMipmapLevel = activeMipmapLevel;
  37569. }
  37570. getRenderTarget() {
  37571. return this._renderTarget;
  37572. }
  37573. setRenderObjectFunction( renderObjectFunction ) {
  37574. this._renderObjectFunction = renderObjectFunction;
  37575. }
  37576. getRenderObjectFunction() {
  37577. return this._renderObjectFunction;
  37578. }
  37579. async computeAsync( computeNodes ) {
  37580. if ( this._initialized === false ) await this.init();
  37581. const nodeFrame = this._nodes.nodeFrame;
  37582. const previousRenderId = nodeFrame.renderId;
  37583. //
  37584. this.info.calls ++;
  37585. this.info.compute.calls ++;
  37586. this.info.compute.frameCalls ++;
  37587. nodeFrame.renderId = this.info.calls;
  37588. //
  37589. const backend = this.backend;
  37590. const pipelines = this._pipelines;
  37591. const bindings = this._bindings;
  37592. const nodes = this._nodes;
  37593. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37594. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37595. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37596. }
  37597. backend.beginCompute( computeNodes );
  37598. for ( const computeNode of computeList ) {
  37599. // onInit
  37600. if ( pipelines.has( computeNode ) === false ) {
  37601. const dispose = () => {
  37602. computeNode.removeEventListener( 'dispose', dispose );
  37603. pipelines.delete( computeNode );
  37604. bindings.delete( computeNode );
  37605. nodes.delete( computeNode );
  37606. };
  37607. computeNode.addEventListener( 'dispose', dispose );
  37608. //
  37609. computeNode.onInit( { renderer: this } );
  37610. }
  37611. nodes.updateForCompute( computeNode );
  37612. bindings.updateForCompute( computeNode );
  37613. const computeBindings = bindings.getForCompute( computeNode );
  37614. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37615. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37616. }
  37617. backend.finishCompute( computeNodes );
  37618. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  37619. //
  37620. nodeFrame.renderId = previousRenderId;
  37621. }
  37622. async hasFeatureAsync( name ) {
  37623. if ( this._initialized === false ) await this.init();
  37624. return this.backend.hasFeature( name );
  37625. }
  37626. hasFeature( name ) {
  37627. if ( this._initialized === false ) {
  37628. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37629. return false;
  37630. }
  37631. return this.backend.hasFeature( name );
  37632. }
  37633. copyFramebufferToTexture( framebufferTexture ) {
  37634. const renderContext = this._currentRenderContext;
  37635. this._textures.updateTexture( framebufferTexture );
  37636. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  37637. }
  37638. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37639. this._textures.updateTexture( srcTexture );
  37640. this._textures.updateTexture( dstTexture );
  37641. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  37642. }
  37643. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  37644. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  37645. }
  37646. _projectObject( object, camera, groupOrder, renderList ) {
  37647. if ( object.visible === false ) return;
  37648. const visible = object.layers.test( camera.layers );
  37649. if ( visible ) {
  37650. if ( object.isGroup ) {
  37651. groupOrder = object.renderOrder;
  37652. } else if ( object.isLOD ) {
  37653. if ( object.autoUpdate === true ) object.update( camera );
  37654. } else if ( object.isLight ) {
  37655. renderList.pushLight( object );
  37656. } else if ( object.isSprite ) {
  37657. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37658. if ( this.sortObjects === true ) {
  37659. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  37660. }
  37661. const geometry = object.geometry;
  37662. const material = object.material;
  37663. if ( material.visible ) {
  37664. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37665. }
  37666. }
  37667. } else if ( object.isLineLoop ) {
  37668. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  37669. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  37670. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  37671. const geometry = object.geometry;
  37672. const material = object.material;
  37673. if ( this.sortObjects === true ) {
  37674. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  37675. _vector3
  37676. .copy( geometry.boundingSphere.center )
  37677. .applyMatrix4( object.matrixWorld )
  37678. .applyMatrix4( _projScreenMatrix );
  37679. }
  37680. if ( Array.isArray( material ) ) {
  37681. const groups = geometry.groups;
  37682. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  37683. const group = groups[ i ];
  37684. const groupMaterial = material[ group.materialIndex ];
  37685. if ( groupMaterial && groupMaterial.visible ) {
  37686. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  37687. }
  37688. }
  37689. } else if ( material.visible ) {
  37690. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37691. }
  37692. }
  37693. }
  37694. }
  37695. if ( object.static === true ) {
  37696. const baseRenderList = renderList;
  37697. // replace render list
  37698. renderList = this._renderLists.get( object, camera );
  37699. renderList.begin();
  37700. baseRenderList.pushBundle( {
  37701. object,
  37702. camera,
  37703. renderList,
  37704. } );
  37705. renderList.finish();
  37706. }
  37707. const children = object.children;
  37708. for ( let i = 0, l = children.length; i < l; i ++ ) {
  37709. this._projectObject( children[ i ], camera, groupOrder, renderList );
  37710. }
  37711. }
  37712. _renderBundles( bundles, sceneRef, lightsNode ) {
  37713. for ( const bundle of bundles ) {
  37714. this._renderBundle( bundle, sceneRef, lightsNode );
  37715. }
  37716. }
  37717. _renderObjects( renderList, camera, scene, lightsNode ) {
  37718. // process renderable objects
  37719. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  37720. const renderItem = renderList[ i ];
  37721. // @TODO: Add support for multiple materials per object. This will require to extract
  37722. // the material from the renderItem object and pass it with its group data to renderObject().
  37723. const { object, geometry, material, group } = renderItem;
  37724. if ( camera.isArrayCamera ) {
  37725. const cameras = camera.cameras;
  37726. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  37727. const camera2 = cameras[ j ];
  37728. if ( object.layers.test( camera2.layers ) ) {
  37729. const vp = camera2.viewport;
  37730. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  37731. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  37732. const viewportValue = this._currentRenderContext.viewportValue;
  37733. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  37734. viewportValue.minDepth = minDepth;
  37735. viewportValue.maxDepth = maxDepth;
  37736. this.backend.updateViewport( this._currentRenderContext );
  37737. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  37738. }
  37739. }
  37740. } else {
  37741. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  37742. }
  37743. }
  37744. }
  37745. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  37746. let overridePositionNode;
  37747. let overrideFragmentNode;
  37748. let overrideDepthNode;
  37749. //
  37750. object.onBeforeRender( this, scene, camera, geometry, material, group );
  37751. //
  37752. if ( scene.overrideMaterial !== null ) {
  37753. const overrideMaterial = scene.overrideMaterial;
  37754. if ( material.positionNode && material.positionNode.isNode ) {
  37755. overridePositionNode = overrideMaterial.positionNode;
  37756. overrideMaterial.positionNode = material.positionNode;
  37757. }
  37758. if ( overrideMaterial.isShadowNodeMaterial ) {
  37759. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  37760. if ( material.depthNode && material.depthNode.isNode ) {
  37761. overrideDepthNode = overrideMaterial.depthNode;
  37762. overrideMaterial.depthNode = material.depthNode;
  37763. }
  37764. if ( material.shadowNode && material.shadowNode.isNode ) {
  37765. overrideFragmentNode = overrideMaterial.fragmentNode;
  37766. overrideMaterial.fragmentNode = material.shadowNode;
  37767. }
  37768. if ( this.localClippingEnabled ) {
  37769. if ( material.clipShadows ) {
  37770. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  37771. overrideMaterial.clippingPlanes = material.clippingPlanes;
  37772. overrideMaterial.needsUpdate = true;
  37773. }
  37774. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  37775. overrideMaterial.clipIntersection = material.clipIntersection;
  37776. }
  37777. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  37778. overrideMaterial.clippingPlanes = null;
  37779. overrideMaterial.needsUpdate = true;
  37780. }
  37781. }
  37782. }
  37783. material = overrideMaterial;
  37784. }
  37785. //
  37786. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  37787. material.side = BackSide;
  37788. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  37789. material.side = FrontSide;
  37790. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  37791. material.side = DoubleSide;
  37792. } else {
  37793. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  37794. }
  37795. //
  37796. if ( overridePositionNode !== undefined ) {
  37797. scene.overrideMaterial.positionNode = overridePositionNode;
  37798. }
  37799. if ( overrideDepthNode !== undefined ) {
  37800. scene.overrideMaterial.depthNode = overrideDepthNode;
  37801. }
  37802. if ( overrideFragmentNode !== undefined ) {
  37803. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  37804. }
  37805. //
  37806. object.onAfterRender( this, scene, camera, geometry, material, group );
  37807. }
  37808. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  37809. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37810. renderObject.drawRange = group || object.geometry.drawRange;
  37811. //
  37812. this._nodes.updateBefore( renderObject );
  37813. //
  37814. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  37815. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  37816. //
  37817. this._nodes.updateForRender( renderObject );
  37818. this._geometries.updateForRender( renderObject );
  37819. this._bindings.updateForRender( renderObject );
  37820. this._pipelines.updateForRender( renderObject );
  37821. //
  37822. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  37823. const renderObjectData = this.backend.get( renderObject );
  37824. renderObjectData.bundleEncoder = undefined;
  37825. renderObjectData.lastPipelineGPU = undefined;
  37826. }
  37827. this.backend.draw( renderObject, this.info );
  37828. if ( this._currentRenderBundle !== null ) {
  37829. const renderContextData = this.backend.get( this._currentRenderContext );
  37830. renderContextData.renderObjects.push( renderObject );
  37831. }
  37832. this._nodes.updateAfter( renderObject );
  37833. }
  37834. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  37835. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37836. //
  37837. this._nodes.updateBefore( renderObject );
  37838. //
  37839. this._nodes.updateForRender( renderObject );
  37840. this._geometries.updateForRender( renderObject );
  37841. this._bindings.updateForRender( renderObject );
  37842. this._pipelines.getForRender( renderObject, this._compilationPromises );
  37843. this._nodes.updateAfter( renderObject );
  37844. }
  37845. get compute() {
  37846. return this.computeAsync;
  37847. }
  37848. get compile() {
  37849. return this.compileAsync;
  37850. }
  37851. }
  37852. class Binding {
  37853. constructor( name = '' ) {
  37854. this.name = name;
  37855. this.visibility = 0;
  37856. }
  37857. setVisibility( visibility ) {
  37858. this.visibility |= visibility;
  37859. }
  37860. clone() {
  37861. return Object.assign( new this.constructor(), this );
  37862. }
  37863. }
  37864. function getFloatLength( floatLength ) {
  37865. // ensure chunk size alignment (STD140 layout)
  37866. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  37867. }
  37868. class Buffer extends Binding {
  37869. constructor( name, buffer = null ) {
  37870. super( name );
  37871. this.isBuffer = true;
  37872. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  37873. this._buffer = buffer;
  37874. }
  37875. get byteLength() {
  37876. return getFloatLength( this._buffer.byteLength );
  37877. }
  37878. get buffer() {
  37879. return this._buffer;
  37880. }
  37881. update() {
  37882. return true;
  37883. }
  37884. }
  37885. class UniformBuffer extends Buffer {
  37886. constructor( name, buffer = null ) {
  37887. super( name, buffer );
  37888. this.isUniformBuffer = true;
  37889. }
  37890. }
  37891. let _id$4 = 0;
  37892. class NodeUniformBuffer extends UniformBuffer {
  37893. constructor( nodeUniform, groupNode ) {
  37894. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37895. this.nodeUniform = nodeUniform;
  37896. this.groupNode = groupNode;
  37897. }
  37898. get buffer() {
  37899. return this.nodeUniform.value;
  37900. }
  37901. }
  37902. class UniformsGroup extends UniformBuffer {
  37903. constructor( name ) {
  37904. super( name );
  37905. this.isUniformsGroup = true;
  37906. this._values = null;
  37907. // the order of uniforms in this array must match the order of uniforms in the shader
  37908. this.uniforms = [];
  37909. }
  37910. addUniform( uniform ) {
  37911. this.uniforms.push( uniform );
  37912. return this;
  37913. }
  37914. removeUniform( uniform ) {
  37915. const index = this.uniforms.indexOf( uniform );
  37916. if ( index !== - 1 ) {
  37917. this.uniforms.splice( index, 1 );
  37918. }
  37919. return this;
  37920. }
  37921. get values() {
  37922. if ( this._values === null ) {
  37923. this._values = Array.from( this.buffer );
  37924. }
  37925. return this._values;
  37926. }
  37927. get buffer() {
  37928. let buffer = this._buffer;
  37929. if ( buffer === null ) {
  37930. const byteLength = this.byteLength;
  37931. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37932. this._buffer = buffer;
  37933. }
  37934. return buffer;
  37935. }
  37936. get byteLength() {
  37937. let offset = 0; // global buffer offset in bytes
  37938. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37939. const uniform = this.uniforms[ i ];
  37940. const { boundary, itemSize } = uniform;
  37941. // offset within a single chunk in bytes
  37942. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37943. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37944. // conformance tests
  37945. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37946. // check for chunk overflow
  37947. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37948. } else if ( chunkOffset % boundary !== 0 ) {
  37949. // check for correct alignment
  37950. offset += ( chunkOffset % boundary );
  37951. }
  37952. uniform.offset = ( offset / this.bytesPerElement );
  37953. offset += ( itemSize * this.bytesPerElement );
  37954. }
  37955. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37956. }
  37957. update() {
  37958. let updated = false;
  37959. for ( const uniform of this.uniforms ) {
  37960. if ( this.updateByType( uniform ) === true ) {
  37961. updated = true;
  37962. }
  37963. }
  37964. return updated;
  37965. }
  37966. updateByType( uniform ) {
  37967. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37968. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37969. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37970. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37971. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37972. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37973. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37974. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37975. }
  37976. updateNumber( uniform ) {
  37977. let updated = false;
  37978. const a = this.values;
  37979. const v = uniform.getValue();
  37980. const offset = uniform.offset;
  37981. if ( a[ offset ] !== v ) {
  37982. const b = this.buffer;
  37983. b[ offset ] = a[ offset ] = v;
  37984. updated = true;
  37985. }
  37986. return updated;
  37987. }
  37988. updateVector2( uniform ) {
  37989. let updated = false;
  37990. const a = this.values;
  37991. const v = uniform.getValue();
  37992. const offset = uniform.offset;
  37993. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37994. const b = this.buffer;
  37995. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37996. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37997. updated = true;
  37998. }
  37999. return updated;
  38000. }
  38001. updateVector3( uniform ) {
  38002. let updated = false;
  38003. const a = this.values;
  38004. const v = uniform.getValue();
  38005. const offset = uniform.offset;
  38006. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38007. const b = this.buffer;
  38008. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38009. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38010. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38011. updated = true;
  38012. }
  38013. return updated;
  38014. }
  38015. updateVector4( uniform ) {
  38016. let updated = false;
  38017. const a = this.values;
  38018. const v = uniform.getValue();
  38019. const offset = uniform.offset;
  38020. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38021. const b = this.buffer;
  38022. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38023. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38024. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38025. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38026. updated = true;
  38027. }
  38028. return updated;
  38029. }
  38030. updateColor( uniform ) {
  38031. let updated = false;
  38032. const a = this.values;
  38033. const c = uniform.getValue();
  38034. const offset = uniform.offset;
  38035. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38036. const b = this.buffer;
  38037. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38038. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38039. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38040. updated = true;
  38041. }
  38042. return updated;
  38043. }
  38044. updateMatrix3( uniform ) {
  38045. let updated = false;
  38046. const a = this.values;
  38047. const e = uniform.getValue().elements;
  38048. const offset = uniform.offset;
  38049. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38050. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38051. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38052. const b = this.buffer;
  38053. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38054. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38055. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38056. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38057. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38058. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38059. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38060. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38061. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38062. updated = true;
  38063. }
  38064. return updated;
  38065. }
  38066. updateMatrix4( uniform ) {
  38067. let updated = false;
  38068. const a = this.values;
  38069. const e = uniform.getValue().elements;
  38070. const offset = uniform.offset;
  38071. if ( arraysEqual( a, e, offset ) === false ) {
  38072. const b = this.buffer;
  38073. b.set( e, offset );
  38074. setArray( a, e, offset );
  38075. updated = true;
  38076. }
  38077. return updated;
  38078. }
  38079. }
  38080. function setArray( a, b, offset ) {
  38081. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38082. a[ offset + i ] = b[ i ];
  38083. }
  38084. }
  38085. function arraysEqual( a, b, offset ) {
  38086. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38087. if ( a[ offset + i ] !== b[ i ] ) return false;
  38088. }
  38089. return true;
  38090. }
  38091. let _id$3 = 0;
  38092. class NodeUniformsGroup extends UniformsGroup {
  38093. constructor( name, groupNode ) {
  38094. super( name );
  38095. this.id = _id$3 ++;
  38096. this.groupNode = groupNode;
  38097. this.isNodeUniformsGroup = true;
  38098. }
  38099. getNodes() {
  38100. const nodes = [];
  38101. for ( const uniform of this.uniforms ) {
  38102. const node = uniform.nodeUniform.node;
  38103. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38104. nodes.push( node );
  38105. }
  38106. return nodes;
  38107. }
  38108. }
  38109. let _id$2 = 0;
  38110. class SampledTexture extends Binding {
  38111. constructor( name, texture ) {
  38112. super( name );
  38113. this.id = _id$2 ++;
  38114. this.texture = texture;
  38115. this.version = texture ? texture.version : 0;
  38116. this.store = false;
  38117. this.isSampledTexture = true;
  38118. }
  38119. get needsBindingsUpdate() {
  38120. const { texture, version } = this;
  38121. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  38122. }
  38123. update() {
  38124. const { texture, version } = this;
  38125. if ( version !== texture.version ) {
  38126. this.version = texture.version;
  38127. return true;
  38128. }
  38129. return false;
  38130. }
  38131. }
  38132. class NodeSampledTexture extends SampledTexture {
  38133. constructor( name, textureNode, groupNode, access = null ) {
  38134. super( name, textureNode ? textureNode.value : null );
  38135. this.textureNode = textureNode;
  38136. this.groupNode = groupNode;
  38137. this.access = access;
  38138. }
  38139. get needsBindingsUpdate() {
  38140. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  38141. }
  38142. update() {
  38143. const { textureNode } = this;
  38144. if ( this.texture !== textureNode.value ) {
  38145. this.texture = textureNode.value;
  38146. return true;
  38147. }
  38148. return super.update();
  38149. }
  38150. }
  38151. class NodeSampledCubeTexture extends NodeSampledTexture {
  38152. constructor( name, textureNode, groupNode, access ) {
  38153. super( name, textureNode, groupNode, access );
  38154. this.isSampledCubeTexture = true;
  38155. }
  38156. }
  38157. class NodeSampledTexture3D extends NodeSampledTexture {
  38158. constructor( name, textureNode, groupNode, access ) {
  38159. super( name, textureNode, groupNode, access );
  38160. this.isSampledTexture3D = true;
  38161. }
  38162. }
  38163. const glslMethods = {
  38164. [ MathNode.ATAN2 ]: 'atan',
  38165. textureDimensions: 'textureSize',
  38166. equals: 'equal'
  38167. };
  38168. const precisionLib = {
  38169. low: 'lowp',
  38170. medium: 'mediump',
  38171. high: 'highp'
  38172. };
  38173. const supports$1 = {
  38174. swizzleAssign: true,
  38175. storageBuffer: false
  38176. };
  38177. const defaultPrecisions = `
  38178. precision highp float;
  38179. precision highp int;
  38180. precision highp sampler2D;
  38181. precision highp sampler3D;
  38182. precision highp samplerCube;
  38183. precision highp sampler2DArray;
  38184. precision highp usampler2D;
  38185. precision highp usampler3D;
  38186. precision highp usamplerCube;
  38187. precision highp usampler2DArray;
  38188. precision highp isampler2D;
  38189. precision highp isampler3D;
  38190. precision highp isamplerCube;
  38191. precision highp isampler2DArray;
  38192. precision lowp sampler2DShadow;
  38193. `;
  38194. class GLSLNodeBuilder extends NodeBuilder {
  38195. constructor( object, renderer ) {
  38196. super( object, renderer, new GLSLNodeParser() );
  38197. this.uniformGroups = {};
  38198. this.transforms = [];
  38199. this.extensions = {};
  38200. this.instanceBindGroups = false;
  38201. }
  38202. getMethod( method ) {
  38203. return glslMethods[ method ] || method;
  38204. }
  38205. getOutputStructName() {
  38206. return '';
  38207. }
  38208. buildFunctionCode( shaderNode ) {
  38209. const layout = shaderNode.layout;
  38210. const flowData = this.flowShaderNode( shaderNode );
  38211. const parameters = [];
  38212. for ( const input of layout.inputs ) {
  38213. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38214. }
  38215. //
  38216. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38217. ${ flowData.vars }
  38218. ${ flowData.code }
  38219. return ${ flowData.result };
  38220. }`;
  38221. //
  38222. return code;
  38223. }
  38224. setupPBO( storageBufferNode ) {
  38225. const attribute = storageBufferNode.value;
  38226. if ( attribute.pbo === undefined ) {
  38227. const originalArray = attribute.array;
  38228. const numElements = attribute.count * attribute.itemSize;
  38229. const { itemSize } = attribute;
  38230. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38231. let format = isInteger ? RedIntegerFormat : RedFormat;
  38232. if ( itemSize === 2 ) {
  38233. format = isInteger ? RGIntegerFormat : RGFormat;
  38234. } else if ( itemSize === 3 ) {
  38235. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38236. } else if ( itemSize === 4 ) {
  38237. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38238. }
  38239. const typeMap = {
  38240. Float32Array: FloatType,
  38241. Uint8Array: UnsignedByteType,
  38242. Uint16Array: UnsignedShortType,
  38243. Uint32Array: UnsignedIntType,
  38244. Int8Array: ByteType,
  38245. Int16Array: ShortType,
  38246. Int32Array: IntType,
  38247. Uint8ClampedArray: UnsignedByteType,
  38248. };
  38249. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38250. let height = Math.ceil( ( numElements / itemSize ) / width );
  38251. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38252. const newSize = width * height * itemSize;
  38253. const newArray = new originalArray.constructor( newSize );
  38254. newArray.set( originalArray, 0 );
  38255. attribute.array = newArray;
  38256. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38257. pboTexture.needsUpdate = true;
  38258. pboTexture.isPBOTexture = true;
  38259. const pbo = new TextureNode( pboTexture, null, null );
  38260. pbo.setPrecision( 'high' );
  38261. attribute.pboNode = pbo;
  38262. attribute.pbo = pbo.value;
  38263. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38264. }
  38265. }
  38266. getPropertyName( node, shaderStage = this.shaderStage ) {
  38267. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38268. return shaderStage.charAt( 0 ) + '_' + node.name;
  38269. }
  38270. return super.getPropertyName( node, shaderStage );
  38271. }
  38272. generatePBO( storageArrayElementNode ) {
  38273. const { node, indexNode } = storageArrayElementNode;
  38274. const attribute = node.value;
  38275. if ( this.renderer.backend.has( attribute ) ) {
  38276. const attributeData = this.renderer.backend.get( attribute );
  38277. attributeData.pbo = attribute.pbo;
  38278. }
  38279. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38280. const textureName = this.getPropertyName( nodeUniform );
  38281. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  38282. const indexSnippet = indexNode.build( this, 'uint' );
  38283. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38284. let propertyName = elementNodeData.propertyName;
  38285. if ( propertyName === undefined ) {
  38286. // property element
  38287. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38288. propertyName = this.getPropertyName( nodeVar );
  38289. // property size
  38290. const bufferNodeData = this.getDataFromNode( node );
  38291. let propertySizeName = bufferNodeData.propertySizeName;
  38292. if ( propertySizeName === undefined ) {
  38293. propertySizeName = propertyName + 'Size';
  38294. this.getVarFromNode( node, propertySizeName, 'uint' );
  38295. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  38296. bufferNodeData.propertySizeName = propertySizeName;
  38297. }
  38298. //
  38299. const { itemSize } = attribute;
  38300. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38301. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38302. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38303. //
  38304. let prefix = 'vec4';
  38305. if ( attribute.pbo.type === UnsignedIntType ) {
  38306. prefix = 'uvec4';
  38307. } else if ( attribute.pbo.type === IntType ) {
  38308. prefix = 'ivec4';
  38309. }
  38310. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  38311. elementNodeData.propertyName = propertyName;
  38312. }
  38313. return propertyName;
  38314. }
  38315. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38316. if ( depthSnippet ) {
  38317. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38318. } else {
  38319. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38320. }
  38321. }
  38322. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38323. if ( texture.isDepthTexture ) {
  38324. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38325. } else {
  38326. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38327. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38328. }
  38329. }
  38330. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38331. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38332. }
  38333. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38334. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38335. }
  38336. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38337. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38338. }
  38339. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38340. if ( shaderStage === 'fragment' ) {
  38341. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38342. } else {
  38343. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38344. }
  38345. }
  38346. getVars( shaderStage ) {
  38347. const snippets = [];
  38348. const vars = this.vars[ shaderStage ];
  38349. if ( vars !== undefined ) {
  38350. for ( const variable of vars ) {
  38351. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38352. }
  38353. }
  38354. return snippets.join( '\n\t' );
  38355. }
  38356. getUniforms( shaderStage ) {
  38357. const uniforms = this.uniforms[ shaderStage ];
  38358. const bindingSnippets = [];
  38359. const uniformGroups = {};
  38360. for ( const uniform of uniforms ) {
  38361. let snippet = null;
  38362. let group = false;
  38363. if ( uniform.type === 'texture' ) {
  38364. const texture = uniform.node.value;
  38365. let typePrefix = '';
  38366. if ( texture.isDataTexture === true ) {
  38367. if ( texture.type === UnsignedIntType ) {
  38368. typePrefix = 'u';
  38369. } else if ( texture.type === IntType ) {
  38370. typePrefix = 'i';
  38371. }
  38372. }
  38373. if ( texture.compareFunction ) {
  38374. snippet = `sampler2DShadow ${ uniform.name };`;
  38375. } else if ( texture.isDataArrayTexture === true ) {
  38376. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38377. } else {
  38378. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38379. }
  38380. } else if ( uniform.type === 'cubeTexture' ) {
  38381. snippet = `samplerCube ${ uniform.name };`;
  38382. } else if ( uniform.type === 'texture3D' ) {
  38383. snippet = `sampler3D ${ uniform.name };`;
  38384. } else if ( uniform.type === 'buffer' ) {
  38385. const bufferNode = uniform.node;
  38386. const bufferType = this.getType( bufferNode.bufferType );
  38387. const bufferCount = bufferNode.bufferCount;
  38388. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38389. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38390. } else {
  38391. const vectorType = this.getVectorType( uniform.type );
  38392. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38393. group = true;
  38394. }
  38395. const precision = uniform.node.precision;
  38396. if ( precision !== null ) {
  38397. snippet = precisionLib[ precision ] + ' ' + snippet;
  38398. }
  38399. if ( group ) {
  38400. snippet = '\t' + snippet;
  38401. const groupName = uniform.groupNode.name;
  38402. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38403. groupSnippets.push( snippet );
  38404. } else {
  38405. snippet = 'uniform ' + snippet;
  38406. bindingSnippets.push( snippet );
  38407. }
  38408. }
  38409. let output = '';
  38410. for ( const name in uniformGroups ) {
  38411. const groupSnippets = uniformGroups[ name ];
  38412. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38413. }
  38414. output += bindingSnippets.join( '\n' );
  38415. return output;
  38416. }
  38417. getTypeFromAttribute( attribute ) {
  38418. let nodeType = super.getTypeFromAttribute( attribute );
  38419. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38420. let dataAttribute = attribute;
  38421. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38422. const array = dataAttribute.array;
  38423. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38424. nodeType = nodeType.slice( 1 );
  38425. }
  38426. }
  38427. return nodeType;
  38428. }
  38429. getAttributes( shaderStage ) {
  38430. let snippet = '';
  38431. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38432. const attributes = this.getAttributesArray();
  38433. let location = 0;
  38434. for ( const attribute of attributes ) {
  38435. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38436. }
  38437. }
  38438. return snippet;
  38439. }
  38440. getStructMembers( struct ) {
  38441. const snippets = [];
  38442. const members = struct.getMemberTypes();
  38443. for ( let i = 0; i < members.length; i ++ ) {
  38444. const member = members[ i ];
  38445. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38446. }
  38447. return snippets.join( '\n' );
  38448. }
  38449. getStructs( shaderStage ) {
  38450. const snippets = [];
  38451. const structs = this.structs[ shaderStage ];
  38452. if ( structs.length === 0 ) {
  38453. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38454. }
  38455. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38456. const struct = structs[ index ];
  38457. let snippet = '\n';
  38458. snippet += this.getStructMembers( struct );
  38459. snippet += '\n';
  38460. snippets.push( snippet );
  38461. }
  38462. return snippets.join( '\n\n' );
  38463. }
  38464. getVaryings( shaderStage ) {
  38465. let snippet = '';
  38466. const varyings = this.varyings;
  38467. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38468. for ( const varying of varyings ) {
  38469. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38470. const type = varying.type;
  38471. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38472. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38473. }
  38474. } else if ( shaderStage === 'fragment' ) {
  38475. for ( const varying of varyings ) {
  38476. if ( varying.needsInterpolation ) {
  38477. const type = varying.type;
  38478. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38479. snippet += `${flat}in ${type} ${varying.name};\n`;
  38480. }
  38481. }
  38482. }
  38483. return snippet;
  38484. }
  38485. getVertexIndex() {
  38486. return 'uint( gl_VertexID )';
  38487. }
  38488. getInstanceIndex() {
  38489. return 'uint( gl_InstanceID )';
  38490. }
  38491. getDrawIndex() {
  38492. const extensions = this.renderer.backend.extensions;
  38493. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38494. return 'uint( gl_DrawID )';
  38495. }
  38496. return null;
  38497. }
  38498. getFrontFacing() {
  38499. return 'gl_FrontFacing';
  38500. }
  38501. getFragCoord() {
  38502. return 'gl_FragCoord';
  38503. }
  38504. getFragDepth() {
  38505. return 'gl_FragDepth';
  38506. }
  38507. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38508. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38509. if ( map.has( name ) === false ) {
  38510. map.set( name, {
  38511. name,
  38512. behavior
  38513. } );
  38514. }
  38515. }
  38516. getExtensions( shaderStage ) {
  38517. const snippets = [];
  38518. if ( shaderStage === 'vertex' ) {
  38519. const ext = this.renderer.backend.extensions;
  38520. const isBatchedMesh = this.object.isBatchedMesh;
  38521. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38522. this.enableExtension( 'GL_ANGLE_multi_draw', 'require' );
  38523. }
  38524. }
  38525. const extensions = this.extensions[ shaderStage ];
  38526. if ( extensions !== undefined ) {
  38527. for ( const { name, behavior } of extensions.values() ) {
  38528. snippets.push( `#extension ${name} : ${behavior}` );
  38529. }
  38530. }
  38531. return snippets.join( '\n' );
  38532. }
  38533. isAvailable( name ) {
  38534. let result = supports$1[ name ];
  38535. if ( result === undefined ) {
  38536. if ( name === 'float32Filterable' ) {
  38537. const extensions = this.renderer.backend.extensions;
  38538. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38539. extensions.get( 'OES_texture_float_linear' );
  38540. result = true;
  38541. } else {
  38542. result = false;
  38543. }
  38544. }
  38545. supports$1[ name ] = result;
  38546. }
  38547. return result;
  38548. }
  38549. isFlipY() {
  38550. return true;
  38551. }
  38552. registerTransform( varyingName, attributeNode ) {
  38553. this.transforms.push( { varyingName, attributeNode } );
  38554. }
  38555. getTransforms( /* shaderStage */ ) {
  38556. const transforms = this.transforms;
  38557. let snippet = '';
  38558. for ( let i = 0; i < transforms.length; i ++ ) {
  38559. const transform = transforms[ i ];
  38560. const attributeName = this.getPropertyName( transform.attributeNode );
  38561. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38562. }
  38563. return snippet;
  38564. }
  38565. _getGLSLUniformStruct( name, vars ) {
  38566. return `
  38567. layout( std140 ) uniform ${name} {
  38568. ${vars}
  38569. };`;
  38570. }
  38571. _getGLSLVertexCode( shaderData ) {
  38572. return `#version 300 es
  38573. // extensions
  38574. ${shaderData.extensions}
  38575. // precision
  38576. ${ defaultPrecisions }
  38577. // uniforms
  38578. ${shaderData.uniforms}
  38579. // varyings
  38580. ${shaderData.varyings}
  38581. // attributes
  38582. ${shaderData.attributes}
  38583. // codes
  38584. ${shaderData.codes}
  38585. void main() {
  38586. // vars
  38587. ${shaderData.vars}
  38588. // transforms
  38589. ${shaderData.transforms}
  38590. // flow
  38591. ${shaderData.flow}
  38592. gl_PointSize = 1.0;
  38593. }
  38594. `;
  38595. }
  38596. _getGLSLFragmentCode( shaderData ) {
  38597. return `#version 300 es
  38598. ${ this.getSignature() }
  38599. // precision
  38600. ${ defaultPrecisions }
  38601. // uniforms
  38602. ${shaderData.uniforms}
  38603. // varyings
  38604. ${shaderData.varyings}
  38605. // codes
  38606. ${shaderData.codes}
  38607. ${shaderData.structs}
  38608. void main() {
  38609. // vars
  38610. ${shaderData.vars}
  38611. // flow
  38612. ${shaderData.flow}
  38613. }
  38614. `;
  38615. }
  38616. buildCode() {
  38617. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38618. for ( const shaderStage in shadersData ) {
  38619. let flow = '// code\n\n';
  38620. flow += this.flowCode[ shaderStage ];
  38621. const flowNodes = this.flowNodes[ shaderStage ];
  38622. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38623. for ( const node of flowNodes ) {
  38624. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38625. const slotName = node.name;
  38626. if ( slotName ) {
  38627. if ( flow.length > 0 ) flow += '\n';
  38628. flow += `\t// flow -> ${ slotName }\n\t`;
  38629. }
  38630. flow += `${ flowSlotData.code }\n\t`;
  38631. if ( node === mainNode && shaderStage !== 'compute' ) {
  38632. flow += '// result\n\t';
  38633. if ( shaderStage === 'vertex' ) {
  38634. flow += 'gl_Position = ';
  38635. flow += `${ flowSlotData.result };`;
  38636. } else if ( shaderStage === 'fragment' ) {
  38637. if ( ! node.outputNode.isOutputStructNode ) {
  38638. flow += 'fragColor = ';
  38639. flow += `${ flowSlotData.result };`;
  38640. }
  38641. }
  38642. }
  38643. }
  38644. const stageData = shadersData[ shaderStage ];
  38645. stageData.extensions = this.getExtensions( shaderStage );
  38646. stageData.uniforms = this.getUniforms( shaderStage );
  38647. stageData.attributes = this.getAttributes( shaderStage );
  38648. stageData.varyings = this.getVaryings( shaderStage );
  38649. stageData.vars = this.getVars( shaderStage );
  38650. stageData.structs = this.getStructs( shaderStage );
  38651. stageData.codes = this.getCodes( shaderStage );
  38652. stageData.transforms = this.getTransforms( shaderStage );
  38653. stageData.flow = flow;
  38654. }
  38655. if ( this.material !== null ) {
  38656. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38657. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38658. } else {
  38659. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38660. }
  38661. }
  38662. getUniformFromNode( node, type, shaderStage, name = null ) {
  38663. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38664. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38665. let uniformGPU = nodeData.uniformGPU;
  38666. if ( uniformGPU === undefined ) {
  38667. const group = node.groupNode;
  38668. const groupName = group.name;
  38669. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38670. if ( type === 'texture' ) {
  38671. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38672. bindings.push( uniformGPU );
  38673. } else if ( type === 'cubeTexture' ) {
  38674. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38675. bindings.push( uniformGPU );
  38676. } else if ( type === 'texture3D' ) {
  38677. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38678. bindings.push( uniformGPU );
  38679. } else if ( type === 'buffer' ) {
  38680. node.name = `NodeBuffer_${ node.id }`;
  38681. uniformNode.name = `buffer${ node.id }`;
  38682. const buffer = new NodeUniformBuffer( node, group );
  38683. buffer.name = node.name;
  38684. bindings.push( buffer );
  38685. uniformGPU = buffer;
  38686. } else {
  38687. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38688. let uniformsGroup = uniformsStage[ groupName ];
  38689. if ( uniformsGroup === undefined ) {
  38690. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38691. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38692. uniformsStage[ groupName ] = uniformsGroup;
  38693. bindings.push( uniformsGroup );
  38694. }
  38695. uniformGPU = this.getNodeUniform( uniformNode, type );
  38696. uniformsGroup.addUniform( uniformGPU );
  38697. }
  38698. nodeData.uniformGPU = uniformGPU;
  38699. }
  38700. return uniformNode;
  38701. }
  38702. }
  38703. let vector2 = null;
  38704. let vector4 = null;
  38705. let color4 = null;
  38706. class Backend {
  38707. constructor( parameters = {} ) {
  38708. this.parameters = Object.assign( {}, parameters );
  38709. this.data = new WeakMap();
  38710. this.renderer = null;
  38711. this.domElement = null;
  38712. }
  38713. async init( renderer ) {
  38714. this.renderer = renderer;
  38715. }
  38716. // render context
  38717. begin( /*renderContext*/ ) { }
  38718. finish( /*renderContext*/ ) { }
  38719. // render object
  38720. draw( /*renderObject, info*/ ) { }
  38721. // program
  38722. createProgram( /*program*/ ) { }
  38723. destroyProgram( /*program*/ ) { }
  38724. // bindings
  38725. createBindings( /*renderObject*/ ) { }
  38726. updateBindings( /*renderObject*/ ) { }
  38727. // pipeline
  38728. createRenderPipeline( /*renderObject*/ ) { }
  38729. createComputePipeline( /*computeNode, pipeline*/ ) { }
  38730. destroyPipeline( /*pipeline*/ ) { }
  38731. // cache key
  38732. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  38733. getRenderCacheKey( /*renderObject*/ ) { } // return String
  38734. // node builder
  38735. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  38736. // textures
  38737. createSampler( /*texture*/ ) { }
  38738. createDefaultTexture( /*texture*/ ) { }
  38739. createTexture( /*texture*/ ) { }
  38740. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  38741. // attributes
  38742. createAttribute( /*attribute*/ ) { }
  38743. createIndexAttribute( /*attribute*/ ) { }
  38744. updateAttribute( /*attribute*/ ) { }
  38745. destroyAttribute( /*attribute*/ ) { }
  38746. // canvas
  38747. getContext() { }
  38748. updateSize() { }
  38749. // utils
  38750. resolveTimestampAsync( /*renderContext, type*/ ) { }
  38751. hasFeatureAsync( /*name*/ ) { } // return Boolean
  38752. hasFeature( /*name*/ ) { } // return Boolean
  38753. getInstanceCount( renderObject ) {
  38754. const { object, geometry } = renderObject;
  38755. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  38756. }
  38757. getDrawingBufferSize() {
  38758. vector2 = vector2 || new Vector2();
  38759. return this.renderer.getDrawingBufferSize( vector2 );
  38760. }
  38761. getScissor() {
  38762. vector4 = vector4 || new Vector4();
  38763. return this.renderer.getScissor( vector4 );
  38764. }
  38765. setScissorTest( /*boolean*/ ) { }
  38766. getClearColor() {
  38767. const renderer = this.renderer;
  38768. color4 = color4 || new Color4();
  38769. renderer.getClearColor( color4 );
  38770. color4.getRGB( color4, this.renderer.currentColorSpace );
  38771. return color4;
  38772. }
  38773. getDomElement() {
  38774. let domElement = this.domElement;
  38775. if ( domElement === null ) {
  38776. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38777. // OffscreenCanvas does not have setAttribute, see #22811
  38778. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38779. this.domElement = domElement;
  38780. }
  38781. return domElement;
  38782. }
  38783. // resource properties
  38784. set( object, value ) {
  38785. this.data.set( object, value );
  38786. }
  38787. get( object ) {
  38788. let map = this.data.get( object );
  38789. if ( map === undefined ) {
  38790. map = {};
  38791. this.data.set( object, map );
  38792. }
  38793. return map;
  38794. }
  38795. has( object ) {
  38796. return this.data.has( object );
  38797. }
  38798. delete( object ) {
  38799. this.data.delete( object );
  38800. }
  38801. }
  38802. let _id$1 = 0;
  38803. class DualAttributeData {
  38804. constructor( attributeData, dualBuffer ) {
  38805. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38806. this.type = attributeData.type;
  38807. this.bufferType = attributeData.bufferType;
  38808. this.pbo = attributeData.pbo;
  38809. this.byteLength = attributeData.byteLength;
  38810. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38811. this.version = attributeData.version;
  38812. this.isInteger = attributeData.isInteger;
  38813. this.activeBufferIndex = 0;
  38814. this.baseId = attributeData.id;
  38815. }
  38816. get id() {
  38817. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38818. }
  38819. get bufferGPU() {
  38820. return this.buffers[ this.activeBufferIndex ];
  38821. }
  38822. get transformBuffer() {
  38823. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38824. }
  38825. switchBuffers() {
  38826. this.activeBufferIndex ^= 1;
  38827. }
  38828. }
  38829. class WebGLAttributeUtils {
  38830. constructor( backend ) {
  38831. this.backend = backend;
  38832. }
  38833. createAttribute( attribute, bufferType ) {
  38834. const backend = this.backend;
  38835. const { gl } = backend;
  38836. const array = attribute.array;
  38837. const usage = attribute.usage || gl.STATIC_DRAW;
  38838. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38839. const bufferData = backend.get( bufferAttribute );
  38840. let bufferGPU = bufferData.bufferGPU;
  38841. if ( bufferGPU === undefined ) {
  38842. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38843. bufferData.bufferGPU = bufferGPU;
  38844. bufferData.bufferType = bufferType;
  38845. bufferData.version = bufferAttribute.version;
  38846. }
  38847. //attribute.onUploadCallback();
  38848. let type;
  38849. if ( array instanceof Float32Array ) {
  38850. type = gl.FLOAT;
  38851. } else if ( array instanceof Uint16Array ) {
  38852. if ( attribute.isFloat16BufferAttribute ) {
  38853. type = gl.HALF_FLOAT;
  38854. } else {
  38855. type = gl.UNSIGNED_SHORT;
  38856. }
  38857. } else if ( array instanceof Int16Array ) {
  38858. type = gl.SHORT;
  38859. } else if ( array instanceof Uint32Array ) {
  38860. type = gl.UNSIGNED_INT;
  38861. } else if ( array instanceof Int32Array ) {
  38862. type = gl.INT;
  38863. } else if ( array instanceof Int8Array ) {
  38864. type = gl.BYTE;
  38865. } else if ( array instanceof Uint8Array ) {
  38866. type = gl.UNSIGNED_BYTE;
  38867. } else if ( array instanceof Uint8ClampedArray ) {
  38868. type = gl.UNSIGNED_BYTE;
  38869. } else {
  38870. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38871. }
  38872. let attributeData = {
  38873. bufferGPU,
  38874. bufferType,
  38875. type,
  38876. byteLength: array.byteLength,
  38877. bytesPerElement: array.BYTES_PER_ELEMENT,
  38878. version: attribute.version,
  38879. pbo: attribute.pbo,
  38880. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38881. id: _id$1 ++
  38882. };
  38883. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38884. // create buffer for tranform feedback use
  38885. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38886. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38887. }
  38888. backend.set( attribute, attributeData );
  38889. }
  38890. updateAttribute( attribute ) {
  38891. const backend = this.backend;
  38892. const { gl } = backend;
  38893. const array = attribute.array;
  38894. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38895. const bufferData = backend.get( bufferAttribute );
  38896. const bufferType = bufferData.bufferType;
  38897. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38898. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38899. if ( updateRanges.length === 0 ) {
  38900. // Not using update ranges
  38901. gl.bufferSubData( bufferType, 0, array );
  38902. } else {
  38903. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38904. const range = updateRanges[ i ];
  38905. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38906. array, range.start, range.count );
  38907. }
  38908. bufferAttribute.clearUpdateRanges();
  38909. }
  38910. gl.bindBuffer( bufferType, null );
  38911. bufferData.version = bufferAttribute.version;
  38912. }
  38913. destroyAttribute( attribute ) {
  38914. const backend = this.backend;
  38915. const { gl } = backend;
  38916. if ( attribute.isInterleavedBufferAttribute ) {
  38917. backend.delete( attribute.data );
  38918. }
  38919. const attributeData = backend.get( attribute );
  38920. gl.deleteBuffer( attributeData.bufferGPU );
  38921. backend.delete( attribute );
  38922. }
  38923. async getArrayBufferAsync( attribute ) {
  38924. const backend = this.backend;
  38925. const { gl } = backend;
  38926. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38927. const { bufferGPU } = backend.get( bufferAttribute );
  38928. const array = attribute.array;
  38929. const byteLength = array.byteLength;
  38930. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38931. const writeBuffer = gl.createBuffer();
  38932. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38933. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38934. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38935. await backend.utils._clientWaitAsync();
  38936. const dstBuffer = new attribute.array.constructor( array.length );
  38937. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38938. gl.deleteBuffer( writeBuffer );
  38939. return dstBuffer.buffer;
  38940. }
  38941. _createBuffer( gl, bufferType, array, usage ) {
  38942. const bufferGPU = gl.createBuffer();
  38943. gl.bindBuffer( bufferType, bufferGPU );
  38944. gl.bufferData( bufferType, array, usage );
  38945. gl.bindBuffer( bufferType, null );
  38946. return bufferGPU;
  38947. }
  38948. }
  38949. let initialized$1 = false, equationToGL, factorToGL;
  38950. class WebGLState {
  38951. constructor( backend ) {
  38952. this.backend = backend;
  38953. this.gl = this.backend.gl;
  38954. this.enabled = {};
  38955. this.currentFlipSided = null;
  38956. this.currentCullFace = null;
  38957. this.currentProgram = null;
  38958. this.currentBlendingEnabled = false;
  38959. this.currentBlending = null;
  38960. this.currentBlendSrc = null;
  38961. this.currentBlendDst = null;
  38962. this.currentBlendSrcAlpha = null;
  38963. this.currentBlendDstAlpha = null;
  38964. this.currentPremultipledAlpha = null;
  38965. this.currentPolygonOffsetFactor = null;
  38966. this.currentPolygonOffsetUnits = null;
  38967. this.currentColorMask = null;
  38968. this.currentDepthFunc = null;
  38969. this.currentDepthMask = null;
  38970. this.currentStencilFunc = null;
  38971. this.currentStencilRef = null;
  38972. this.currentStencilFuncMask = null;
  38973. this.currentStencilFail = null;
  38974. this.currentStencilZFail = null;
  38975. this.currentStencilZPass = null;
  38976. this.currentStencilMask = null;
  38977. this.currentLineWidth = null;
  38978. this.currentBoundFramebuffers = {};
  38979. this.currentDrawbuffers = new WeakMap();
  38980. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38981. this.currentTextureSlot = null;
  38982. this.currentBoundTextures = {};
  38983. if ( initialized$1 === false ) {
  38984. this._init( this.gl );
  38985. initialized$1 = true;
  38986. }
  38987. }
  38988. _init( gl ) {
  38989. // Store only WebGL constants here.
  38990. equationToGL = {
  38991. [ AddEquation ]: gl.FUNC_ADD,
  38992. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38993. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38994. };
  38995. factorToGL = {
  38996. [ ZeroFactor ]: gl.ZERO,
  38997. [ OneFactor ]: gl.ONE,
  38998. [ SrcColorFactor ]: gl.SRC_COLOR,
  38999. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39000. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39001. [ DstColorFactor ]: gl.DST_COLOR,
  39002. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39003. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39004. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39005. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39006. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39007. };
  39008. }
  39009. enable( id ) {
  39010. const { enabled } = this;
  39011. if ( enabled[ id ] !== true ) {
  39012. this.gl.enable( id );
  39013. enabled[ id ] = true;
  39014. }
  39015. }
  39016. disable( id ) {
  39017. const { enabled } = this;
  39018. if ( enabled[ id ] !== false ) {
  39019. this.gl.disable( id );
  39020. enabled[ id ] = false;
  39021. }
  39022. }
  39023. setFlipSided( flipSided ) {
  39024. if ( this.currentFlipSided !== flipSided ) {
  39025. const { gl } = this;
  39026. if ( flipSided ) {
  39027. gl.frontFace( gl.CW );
  39028. } else {
  39029. gl.frontFace( gl.CCW );
  39030. }
  39031. this.currentFlipSided = flipSided;
  39032. }
  39033. }
  39034. setCullFace( cullFace ) {
  39035. const { gl } = this;
  39036. if ( cullFace !== CullFaceNone ) {
  39037. this.enable( gl.CULL_FACE );
  39038. if ( cullFace !== this.currentCullFace ) {
  39039. if ( cullFace === CullFaceBack ) {
  39040. gl.cullFace( gl.BACK );
  39041. } else if ( cullFace === CullFaceFront ) {
  39042. gl.cullFace( gl.FRONT );
  39043. } else {
  39044. gl.cullFace( gl.FRONT_AND_BACK );
  39045. }
  39046. }
  39047. } else {
  39048. this.disable( gl.CULL_FACE );
  39049. }
  39050. this.currentCullFace = cullFace;
  39051. }
  39052. setLineWidth( width ) {
  39053. const { currentLineWidth, gl } = this;
  39054. if ( width !== currentLineWidth ) {
  39055. gl.lineWidth( width );
  39056. this.currentLineWidth = width;
  39057. }
  39058. }
  39059. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39060. const { gl } = this;
  39061. if ( blending === NoBlending ) {
  39062. if ( this.currentBlendingEnabled === true ) {
  39063. this.disable( gl.BLEND );
  39064. this.currentBlendingEnabled = false;
  39065. }
  39066. return;
  39067. }
  39068. if ( this.currentBlendingEnabled === false ) {
  39069. this.enable( gl.BLEND );
  39070. this.currentBlendingEnabled = true;
  39071. }
  39072. if ( blending !== CustomBlending ) {
  39073. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39074. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39075. gl.blendEquation( gl.FUNC_ADD );
  39076. this.currentBlendEquation = AddEquation;
  39077. this.currentBlendEquationAlpha = AddEquation;
  39078. }
  39079. if ( premultipliedAlpha ) {
  39080. switch ( blending ) {
  39081. case NormalBlending:
  39082. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39083. break;
  39084. case AdditiveBlending:
  39085. gl.blendFunc( gl.ONE, gl.ONE );
  39086. break;
  39087. case SubtractiveBlending:
  39088. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39089. break;
  39090. case MultiplyBlending:
  39091. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39092. break;
  39093. default:
  39094. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39095. break;
  39096. }
  39097. } else {
  39098. switch ( blending ) {
  39099. case NormalBlending:
  39100. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39101. break;
  39102. case AdditiveBlending:
  39103. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39104. break;
  39105. case SubtractiveBlending:
  39106. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39107. break;
  39108. case MultiplyBlending:
  39109. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39110. break;
  39111. default:
  39112. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39113. break;
  39114. }
  39115. }
  39116. this.currentBlendSrc = null;
  39117. this.currentBlendDst = null;
  39118. this.currentBlendSrcAlpha = null;
  39119. this.currentBlendDstAlpha = null;
  39120. this.currentBlending = blending;
  39121. this.currentPremultipledAlpha = premultipliedAlpha;
  39122. }
  39123. return;
  39124. }
  39125. // custom blending
  39126. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39127. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39128. blendDstAlpha = blendDstAlpha || blendDst;
  39129. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39130. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39131. this.currentBlendEquation = blendEquation;
  39132. this.currentBlendEquationAlpha = blendEquationAlpha;
  39133. }
  39134. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39135. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39136. this.currentBlendSrc = blendSrc;
  39137. this.currentBlendDst = blendDst;
  39138. this.currentBlendSrcAlpha = blendSrcAlpha;
  39139. this.currentBlendDstAlpha = blendDstAlpha;
  39140. }
  39141. this.currentBlending = blending;
  39142. this.currentPremultipledAlpha = false;
  39143. }
  39144. setColorMask( colorMask ) {
  39145. if ( this.currentColorMask !== colorMask ) {
  39146. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39147. this.currentColorMask = colorMask;
  39148. }
  39149. }
  39150. setDepthTest( depthTest ) {
  39151. const { gl } = this;
  39152. if ( depthTest ) {
  39153. this.enable( gl.DEPTH_TEST );
  39154. } else {
  39155. this.disable( gl.DEPTH_TEST );
  39156. }
  39157. }
  39158. setDepthMask( depthMask ) {
  39159. if ( this.currentDepthMask !== depthMask ) {
  39160. this.gl.depthMask( depthMask );
  39161. this.currentDepthMask = depthMask;
  39162. }
  39163. }
  39164. setDepthFunc( depthFunc ) {
  39165. if ( this.currentDepthFunc !== depthFunc ) {
  39166. const { gl } = this;
  39167. switch ( depthFunc ) {
  39168. case NeverDepth:
  39169. gl.depthFunc( gl.NEVER );
  39170. break;
  39171. case AlwaysDepth:
  39172. gl.depthFunc( gl.ALWAYS );
  39173. break;
  39174. case LessDepth:
  39175. gl.depthFunc( gl.LESS );
  39176. break;
  39177. case LessEqualDepth:
  39178. gl.depthFunc( gl.LEQUAL );
  39179. break;
  39180. case EqualDepth:
  39181. gl.depthFunc( gl.EQUAL );
  39182. break;
  39183. case GreaterEqualDepth:
  39184. gl.depthFunc( gl.GEQUAL );
  39185. break;
  39186. case GreaterDepth:
  39187. gl.depthFunc( gl.GREATER );
  39188. break;
  39189. case NotEqualDepth:
  39190. gl.depthFunc( gl.NOTEQUAL );
  39191. break;
  39192. default:
  39193. gl.depthFunc( gl.LEQUAL );
  39194. }
  39195. this.currentDepthFunc = depthFunc;
  39196. }
  39197. }
  39198. setStencilTest( stencilTest ) {
  39199. const { gl } = this;
  39200. if ( stencilTest ) {
  39201. this.enable( gl.STENCIL_TEST );
  39202. } else {
  39203. this.disable( gl.STENCIL_TEST );
  39204. }
  39205. }
  39206. setStencilMask( stencilMask ) {
  39207. if ( this.currentStencilMask !== stencilMask ) {
  39208. this.gl.stencilMask( stencilMask );
  39209. this.currentStencilMask = stencilMask;
  39210. }
  39211. }
  39212. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39213. if ( this.currentStencilFunc !== stencilFunc ||
  39214. this.currentStencilRef !== stencilRef ||
  39215. this.currentStencilFuncMask !== stencilMask ) {
  39216. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39217. this.currentStencilFunc = stencilFunc;
  39218. this.currentStencilRef = stencilRef;
  39219. this.currentStencilFuncMask = stencilMask;
  39220. }
  39221. }
  39222. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39223. if ( this.currentStencilFail !== stencilFail ||
  39224. this.currentStencilZFail !== stencilZFail ||
  39225. this.currentStencilZPass !== stencilZPass ) {
  39226. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39227. this.currentStencilFail = stencilFail;
  39228. this.currentStencilZFail = stencilZFail;
  39229. this.currentStencilZPass = stencilZPass;
  39230. }
  39231. }
  39232. setMaterial( material, frontFaceCW ) {
  39233. const { gl } = this;
  39234. material.side === DoubleSide
  39235. ? this.disable( gl.CULL_FACE )
  39236. : this.enable( gl.CULL_FACE );
  39237. let flipSided = ( material.side === BackSide );
  39238. if ( frontFaceCW ) flipSided = ! flipSided;
  39239. this.setFlipSided( flipSided );
  39240. ( material.blending === NormalBlending && material.transparent === false )
  39241. ? this.setBlending( NoBlending )
  39242. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39243. this.setDepthFunc( material.depthFunc );
  39244. this.setDepthTest( material.depthTest );
  39245. this.setDepthMask( material.depthWrite );
  39246. this.setColorMask( material.colorWrite );
  39247. const stencilWrite = material.stencilWrite;
  39248. this.setStencilTest( stencilWrite );
  39249. if ( stencilWrite ) {
  39250. this.setStencilMask( material.stencilWriteMask );
  39251. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39252. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39253. }
  39254. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39255. material.alphaToCoverage === true
  39256. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39257. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39258. }
  39259. setPolygonOffset( polygonOffset, factor, units ) {
  39260. const { gl } = this;
  39261. if ( polygonOffset ) {
  39262. this.enable( gl.POLYGON_OFFSET_FILL );
  39263. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39264. gl.polygonOffset( factor, units );
  39265. this.currentPolygonOffsetFactor = factor;
  39266. this.currentPolygonOffsetUnits = units;
  39267. }
  39268. } else {
  39269. this.disable( gl.POLYGON_OFFSET_FILL );
  39270. }
  39271. }
  39272. useProgram( program ) {
  39273. if ( this.currentProgram !== program ) {
  39274. this.gl.useProgram( program );
  39275. this.currentProgram = program;
  39276. return true;
  39277. }
  39278. return false;
  39279. }
  39280. // framebuffer
  39281. bindFramebuffer( target, framebuffer ) {
  39282. const { gl, currentBoundFramebuffers } = this;
  39283. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39284. gl.bindFramebuffer( target, framebuffer );
  39285. currentBoundFramebuffers[ target ] = framebuffer;
  39286. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39287. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39288. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39289. }
  39290. if ( target === gl.FRAMEBUFFER ) {
  39291. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39292. }
  39293. return true;
  39294. }
  39295. return false;
  39296. }
  39297. drawBuffers( renderContext, framebuffer ) {
  39298. const { gl } = this;
  39299. let drawBuffers = [];
  39300. let needsUpdate = false;
  39301. if ( renderContext.textures !== null ) {
  39302. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39303. if ( drawBuffers === undefined ) {
  39304. drawBuffers = [];
  39305. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39306. }
  39307. const textures = renderContext.textures;
  39308. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39309. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39310. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39311. }
  39312. drawBuffers.length = textures.length;
  39313. needsUpdate = true;
  39314. }
  39315. } else {
  39316. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39317. drawBuffers[ 0 ] = gl.BACK;
  39318. needsUpdate = true;
  39319. }
  39320. }
  39321. if ( needsUpdate ) {
  39322. gl.drawBuffers( drawBuffers );
  39323. }
  39324. }
  39325. // texture
  39326. activeTexture( webglSlot ) {
  39327. const { gl, currentTextureSlot, maxTextures } = this;
  39328. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39329. if ( currentTextureSlot !== webglSlot ) {
  39330. gl.activeTexture( webglSlot );
  39331. this.currentTextureSlot = webglSlot;
  39332. }
  39333. }
  39334. bindTexture( webglType, webglTexture, webglSlot ) {
  39335. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39336. if ( webglSlot === undefined ) {
  39337. if ( currentTextureSlot === null ) {
  39338. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39339. } else {
  39340. webglSlot = currentTextureSlot;
  39341. }
  39342. }
  39343. let boundTexture = currentBoundTextures[ webglSlot ];
  39344. if ( boundTexture === undefined ) {
  39345. boundTexture = { type: undefined, texture: undefined };
  39346. currentBoundTextures[ webglSlot ] = boundTexture;
  39347. }
  39348. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39349. if ( currentTextureSlot !== webglSlot ) {
  39350. gl.activeTexture( webglSlot );
  39351. this.currentTextureSlot = webglSlot;
  39352. }
  39353. gl.bindTexture( webglType, webglTexture );
  39354. boundTexture.type = webglType;
  39355. boundTexture.texture = webglTexture;
  39356. }
  39357. }
  39358. unbindTexture() {
  39359. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39360. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39361. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39362. gl.bindTexture( boundTexture.type, null );
  39363. boundTexture.type = undefined;
  39364. boundTexture.texture = undefined;
  39365. }
  39366. }
  39367. }
  39368. class WebGLUtils {
  39369. constructor( backend ) {
  39370. this.backend = backend;
  39371. this.gl = this.backend.gl;
  39372. this.extensions = backend.extensions;
  39373. }
  39374. convert( p, colorSpace = NoColorSpace ) {
  39375. const { gl, extensions } = this;
  39376. let extension;
  39377. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39378. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39379. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39380. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39381. if ( p === ByteType ) return gl.BYTE;
  39382. if ( p === ShortType ) return gl.SHORT;
  39383. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39384. if ( p === IntType ) return gl.INT;
  39385. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39386. if ( p === FloatType ) return gl.FLOAT;
  39387. if ( p === HalfFloatType ) {
  39388. return gl.HALF_FLOAT;
  39389. }
  39390. if ( p === AlphaFormat ) return gl.ALPHA;
  39391. if ( p === RGBFormat ) return gl.RGB;
  39392. if ( p === RGBAFormat ) return gl.RGBA;
  39393. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39394. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39395. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39396. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39397. // WebGL2 formats.
  39398. if ( p === RedFormat ) return gl.RED;
  39399. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39400. if ( p === RGFormat ) return gl.RG;
  39401. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39402. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39403. // S3TC
  39404. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39405. if ( colorSpace === SRGBColorSpace ) {
  39406. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39407. if ( extension !== null ) {
  39408. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39409. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39410. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39411. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39412. } else {
  39413. return null;
  39414. }
  39415. } else {
  39416. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39417. if ( extension !== null ) {
  39418. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39419. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39420. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39421. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39422. } else {
  39423. return null;
  39424. }
  39425. }
  39426. }
  39427. // PVRTC
  39428. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39429. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39430. if ( extension !== null ) {
  39431. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39432. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39433. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39434. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39435. } else {
  39436. return null;
  39437. }
  39438. }
  39439. // ETC
  39440. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39441. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39442. if ( extension !== null ) {
  39443. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39444. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39445. } else {
  39446. return null;
  39447. }
  39448. }
  39449. // ASTC
  39450. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39451. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39452. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39453. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39454. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39455. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39456. if ( extension !== null ) {
  39457. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39458. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39459. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39460. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39461. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39462. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39463. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39464. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39465. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39466. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39467. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39468. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39469. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39470. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39471. } else {
  39472. return null;
  39473. }
  39474. }
  39475. // BPTC
  39476. if ( p === RGBA_BPTC_Format ) {
  39477. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39478. if ( extension !== null ) {
  39479. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39480. } else {
  39481. return null;
  39482. }
  39483. }
  39484. // RGTC
  39485. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39486. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39487. if ( extension !== null ) {
  39488. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39489. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39490. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39491. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39492. } else {
  39493. return null;
  39494. }
  39495. }
  39496. //
  39497. if ( p === UnsignedInt248Type ) {
  39498. return gl.UNSIGNED_INT_24_8;
  39499. }
  39500. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39501. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39502. }
  39503. _clientWaitAsync() {
  39504. const { gl } = this;
  39505. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39506. gl.flush();
  39507. return new Promise( ( resolve, reject ) => {
  39508. function test() {
  39509. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39510. if ( res === gl.WAIT_FAILED ) {
  39511. gl.deleteSync( sync );
  39512. reject();
  39513. return;
  39514. }
  39515. if ( res === gl.TIMEOUT_EXPIRED ) {
  39516. requestAnimationFrame( test );
  39517. return;
  39518. }
  39519. gl.deleteSync( sync );
  39520. resolve();
  39521. }
  39522. test();
  39523. } );
  39524. }
  39525. }
  39526. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39527. class WebGLTextureUtils {
  39528. constructor( backend ) {
  39529. this.backend = backend;
  39530. this.gl = backend.gl;
  39531. this.extensions = backend.extensions;
  39532. this.defaultTextures = {};
  39533. if ( initialized === false ) {
  39534. this._init( this.gl );
  39535. initialized = true;
  39536. }
  39537. }
  39538. _init( gl ) {
  39539. // Store only WebGL constants here.
  39540. wrappingToGL = {
  39541. [ RepeatWrapping ]: gl.REPEAT,
  39542. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39543. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39544. };
  39545. filterToGL = {
  39546. [ NearestFilter ]: gl.NEAREST,
  39547. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39548. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39549. [ LinearFilter ]: gl.LINEAR,
  39550. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39551. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39552. };
  39553. compareToGL = {
  39554. [ NeverCompare ]: gl.NEVER,
  39555. [ AlwaysCompare ]: gl.ALWAYS,
  39556. [ LessCompare ]: gl.LESS,
  39557. [ LessEqualCompare ]: gl.LEQUAL,
  39558. [ EqualCompare ]: gl.EQUAL,
  39559. [ GreaterEqualCompare ]: gl.GEQUAL,
  39560. [ GreaterCompare ]: gl.GREATER,
  39561. [ NotEqualCompare ]: gl.NOTEQUAL
  39562. };
  39563. }
  39564. filterFallback( f ) {
  39565. const { gl } = this;
  39566. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  39567. return gl.NEAREST;
  39568. }
  39569. return gl.LINEAR;
  39570. }
  39571. getGLTextureType( texture ) {
  39572. const { gl } = this;
  39573. let glTextureType;
  39574. if ( texture.isCubeTexture === true ) {
  39575. glTextureType = gl.TEXTURE_CUBE_MAP;
  39576. } else if ( texture.isDataArrayTexture === true ) {
  39577. glTextureType = gl.TEXTURE_2D_ARRAY;
  39578. } else if ( texture.isData3DTexture === true ) {
  39579. glTextureType = gl.TEXTURE_3D;
  39580. } else {
  39581. glTextureType = gl.TEXTURE_2D;
  39582. }
  39583. return glTextureType;
  39584. }
  39585. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39586. const { gl, extensions } = this;
  39587. if ( internalFormatName !== null ) {
  39588. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39589. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39590. }
  39591. let internalFormat = glFormat;
  39592. if ( glFormat === gl.RED ) {
  39593. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39594. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39595. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39596. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39597. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39598. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39599. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39600. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39601. }
  39602. if ( glFormat === gl.RED_INTEGER ) {
  39603. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39604. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39605. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39606. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39607. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39608. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39609. }
  39610. if ( glFormat === gl.RG ) {
  39611. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39612. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39613. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39614. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39615. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39616. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39617. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39618. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39619. }
  39620. if ( glFormat === gl.RG_INTEGER ) {
  39621. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39622. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39623. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39624. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39625. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39626. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39627. }
  39628. if ( glFormat === gl.RGB ) {
  39629. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39630. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39631. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39632. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39633. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39634. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39635. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39636. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39637. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39638. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39639. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39640. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39641. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39642. }
  39643. if ( glFormat === gl.RGB_INTEGER ) {
  39644. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39645. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39646. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39647. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39648. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39649. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39650. }
  39651. if ( glFormat === gl.RGBA ) {
  39652. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39653. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39654. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39655. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39656. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39657. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39658. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39659. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39660. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39661. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39662. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39663. }
  39664. if ( glFormat === gl.RGBA_INTEGER ) {
  39665. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39666. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39667. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39668. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39669. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39670. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39671. }
  39672. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39673. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39674. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39675. }
  39676. if ( glFormat === gl.DEPTH_STENCIL ) {
  39677. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39678. }
  39679. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39680. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39681. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39682. extensions.get( 'EXT_color_buffer_float' );
  39683. }
  39684. return internalFormat;
  39685. }
  39686. setTextureParameters( textureType, texture ) {
  39687. const { gl, extensions, backend } = this;
  39688. const { currentAnisotropy } = backend.get( texture );
  39689. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39690. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39691. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39692. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39693. }
  39694. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39695. // follow WebGPU backend mapping for texture filtering
  39696. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  39697. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39698. if ( texture.compareFunction ) {
  39699. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39700. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39701. }
  39702. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39703. if ( texture.magFilter === NearestFilter ) return;
  39704. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39705. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39706. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  39707. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39708. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39709. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  39710. }
  39711. }
  39712. }
  39713. createDefaultTexture( texture ) {
  39714. const { gl, backend, defaultTextures } = this;
  39715. const glTextureType = this.getGLTextureType( texture );
  39716. let textureGPU = defaultTextures[ glTextureType ];
  39717. if ( textureGPU === undefined ) {
  39718. textureGPU = gl.createTexture();
  39719. backend.state.bindTexture( glTextureType, textureGPU );
  39720. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39721. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39722. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39723. defaultTextures[ glTextureType ] = textureGPU;
  39724. }
  39725. backend.set( texture, {
  39726. textureGPU,
  39727. glTextureType,
  39728. isDefault: true
  39729. } );
  39730. }
  39731. createTexture( texture, options ) {
  39732. const { gl, backend } = this;
  39733. const { levels, width, height, depth } = options;
  39734. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39735. const glType = backend.utils.convert( texture.type );
  39736. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39737. const textureGPU = gl.createTexture();
  39738. const glTextureType = this.getGLTextureType( texture );
  39739. backend.state.bindTexture( glTextureType, textureGPU );
  39740. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39741. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39742. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39743. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39744. this.setTextureParameters( glTextureType, texture );
  39745. if ( texture.isDataArrayTexture ) {
  39746. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39747. } else if ( texture.isData3DTexture ) {
  39748. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39749. } else if ( ! texture.isVideoTexture ) {
  39750. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39751. }
  39752. backend.set( texture, {
  39753. textureGPU,
  39754. glTextureType,
  39755. glFormat,
  39756. glType,
  39757. glInternalFormat
  39758. } );
  39759. }
  39760. copyBufferToTexture( buffer, texture ) {
  39761. const { gl, backend } = this;
  39762. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39763. const { width, height } = texture.source.data;
  39764. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39765. backend.state.bindTexture( glTextureType, textureGPU );
  39766. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39767. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39768. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39769. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39770. backend.state.unbindTexture();
  39771. // debug
  39772. // const framebuffer = gl.createFramebuffer();
  39773. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39774. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39775. // const readout = new Float32Array( width * height * 4 );
  39776. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39777. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39778. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39779. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39780. // console.log( readout );
  39781. }
  39782. updateTexture( texture, options ) {
  39783. const { gl } = this;
  39784. const { width, height } = options;
  39785. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39786. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39787. return;
  39788. const getImage = ( source ) => {
  39789. if ( source.isDataTexture ) {
  39790. return source.image.data;
  39791. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  39792. return source;
  39793. }
  39794. return source.data;
  39795. };
  39796. this.backend.state.bindTexture( glTextureType, textureGPU );
  39797. if ( texture.isCompressedTexture ) {
  39798. const mipmaps = texture.mipmaps;
  39799. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39800. const mipmap = mipmaps[ i ];
  39801. if ( texture.isCompressedArrayTexture ) {
  39802. const image = options.image;
  39803. if ( texture.format !== gl.RGBA ) {
  39804. if ( glFormat !== null ) {
  39805. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  39806. } else {
  39807. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39808. }
  39809. } else {
  39810. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39811. }
  39812. } else {
  39813. if ( glFormat !== null ) {
  39814. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39815. } else {
  39816. console.warn( 'Unsupported compressed texture format' );
  39817. }
  39818. }
  39819. }
  39820. } else if ( texture.isCubeTexture ) {
  39821. const images = options.images;
  39822. for ( let i = 0; i < 6; i ++ ) {
  39823. const image = getImage( images[ i ] );
  39824. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39825. }
  39826. } else if ( texture.isDataArrayTexture ) {
  39827. const image = options.image;
  39828. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39829. } else if ( texture.isData3DTexture ) {
  39830. const image = options.image;
  39831. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39832. } else if ( texture.isVideoTexture ) {
  39833. texture.update();
  39834. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39835. } else {
  39836. const image = getImage( options.image );
  39837. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39838. }
  39839. }
  39840. generateMipmaps( texture ) {
  39841. const { gl, backend } = this;
  39842. const { textureGPU, glTextureType } = backend.get( texture );
  39843. backend.state.bindTexture( glTextureType, textureGPU );
  39844. gl.generateMipmap( glTextureType );
  39845. }
  39846. deallocateRenderBuffers( renderTarget ) {
  39847. const { gl, backend } = this;
  39848. // remove framebuffer reference
  39849. if ( renderTarget ) {
  39850. const renderContextData = backend.get( renderTarget );
  39851. renderContextData.renderBufferStorageSetup = undefined;
  39852. if ( renderContextData.framebuffer ) {
  39853. gl.deleteFramebuffer( renderContextData.framebuffer );
  39854. renderContextData.framebuffer = undefined;
  39855. }
  39856. if ( renderContextData.depthRenderbuffer ) {
  39857. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39858. renderContextData.depthRenderbuffer = undefined;
  39859. }
  39860. if ( renderContextData.stencilRenderbuffer ) {
  39861. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39862. renderContextData.stencilRenderbuffer = undefined;
  39863. }
  39864. if ( renderContextData.msaaFrameBuffer ) {
  39865. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39866. renderContextData.msaaFrameBuffer = undefined;
  39867. }
  39868. if ( renderContextData.msaaRenderbuffers ) {
  39869. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39870. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39871. }
  39872. renderContextData.msaaRenderbuffers = undefined;
  39873. }
  39874. }
  39875. }
  39876. destroyTexture( texture ) {
  39877. const { gl, backend } = this;
  39878. const { textureGPU, renderTarget } = backend.get( texture );
  39879. this.deallocateRenderBuffers( renderTarget );
  39880. gl.deleteTexture( textureGPU );
  39881. backend.delete( texture );
  39882. }
  39883. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39884. const { gl, backend } = this;
  39885. const { state } = this.backend;
  39886. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39887. let width, height, minX, minY;
  39888. let dstX, dstY;
  39889. if ( srcRegion !== null ) {
  39890. width = srcRegion.max.x - srcRegion.min.x;
  39891. height = srcRegion.max.y - srcRegion.min.y;
  39892. minX = srcRegion.min.x;
  39893. minY = srcRegion.min.y;
  39894. } else {
  39895. width = srcTexture.image.width;
  39896. height = srcTexture.image.height;
  39897. minX = 0;
  39898. minY = 0;
  39899. }
  39900. if ( dstPosition !== null ) {
  39901. dstX = dstPosition.x;
  39902. dstY = dstPosition.y;
  39903. } else {
  39904. dstX = 0;
  39905. dstY = 0;
  39906. }
  39907. state.bindTexture( glTextureType, dstTextureGPU );
  39908. // As another texture upload may have changed pixelStorei
  39909. // parameters, make sure they are correct for the dstTexture
  39910. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39911. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39912. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39913. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39914. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39915. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39916. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39917. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39918. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39919. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39920. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39921. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39922. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39923. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39924. if ( srcTexture.isDataTexture ) {
  39925. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39926. } else {
  39927. if ( srcTexture.isCompressedTexture ) {
  39928. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39929. } else {
  39930. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39931. }
  39932. }
  39933. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39934. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39935. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39936. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39937. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39938. // Generate mipmaps only when copying level 0
  39939. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39940. state.unbindTexture();
  39941. }
  39942. copyFramebufferToTexture( texture, renderContext ) {
  39943. const { gl } = this;
  39944. const { state } = this.backend;
  39945. const { textureGPU } = this.backend.get( texture );
  39946. const width = texture.image.width;
  39947. const height = texture.image.height;
  39948. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39949. if ( requireDrawFrameBuffer ) {
  39950. let mask;
  39951. let attachment;
  39952. if ( texture.isDepthTexture === true ) {
  39953. mask = gl.DEPTH_BUFFER_BIT;
  39954. attachment = gl.DEPTH_ATTACHMENT;
  39955. if ( renderContext.stencil ) {
  39956. mask |= gl.STENCIL_BUFFER_BIT;
  39957. }
  39958. } else {
  39959. mask = gl.COLOR_BUFFER_BIT;
  39960. attachment = gl.COLOR_ATTACHMENT0;
  39961. }
  39962. const fb = gl.createFramebuffer();
  39963. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39964. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39965. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39966. gl.deleteFramebuffer( fb );
  39967. } else {
  39968. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39969. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  39970. state.unbindTexture();
  39971. }
  39972. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39973. this.backend._setFramebuffer( renderContext );
  39974. }
  39975. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  39976. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39977. const { gl } = this;
  39978. const renderTarget = renderContext.renderTarget;
  39979. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39980. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39981. if ( depthBuffer && ! stencilBuffer ) {
  39982. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39983. if ( samples > 0 ) {
  39984. if ( depthTexture && depthTexture.isDepthTexture ) {
  39985. if ( depthTexture.type === gl.FLOAT ) {
  39986. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39987. }
  39988. }
  39989. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39990. } else {
  39991. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39992. }
  39993. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39994. } else if ( depthBuffer && stencilBuffer ) {
  39995. if ( samples > 0 ) {
  39996. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39997. } else {
  39998. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39999. }
  40000. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40001. }
  40002. }
  40003. async copyTextureToBuffer( texture, x, y, width, height ) {
  40004. const { backend, gl } = this;
  40005. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40006. const fb = gl.createFramebuffer();
  40007. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40008. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  40009. const typedArrayType = this._getTypedArrayType( glType );
  40010. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  40011. const elementCount = width * height;
  40012. const byteLength = elementCount * bytesPerTexel;
  40013. const buffer = gl.createBuffer();
  40014. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40015. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40016. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40017. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40018. await backend.utils._clientWaitAsync();
  40019. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40020. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40021. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40022. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40023. gl.deleteFramebuffer( fb );
  40024. return dstBuffer;
  40025. }
  40026. _getTypedArrayType( glType ) {
  40027. const { gl } = this;
  40028. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40029. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40030. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40031. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40032. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40033. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40034. if ( glType === gl.FLOAT ) return Float32Array;
  40035. throw new Error( `Unsupported WebGL type: ${glType}` );
  40036. }
  40037. _getBytesPerTexel( glFormat ) {
  40038. const { gl } = this;
  40039. if ( glFormat === gl.RGBA ) return 4;
  40040. if ( glFormat === gl.RGB ) return 3;
  40041. if ( glFormat === gl.ALPHA ) return 1;
  40042. }
  40043. }
  40044. class WebGLExtensions {
  40045. constructor( backend ) {
  40046. this.backend = backend;
  40047. this.gl = this.backend.gl;
  40048. this.availableExtensions = this.gl.getSupportedExtensions();
  40049. this.extensions = {};
  40050. }
  40051. get( name ) {
  40052. let extension = this.extensions[ name ];
  40053. if ( extension === undefined ) {
  40054. extension = this.gl.getExtension( name );
  40055. this.extensions[ name ] = extension;
  40056. }
  40057. return extension;
  40058. }
  40059. has( name ) {
  40060. return this.availableExtensions.includes( name );
  40061. }
  40062. }
  40063. class WebGLCapabilities {
  40064. constructor( backend ) {
  40065. this.backend = backend;
  40066. this.maxAnisotropy = null;
  40067. }
  40068. getMaxAnisotropy() {
  40069. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40070. const gl = this.backend.gl;
  40071. const extensions = this.backend.extensions;
  40072. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40073. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40074. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40075. } else {
  40076. this.maxAnisotropy = 0;
  40077. }
  40078. return this.maxAnisotropy;
  40079. }
  40080. }
  40081. const GLFeatureName = {
  40082. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40083. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40084. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40085. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40086. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40087. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40088. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40089. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40090. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40091. };
  40092. class WebGLBufferRenderer {
  40093. constructor( backend ) {
  40094. this.gl = backend.gl;
  40095. this.extensions = backend.extensions;
  40096. this.info = backend.renderer.info;
  40097. this.mode = null;
  40098. this.index = 0;
  40099. this.type = null;
  40100. this.object = null;
  40101. }
  40102. render( start, count ) {
  40103. const { gl, mode, object, type, info, index } = this;
  40104. if ( index !== 0 ) {
  40105. gl.drawElements( mode, count, type, start );
  40106. } else {
  40107. gl.drawArrays( mode, start, count );
  40108. }
  40109. info.update( object, count, mode, 1 );
  40110. }
  40111. renderInstances( start, count, primcount ) {
  40112. const { gl, mode, type, index, object, info } = this;
  40113. if ( primcount === 0 ) return;
  40114. if ( index !== 0 ) {
  40115. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40116. } else {
  40117. gl.drawArraysInstanced( mode, start, count, primcount );
  40118. }
  40119. info.update( object, count, mode, primcount );
  40120. }
  40121. renderMultiDraw( starts, counts, drawCount ) {
  40122. const { extensions, mode, object, info } = this;
  40123. if ( drawCount === 0 ) return;
  40124. const extension = extensions.get( 'WEBGL_multi_draw' );
  40125. if ( extension === null ) {
  40126. for ( let i = 0; i < drawCount; i ++ ) {
  40127. this.render( starts[ i ], counts[ i ] );
  40128. }
  40129. } else {
  40130. if ( this.index !== 0 ) {
  40131. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40132. } else {
  40133. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40134. }
  40135. let elementCount = 0;
  40136. for ( let i = 0; i < drawCount; i ++ ) {
  40137. elementCount += counts[ i ];
  40138. }
  40139. info.update( object, elementCount, mode, 1 );
  40140. }
  40141. }
  40142. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40143. const { extensions, mode, object, info } = this;
  40144. if ( drawCount === 0 ) return;
  40145. const extension = extensions.get( 'WEBGL_multi_draw' );
  40146. if ( extension === null ) {
  40147. for ( let i = 0; i < drawCount; i ++ ) {
  40148. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40149. }
  40150. } else {
  40151. if ( this.index !== 0 ) {
  40152. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40153. } else {
  40154. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40155. }
  40156. let elementCount = 0;
  40157. for ( let i = 0; i < drawCount; i ++ ) {
  40158. elementCount += counts[ i ];
  40159. }
  40160. for ( let i = 0; i < primcount.length; i ++ ) {
  40161. info.update( object, elementCount, mode, primcount[ i ] );
  40162. }
  40163. }
  40164. }
  40165. //
  40166. }
  40167. //
  40168. class WebGLBackend extends Backend {
  40169. constructor( parameters = {} ) {
  40170. super( parameters );
  40171. this.isWebGLBackend = true;
  40172. }
  40173. init( renderer ) {
  40174. super.init( renderer );
  40175. //
  40176. const parameters = this.parameters;
  40177. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40178. this.gl = glContext;
  40179. this.extensions = new WebGLExtensions( this );
  40180. this.capabilities = new WebGLCapabilities( this );
  40181. this.attributeUtils = new WebGLAttributeUtils( this );
  40182. this.textureUtils = new WebGLTextureUtils( this );
  40183. this.bufferRenderer = new WebGLBufferRenderer( this );
  40184. this.state = new WebGLState( this );
  40185. this.utils = new WebGLUtils( this );
  40186. this.vaoCache = {};
  40187. this.transformFeedbackCache = {};
  40188. this.discard = false;
  40189. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40190. this.extensions.get( 'EXT_color_buffer_float' );
  40191. this.extensions.get( 'WEBGL_multi_draw' );
  40192. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40193. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40194. this._currentContext = null;
  40195. }
  40196. get coordinateSystem() {
  40197. return WebGLCoordinateSystem;
  40198. }
  40199. async getArrayBufferAsync( attribute ) {
  40200. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40201. }
  40202. initTimestampQuery( renderContext ) {
  40203. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40204. const renderContextData = this.get( renderContext );
  40205. if ( this.queryRunning ) {
  40206. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40207. renderContextData.queryQueue.push( renderContext );
  40208. return;
  40209. }
  40210. if ( renderContextData.activeQuery ) {
  40211. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40212. renderContextData.activeQuery = null;
  40213. }
  40214. renderContextData.activeQuery = this.gl.createQuery();
  40215. if ( renderContextData.activeQuery !== null ) {
  40216. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40217. this.queryRunning = true;
  40218. }
  40219. }
  40220. // timestamp utils
  40221. prepareTimestampBuffer( renderContext ) {
  40222. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40223. const renderContextData = this.get( renderContext );
  40224. if ( renderContextData.activeQuery ) {
  40225. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40226. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40227. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40228. renderContextData.activeQuery = null;
  40229. this.queryRunning = false;
  40230. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40231. const nextRenderContext = renderContextData.queryQueue.shift();
  40232. this.initTimestampQuery( nextRenderContext );
  40233. }
  40234. }
  40235. }
  40236. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40237. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40238. const renderContextData = this.get( renderContext );
  40239. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40240. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40241. const queryInfo = renderContextData.gpuQueries[ i ];
  40242. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40243. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40244. if ( available && ! disjoint ) {
  40245. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40246. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40247. this.gl.deleteQuery( queryInfo.query );
  40248. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40249. i --;
  40250. this.renderer.info.updateTimestamp( type, duration );
  40251. }
  40252. }
  40253. }
  40254. getContext() {
  40255. return this.gl;
  40256. }
  40257. beginRender( renderContext ) {
  40258. const { gl } = this;
  40259. const renderContextData = this.get( renderContext );
  40260. //
  40261. //
  40262. this.initTimestampQuery( renderContext );
  40263. renderContextData.previousContext = this._currentContext;
  40264. this._currentContext = renderContext;
  40265. this._setFramebuffer( renderContext );
  40266. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40267. //
  40268. if ( renderContext.viewport ) {
  40269. this.updateViewport( renderContext );
  40270. } else {
  40271. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40272. }
  40273. if ( renderContext.scissor ) {
  40274. const { x, y, width, height } = renderContext.scissorValue;
  40275. gl.scissor( x, y, width, height );
  40276. }
  40277. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40278. if ( occlusionQueryCount > 0 ) {
  40279. // Get a reference to the array of objects with queries. The renderContextData property
  40280. // can be changed by another render pass before the async reading of all previous queries complete
  40281. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40282. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40283. renderContextData.lastOcclusionObject = null;
  40284. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40285. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40286. renderContextData.occlusionQueryIndex = 0;
  40287. }
  40288. }
  40289. finishRender( renderContext ) {
  40290. const { gl, state } = this;
  40291. const renderContextData = this.get( renderContext );
  40292. const previousContext = renderContextData.previousContext;
  40293. const textures = renderContext.textures;
  40294. if ( textures !== null ) {
  40295. for ( let i = 0; i < textures.length; i ++ ) {
  40296. const texture = textures[ i ];
  40297. if ( texture.generateMipmaps ) {
  40298. this.generateMipmaps( texture );
  40299. }
  40300. }
  40301. }
  40302. this._currentContext = previousContext;
  40303. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40304. const renderTargetContextData = this.get( renderContext.renderTarget );
  40305. const { samples } = renderContext.renderTarget;
  40306. const fb = renderTargetContextData.framebuffer;
  40307. const mask = gl.COLOR_BUFFER_BIT;
  40308. if ( samples > 0 ) {
  40309. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40310. const textures = renderContext.textures;
  40311. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40312. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40313. for ( let i = 0; i < textures.length; i ++ ) {
  40314. // TODO Add support for MRT
  40315. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40316. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40317. }
  40318. }
  40319. }
  40320. if ( previousContext !== null ) {
  40321. this._setFramebuffer( previousContext );
  40322. if ( previousContext.viewport ) {
  40323. this.updateViewport( previousContext );
  40324. } else {
  40325. const gl = this.gl;
  40326. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40327. }
  40328. }
  40329. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40330. if ( occlusionQueryCount > 0 ) {
  40331. const renderContextData = this.get( renderContext );
  40332. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40333. const { gl } = this;
  40334. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40335. }
  40336. this.resolveOccludedAsync( renderContext );
  40337. }
  40338. this.prepareTimestampBuffer( renderContext );
  40339. }
  40340. resolveOccludedAsync( renderContext ) {
  40341. const renderContextData = this.get( renderContext );
  40342. // handle occlusion query results
  40343. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40344. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40345. const occluded = new WeakSet();
  40346. const { gl } = this;
  40347. renderContextData.currentOcclusionQueryObjects = null;
  40348. renderContextData.currentOcclusionQueries = null;
  40349. const check = () => {
  40350. let completed = 0;
  40351. // check all queries and requeue as appropriate
  40352. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40353. const query = currentOcclusionQueries[ i ];
  40354. if ( query === null ) continue;
  40355. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40356. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40357. currentOcclusionQueries[ i ] = null;
  40358. gl.deleteQuery( query );
  40359. completed ++;
  40360. }
  40361. }
  40362. if ( completed < currentOcclusionQueries.length ) {
  40363. requestAnimationFrame( check );
  40364. } else {
  40365. renderContextData.occluded = occluded;
  40366. }
  40367. };
  40368. check();
  40369. }
  40370. }
  40371. isOccluded( renderContext, object ) {
  40372. const renderContextData = this.get( renderContext );
  40373. return renderContextData.occluded && renderContextData.occluded.has( object );
  40374. }
  40375. updateViewport( renderContext ) {
  40376. const gl = this.gl;
  40377. const { x, y, width, height } = renderContext.viewportValue;
  40378. gl.viewport( x, y, width, height );
  40379. }
  40380. setScissorTest( boolean ) {
  40381. const gl = this.gl;
  40382. if ( boolean ) {
  40383. gl.enable( gl.SCISSOR_TEST );
  40384. } else {
  40385. gl.disable( gl.SCISSOR_TEST );
  40386. }
  40387. }
  40388. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40389. const { gl } = this;
  40390. if ( descriptor === null ) {
  40391. descriptor = {
  40392. textures: null,
  40393. clearColorValue: this.getClearColor()
  40394. };
  40395. }
  40396. //
  40397. let clear = 0;
  40398. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40399. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40400. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40401. if ( clear !== 0 ) {
  40402. const clearColor = descriptor.clearColorValue || this.getClearColor();
  40403. if ( depth ) this.state.setDepthMask( true );
  40404. if ( descriptor.textures === null ) {
  40405. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40406. gl.clear( clear );
  40407. } else {
  40408. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40409. if ( color ) {
  40410. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40411. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40412. }
  40413. }
  40414. if ( depth && stencil ) {
  40415. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40416. } else if ( depth ) {
  40417. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40418. } else if ( stencil ) {
  40419. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40420. }
  40421. }
  40422. }
  40423. }
  40424. beginCompute( computeGroup ) {
  40425. const gl = this.gl;
  40426. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40427. this.initTimestampQuery( computeGroup );
  40428. }
  40429. compute( computeGroup, computeNode, bindings, pipeline ) {
  40430. const gl = this.gl;
  40431. if ( ! this.discard ) {
  40432. // required here to handle async behaviour of render.compute()
  40433. gl.enable( gl.RASTERIZER_DISCARD );
  40434. this.discard = true;
  40435. }
  40436. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40437. const vaoKey = this._getVaoKey( null, attributes );
  40438. const vaoGPU = this.vaoCache[ vaoKey ];
  40439. if ( vaoGPU === undefined ) {
  40440. this._createVao( null, attributes );
  40441. } else {
  40442. gl.bindVertexArray( vaoGPU );
  40443. }
  40444. gl.useProgram( programGPU );
  40445. this._bindUniforms( bindings );
  40446. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40447. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40448. gl.beginTransformFeedback( gl.POINTS );
  40449. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40450. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40451. } else {
  40452. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40453. }
  40454. gl.endTransformFeedback();
  40455. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40456. // switch active buffers
  40457. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40458. const dualAttributeData = transformBuffers[ i ];
  40459. if ( dualAttributeData.pbo ) {
  40460. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40461. }
  40462. dualAttributeData.switchBuffers();
  40463. }
  40464. }
  40465. finishCompute( computeGroup ) {
  40466. const gl = this.gl;
  40467. this.discard = false;
  40468. gl.disable( gl.RASTERIZER_DISCARD );
  40469. this.prepareTimestampBuffer( computeGroup );
  40470. }
  40471. draw( renderObject/*, info*/ ) {
  40472. const { object, pipeline, material, context } = renderObject;
  40473. const { programGPU } = this.get( pipeline );
  40474. const { gl, state } = this;
  40475. const contextData = this.get( context );
  40476. //
  40477. this._bindUniforms( renderObject.getBindings() );
  40478. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40479. state.setMaterial( material, frontFaceCW );
  40480. gl.useProgram( programGPU );
  40481. //
  40482. let vaoGPU = renderObject.staticVao;
  40483. if ( vaoGPU === undefined ) {
  40484. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40485. vaoGPU = this.vaoCache[ vaoKey ];
  40486. if ( vaoGPU === undefined ) {
  40487. let staticVao;
  40488. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40489. if ( staticVao ) renderObject.staticVao = vaoGPU;
  40490. }
  40491. }
  40492. gl.bindVertexArray( vaoGPU );
  40493. //
  40494. const index = renderObject.getIndex();
  40495. const geometry = renderObject.geometry;
  40496. const drawRange = renderObject.drawRange;
  40497. const firstVertex = drawRange.start;
  40498. //
  40499. const lastObject = contextData.lastOcclusionObject;
  40500. if ( lastObject !== object && lastObject !== undefined ) {
  40501. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40502. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40503. contextData.occlusionQueryIndex ++;
  40504. }
  40505. if ( object.occlusionTest === true ) {
  40506. const query = gl.createQuery();
  40507. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40508. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40509. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40510. }
  40511. contextData.lastOcclusionObject = object;
  40512. }
  40513. //
  40514. const renderer = this.bufferRenderer;
  40515. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40516. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40517. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40518. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40519. else {
  40520. if ( material.wireframe === true ) {
  40521. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40522. renderer.mode = gl.LINES;
  40523. } else {
  40524. renderer.mode = gl.TRIANGLES;
  40525. }
  40526. }
  40527. //
  40528. let count;
  40529. renderer.object = object;
  40530. if ( index !== null ) {
  40531. const indexData = this.get( index );
  40532. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  40533. renderer.index = index.count;
  40534. renderer.type = indexData.type;
  40535. count = indexCount;
  40536. } else {
  40537. renderer.index = 0;
  40538. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  40539. count = vertexCount;
  40540. }
  40541. const instanceCount = this.getInstanceCount( renderObject );
  40542. if ( object.isBatchedMesh ) {
  40543. if ( object._multiDrawInstances !== null ) {
  40544. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40545. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40546. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40547. } else {
  40548. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40549. }
  40550. } else if ( instanceCount > 1 ) {
  40551. renderer.renderInstances( firstVertex, count, instanceCount );
  40552. } else {
  40553. renderer.render( firstVertex, count );
  40554. }
  40555. //
  40556. gl.bindVertexArray( null );
  40557. }
  40558. needsRenderUpdate( /*renderObject*/ ) {
  40559. return false;
  40560. }
  40561. getRenderCacheKey( renderObject ) {
  40562. return renderObject.id;
  40563. }
  40564. // textures
  40565. createDefaultTexture( texture ) {
  40566. this.textureUtils.createDefaultTexture( texture );
  40567. }
  40568. createTexture( texture, options ) {
  40569. this.textureUtils.createTexture( texture, options );
  40570. }
  40571. updateTexture( texture, options ) {
  40572. this.textureUtils.updateTexture( texture, options );
  40573. }
  40574. generateMipmaps( texture ) {
  40575. this.textureUtils.generateMipmaps( texture );
  40576. }
  40577. destroyTexture( texture ) {
  40578. this.textureUtils.destroyTexture( texture );
  40579. }
  40580. copyTextureToBuffer( texture, x, y, width, height ) {
  40581. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  40582. }
  40583. createSampler( /*texture*/ ) {
  40584. //console.warn( 'Abstract class.' );
  40585. }
  40586. destroySampler() {}
  40587. // node builder
  40588. createNodeBuilder( object, renderer ) {
  40589. return new GLSLNodeBuilder( object, renderer );
  40590. }
  40591. // program
  40592. createProgram( program ) {
  40593. const gl = this.gl;
  40594. const { stage, code } = program;
  40595. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40596. gl.shaderSource( shader, code );
  40597. gl.compileShader( shader );
  40598. this.set( program, {
  40599. shaderGPU: shader
  40600. } );
  40601. }
  40602. destroyProgram( /*program*/ ) {
  40603. console.warn( 'Abstract class.' );
  40604. }
  40605. createRenderPipeline( renderObject, promises ) {
  40606. const gl = this.gl;
  40607. const pipeline = renderObject.pipeline;
  40608. // Program
  40609. const { fragmentProgram, vertexProgram } = pipeline;
  40610. const programGPU = gl.createProgram();
  40611. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40612. const vertexShader = this.get( vertexProgram ).shaderGPU;
  40613. gl.attachShader( programGPU, fragmentShader );
  40614. gl.attachShader( programGPU, vertexShader );
  40615. gl.linkProgram( programGPU );
  40616. this.set( pipeline, {
  40617. programGPU,
  40618. fragmentShader,
  40619. vertexShader
  40620. } );
  40621. if ( promises !== null && this.parallel ) {
  40622. const p = new Promise( ( resolve /*, reject*/ ) => {
  40623. const parallel = this.parallel;
  40624. const checkStatus = () => {
  40625. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  40626. this._completeCompile( renderObject, pipeline );
  40627. resolve();
  40628. } else {
  40629. requestAnimationFrame( checkStatus );
  40630. }
  40631. };
  40632. checkStatus();
  40633. } );
  40634. promises.push( p );
  40635. return;
  40636. }
  40637. this._completeCompile( renderObject, pipeline );
  40638. }
  40639. _handleSource( string, errorLine ) {
  40640. const lines = string.split( '\n' );
  40641. const lines2 = [];
  40642. const from = Math.max( errorLine - 6, 0 );
  40643. const to = Math.min( errorLine + 6, lines.length );
  40644. for ( let i = from; i < to; i ++ ) {
  40645. const line = i + 1;
  40646. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  40647. }
  40648. return lines2.join( '\n' );
  40649. }
  40650. _getShaderErrors( gl, shader, type ) {
  40651. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  40652. const errors = gl.getShaderInfoLog( shader ).trim();
  40653. if ( status && errors === '' ) return '';
  40654. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  40655. if ( errorMatches ) {
  40656. const errorLine = parseInt( errorMatches[ 1 ] );
  40657. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  40658. } else {
  40659. return errors;
  40660. }
  40661. }
  40662. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  40663. if ( this.renderer.debug.checkShaderErrors ) {
  40664. const gl = this.gl;
  40665. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  40666. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40667. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  40668. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  40669. } else {
  40670. // default error reporting
  40671. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  40672. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  40673. console.error(
  40674. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  40675. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  40676. 'Program Info Log: ' + programLog + '\n' +
  40677. vertexErrors + '\n' +
  40678. fragmentErrors
  40679. );
  40680. }
  40681. } else if ( programLog !== '' ) {
  40682. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  40683. }
  40684. }
  40685. }
  40686. _completeCompile( renderObject, pipeline ) {
  40687. const gl = this.gl;
  40688. const pipelineData = this.get( pipeline );
  40689. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  40690. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40691. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40692. }
  40693. gl.useProgram( programGPU );
  40694. // Bindings
  40695. const bindings = renderObject.getBindings();
  40696. this._setupBindings( bindings, programGPU );
  40697. //
  40698. this.set( pipeline, {
  40699. programGPU
  40700. } );
  40701. }
  40702. createComputePipeline( computePipeline, bindings ) {
  40703. const gl = this.gl;
  40704. // Program
  40705. const fragmentProgram = {
  40706. stage: 'fragment',
  40707. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  40708. };
  40709. this.createProgram( fragmentProgram );
  40710. const { computeProgram } = computePipeline;
  40711. const programGPU = gl.createProgram();
  40712. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40713. const vertexShader = this.get( computeProgram ).shaderGPU;
  40714. const transforms = computeProgram.transforms;
  40715. const transformVaryingNames = [];
  40716. const transformAttributeNodes = [];
  40717. for ( let i = 0; i < transforms.length; i ++ ) {
  40718. const transform = transforms[ i ];
  40719. transformVaryingNames.push( transform.varyingName );
  40720. transformAttributeNodes.push( transform.attributeNode );
  40721. }
  40722. gl.attachShader( programGPU, fragmentShader );
  40723. gl.attachShader( programGPU, vertexShader );
  40724. gl.transformFeedbackVaryings(
  40725. programGPU,
  40726. transformVaryingNames,
  40727. gl.SEPARATE_ATTRIBS
  40728. );
  40729. gl.linkProgram( programGPU );
  40730. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40731. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40732. }
  40733. gl.useProgram( programGPU );
  40734. // Bindings
  40735. this.createBindings( null, bindings );
  40736. this._setupBindings( bindings, programGPU );
  40737. const attributeNodes = computeProgram.attributes;
  40738. const attributes = [];
  40739. const transformBuffers = [];
  40740. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  40741. const attribute = attributeNodes[ i ].node.attribute;
  40742. attributes.push( attribute );
  40743. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40744. }
  40745. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  40746. const attribute = transformAttributeNodes[ i ].attribute;
  40747. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40748. const attributeData = this.get( attribute );
  40749. transformBuffers.push( attributeData );
  40750. }
  40751. //
  40752. this.set( computePipeline, {
  40753. programGPU,
  40754. transformBuffers,
  40755. attributes
  40756. } );
  40757. }
  40758. createBindings( bindGroup, bindings ) {
  40759. this.updateBindings( bindGroup, bindings );
  40760. }
  40761. updateBindings( bindGroup, bindings ) {
  40762. const { gl } = this;
  40763. let groupIndex = 0;
  40764. let textureIndex = 0;
  40765. for ( const bindGroup of bindings ) {
  40766. for ( const binding of bindGroup.bindings ) {
  40767. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40768. const bufferGPU = gl.createBuffer();
  40769. const data = binding.buffer;
  40770. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40771. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40772. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  40773. this.set( binding, {
  40774. index: groupIndex ++,
  40775. bufferGPU
  40776. } );
  40777. } else if ( binding.isSampledTexture ) {
  40778. const { textureGPU, glTextureType } = this.get( binding.texture );
  40779. this.set( binding, {
  40780. index: textureIndex ++,
  40781. textureGPU,
  40782. glTextureType
  40783. } );
  40784. }
  40785. }
  40786. }
  40787. }
  40788. updateBinding( binding ) {
  40789. const gl = this.gl;
  40790. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40791. const bindingData = this.get( binding );
  40792. const bufferGPU = bindingData.bufferGPU;
  40793. const data = binding.buffer;
  40794. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40795. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40796. }
  40797. }
  40798. // attributes
  40799. createIndexAttribute( attribute ) {
  40800. const gl = this.gl;
  40801. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  40802. }
  40803. createAttribute( attribute ) {
  40804. if ( this.has( attribute ) ) return;
  40805. const gl = this.gl;
  40806. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40807. }
  40808. createStorageAttribute( attribute ) {
  40809. if ( this.has( attribute ) ) return;
  40810. const gl = this.gl;
  40811. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40812. }
  40813. updateAttribute( attribute ) {
  40814. this.attributeUtils.updateAttribute( attribute );
  40815. }
  40816. destroyAttribute( attribute ) {
  40817. this.attributeUtils.destroyAttribute( attribute );
  40818. }
  40819. updateSize() {
  40820. //console.warn( 'Abstract class.' );
  40821. }
  40822. hasFeature( name ) {
  40823. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  40824. const extensions = this.extensions;
  40825. for ( let i = 0; i < keysMatching.length; i ++ ) {
  40826. if ( extensions.has( keysMatching[ i ] ) ) return true;
  40827. }
  40828. return false;
  40829. }
  40830. getMaxAnisotropy() {
  40831. return this.capabilities.getMaxAnisotropy();
  40832. }
  40833. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  40834. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  40835. }
  40836. copyFramebufferToTexture( texture, renderContext ) {
  40837. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  40838. }
  40839. _setFramebuffer( renderContext ) {
  40840. const { gl, state } = this;
  40841. let currentFrameBuffer = null;
  40842. if ( renderContext.textures !== null ) {
  40843. const renderTarget = renderContext.renderTarget;
  40844. const renderTargetContextData = this.get( renderTarget );
  40845. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  40846. const cubeFace = this.renderer._activeCubeFace;
  40847. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  40848. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  40849. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  40850. let fb;
  40851. if ( isCube ) {
  40852. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  40853. renderTargetContextData.cubeFramebuffers = [];
  40854. }
  40855. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  40856. } else {
  40857. fb = renderTargetContextData.framebuffer;
  40858. }
  40859. if ( fb === undefined ) {
  40860. fb = gl.createFramebuffer();
  40861. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  40862. const textures = renderContext.textures;
  40863. if ( isCube ) {
  40864. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  40865. const { textureGPU } = this.get( textures[ 0 ] );
  40866. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  40867. } else {
  40868. for ( let i = 0; i < textures.length; i ++ ) {
  40869. const texture = textures[ i ];
  40870. const textureData = this.get( texture );
  40871. textureData.renderTarget = renderContext.renderTarget;
  40872. const attachment = gl.COLOR_ATTACHMENT0 + i;
  40873. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40874. }
  40875. renderTargetContextData.framebuffer = fb;
  40876. state.drawBuffers( renderContext, fb );
  40877. }
  40878. if ( renderContext.depthTexture !== null ) {
  40879. const textureData = this.get( renderContext.depthTexture );
  40880. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40881. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40882. }
  40883. }
  40884. if ( samples > 0 ) {
  40885. if ( msaaFb === undefined ) {
  40886. const invalidationArray = [];
  40887. msaaFb = gl.createFramebuffer();
  40888. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  40889. const msaaRenderbuffers = [];
  40890. const textures = renderContext.textures;
  40891. for ( let i = 0; i < textures.length; i ++ ) {
  40892. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  40893. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40894. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  40895. if ( depthBuffer ) {
  40896. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40897. invalidationArray.push( depthStyle );
  40898. }
  40899. const texture = renderContext.textures[ i ];
  40900. const textureData = this.get( texture );
  40901. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  40902. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40903. }
  40904. renderTargetContextData.msaaFrameBuffer = msaaFb;
  40905. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  40906. if ( depthRenderbuffer === undefined ) {
  40907. depthRenderbuffer = gl.createRenderbuffer();
  40908. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  40909. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  40910. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40911. invalidationArray.push( depthStyle );
  40912. }
  40913. renderTargetContextData.invalidationArray = invalidationArray;
  40914. }
  40915. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40916. } else {
  40917. currentFrameBuffer = fb;
  40918. }
  40919. }
  40920. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  40921. }
  40922. _getVaoKey( index, attributes ) {
  40923. let key = [];
  40924. if ( index !== null ) {
  40925. const indexData = this.get( index );
  40926. key += ':' + indexData.id;
  40927. }
  40928. for ( let i = 0; i < attributes.length; i ++ ) {
  40929. const attributeData = this.get( attributes[ i ] );
  40930. key += ':' + attributeData.id;
  40931. }
  40932. return key;
  40933. }
  40934. _createVao( index, attributes ) {
  40935. const { gl } = this;
  40936. const vaoGPU = gl.createVertexArray();
  40937. let key = '';
  40938. let staticVao = true;
  40939. gl.bindVertexArray( vaoGPU );
  40940. if ( index !== null ) {
  40941. const indexData = this.get( index );
  40942. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  40943. key += ':' + indexData.id;
  40944. }
  40945. for ( let i = 0; i < attributes.length; i ++ ) {
  40946. const attribute = attributes[ i ];
  40947. const attributeData = this.get( attribute );
  40948. key += ':' + attributeData.id;
  40949. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  40950. gl.enableVertexAttribArray( i );
  40951. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  40952. let stride, offset;
  40953. if ( attribute.isInterleavedBufferAttribute === true ) {
  40954. stride = attribute.data.stride * attributeData.bytesPerElement;
  40955. offset = attribute.offset * attributeData.bytesPerElement;
  40956. } else {
  40957. stride = 0;
  40958. offset = 0;
  40959. }
  40960. if ( attributeData.isInteger ) {
  40961. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  40962. } else {
  40963. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  40964. }
  40965. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  40966. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  40967. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  40968. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  40969. }
  40970. }
  40971. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  40972. this.vaoCache[ key ] = vaoGPU;
  40973. return { vaoGPU, staticVao };
  40974. }
  40975. _getTransformFeedback( transformBuffers ) {
  40976. let key = '';
  40977. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40978. key += ':' + transformBuffers[ i ].id;
  40979. }
  40980. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  40981. if ( transformFeedbackGPU !== undefined ) {
  40982. return transformFeedbackGPU;
  40983. }
  40984. const gl = this.gl;
  40985. transformFeedbackGPU = gl.createTransformFeedback();
  40986. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40987. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40988. const attributeData = transformBuffers[ i ];
  40989. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  40990. }
  40991. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40992. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  40993. return transformFeedbackGPU;
  40994. }
  40995. _setupBindings( bindings, programGPU ) {
  40996. const gl = this.gl;
  40997. for ( const bindGroup of bindings ) {
  40998. for ( const binding of bindGroup.bindings ) {
  40999. const bindingData = this.get( binding );
  41000. const index = bindingData.index;
  41001. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41002. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41003. gl.uniformBlockBinding( programGPU, location, index );
  41004. } else if ( binding.isSampledTexture ) {
  41005. const location = gl.getUniformLocation( programGPU, binding.name );
  41006. gl.uniform1i( location, index );
  41007. }
  41008. }
  41009. }
  41010. }
  41011. _bindUniforms( bindings ) {
  41012. const { gl, state } = this;
  41013. for ( const bindGroup of bindings ) {
  41014. for ( const binding of bindGroup.bindings ) {
  41015. const bindingData = this.get( binding );
  41016. const index = bindingData.index;
  41017. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41018. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41019. } else if ( binding.isSampledTexture ) {
  41020. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41021. }
  41022. }
  41023. }
  41024. }
  41025. }
  41026. class Sampler extends Binding {
  41027. constructor( name, texture ) {
  41028. super( name );
  41029. this.texture = texture;
  41030. this.version = texture ? texture.version : 0;
  41031. this.isSampler = true;
  41032. }
  41033. }
  41034. class NodeSampler extends Sampler {
  41035. constructor( name, textureNode, groupNode ) {
  41036. super( name, textureNode ? textureNode.value : null );
  41037. this.textureNode = textureNode;
  41038. this.groupNode = groupNode;
  41039. }
  41040. update() {
  41041. this.texture = this.textureNode.value;
  41042. }
  41043. }
  41044. class StorageBuffer extends Buffer {
  41045. constructor( name, attribute ) {
  41046. super( name, attribute ? attribute.array : null );
  41047. this.attribute = attribute;
  41048. this.isStorageBuffer = true;
  41049. }
  41050. }
  41051. let _id = 0;
  41052. class NodeStorageBuffer extends StorageBuffer {
  41053. constructor( nodeUniform, groupNode ) {
  41054. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41055. this.nodeUniform = nodeUniform;
  41056. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41057. this.groupNode = groupNode;
  41058. }
  41059. get buffer() {
  41060. return this.nodeUniform.value;
  41061. }
  41062. }
  41063. class WebGPUTexturePassUtils {
  41064. constructor( device ) {
  41065. this.device = device;
  41066. const mipmapVertexSource = `
  41067. struct VarysStruct {
  41068. @builtin( position ) Position: vec4<f32>,
  41069. @location( 0 ) vTex : vec2<f32>
  41070. };
  41071. @vertex
  41072. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41073. var Varys : VarysStruct;
  41074. var pos = array< vec2<f32>, 4 >(
  41075. vec2<f32>( -1.0, 1.0 ),
  41076. vec2<f32>( 1.0, 1.0 ),
  41077. vec2<f32>( -1.0, -1.0 ),
  41078. vec2<f32>( 1.0, -1.0 )
  41079. );
  41080. var tex = array< vec2<f32>, 4 >(
  41081. vec2<f32>( 0.0, 0.0 ),
  41082. vec2<f32>( 1.0, 0.0 ),
  41083. vec2<f32>( 0.0, 1.0 ),
  41084. vec2<f32>( 1.0, 1.0 )
  41085. );
  41086. Varys.vTex = tex[ vertexIndex ];
  41087. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41088. return Varys;
  41089. }
  41090. `;
  41091. const mipmapFragmentSource = `
  41092. @group( 0 ) @binding( 0 )
  41093. var imgSampler : sampler;
  41094. @group( 0 ) @binding( 1 )
  41095. var img : texture_2d<f32>;
  41096. @fragment
  41097. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41098. return textureSample( img, imgSampler, vTex );
  41099. }
  41100. `;
  41101. const flipYFragmentSource = `
  41102. @group( 0 ) @binding( 0 )
  41103. var imgSampler : sampler;
  41104. @group( 0 ) @binding( 1 )
  41105. var img : texture_2d<f32>;
  41106. @fragment
  41107. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41108. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41109. }
  41110. `;
  41111. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41112. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41113. // We'll need a new pipeline for every texture format used.
  41114. this.transferPipelines = {};
  41115. this.flipYPipelines = {};
  41116. this.mipmapVertexShaderModule = device.createShaderModule( {
  41117. label: 'mipmapVertex',
  41118. code: mipmapVertexSource
  41119. } );
  41120. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41121. label: 'mipmapFragment',
  41122. code: mipmapFragmentSource
  41123. } );
  41124. this.flipYFragmentShaderModule = device.createShaderModule( {
  41125. label: 'flipYFragment',
  41126. code: flipYFragmentSource
  41127. } );
  41128. }
  41129. getTransferPipeline( format ) {
  41130. let pipeline = this.transferPipelines[ format ];
  41131. if ( pipeline === undefined ) {
  41132. pipeline = this.device.createRenderPipeline( {
  41133. vertex: {
  41134. module: this.mipmapVertexShaderModule,
  41135. entryPoint: 'main'
  41136. },
  41137. fragment: {
  41138. module: this.mipmapFragmentShaderModule,
  41139. entryPoint: 'main',
  41140. targets: [ { format } ]
  41141. },
  41142. primitive: {
  41143. topology: GPUPrimitiveTopology.TriangleStrip,
  41144. stripIndexFormat: GPUIndexFormat.Uint32
  41145. },
  41146. layout: 'auto'
  41147. } );
  41148. this.transferPipelines[ format ] = pipeline;
  41149. }
  41150. return pipeline;
  41151. }
  41152. getFlipYPipeline( format ) {
  41153. let pipeline = this.flipYPipelines[ format ];
  41154. if ( pipeline === undefined ) {
  41155. pipeline = this.device.createRenderPipeline( {
  41156. vertex: {
  41157. module: this.mipmapVertexShaderModule,
  41158. entryPoint: 'main'
  41159. },
  41160. fragment: {
  41161. module: this.flipYFragmentShaderModule,
  41162. entryPoint: 'main',
  41163. targets: [ { format } ]
  41164. },
  41165. primitive: {
  41166. topology: GPUPrimitiveTopology.TriangleStrip,
  41167. stripIndexFormat: GPUIndexFormat.Uint32
  41168. },
  41169. layout: 'auto'
  41170. } );
  41171. this.flipYPipelines[ format ] = pipeline;
  41172. }
  41173. return pipeline;
  41174. }
  41175. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41176. const format = textureGPUDescriptor.format;
  41177. const { width, height } = textureGPUDescriptor.size;
  41178. const transferPipeline = this.getTransferPipeline( format );
  41179. const flipYPipeline = this.getFlipYPipeline( format );
  41180. const tempTexture = this.device.createTexture( {
  41181. size: { width, height, depthOrArrayLayers: 1 },
  41182. format,
  41183. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41184. } );
  41185. const srcView = textureGPU.createView( {
  41186. baseMipLevel: 0,
  41187. mipLevelCount: 1,
  41188. dimension: GPUTextureViewDimension.TwoD,
  41189. baseArrayLayer
  41190. } );
  41191. const dstView = tempTexture.createView( {
  41192. baseMipLevel: 0,
  41193. mipLevelCount: 1,
  41194. dimension: GPUTextureViewDimension.TwoD,
  41195. baseArrayLayer: 0
  41196. } );
  41197. const commandEncoder = this.device.createCommandEncoder( {} );
  41198. const pass = ( pipeline, sourceView, destinationView ) => {
  41199. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41200. const bindGroup = this.device.createBindGroup( {
  41201. layout: bindGroupLayout,
  41202. entries: [ {
  41203. binding: 0,
  41204. resource: this.flipYSampler
  41205. }, {
  41206. binding: 1,
  41207. resource: sourceView
  41208. } ]
  41209. } );
  41210. const passEncoder = commandEncoder.beginRenderPass( {
  41211. colorAttachments: [ {
  41212. view: destinationView,
  41213. loadOp: GPULoadOp.Clear,
  41214. storeOp: GPUStoreOp.Store,
  41215. clearValue: [ 0, 0, 0, 0 ]
  41216. } ]
  41217. } );
  41218. passEncoder.setPipeline( pipeline );
  41219. passEncoder.setBindGroup( 0, bindGroup );
  41220. passEncoder.draw( 4, 1, 0, 0 );
  41221. passEncoder.end();
  41222. };
  41223. pass( transferPipeline, srcView, dstView );
  41224. pass( flipYPipeline, dstView, srcView );
  41225. this.device.queue.submit( [ commandEncoder.finish() ] );
  41226. tempTexture.destroy();
  41227. }
  41228. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41229. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41230. const commandEncoder = this.device.createCommandEncoder( {} );
  41231. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41232. let srcView = textureGPU.createView( {
  41233. baseMipLevel: 0,
  41234. mipLevelCount: 1,
  41235. dimension: GPUTextureViewDimension.TwoD,
  41236. baseArrayLayer
  41237. } );
  41238. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41239. const bindGroup = this.device.createBindGroup( {
  41240. layout: bindGroupLayout,
  41241. entries: [ {
  41242. binding: 0,
  41243. resource: this.mipmapSampler
  41244. }, {
  41245. binding: 1,
  41246. resource: srcView
  41247. } ]
  41248. } );
  41249. const dstView = textureGPU.createView( {
  41250. baseMipLevel: i,
  41251. mipLevelCount: 1,
  41252. dimension: GPUTextureViewDimension.TwoD,
  41253. baseArrayLayer
  41254. } );
  41255. const passEncoder = commandEncoder.beginRenderPass( {
  41256. colorAttachments: [ {
  41257. view: dstView,
  41258. loadOp: GPULoadOp.Clear,
  41259. storeOp: GPUStoreOp.Store,
  41260. clearValue: [ 0, 0, 0, 0 ]
  41261. } ]
  41262. } );
  41263. passEncoder.setPipeline( pipeline );
  41264. passEncoder.setBindGroup( 0, bindGroup );
  41265. passEncoder.draw( 4, 1, 0, 0 );
  41266. passEncoder.end();
  41267. srcView = dstView;
  41268. }
  41269. this.device.queue.submit( [ commandEncoder.finish() ] );
  41270. }
  41271. }
  41272. const _compareToWebGPU = {
  41273. [ NeverCompare ]: 'never',
  41274. [ LessCompare ]: 'less',
  41275. [ EqualCompare ]: 'equal',
  41276. [ LessEqualCompare ]: 'less-equal',
  41277. [ GreaterCompare ]: 'greater',
  41278. [ GreaterEqualCompare ]: 'greater-equal',
  41279. [ AlwaysCompare ]: 'always',
  41280. [ NotEqualCompare ]: 'not-equal'
  41281. };
  41282. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41283. class WebGPUTextureUtils {
  41284. constructor( backend ) {
  41285. this.backend = backend;
  41286. this._passUtils = null;
  41287. this.defaultTexture = {};
  41288. this.defaultCubeTexture = {};
  41289. this.defaultVideoFrame = null;
  41290. this.colorBuffer = null;
  41291. this.depthTexture = new DepthTexture();
  41292. this.depthTexture.name = 'depthBuffer';
  41293. }
  41294. createSampler( texture ) {
  41295. const backend = this.backend;
  41296. const device = backend.device;
  41297. const textureGPU = backend.get( texture );
  41298. const samplerDescriptorGPU = {
  41299. addressModeU: this._convertAddressMode( texture.wrapS ),
  41300. addressModeV: this._convertAddressMode( texture.wrapT ),
  41301. addressModeW: this._convertAddressMode( texture.wrapR ),
  41302. magFilter: this._convertFilterMode( texture.magFilter ),
  41303. minFilter: this._convertFilterMode( texture.minFilter ),
  41304. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41305. maxAnisotropy: texture.anisotropy
  41306. };
  41307. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41308. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41309. }
  41310. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41311. }
  41312. createDefaultTexture( texture ) {
  41313. let textureGPU;
  41314. const format = getFormat( texture );
  41315. if ( texture.isCubeTexture ) {
  41316. textureGPU = this._getDefaultCubeTextureGPU( format );
  41317. } else if ( texture.isVideoTexture ) {
  41318. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41319. } else {
  41320. textureGPU = this._getDefaultTextureGPU( format );
  41321. }
  41322. this.backend.get( texture ).texture = textureGPU;
  41323. }
  41324. createTexture( texture, options = {} ) {
  41325. const backend = this.backend;
  41326. const textureData = backend.get( texture );
  41327. if ( textureData.initialized ) {
  41328. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41329. }
  41330. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41331. if ( options.levels === undefined ) options.levels = 1;
  41332. if ( options.depth === undefined ) options.depth = 1;
  41333. const { width, height, depth, levels } = options;
  41334. const dimension = this._getDimension( texture );
  41335. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41336. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41337. sampleCount = backend.utils.getSampleCount( sampleCount );
  41338. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41339. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41340. if ( texture.isStorageTexture === true ) {
  41341. usage |= GPUTextureUsage.STORAGE_BINDING;
  41342. }
  41343. if ( texture.isCompressedTexture !== true ) {
  41344. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41345. }
  41346. const textureDescriptorGPU = {
  41347. label: texture.name,
  41348. size: {
  41349. width: width,
  41350. height: height,
  41351. depthOrArrayLayers: depth,
  41352. },
  41353. mipLevelCount: levels,
  41354. sampleCount: primarySampleCount,
  41355. dimension: dimension,
  41356. format: format,
  41357. usage: usage
  41358. };
  41359. // texture creation
  41360. if ( texture.isVideoTexture ) {
  41361. const video = texture.source.data;
  41362. const videoFrame = new VideoFrame( video );
  41363. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41364. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41365. videoFrame.close();
  41366. textureData.externalTexture = video;
  41367. } else {
  41368. if ( format === undefined ) {
  41369. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41370. return this.createDefaultTexture( texture );
  41371. }
  41372. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41373. }
  41374. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41375. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41376. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41377. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41378. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41379. }
  41380. textureData.initialized = true;
  41381. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41382. }
  41383. destroyTexture( texture ) {
  41384. const backend = this.backend;
  41385. const textureData = backend.get( texture );
  41386. textureData.texture.destroy();
  41387. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41388. backend.delete( texture );
  41389. }
  41390. destroySampler( texture ) {
  41391. const backend = this.backend;
  41392. const textureData = backend.get( texture );
  41393. delete textureData.sampler;
  41394. }
  41395. generateMipmaps( texture ) {
  41396. const textureData = this.backend.get( texture );
  41397. if ( texture.isCubeTexture ) {
  41398. for ( let i = 0; i < 6; i ++ ) {
  41399. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41400. }
  41401. } else {
  41402. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  41403. }
  41404. }
  41405. getColorBuffer() {
  41406. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41407. const backend = this.backend;
  41408. const { width, height } = backend.getDrawingBufferSize();
  41409. this.colorBuffer = backend.device.createTexture( {
  41410. label: 'colorBuffer',
  41411. size: {
  41412. width: width,
  41413. height: height,
  41414. depthOrArrayLayers: 1
  41415. },
  41416. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41417. format: GPUTextureFormat.BGRA8Unorm,
  41418. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41419. } );
  41420. return this.colorBuffer;
  41421. }
  41422. getDepthBuffer( depth = true, stencil = false ) {
  41423. const backend = this.backend;
  41424. const { width, height } = backend.getDrawingBufferSize();
  41425. const depthTexture = this.depthTexture;
  41426. const depthTextureGPU = backend.get( depthTexture ).texture;
  41427. let format, type;
  41428. if ( stencil ) {
  41429. format = DepthStencilFormat;
  41430. type = UnsignedInt248Type;
  41431. } else if ( depth ) {
  41432. format = DepthFormat;
  41433. type = UnsignedIntType;
  41434. }
  41435. if ( depthTextureGPU !== undefined ) {
  41436. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41437. return depthTextureGPU;
  41438. }
  41439. this.destroyTexture( depthTexture );
  41440. }
  41441. depthTexture.name = 'depthBuffer';
  41442. depthTexture.format = format;
  41443. depthTexture.type = type;
  41444. depthTexture.image.width = width;
  41445. depthTexture.image.height = height;
  41446. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  41447. return backend.get( depthTexture ).texture;
  41448. }
  41449. updateTexture( texture, options ) {
  41450. const textureData = this.backend.get( texture );
  41451. const { textureDescriptorGPU } = textureData;
  41452. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41453. return;
  41454. // transfer texture data
  41455. if ( texture.isDataTexture ) {
  41456. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41457. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41458. for ( let i = 0; i < options.image.depth; i ++ ) {
  41459. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41460. }
  41461. } else if ( texture.isCompressedTexture ) {
  41462. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41463. } else if ( texture.isCubeTexture ) {
  41464. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41465. } else if ( texture.isVideoTexture ) {
  41466. const video = texture.source.data;
  41467. textureData.externalTexture = video;
  41468. } else {
  41469. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41470. }
  41471. //
  41472. textureData.version = texture.version;
  41473. if ( texture.onUpdate ) texture.onUpdate( texture );
  41474. }
  41475. async copyTextureToBuffer( texture, x, y, width, height ) {
  41476. const device = this.backend.device;
  41477. const textureData = this.backend.get( texture );
  41478. const textureGPU = textureData.texture;
  41479. const format = textureData.textureDescriptorGPU.format;
  41480. const bytesPerTexel = this._getBytesPerTexel( format );
  41481. let bytesPerRow = width * bytesPerTexel;
  41482. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41483. const readBuffer = device.createBuffer(
  41484. {
  41485. size: width * height * bytesPerTexel,
  41486. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41487. }
  41488. );
  41489. const encoder = device.createCommandEncoder();
  41490. encoder.copyTextureToBuffer(
  41491. {
  41492. texture: textureGPU,
  41493. origin: { x, y },
  41494. },
  41495. {
  41496. buffer: readBuffer,
  41497. bytesPerRow: bytesPerRow
  41498. },
  41499. {
  41500. width: width,
  41501. height: height
  41502. }
  41503. );
  41504. const typedArrayType = this._getTypedArrayType( format );
  41505. device.queue.submit( [ encoder.finish() ] );
  41506. await readBuffer.mapAsync( GPUMapMode.READ );
  41507. const buffer = readBuffer.getMappedRange();
  41508. return new typedArrayType( buffer );
  41509. }
  41510. _isEnvironmentTexture( texture ) {
  41511. const mapping = texture.mapping;
  41512. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41513. }
  41514. _getDefaultTextureGPU( format ) {
  41515. let defaultTexture = this.defaultTexture[ format ];
  41516. if ( defaultTexture === undefined ) {
  41517. const texture = new Texture();
  41518. texture.minFilter = NearestFilter;
  41519. texture.magFilter = NearestFilter;
  41520. this.createTexture( texture, { width: 1, height: 1, format } );
  41521. this.defaultTexture[ format ] = defaultTexture = texture;
  41522. }
  41523. return this.backend.get( defaultTexture ).texture;
  41524. }
  41525. _getDefaultCubeTextureGPU( format ) {
  41526. let defaultCubeTexture = this.defaultTexture[ format ];
  41527. if ( defaultCubeTexture === undefined ) {
  41528. const texture = new CubeTexture();
  41529. texture.minFilter = NearestFilter;
  41530. texture.magFilter = NearestFilter;
  41531. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41532. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41533. }
  41534. return this.backend.get( defaultCubeTexture ).texture;
  41535. }
  41536. _getDefaultVideoFrame() {
  41537. let defaultVideoFrame = this.defaultVideoFrame;
  41538. if ( defaultVideoFrame === null ) {
  41539. const init = {
  41540. timestamp: 0,
  41541. codedWidth: 1,
  41542. codedHeight: 1,
  41543. format: 'RGBA',
  41544. };
  41545. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41546. }
  41547. return defaultVideoFrame;
  41548. }
  41549. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  41550. for ( let i = 0; i < 6; i ++ ) {
  41551. const image = images[ i ];
  41552. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  41553. if ( image.isDataTexture ) {
  41554. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41555. } else {
  41556. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41557. }
  41558. }
  41559. }
  41560. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  41561. const device = this.backend.device;
  41562. device.queue.copyExternalImageToTexture(
  41563. {
  41564. source: image
  41565. }, {
  41566. texture: textureGPU,
  41567. mipLevel: 0,
  41568. origin: { x: 0, y: 0, z: originDepth }
  41569. }, {
  41570. width: image.width,
  41571. height: image.height,
  41572. depthOrArrayLayers: 1
  41573. }
  41574. );
  41575. if ( flipY === true ) {
  41576. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41577. }
  41578. }
  41579. _getPassUtils() {
  41580. let passUtils = this._passUtils;
  41581. if ( passUtils === null ) {
  41582. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  41583. }
  41584. return passUtils;
  41585. }
  41586. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  41587. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  41588. }
  41589. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  41590. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  41591. }
  41592. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  41593. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41594. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  41595. const device = this.backend.device;
  41596. const data = image.data;
  41597. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  41598. const bytesPerRow = image.width * bytesPerTexel;
  41599. device.queue.writeTexture(
  41600. {
  41601. texture: textureGPU,
  41602. mipLevel: 0,
  41603. origin: { x: 0, y: 0, z: originDepth }
  41604. },
  41605. data,
  41606. {
  41607. offset: image.width * image.height * bytesPerTexel * depth,
  41608. bytesPerRow
  41609. },
  41610. {
  41611. width: image.width,
  41612. height: image.height,
  41613. depthOrArrayLayers: 1
  41614. } );
  41615. if ( flipY === true ) {
  41616. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41617. }
  41618. }
  41619. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  41620. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41621. const device = this.backend.device;
  41622. const blockData = this._getBlockData( textureDescriptorGPU.format );
  41623. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41624. const mipmap = mipmaps[ i ];
  41625. const width = mipmap.width;
  41626. const height = mipmap.height;
  41627. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  41628. device.queue.writeTexture(
  41629. {
  41630. texture: textureGPU,
  41631. mipLevel: i
  41632. },
  41633. mipmap.data,
  41634. {
  41635. offset: 0,
  41636. bytesPerRow
  41637. },
  41638. {
  41639. width: Math.ceil( width / blockData.width ) * blockData.width,
  41640. height: Math.ceil( height / blockData.width ) * blockData.width,
  41641. depthOrArrayLayers: 1
  41642. }
  41643. );
  41644. }
  41645. }
  41646. _getBlockData( format ) {
  41647. // this method is only relevant for compressed texture formats
  41648. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  41649. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  41650. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  41651. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  41652. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  41653. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  41654. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  41655. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41656. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41657. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41658. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  41659. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  41660. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  41661. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  41662. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41663. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  41664. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  41665. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  41666. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  41667. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  41668. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  41669. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  41670. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  41671. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  41672. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  41673. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  41674. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  41675. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  41676. }
  41677. _convertAddressMode( value ) {
  41678. let addressMode = GPUAddressMode.ClampToEdge;
  41679. if ( value === RepeatWrapping ) {
  41680. addressMode = GPUAddressMode.Repeat;
  41681. } else if ( value === MirroredRepeatWrapping ) {
  41682. addressMode = GPUAddressMode.MirrorRepeat;
  41683. }
  41684. return addressMode;
  41685. }
  41686. _convertFilterMode( value ) {
  41687. let filterMode = GPUFilterMode.Linear;
  41688. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  41689. filterMode = GPUFilterMode.Nearest;
  41690. }
  41691. return filterMode;
  41692. }
  41693. _getBytesPerTexel( format ) {
  41694. // 8-bit formats
  41695. if ( format === GPUTextureFormat.R8Unorm ||
  41696. format === GPUTextureFormat.R8Snorm ||
  41697. format === GPUTextureFormat.R8Uint ||
  41698. format === GPUTextureFormat.R8Sint ) return 1;
  41699. // 16-bit formats
  41700. if ( format === GPUTextureFormat.R16Uint ||
  41701. format === GPUTextureFormat.R16Sint ||
  41702. format === GPUTextureFormat.R16Float ||
  41703. format === GPUTextureFormat.RG8Unorm ||
  41704. format === GPUTextureFormat.RG8Snorm ||
  41705. format === GPUTextureFormat.RG8Uint ||
  41706. format === GPUTextureFormat.RG8Sint ) return 2;
  41707. // 32-bit formats
  41708. if ( format === GPUTextureFormat.R32Uint ||
  41709. format === GPUTextureFormat.R32Sint ||
  41710. format === GPUTextureFormat.R32Float ||
  41711. format === GPUTextureFormat.RG16Uint ||
  41712. format === GPUTextureFormat.RG16Sint ||
  41713. format === GPUTextureFormat.RG16Float ||
  41714. format === GPUTextureFormat.RGBA8Unorm ||
  41715. format === GPUTextureFormat.RGBA8UnormSRGB ||
  41716. format === GPUTextureFormat.RGBA8Snorm ||
  41717. format === GPUTextureFormat.RGBA8Uint ||
  41718. format === GPUTextureFormat.RGBA8Sint ||
  41719. format === GPUTextureFormat.BGRA8Unorm ||
  41720. format === GPUTextureFormat.BGRA8UnormSRGB ||
  41721. // Packed 32-bit formats
  41722. format === GPUTextureFormat.RGB9E5UFloat ||
  41723. format === GPUTextureFormat.RGB10A2Unorm ||
  41724. format === GPUTextureFormat.RG11B10UFloat ||
  41725. format === GPUTextureFormat.Depth32Float ||
  41726. format === GPUTextureFormat.Depth24Plus ||
  41727. format === GPUTextureFormat.Depth24PlusStencil8 ||
  41728. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  41729. // 64-bit formats
  41730. if ( format === GPUTextureFormat.RG32Uint ||
  41731. format === GPUTextureFormat.RG32Sint ||
  41732. format === GPUTextureFormat.RG32Float ||
  41733. format === GPUTextureFormat.RGBA16Uint ||
  41734. format === GPUTextureFormat.RGBA16Sint ||
  41735. format === GPUTextureFormat.RGBA16Float ) return 8;
  41736. // 128-bit formats
  41737. if ( format === GPUTextureFormat.RGBA32Uint ||
  41738. format === GPUTextureFormat.RGBA32Sint ||
  41739. format === GPUTextureFormat.RGBA32Float ) return 16;
  41740. }
  41741. _getTypedArrayType( format ) {
  41742. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  41743. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  41744. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  41745. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  41746. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  41747. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  41748. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  41749. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  41750. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  41751. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  41752. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  41753. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  41754. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  41755. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  41756. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  41757. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  41758. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  41759. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  41760. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  41761. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  41762. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  41763. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  41764. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  41765. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  41766. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  41767. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  41768. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  41769. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  41770. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  41771. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  41772. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  41773. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  41774. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  41775. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  41776. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  41777. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  41778. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  41779. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  41780. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  41781. }
  41782. _getDimension( texture ) {
  41783. let dimension;
  41784. if ( texture.isData3DTexture ) {
  41785. dimension = GPUTextureDimension.ThreeD;
  41786. } else {
  41787. dimension = GPUTextureDimension.TwoD;
  41788. }
  41789. return dimension;
  41790. }
  41791. }
  41792. function getFormat( texture, device = null ) {
  41793. const format = texture.format;
  41794. const type = texture.type;
  41795. const colorSpace = texture.colorSpace;
  41796. let formatGPU;
  41797. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  41798. formatGPU = GPUTextureFormat.BGRA8Unorm;
  41799. } else if ( texture.isCompressedTexture === true ) {
  41800. switch ( format ) {
  41801. case RGBA_S3TC_DXT1_Format:
  41802. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  41803. break;
  41804. case RGBA_S3TC_DXT3_Format:
  41805. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  41806. break;
  41807. case RGBA_S3TC_DXT5_Format:
  41808. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  41809. break;
  41810. case RGB_ETC2_Format:
  41811. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  41812. break;
  41813. case RGBA_ETC2_EAC_Format:
  41814. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  41815. break;
  41816. case RGBA_ASTC_4x4_Format:
  41817. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  41818. break;
  41819. case RGBA_ASTC_5x4_Format:
  41820. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  41821. break;
  41822. case RGBA_ASTC_5x5_Format:
  41823. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  41824. break;
  41825. case RGBA_ASTC_6x5_Format:
  41826. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  41827. break;
  41828. case RGBA_ASTC_6x6_Format:
  41829. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  41830. break;
  41831. case RGBA_ASTC_8x5_Format:
  41832. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  41833. break;
  41834. case RGBA_ASTC_8x6_Format:
  41835. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  41836. break;
  41837. case RGBA_ASTC_8x8_Format:
  41838. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  41839. break;
  41840. case RGBA_ASTC_10x5_Format:
  41841. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  41842. break;
  41843. case RGBA_ASTC_10x6_Format:
  41844. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  41845. break;
  41846. case RGBA_ASTC_10x8_Format:
  41847. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  41848. break;
  41849. case RGBA_ASTC_10x10_Format:
  41850. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  41851. break;
  41852. case RGBA_ASTC_12x10_Format:
  41853. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  41854. break;
  41855. case RGBA_ASTC_12x12_Format:
  41856. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  41857. break;
  41858. default:
  41859. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41860. }
  41861. } else {
  41862. switch ( format ) {
  41863. case RGBAFormat:
  41864. switch ( type ) {
  41865. case ByteType:
  41866. formatGPU = GPUTextureFormat.RGBA8Snorm;
  41867. break;
  41868. case ShortType:
  41869. formatGPU = GPUTextureFormat.RGBA16Sint;
  41870. break;
  41871. case UnsignedShortType:
  41872. formatGPU = GPUTextureFormat.RGBA16Uint;
  41873. break;
  41874. case UnsignedIntType:
  41875. formatGPU = GPUTextureFormat.RGBA32Uint;
  41876. break;
  41877. case IntType:
  41878. formatGPU = GPUTextureFormat.RGBA32Sint;
  41879. break;
  41880. case UnsignedByteType:
  41881. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  41882. break;
  41883. case HalfFloatType:
  41884. formatGPU = GPUTextureFormat.RGBA16Float;
  41885. break;
  41886. case FloatType:
  41887. formatGPU = GPUTextureFormat.RGBA32Float;
  41888. break;
  41889. default:
  41890. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  41891. }
  41892. break;
  41893. case RGBFormat:
  41894. switch ( type ) {
  41895. case UnsignedInt5999Type:
  41896. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  41897. break;
  41898. default:
  41899. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  41900. }
  41901. break;
  41902. case RedFormat:
  41903. switch ( type ) {
  41904. case ByteType:
  41905. formatGPU = GPUTextureFormat.R8Snorm;
  41906. break;
  41907. case ShortType:
  41908. formatGPU = GPUTextureFormat.R16Sint;
  41909. break;
  41910. case UnsignedShortType:
  41911. formatGPU = GPUTextureFormat.R16Uint;
  41912. break;
  41913. case UnsignedIntType:
  41914. formatGPU = GPUTextureFormat.R32Uint;
  41915. break;
  41916. case IntType:
  41917. formatGPU = GPUTextureFormat.R32Sint;
  41918. break;
  41919. case UnsignedByteType:
  41920. formatGPU = GPUTextureFormat.R8Unorm;
  41921. break;
  41922. case HalfFloatType:
  41923. formatGPU = GPUTextureFormat.R16Float;
  41924. break;
  41925. case FloatType:
  41926. formatGPU = GPUTextureFormat.R32Float;
  41927. break;
  41928. default:
  41929. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  41930. }
  41931. break;
  41932. case RGFormat:
  41933. switch ( type ) {
  41934. case ByteType:
  41935. formatGPU = GPUTextureFormat.RG8Snorm;
  41936. break;
  41937. case ShortType:
  41938. formatGPU = GPUTextureFormat.RG16Sint;
  41939. break;
  41940. case UnsignedShortType:
  41941. formatGPU = GPUTextureFormat.RG16Uint;
  41942. break;
  41943. case UnsignedIntType:
  41944. formatGPU = GPUTextureFormat.RG32Uint;
  41945. break;
  41946. case IntType:
  41947. formatGPU = GPUTextureFormat.RG32Sint;
  41948. break;
  41949. case UnsignedByteType:
  41950. formatGPU = GPUTextureFormat.RG8Unorm;
  41951. break;
  41952. case HalfFloatType:
  41953. formatGPU = GPUTextureFormat.RG16Float;
  41954. break;
  41955. case FloatType:
  41956. formatGPU = GPUTextureFormat.RG32Float;
  41957. break;
  41958. default:
  41959. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  41960. }
  41961. break;
  41962. case DepthFormat:
  41963. switch ( type ) {
  41964. case UnsignedShortType:
  41965. formatGPU = GPUTextureFormat.Depth16Unorm;
  41966. break;
  41967. case UnsignedIntType:
  41968. formatGPU = GPUTextureFormat.Depth24Plus;
  41969. break;
  41970. case FloatType:
  41971. formatGPU = GPUTextureFormat.Depth32Float;
  41972. break;
  41973. default:
  41974. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  41975. }
  41976. break;
  41977. case DepthStencilFormat:
  41978. switch ( type ) {
  41979. case UnsignedInt248Type:
  41980. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  41981. break;
  41982. case FloatType:
  41983. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  41984. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  41985. }
  41986. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  41987. break;
  41988. default:
  41989. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  41990. }
  41991. break;
  41992. case RedIntegerFormat:
  41993. switch ( type ) {
  41994. case IntType:
  41995. formatGPU = GPUTextureFormat.R32Sint;
  41996. break;
  41997. case UnsignedIntType:
  41998. formatGPU = GPUTextureFormat.R32Uint;
  41999. break;
  42000. default:
  42001. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42002. }
  42003. break;
  42004. case RGIntegerFormat:
  42005. switch ( type ) {
  42006. case IntType:
  42007. formatGPU = GPUTextureFormat.RG32Sint;
  42008. break;
  42009. case UnsignedIntType:
  42010. formatGPU = GPUTextureFormat.RG32Uint;
  42011. break;
  42012. default:
  42013. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42014. }
  42015. break;
  42016. case RGBAIntegerFormat:
  42017. switch ( type ) {
  42018. case IntType:
  42019. formatGPU = GPUTextureFormat.RGBA32Sint;
  42020. break;
  42021. case UnsignedIntType:
  42022. formatGPU = GPUTextureFormat.RGBA32Uint;
  42023. break;
  42024. default:
  42025. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42026. }
  42027. break;
  42028. default:
  42029. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42030. }
  42031. }
  42032. return formatGPU;
  42033. }
  42034. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42035. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42036. const wgslTypeLib$1 = {
  42037. 'f32': 'float',
  42038. 'i32': 'int',
  42039. 'u32': 'uint',
  42040. 'bool': 'bool',
  42041. 'vec2<f32>': 'vec2',
  42042. 'vec2<i32>': 'ivec2',
  42043. 'vec2<u32>': 'uvec2',
  42044. 'vec2<bool>': 'bvec2',
  42045. 'vec2f': 'vec2',
  42046. 'vec2i': 'ivec2',
  42047. 'vec2u': 'uvec2',
  42048. 'vec2b': 'bvec2',
  42049. 'vec3<f32>': 'vec3',
  42050. 'vec3<i32>': 'ivec3',
  42051. 'vec3<u32>': 'uvec3',
  42052. 'vec3<bool>': 'bvec3',
  42053. 'vec3f': 'vec3',
  42054. 'vec3i': 'ivec3',
  42055. 'vec3u': 'uvec3',
  42056. 'vec3b': 'bvec3',
  42057. 'vec4<f32>': 'vec4',
  42058. 'vec4<i32>': 'ivec4',
  42059. 'vec4<u32>': 'uvec4',
  42060. 'vec4<bool>': 'bvec4',
  42061. 'vec4f': 'vec4',
  42062. 'vec4i': 'ivec4',
  42063. 'vec4u': 'uvec4',
  42064. 'vec4b': 'bvec4',
  42065. 'mat2x2<f32>': 'mat2',
  42066. 'mat2x2f': 'mat2',
  42067. 'mat3x3<f32>': 'mat3',
  42068. 'mat3x3f': 'mat3',
  42069. 'mat4x4<f32>': 'mat4',
  42070. 'mat4x4f': 'mat4',
  42071. 'sampler': 'sampler',
  42072. 'texture_1d': 'texture',
  42073. 'texture_2d': 'texture',
  42074. 'texture_2d_array': 'texture',
  42075. 'texture_multisampled_2d': 'cubeTexture',
  42076. 'texture_depth_2d': 'depthTexture',
  42077. 'texture_3d': 'texture3D',
  42078. 'texture_cube': 'cubeTexture',
  42079. 'texture_cube_array': 'cubeTexture',
  42080. 'texture_storage_1d': 'storageTexture',
  42081. 'texture_storage_2d': 'storageTexture',
  42082. 'texture_storage_2d_array': 'storageTexture',
  42083. 'texture_storage_3d': 'storageTexture'
  42084. };
  42085. const parse = ( source ) => {
  42086. source = source.trim();
  42087. const declaration = source.match( declarationRegexp );
  42088. if ( declaration !== null && declaration.length === 4 ) {
  42089. const inputsCode = declaration[ 2 ];
  42090. const propsMatches = [];
  42091. let match = null;
  42092. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42093. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42094. }
  42095. // Process matches to correctly pair names and types
  42096. const inputs = [];
  42097. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42098. const { name, type } = propsMatches[ i ];
  42099. let resolvedType = type;
  42100. if ( resolvedType.startsWith( 'texture' ) ) {
  42101. resolvedType = type.split( '<' )[ 0 ];
  42102. }
  42103. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  42104. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42105. }
  42106. const blockCode = source.substring( declaration[ 0 ].length );
  42107. const outputType = declaration[ 3 ] || 'void';
  42108. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42109. const type = wgslTypeLib$1[ outputType ] || outputType;
  42110. return {
  42111. type,
  42112. inputs,
  42113. name,
  42114. inputsCode,
  42115. blockCode,
  42116. outputType
  42117. };
  42118. } else {
  42119. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42120. }
  42121. };
  42122. class WGSLNodeFunction extends NodeFunction {
  42123. constructor( source ) {
  42124. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42125. super( type, inputs, name );
  42126. this.inputsCode = inputsCode;
  42127. this.blockCode = blockCode;
  42128. this.outputType = outputType;
  42129. }
  42130. getCode( name = this.name ) {
  42131. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42132. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42133. }
  42134. }
  42135. class WGSLNodeParser extends NodeParser {
  42136. parseFunction( source ) {
  42137. return new WGSLNodeFunction( source );
  42138. }
  42139. }
  42140. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42141. const GPUShaderStage = self.GPUShaderStage;
  42142. const gpuShaderStageLib = {
  42143. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42144. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42145. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42146. };
  42147. const supports = {
  42148. instance: true,
  42149. swizzleAssign: false,
  42150. storageBuffer: true
  42151. };
  42152. const wgslFnOpLib = {
  42153. '^^': 'threejs_xor'
  42154. };
  42155. const wgslTypeLib = {
  42156. float: 'f32',
  42157. int: 'i32',
  42158. uint: 'u32',
  42159. bool: 'bool',
  42160. color: 'vec3<f32>',
  42161. vec2: 'vec2<f32>',
  42162. ivec2: 'vec2<i32>',
  42163. uvec2: 'vec2<u32>',
  42164. bvec2: 'vec2<bool>',
  42165. vec3: 'vec3<f32>',
  42166. ivec3: 'vec3<i32>',
  42167. uvec3: 'vec3<u32>',
  42168. bvec3: 'vec3<bool>',
  42169. vec4: 'vec4<f32>',
  42170. ivec4: 'vec4<i32>',
  42171. uvec4: 'vec4<u32>',
  42172. bvec4: 'vec4<bool>',
  42173. mat2: 'mat2x2<f32>',
  42174. imat2: 'mat2x2<i32>',
  42175. umat2: 'mat2x2<u32>',
  42176. bmat2: 'mat2x2<bool>',
  42177. mat3: 'mat3x3<f32>',
  42178. imat3: 'mat3x3<i32>',
  42179. umat3: 'mat3x3<u32>',
  42180. bmat3: 'mat3x3<bool>',
  42181. mat4: 'mat4x4<f32>',
  42182. imat4: 'mat4x4<i32>',
  42183. umat4: 'mat4x4<u32>',
  42184. bmat4: 'mat4x4<bool>'
  42185. };
  42186. const wgslPolyfill = {
  42187. threejs_xor: new CodeNode( `
  42188. fn threejs_xor( a : bool, b : bool ) -> bool {
  42189. return ( a || b ) && !( a && b );
  42190. }
  42191. ` ),
  42192. lessThanEqual: new CodeNode( `
  42193. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42194. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  42195. }
  42196. ` ),
  42197. greaterThan: new CodeNode( `
  42198. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42199. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  42200. }
  42201. ` ),
  42202. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42203. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42204. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42205. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42206. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42207. equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  42208. equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  42209. equals_bvec4: new CodeNode( 'fn threejs_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  42210. repeatWrapping: new CodeNode( `
  42211. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42212. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42213. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42214. }
  42215. ` ),
  42216. biquadraticTexture: new CodeNode( `
  42217. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42218. let res = vec2f( textureDimensions( map, level ) );
  42219. let uvScaled = coord * res;
  42220. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42221. // https://www.shadertoy.com/view/WtyXRy
  42222. let uv = uvWrapping - 0.5;
  42223. let iuv = floor( uv );
  42224. let f = fract( uv );
  42225. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  42226. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  42227. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  42228. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  42229. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42230. }
  42231. ` )
  42232. };
  42233. const wgslMethods = {
  42234. dFdx: 'dpdx',
  42235. dFdy: '- dpdy',
  42236. mod_float: 'threejs_mod_float',
  42237. mod_vec2: 'threejs_mod_vec2',
  42238. mod_vec3: 'threejs_mod_vec3',
  42239. mod_vec4: 'threejs_mod_vec4',
  42240. equals_bool: 'threejs_equals_bool',
  42241. equals_bvec2: 'threejs_equals_bvec2',
  42242. equals_bvec3: 'threejs_equals_bvec3',
  42243. equals_bvec4: 'threejs_equals_bvec4',
  42244. lessThanEqual: 'threejs_lessThanEqual',
  42245. greaterThan: 'threejs_greaterThan',
  42246. inversesqrt: 'inverseSqrt',
  42247. bitcast: 'bitcast<f32>'
  42248. };
  42249. // WebGPU issue: does not support pow() with negative base on Windows
  42250. if ( /Windows/g.test( navigator.userAgent ) ) {
  42251. wgslPolyfill.pow_float = new CodeNode( 'fn threejs_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  42252. wgslPolyfill.pow_vec2 = new CodeNode( 'fn threejs_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( threejs_pow_float( a.x, b.x ), threejs_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  42253. wgslPolyfill.pow_vec3 = new CodeNode( 'fn threejs_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( threejs_pow_float( a.x, b.x ), threejs_pow_float( a.y, b.y ), threejs_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  42254. wgslPolyfill.pow_vec4 = new CodeNode( 'fn threejs_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( threejs_pow_float( a.x, b.x ), threejs_pow_float( a.y, b.y ), threejs_pow_float( a.z, b.z ), threejs_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  42255. wgslMethods.pow_float = 'threejs_pow_float';
  42256. wgslMethods.pow_vec2 = 'threejs_pow_vec2';
  42257. wgslMethods.pow_vec3 = 'threejs_pow_vec3';
  42258. wgslMethods.pow_vec4 = 'threejs_pow_vec4';
  42259. }
  42260. //
  42261. class WGSLNodeBuilder extends NodeBuilder {
  42262. constructor( object, renderer ) {
  42263. super( object, renderer, new WGSLNodeParser() );
  42264. this.uniformGroups = {};
  42265. this.builtins = {};
  42266. this.directives = {};
  42267. }
  42268. needsColorSpaceToLinear( texture ) {
  42269. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42270. }
  42271. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42272. if ( shaderStage === 'fragment' ) {
  42273. if ( depthSnippet ) {
  42274. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42275. } else {
  42276. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42277. }
  42278. } else if ( this.isFilteredTexture( texture ) ) {
  42279. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42280. } else {
  42281. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42282. }
  42283. }
  42284. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42285. if ( shaderStage === 'fragment' ) {
  42286. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42287. } else {
  42288. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42289. }
  42290. }
  42291. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42292. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42293. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42294. } else if ( this.isFilteredTexture( texture ) ) {
  42295. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42296. } else {
  42297. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42298. }
  42299. }
  42300. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42301. this._include( 'biquadraticTexture' );
  42302. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42303. }
  42304. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42305. this._include( 'repeatWrapping' );
  42306. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42307. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42308. }
  42309. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42310. if ( depthSnippet ) {
  42311. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42312. } else {
  42313. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42314. }
  42315. }
  42316. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42317. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42318. }
  42319. isUnfilterable( texture ) {
  42320. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42321. }
  42322. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42323. let snippet = null;
  42324. if ( texture.isVideoTexture === true ) {
  42325. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42326. } else if ( this.isUnfilterable( texture ) ) {
  42327. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42328. } else {
  42329. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42330. }
  42331. return snippet;
  42332. }
  42333. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42334. if ( shaderStage === 'fragment' ) {
  42335. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42336. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42337. } else {
  42338. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42339. }
  42340. }
  42341. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42342. if ( shaderStage === 'fragment' ) {
  42343. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42344. } else {
  42345. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42346. }
  42347. }
  42348. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42349. let snippet = null;
  42350. if ( texture.isVideoTexture === true ) {
  42351. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42352. } else {
  42353. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42354. }
  42355. return snippet;
  42356. }
  42357. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42358. if ( shaderStage === 'fragment' ) {
  42359. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42360. } else {
  42361. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42362. }
  42363. }
  42364. getPropertyName( node, shaderStage = this.shaderStage ) {
  42365. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42366. if ( shaderStage === 'vertex' ) {
  42367. return `varyings.${ node.name }`;
  42368. }
  42369. } else if ( node.isNodeUniform === true ) {
  42370. const name = node.name;
  42371. const type = node.type;
  42372. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42373. return name;
  42374. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42375. return `NodeBuffer_${ node.id }.${name}`;
  42376. } else {
  42377. return node.groupNode.name + '.' + name;
  42378. }
  42379. }
  42380. return super.getPropertyName( node );
  42381. }
  42382. getOutputStructName() {
  42383. return 'output';
  42384. }
  42385. _getUniformGroupCount( shaderStage ) {
  42386. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42387. }
  42388. getFunctionOperator( op ) {
  42389. const fnOp = wgslFnOpLib[ op ];
  42390. if ( fnOp !== undefined ) {
  42391. this._include( fnOp );
  42392. return fnOp;
  42393. }
  42394. return null;
  42395. }
  42396. getStorageAccess( node ) {
  42397. if ( node.isStorageTextureNode ) {
  42398. switch ( node.access ) {
  42399. case GPUStorageTextureAccess.ReadOnly:
  42400. return 'read';
  42401. case GPUStorageTextureAccess.WriteOnly:
  42402. return 'write';
  42403. default:
  42404. return 'read_write';
  42405. }
  42406. } else {
  42407. switch ( node.access ) {
  42408. case GPUBufferBindingType.Storage:
  42409. return 'read_write';
  42410. case GPUBufferBindingType.ReadOnlyStorage:
  42411. return 'read';
  42412. default:
  42413. return 'write';
  42414. }
  42415. }
  42416. }
  42417. getUniformFromNode( node, type, shaderStage, name = null ) {
  42418. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42419. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42420. if ( nodeData.uniformGPU === undefined ) {
  42421. let uniformGPU;
  42422. const group = node.groupNode;
  42423. const groupName = group.name;
  42424. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42425. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42426. let texture = null;
  42427. if ( type === 'texture' || type === 'storageTexture' ) {
  42428. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42429. } else if ( type === 'cubeTexture' ) {
  42430. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42431. } else if ( type === 'texture3D' ) {
  42432. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42433. }
  42434. texture.store = node.isStorageTextureNode === true;
  42435. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42436. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42437. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42438. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42439. bindings.push( sampler, texture );
  42440. uniformGPU = [ sampler, texture ];
  42441. } else {
  42442. bindings.push( texture );
  42443. uniformGPU = [ texture ];
  42444. }
  42445. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42446. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  42447. const buffer = new bufferClass( node, group );
  42448. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42449. bindings.push( buffer );
  42450. uniformGPU = buffer;
  42451. } else {
  42452. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42453. let uniformsGroup = uniformsStage[ groupName ];
  42454. if ( uniformsGroup === undefined ) {
  42455. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42456. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42457. uniformsStage[ groupName ] = uniformsGroup;
  42458. bindings.push( uniformsGroup );
  42459. }
  42460. uniformGPU = this.getNodeUniform( uniformNode, type );
  42461. uniformsGroup.addUniform( uniformGPU );
  42462. }
  42463. nodeData.uniformGPU = uniformGPU;
  42464. }
  42465. return uniformNode;
  42466. }
  42467. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42468. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42469. if ( map.has( name ) === false ) {
  42470. map.set( name, {
  42471. name,
  42472. property,
  42473. type
  42474. } );
  42475. }
  42476. return property;
  42477. }
  42478. getVertexIndex() {
  42479. if ( this.shaderStage === 'vertex' ) {
  42480. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  42481. }
  42482. return 'vertexIndex';
  42483. }
  42484. buildFunctionCode( shaderNode ) {
  42485. const layout = shaderNode.layout;
  42486. const flowData = this.flowShaderNode( shaderNode );
  42487. const parameters = [];
  42488. for ( const input of layout.inputs ) {
  42489. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  42490. }
  42491. //
  42492. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  42493. ${ flowData.vars }
  42494. ${ flowData.code }
  42495. return ${ flowData.result };
  42496. }`;
  42497. //
  42498. return code;
  42499. }
  42500. getInstanceIndex() {
  42501. if ( this.shaderStage === 'vertex' ) {
  42502. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  42503. }
  42504. return 'instanceIndex';
  42505. }
  42506. getDrawIndex() {
  42507. return null;
  42508. }
  42509. getFrontFacing() {
  42510. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  42511. }
  42512. getFragCoord() {
  42513. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  42514. }
  42515. getFragDepth() {
  42516. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  42517. }
  42518. isFlipY() {
  42519. return false;
  42520. }
  42521. enableDirective( name, shaderStage = this.shaderStage ) {
  42522. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = [] );
  42523. stage.push( name );
  42524. }
  42525. getDirectives( shaderStage ) {
  42526. const snippets = [];
  42527. const directives = this.directives[ shaderStage ];
  42528. if ( directives !== undefined ) {
  42529. for ( const directive of directives ) {
  42530. snippets.push( `enable ${directive};` );
  42531. }
  42532. }
  42533. return snippets.join( '\n' );
  42534. }
  42535. enableClipDistances() {
  42536. this.enableDirective( 'clip_distances' );
  42537. }
  42538. enableShaderF16() {
  42539. this.enableDirective( 'f16' );
  42540. }
  42541. enableDualSourceBlending() {
  42542. this.enableDirective( 'dual_source_blending' );
  42543. }
  42544. getBuiltins( shaderStage ) {
  42545. const snippets = [];
  42546. const builtins = this.builtins[ shaderStage ];
  42547. if ( builtins !== undefined ) {
  42548. for ( const { name, property, type } of builtins.values() ) {
  42549. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  42550. }
  42551. }
  42552. return snippets.join( ',\n\t' );
  42553. }
  42554. getAttributes( shaderStage ) {
  42555. const snippets = [];
  42556. if ( shaderStage === 'compute' ) {
  42557. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  42558. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  42559. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  42560. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  42561. }
  42562. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42563. const builtins = this.getBuiltins( 'attribute' );
  42564. if ( builtins ) snippets.push( builtins );
  42565. const attributes = this.getAttributesArray();
  42566. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  42567. const attribute = attributes[ index ];
  42568. const name = attribute.name;
  42569. const type = this.getType( attribute.type );
  42570. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  42571. }
  42572. }
  42573. return snippets.join( ',\n\t' );
  42574. }
  42575. getStructMembers( struct ) {
  42576. const snippets = [];
  42577. const members = struct.getMemberTypes();
  42578. for ( let i = 0; i < members.length; i ++ ) {
  42579. const member = members[ i ];
  42580. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  42581. }
  42582. const builtins = this.getBuiltins( 'output' );
  42583. if ( builtins ) snippets.push( builtins );
  42584. return snippets.join( ',\n' );
  42585. }
  42586. getStructs( shaderStage ) {
  42587. const snippets = [];
  42588. const structs = this.structs[ shaderStage ];
  42589. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  42590. const struct = structs[ index ];
  42591. const name = struct.name;
  42592. let snippet = `\struct ${ name } {\n`;
  42593. snippet += this.getStructMembers( struct );
  42594. snippet += '\n}';
  42595. snippets.push( snippet );
  42596. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  42597. }
  42598. return snippets.join( '\n\n' );
  42599. }
  42600. getVar( type, name ) {
  42601. return `var ${ name } : ${ this.getType( type ) }`;
  42602. }
  42603. getVars( shaderStage ) {
  42604. const snippets = [];
  42605. const vars = this.vars[ shaderStage ];
  42606. if ( vars !== undefined ) {
  42607. for ( const variable of vars ) {
  42608. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  42609. }
  42610. }
  42611. return `\n${ snippets.join( '\n' ) }\n`;
  42612. }
  42613. getVaryings( shaderStage ) {
  42614. const snippets = [];
  42615. if ( shaderStage === 'vertex' ) {
  42616. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  42617. }
  42618. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  42619. const varyings = this.varyings;
  42620. const vars = this.vars[ shaderStage ];
  42621. for ( let index = 0; index < varyings.length; index ++ ) {
  42622. const varying = varyings[ index ];
  42623. if ( varying.needsInterpolation ) {
  42624. let attributesSnippet = `@location( ${index} )`;
  42625. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  42626. attributesSnippet += ' @interpolate( flat )';
  42627. }
  42628. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  42629. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  42630. vars.push( varying );
  42631. }
  42632. }
  42633. }
  42634. const builtins = this.getBuiltins( shaderStage );
  42635. if ( builtins ) snippets.push( builtins );
  42636. const code = snippets.join( ',\n\t' );
  42637. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  42638. }
  42639. getUniforms( shaderStage ) {
  42640. const uniforms = this.uniforms[ shaderStage ];
  42641. const bindingSnippets = [];
  42642. const bufferSnippets = [];
  42643. const structSnippets = [];
  42644. const uniformGroups = {};
  42645. for ( const uniform of uniforms ) {
  42646. const groundName = uniform.groupNode.name;
  42647. const uniformIndexes = this.bindingsIndexes[ groundName ];
  42648. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  42649. const texture = uniform.node.value;
  42650. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  42651. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  42652. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  42653. } else {
  42654. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  42655. }
  42656. }
  42657. let textureType;
  42658. let multisampled = '';
  42659. if ( texture.isMultisampleRenderTargetTexture === true ) {
  42660. multisampled = '_multisampled';
  42661. }
  42662. if ( texture.isCubeTexture === true ) {
  42663. textureType = 'texture_cube<f32>';
  42664. } else if ( texture.isDataArrayTexture === true ) {
  42665. textureType = 'texture_2d_array<f32>';
  42666. } else if ( texture.isDepthTexture === true ) {
  42667. textureType = `texture_depth${multisampled}_2d`;
  42668. } else if ( texture.isVideoTexture === true ) {
  42669. textureType = 'texture_external';
  42670. } else if ( texture.isData3DTexture === true ) {
  42671. textureType = 'texture_3d<f32>';
  42672. } else if ( uniform.node.isStorageTextureNode === true ) {
  42673. const format = getFormat( texture );
  42674. const access = this.getStorageAccess( uniform.node );
  42675. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  42676. } else {
  42677. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  42678. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  42679. }
  42680. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  42681. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  42682. const bufferNode = uniform.node;
  42683. const bufferType = this.getType( bufferNode.bufferType );
  42684. const bufferCount = bufferNode.bufferCount;
  42685. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  42686. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  42687. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  42688. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  42689. } else {
  42690. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  42691. const groupName = uniform.groupNode.name;
  42692. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  42693. index: uniformIndexes.binding ++,
  42694. id: uniformIndexes.group,
  42695. snippets: []
  42696. } );
  42697. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  42698. }
  42699. }
  42700. for ( const name in uniformGroups ) {
  42701. const group = uniformGroups[ name ];
  42702. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  42703. }
  42704. let code = bindingSnippets.join( '\n' );
  42705. code += bufferSnippets.join( '\n' );
  42706. code += structSnippets.join( '\n' );
  42707. return code;
  42708. }
  42709. buildCode() {
  42710. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42711. for ( const shaderStage in shadersData ) {
  42712. const stageData = shadersData[ shaderStage ];
  42713. stageData.uniforms = this.getUniforms( shaderStage );
  42714. stageData.attributes = this.getAttributes( shaderStage );
  42715. stageData.varyings = this.getVaryings( shaderStage );
  42716. stageData.structs = this.getStructs( shaderStage );
  42717. stageData.vars = this.getVars( shaderStage );
  42718. stageData.codes = this.getCodes( shaderStage );
  42719. stageData.directives = this.getDirectives( shaderStage );
  42720. //
  42721. let flow = '// code\n\n';
  42722. flow += this.flowCode[ shaderStage ];
  42723. const flowNodes = this.flowNodes[ shaderStage ];
  42724. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42725. const outputNode = mainNode.outputNode;
  42726. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  42727. for ( const node of flowNodes ) {
  42728. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42729. const slotName = node.name;
  42730. if ( slotName ) {
  42731. if ( flow.length > 0 ) flow += '\n';
  42732. flow += `\t// flow -> ${ slotName }\n\t`;
  42733. }
  42734. flow += `${ flowSlotData.code }\n\t`;
  42735. if ( node === mainNode && shaderStage !== 'compute' ) {
  42736. flow += '// result\n\n\t';
  42737. if ( shaderStage === 'vertex' ) {
  42738. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  42739. } else if ( shaderStage === 'fragment' ) {
  42740. if ( isOutputStruct ) {
  42741. stageData.returnType = outputNode.nodeType;
  42742. flow += `return ${ flowSlotData.result };`;
  42743. } else {
  42744. let structSnippet = '\t@location(0) color: vec4<f32>';
  42745. const builtins = this.getBuiltins( 'output' );
  42746. if ( builtins ) structSnippet += ',\n\t' + builtins;
  42747. stageData.returnType = 'OutputStruct';
  42748. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  42749. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  42750. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  42751. }
  42752. }
  42753. }
  42754. }
  42755. stageData.flow = flow;
  42756. }
  42757. if ( this.material !== null ) {
  42758. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  42759. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  42760. } else {
  42761. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  42762. }
  42763. }
  42764. getMethod( method, output = null ) {
  42765. let wgslMethod;
  42766. if ( output !== null ) {
  42767. wgslMethod = this._getWGSLMethod( method + '_' + output );
  42768. }
  42769. if ( wgslMethod === undefined ) {
  42770. wgslMethod = this._getWGSLMethod( method );
  42771. }
  42772. return wgslMethod || method;
  42773. }
  42774. getType( type ) {
  42775. return wgslTypeLib[ type ] || type;
  42776. }
  42777. isAvailable( name ) {
  42778. let result = supports[ name ];
  42779. if ( result === undefined ) {
  42780. if ( name === 'float32Filterable' ) {
  42781. result = this.renderer.hasFeature( 'float32-filterable' );
  42782. }
  42783. supports[ name ] = result;
  42784. }
  42785. return result;
  42786. }
  42787. _getWGSLMethod( method ) {
  42788. if ( wgslPolyfill[ method ] !== undefined ) {
  42789. this._include( method );
  42790. }
  42791. return wgslMethods[ method ];
  42792. }
  42793. _include( name ) {
  42794. const codeNode = wgslPolyfill[ name ];
  42795. codeNode.build( this );
  42796. if ( this.currentFunctionNode !== null ) {
  42797. this.currentFunctionNode.includes.push( codeNode );
  42798. }
  42799. return codeNode;
  42800. }
  42801. _getWGSLVertexCode( shaderData ) {
  42802. return `${ this.getSignature() }
  42803. // directives
  42804. ${shaderData.directives}
  42805. // uniforms
  42806. ${shaderData.uniforms}
  42807. // varyings
  42808. ${shaderData.varyings}
  42809. var<private> varyings : VaryingsStruct;
  42810. // codes
  42811. ${shaderData.codes}
  42812. @vertex
  42813. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  42814. // vars
  42815. ${shaderData.vars}
  42816. // flow
  42817. ${shaderData.flow}
  42818. return varyings;
  42819. }
  42820. `;
  42821. }
  42822. _getWGSLFragmentCode( shaderData ) {
  42823. return `${ this.getSignature() }
  42824. diagnostic( off, derivative_uniformity );
  42825. // uniforms
  42826. ${shaderData.uniforms}
  42827. // structs
  42828. ${shaderData.structs}
  42829. // codes
  42830. ${shaderData.codes}
  42831. @fragment
  42832. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  42833. // vars
  42834. ${shaderData.vars}
  42835. // flow
  42836. ${shaderData.flow}
  42837. }
  42838. `;
  42839. }
  42840. _getWGSLComputeCode( shaderData, workgroupSize ) {
  42841. return `${ this.getSignature() }
  42842. // directives
  42843. ${shaderData.directives}
  42844. // system
  42845. var<private> instanceIndex : u32;
  42846. // uniforms
  42847. ${shaderData.uniforms}
  42848. // codes
  42849. ${shaderData.codes}
  42850. @compute @workgroup_size( ${workgroupSize} )
  42851. fn main( ${shaderData.attributes} ) {
  42852. // system
  42853. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  42854. // vars
  42855. ${shaderData.vars}
  42856. // flow
  42857. ${shaderData.flow}
  42858. }
  42859. `;
  42860. }
  42861. _getWGSLStruct( name, vars ) {
  42862. return `
  42863. struct ${name} {
  42864. ${vars}
  42865. };`;
  42866. }
  42867. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  42868. const structName = name + 'Struct';
  42869. const structSnippet = this._getWGSLStruct( structName, vars );
  42870. return `${structSnippet}
  42871. @binding( ${binding} ) @group( ${group} )
  42872. var<${access}> ${name} : ${structName};`;
  42873. }
  42874. }
  42875. class WebGPUUtils {
  42876. constructor( backend ) {
  42877. this.backend = backend;
  42878. }
  42879. getCurrentDepthStencilFormat( renderContext ) {
  42880. let format;
  42881. if ( renderContext.depthTexture !== null ) {
  42882. format = this.getTextureFormatGPU( renderContext.depthTexture );
  42883. } else if ( renderContext.depth && renderContext.stencil ) {
  42884. format = GPUTextureFormat.Depth24PlusStencil8;
  42885. } else if ( renderContext.depth ) {
  42886. format = GPUTextureFormat.Depth24Plus;
  42887. }
  42888. return format;
  42889. }
  42890. getTextureFormatGPU( texture ) {
  42891. return this.backend.get( texture ).texture.format;
  42892. }
  42893. getCurrentColorFormat( renderContext ) {
  42894. let format;
  42895. if ( renderContext.textures !== null ) {
  42896. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  42897. } else {
  42898. format = GPUTextureFormat.BGRA8Unorm; // default context format
  42899. }
  42900. return format;
  42901. }
  42902. getCurrentColorSpace( renderContext ) {
  42903. if ( renderContext.textures !== null ) {
  42904. return renderContext.textures[ 0 ].colorSpace;
  42905. }
  42906. return this.backend.renderer.outputColorSpace;
  42907. }
  42908. getPrimitiveTopology( object, material ) {
  42909. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  42910. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  42911. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  42912. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  42913. }
  42914. getSampleCount( sampleCount ) {
  42915. let count = 1;
  42916. if ( sampleCount > 1 ) {
  42917. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  42918. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  42919. if ( count === 2 ) {
  42920. count = 4;
  42921. }
  42922. }
  42923. return count;
  42924. }
  42925. getSampleCountRenderContext( renderContext ) {
  42926. if ( renderContext.textures !== null ) {
  42927. return this.getSampleCount( renderContext.sampleCount );
  42928. }
  42929. return this.getSampleCount( this.backend.renderer.samples );
  42930. }
  42931. }
  42932. const typedArraysToVertexFormatPrefix = new Map( [
  42933. [ Int8Array, [ 'sint8', 'snorm8' ]],
  42934. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  42935. [ Int16Array, [ 'sint16', 'snorm16' ]],
  42936. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  42937. [ Int32Array, [ 'sint32', 'snorm32' ]],
  42938. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  42939. [ Float32Array, [ 'float32', ]],
  42940. ] );
  42941. const typedAttributeToVertexFormatPrefix = new Map( [
  42942. [ Float16BufferAttribute, [ 'float16', ]],
  42943. ] );
  42944. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  42945. [ Int32Array, 'sint32' ],
  42946. [ Int16Array, 'sint32' ], // patch for INT16
  42947. [ Uint32Array, 'uint32' ],
  42948. [ Uint16Array, 'uint32' ], // patch for UINT16
  42949. [ Float32Array, 'float32' ]
  42950. ] );
  42951. class WebGPUAttributeUtils {
  42952. constructor( backend ) {
  42953. this.backend = backend;
  42954. }
  42955. createAttribute( attribute, usage ) {
  42956. const bufferAttribute = this._getBufferAttribute( attribute );
  42957. const backend = this.backend;
  42958. const bufferData = backend.get( bufferAttribute );
  42959. let buffer = bufferData.buffer;
  42960. if ( buffer === undefined ) {
  42961. const device = backend.device;
  42962. let array = bufferAttribute.array;
  42963. // patch for INT16 and UINT16
  42964. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  42965. const tempArray = new Uint32Array( array.length );
  42966. for ( let i = 0; i < array.length; i ++ ) {
  42967. tempArray[ i ] = array[ i ];
  42968. }
  42969. array = tempArray;
  42970. }
  42971. bufferAttribute.array = array;
  42972. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  42973. array = new array.constructor( bufferAttribute.count * 4 );
  42974. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  42975. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  42976. }
  42977. // Update BufferAttribute
  42978. bufferAttribute.itemSize = 4;
  42979. bufferAttribute.array = array;
  42980. }
  42981. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  42982. buffer = device.createBuffer( {
  42983. label: bufferAttribute.name,
  42984. size: size,
  42985. usage: usage,
  42986. mappedAtCreation: true
  42987. } );
  42988. new array.constructor( buffer.getMappedRange() ).set( array );
  42989. buffer.unmap();
  42990. bufferData.buffer = buffer;
  42991. }
  42992. }
  42993. updateAttribute( attribute ) {
  42994. const bufferAttribute = this._getBufferAttribute( attribute );
  42995. const backend = this.backend;
  42996. const device = backend.device;
  42997. const buffer = backend.get( bufferAttribute ).buffer;
  42998. const array = bufferAttribute.array;
  42999. const updateRanges = bufferAttribute.updateRanges;
  43000. if ( updateRanges.length === 0 ) {
  43001. // Not using update ranges
  43002. device.queue.writeBuffer(
  43003. buffer,
  43004. 0,
  43005. array,
  43006. 0
  43007. );
  43008. } else {
  43009. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43010. const range = updateRanges[ i ];
  43011. device.queue.writeBuffer(
  43012. buffer,
  43013. 0,
  43014. array,
  43015. range.start * array.BYTES_PER_ELEMENT,
  43016. range.count * array.BYTES_PER_ELEMENT
  43017. );
  43018. }
  43019. bufferAttribute.clearUpdateRanges();
  43020. }
  43021. }
  43022. createShaderVertexBuffers( renderObject ) {
  43023. const attributes = renderObject.getAttributes();
  43024. const vertexBuffers = new Map();
  43025. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43026. const geometryAttribute = attributes[ slot ];
  43027. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43028. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43029. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43030. if ( vertexBufferLayout === undefined ) {
  43031. let arrayStride, stepMode;
  43032. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43033. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43034. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43035. } else {
  43036. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43037. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43038. }
  43039. // patch for INT16 and UINT16
  43040. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43041. arrayStride = 4;
  43042. }
  43043. vertexBufferLayout = {
  43044. arrayStride,
  43045. attributes: [],
  43046. stepMode
  43047. };
  43048. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43049. }
  43050. const format = this._getVertexFormat( geometryAttribute );
  43051. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43052. vertexBufferLayout.attributes.push( {
  43053. shaderLocation: slot,
  43054. offset,
  43055. format
  43056. } );
  43057. }
  43058. return Array.from( vertexBuffers.values() );
  43059. }
  43060. destroyAttribute( attribute ) {
  43061. const backend = this.backend;
  43062. const data = backend.get( this._getBufferAttribute( attribute ) );
  43063. data.buffer.destroy();
  43064. backend.delete( attribute );
  43065. }
  43066. async getArrayBufferAsync( attribute ) {
  43067. const backend = this.backend;
  43068. const device = backend.device;
  43069. const data = backend.get( this._getBufferAttribute( attribute ) );
  43070. const bufferGPU = data.buffer;
  43071. const size = bufferGPU.size;
  43072. let readBufferGPU = data.readBuffer;
  43073. let needsUnmap = true;
  43074. if ( readBufferGPU === undefined ) {
  43075. readBufferGPU = device.createBuffer( {
  43076. label: attribute.name,
  43077. size,
  43078. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43079. } );
  43080. needsUnmap = false;
  43081. data.readBuffer = readBufferGPU;
  43082. }
  43083. const cmdEncoder = device.createCommandEncoder( {} );
  43084. cmdEncoder.copyBufferToBuffer(
  43085. bufferGPU,
  43086. 0,
  43087. readBufferGPU,
  43088. 0,
  43089. size
  43090. );
  43091. if ( needsUnmap ) readBufferGPU.unmap();
  43092. const gpuCommands = cmdEncoder.finish();
  43093. device.queue.submit( [ gpuCommands ] );
  43094. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43095. const arrayBuffer = readBufferGPU.getMappedRange();
  43096. return arrayBuffer;
  43097. }
  43098. _getVertexFormat( geometryAttribute ) {
  43099. const { itemSize, normalized } = geometryAttribute;
  43100. const ArrayType = geometryAttribute.array.constructor;
  43101. const AttributeType = geometryAttribute.constructor;
  43102. let format;
  43103. if ( itemSize == 1 ) {
  43104. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43105. } else {
  43106. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43107. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43108. if ( prefix ) {
  43109. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43110. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43111. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43112. if ( paddedItemSize % 1 ) {
  43113. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43114. }
  43115. format = `${prefix}x${paddedItemSize}`;
  43116. }
  43117. }
  43118. if ( ! format ) {
  43119. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43120. }
  43121. return format;
  43122. }
  43123. _getBufferAttribute( attribute ) {
  43124. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43125. return attribute;
  43126. }
  43127. }
  43128. class WebGPUBindingUtils {
  43129. constructor( backend ) {
  43130. this.backend = backend;
  43131. }
  43132. createBindingsLayout( bindGroup ) {
  43133. const backend = this.backend;
  43134. const device = backend.device;
  43135. const entries = [];
  43136. let index = 0;
  43137. for ( const binding of bindGroup.bindings ) {
  43138. const bindingGPU = {
  43139. binding: index ++,
  43140. visibility: binding.visibility
  43141. };
  43142. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43143. const buffer = {}; // GPUBufferBindingLayout
  43144. if ( binding.isStorageBuffer ) {
  43145. buffer.type = binding.access;
  43146. }
  43147. bindingGPU.buffer = buffer;
  43148. } else if ( binding.isSampler ) {
  43149. const sampler = {}; // GPUSamplerBindingLayout
  43150. if ( binding.texture.isDepthTexture ) {
  43151. if ( binding.texture.compareFunction !== null ) {
  43152. sampler.type = 'comparison';
  43153. }
  43154. }
  43155. bindingGPU.sampler = sampler;
  43156. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43157. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43158. } else if ( binding.isSampledTexture && binding.store ) {
  43159. const format = this.backend.get( binding.texture ).texture.format;
  43160. const access = binding.access;
  43161. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43162. } else if ( binding.isSampledTexture ) {
  43163. const texture = {}; // GPUTextureBindingLayout
  43164. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43165. texture.multisampled = true;
  43166. }
  43167. if ( binding.texture.isDepthTexture ) {
  43168. texture.sampleType = GPUTextureSampleType.Depth;
  43169. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43170. const type = binding.texture.type;
  43171. if ( type === IntType ) {
  43172. texture.sampleType = GPUTextureSampleType.SInt;
  43173. } else if ( type === UnsignedIntType ) {
  43174. texture.sampleType = GPUTextureSampleType.UInt;
  43175. } else if ( type === FloatType ) {
  43176. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  43177. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43178. }
  43179. }
  43180. if ( binding.isSampledCubeTexture ) {
  43181. texture.viewDimension = GPUTextureViewDimension.Cube;
  43182. } else if ( binding.texture.isDataArrayTexture ) {
  43183. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43184. } else if ( binding.isSampledTexture3D ) {
  43185. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43186. }
  43187. bindingGPU.texture = texture;
  43188. } else {
  43189. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43190. }
  43191. entries.push( bindingGPU );
  43192. }
  43193. return device.createBindGroupLayout( { entries } );
  43194. }
  43195. createBindings( bindGroup ) {
  43196. const backend = this.backend;
  43197. const bindingsData = backend.get( bindGroup );
  43198. // setup (static) binding layout and (dynamic) binding group
  43199. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43200. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43201. bindingsData.layout = bindLayoutGPU;
  43202. bindingsData.group = bindGroupGPU;
  43203. }
  43204. updateBinding( binding ) {
  43205. const backend = this.backend;
  43206. const device = backend.device;
  43207. const buffer = binding.buffer;
  43208. const bufferGPU = backend.get( binding ).buffer;
  43209. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43210. }
  43211. createBindGroup( bindGroup, layoutGPU ) {
  43212. const backend = this.backend;
  43213. const device = backend.device;
  43214. let bindingPoint = 0;
  43215. const entriesGPU = [];
  43216. for ( const binding of bindGroup.bindings ) {
  43217. if ( binding.isUniformBuffer ) {
  43218. const bindingData = backend.get( binding );
  43219. if ( bindingData.buffer === undefined ) {
  43220. const byteLength = binding.byteLength;
  43221. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43222. const bufferGPU = device.createBuffer( {
  43223. label: 'bindingBuffer_' + binding.name,
  43224. size: byteLength,
  43225. usage: usage
  43226. } );
  43227. bindingData.buffer = bufferGPU;
  43228. }
  43229. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43230. } else if ( binding.isStorageBuffer ) {
  43231. const bindingData = backend.get( binding );
  43232. if ( bindingData.buffer === undefined ) {
  43233. const attribute = binding.attribute;
  43234. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43235. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43236. bindingData.buffer = backend.get( attribute ).buffer;
  43237. }
  43238. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43239. } else if ( binding.isSampler ) {
  43240. const textureGPU = backend.get( binding.texture );
  43241. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43242. } else if ( binding.isSampledTexture ) {
  43243. const textureData = backend.get( binding.texture );
  43244. let dimensionViewGPU;
  43245. if ( binding.isSampledCubeTexture ) {
  43246. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43247. } else if ( binding.isSampledTexture3D ) {
  43248. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43249. } else if ( binding.texture.isDataArrayTexture ) {
  43250. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43251. } else {
  43252. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43253. }
  43254. let resourceGPU;
  43255. if ( textureData.externalTexture !== undefined ) {
  43256. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43257. } else {
  43258. const aspectGPU = GPUTextureAspect.All;
  43259. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  43260. }
  43261. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43262. }
  43263. bindingPoint ++;
  43264. }
  43265. return device.createBindGroup( {
  43266. label: 'bindGroup_' + bindGroup.name,
  43267. layout: layoutGPU,
  43268. entries: entriesGPU
  43269. } );
  43270. }
  43271. }
  43272. class WebGPUPipelineUtils {
  43273. constructor( backend ) {
  43274. this.backend = backend;
  43275. }
  43276. _getSampleCount( renderObjectContext ) {
  43277. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43278. }
  43279. createRenderPipeline( renderObject, promises ) {
  43280. const { object, material, geometry, pipeline } = renderObject;
  43281. const { vertexProgram, fragmentProgram } = pipeline;
  43282. const backend = this.backend;
  43283. const device = backend.device;
  43284. const utils = backend.utils;
  43285. const pipelineData = backend.get( pipeline );
  43286. // bind group layouts
  43287. const bindGroupLayouts = [];
  43288. for ( const bindGroup of renderObject.getBindings() ) {
  43289. const bindingsData = backend.get( bindGroup );
  43290. bindGroupLayouts.push( bindingsData.layout );
  43291. }
  43292. // vertex buffers
  43293. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43294. // blending
  43295. let blending;
  43296. if ( material.transparent === true && material.blending !== NoBlending ) {
  43297. blending = this._getBlending( material );
  43298. }
  43299. // stencil
  43300. let stencilFront = {};
  43301. if ( material.stencilWrite === true ) {
  43302. stencilFront = {
  43303. compare: this._getStencilCompare( material ),
  43304. failOp: this._getStencilOperation( material.stencilFail ),
  43305. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43306. passOp: this._getStencilOperation( material.stencilZPass )
  43307. };
  43308. }
  43309. const colorWriteMask = this._getColorWriteMask( material );
  43310. const targets = [];
  43311. if ( renderObject.context.textures !== null ) {
  43312. const textures = renderObject.context.textures;
  43313. for ( let i = 0; i < textures.length; i ++ ) {
  43314. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43315. targets.push( {
  43316. format: colorFormat,
  43317. blend: blending,
  43318. writeMask: colorWriteMask
  43319. } );
  43320. }
  43321. } else {
  43322. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43323. targets.push( {
  43324. format: colorFormat,
  43325. blend: blending,
  43326. writeMask: colorWriteMask
  43327. } );
  43328. }
  43329. const vertexModule = backend.get( vertexProgram ).module;
  43330. const fragmentModule = backend.get( fragmentProgram ).module;
  43331. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43332. const depthCompare = this._getDepthCompare( material );
  43333. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43334. const sampleCount = this._getSampleCount( renderObject.context );
  43335. const pipelineDescriptor = {
  43336. label: 'renderPipeline',
  43337. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43338. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43339. primitive: primitiveState,
  43340. depthStencil: {
  43341. format: depthStencilFormat,
  43342. depthWriteEnabled: material.depthWrite,
  43343. depthCompare: depthCompare,
  43344. stencilFront: stencilFront,
  43345. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43346. stencilReadMask: material.stencilFuncMask,
  43347. stencilWriteMask: material.stencilWriteMask
  43348. },
  43349. multisample: {
  43350. count: sampleCount,
  43351. alphaToCoverageEnabled: material.alphaToCoverage
  43352. },
  43353. layout: device.createPipelineLayout( {
  43354. bindGroupLayouts
  43355. } )
  43356. };
  43357. if ( promises === null ) {
  43358. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43359. } else {
  43360. const p = new Promise( ( resolve /*, reject*/ ) => {
  43361. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43362. pipelineData.pipeline = pipeline;
  43363. resolve();
  43364. } );
  43365. } );
  43366. promises.push( p );
  43367. }
  43368. }
  43369. createBundleEncoder( renderContext, renderObject ) {
  43370. const backend = this.backend;
  43371. const { utils, device } = backend;
  43372. const renderContextData = backend.get( renderContext );
  43373. const renderObjectData = backend.get( renderObject );
  43374. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  43375. const colorFormat = utils.getCurrentColorFormat( renderContext );
  43376. const sampleCount = this._getSampleCount( renderObject.context );
  43377. const descriptor = {
  43378. label: 'renderBundleEncoder',
  43379. colorFormats: [ colorFormat ],
  43380. depthStencilFormat,
  43381. sampleCount
  43382. };
  43383. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  43384. renderObjectData.bundleEncoder = bundleEncoder;
  43385. renderContextData.currentSets = { attributes: {} };
  43386. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  43387. return bundleEncoder;
  43388. }
  43389. createComputePipeline( pipeline, bindings ) {
  43390. const backend = this.backend;
  43391. const device = backend.device;
  43392. const computeProgram = backend.get( pipeline.computeProgram ).module;
  43393. const pipelineGPU = backend.get( pipeline );
  43394. // bind group layouts
  43395. const bindGroupLayouts = [];
  43396. for ( const bindingsGroup of bindings ) {
  43397. const bindingsData = backend.get( bindingsGroup );
  43398. bindGroupLayouts.push( bindingsData.layout );
  43399. }
  43400. pipelineGPU.pipeline = device.createComputePipeline( {
  43401. compute: computeProgram,
  43402. layout: device.createPipelineLayout( {
  43403. bindGroupLayouts
  43404. } )
  43405. } );
  43406. }
  43407. _getBlending( material ) {
  43408. let color, alpha;
  43409. const blending = material.blending;
  43410. const blendSrc = material.blendSrc;
  43411. const blendDst = material.blendDst;
  43412. const blendEquation = material.blendEquation;
  43413. if ( blending === CustomBlending ) {
  43414. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  43415. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  43416. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  43417. color = {
  43418. srcFactor: this._getBlendFactor( blendSrc ),
  43419. dstFactor: this._getBlendFactor( blendDst ),
  43420. operation: this._getBlendOperation( blendEquation )
  43421. };
  43422. alpha = {
  43423. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  43424. dstFactor: this._getBlendFactor( blendDstAlpha ),
  43425. operation: this._getBlendOperation( blendEquationAlpha )
  43426. };
  43427. } else {
  43428. const premultipliedAlpha = material.premultipliedAlpha;
  43429. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  43430. color = {
  43431. srcFactor: srcRGB,
  43432. dstFactor: dstRGB,
  43433. operation: GPUBlendOperation.Add
  43434. };
  43435. alpha = {
  43436. srcFactor: srcAlpha,
  43437. dstFactor: dstAlpha,
  43438. operation: GPUBlendOperation.Add
  43439. };
  43440. };
  43441. if ( premultipliedAlpha ) {
  43442. switch ( blending ) {
  43443. case NormalBlending:
  43444. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43445. break;
  43446. case AdditiveBlending:
  43447. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  43448. break;
  43449. case SubtractiveBlending:
  43450. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43451. break;
  43452. case MultiplyBlending:
  43453. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  43454. break;
  43455. }
  43456. } else {
  43457. switch ( blending ) {
  43458. case NormalBlending:
  43459. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43460. break;
  43461. case AdditiveBlending:
  43462. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  43463. break;
  43464. case SubtractiveBlending:
  43465. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43466. break;
  43467. case MultiplyBlending:
  43468. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  43469. break;
  43470. }
  43471. }
  43472. }
  43473. if ( color !== undefined && alpha !== undefined ) {
  43474. return { color, alpha };
  43475. } else {
  43476. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  43477. }
  43478. }
  43479. _getBlendFactor( blend ) {
  43480. let blendFactor;
  43481. switch ( blend ) {
  43482. case ZeroFactor:
  43483. blendFactor = GPUBlendFactor.Zero;
  43484. break;
  43485. case OneFactor:
  43486. blendFactor = GPUBlendFactor.One;
  43487. break;
  43488. case SrcColorFactor:
  43489. blendFactor = GPUBlendFactor.Src;
  43490. break;
  43491. case OneMinusSrcColorFactor:
  43492. blendFactor = GPUBlendFactor.OneMinusSrc;
  43493. break;
  43494. case SrcAlphaFactor:
  43495. blendFactor = GPUBlendFactor.SrcAlpha;
  43496. break;
  43497. case OneMinusSrcAlphaFactor:
  43498. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  43499. break;
  43500. case DstColorFactor:
  43501. blendFactor = GPUBlendFactor.Dst;
  43502. break;
  43503. case OneMinusDstColorFactor:
  43504. blendFactor = GPUBlendFactor.OneMinusDstColor;
  43505. break;
  43506. case DstAlphaFactor:
  43507. blendFactor = GPUBlendFactor.DstAlpha;
  43508. break;
  43509. case OneMinusDstAlphaFactor:
  43510. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  43511. break;
  43512. case SrcAlphaSaturateFactor:
  43513. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  43514. break;
  43515. case BlendColorFactor:
  43516. blendFactor = GPUBlendFactor.Constant;
  43517. break;
  43518. case OneMinusBlendColorFactor:
  43519. blendFactor = GPUBlendFactor.OneMinusConstant;
  43520. break;
  43521. default:
  43522. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  43523. }
  43524. return blendFactor;
  43525. }
  43526. _getStencilCompare( material ) {
  43527. let stencilCompare;
  43528. const stencilFunc = material.stencilFunc;
  43529. switch ( stencilFunc ) {
  43530. case NeverStencilFunc:
  43531. stencilCompare = GPUCompareFunction.Never;
  43532. break;
  43533. case AlwaysStencilFunc:
  43534. stencilCompare = GPUCompareFunction.Always;
  43535. break;
  43536. case LessStencilFunc:
  43537. stencilCompare = GPUCompareFunction.Less;
  43538. break;
  43539. case LessEqualStencilFunc:
  43540. stencilCompare = GPUCompareFunction.LessEqual;
  43541. break;
  43542. case EqualStencilFunc:
  43543. stencilCompare = GPUCompareFunction.Equal;
  43544. break;
  43545. case GreaterEqualStencilFunc:
  43546. stencilCompare = GPUCompareFunction.GreaterEqual;
  43547. break;
  43548. case GreaterStencilFunc:
  43549. stencilCompare = GPUCompareFunction.Greater;
  43550. break;
  43551. case NotEqualStencilFunc:
  43552. stencilCompare = GPUCompareFunction.NotEqual;
  43553. break;
  43554. default:
  43555. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  43556. }
  43557. return stencilCompare;
  43558. }
  43559. _getStencilOperation( op ) {
  43560. let stencilOperation;
  43561. switch ( op ) {
  43562. case KeepStencilOp:
  43563. stencilOperation = GPUStencilOperation.Keep;
  43564. break;
  43565. case ZeroStencilOp:
  43566. stencilOperation = GPUStencilOperation.Zero;
  43567. break;
  43568. case ReplaceStencilOp:
  43569. stencilOperation = GPUStencilOperation.Replace;
  43570. break;
  43571. case InvertStencilOp:
  43572. stencilOperation = GPUStencilOperation.Invert;
  43573. break;
  43574. case IncrementStencilOp:
  43575. stencilOperation = GPUStencilOperation.IncrementClamp;
  43576. break;
  43577. case DecrementStencilOp:
  43578. stencilOperation = GPUStencilOperation.DecrementClamp;
  43579. break;
  43580. case IncrementWrapStencilOp:
  43581. stencilOperation = GPUStencilOperation.IncrementWrap;
  43582. break;
  43583. case DecrementWrapStencilOp:
  43584. stencilOperation = GPUStencilOperation.DecrementWrap;
  43585. break;
  43586. default:
  43587. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  43588. }
  43589. return stencilOperation;
  43590. }
  43591. _getBlendOperation( blendEquation ) {
  43592. let blendOperation;
  43593. switch ( blendEquation ) {
  43594. case AddEquation:
  43595. blendOperation = GPUBlendOperation.Add;
  43596. break;
  43597. case SubtractEquation:
  43598. blendOperation = GPUBlendOperation.Subtract;
  43599. break;
  43600. case ReverseSubtractEquation:
  43601. blendOperation = GPUBlendOperation.ReverseSubtract;
  43602. break;
  43603. case MinEquation:
  43604. blendOperation = GPUBlendOperation.Min;
  43605. break;
  43606. case MaxEquation:
  43607. blendOperation = GPUBlendOperation.Max;
  43608. break;
  43609. default:
  43610. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  43611. }
  43612. return blendOperation;
  43613. }
  43614. _getPrimitiveState( object, geometry, material ) {
  43615. const descriptor = {};
  43616. const utils = this.backend.utils;
  43617. descriptor.topology = utils.getPrimitiveTopology( object, material );
  43618. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  43619. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43620. }
  43621. switch ( material.side ) {
  43622. case FrontSide:
  43623. descriptor.frontFace = GPUFrontFace.CCW;
  43624. descriptor.cullMode = GPUCullMode.Back;
  43625. break;
  43626. case BackSide:
  43627. descriptor.frontFace = GPUFrontFace.CCW;
  43628. descriptor.cullMode = GPUCullMode.Front;
  43629. break;
  43630. case DoubleSide:
  43631. descriptor.frontFace = GPUFrontFace.CCW;
  43632. descriptor.cullMode = GPUCullMode.None;
  43633. break;
  43634. default:
  43635. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  43636. break;
  43637. }
  43638. return descriptor;
  43639. }
  43640. _getColorWriteMask( material ) {
  43641. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  43642. }
  43643. _getDepthCompare( material ) {
  43644. let depthCompare;
  43645. if ( material.depthTest === false ) {
  43646. depthCompare = GPUCompareFunction.Always;
  43647. } else {
  43648. const depthFunc = material.depthFunc;
  43649. switch ( depthFunc ) {
  43650. case NeverDepth:
  43651. depthCompare = GPUCompareFunction.Never;
  43652. break;
  43653. case AlwaysDepth:
  43654. depthCompare = GPUCompareFunction.Always;
  43655. break;
  43656. case LessDepth:
  43657. depthCompare = GPUCompareFunction.Less;
  43658. break;
  43659. case LessEqualDepth:
  43660. depthCompare = GPUCompareFunction.LessEqual;
  43661. break;
  43662. case EqualDepth:
  43663. depthCompare = GPUCompareFunction.Equal;
  43664. break;
  43665. case GreaterEqualDepth:
  43666. depthCompare = GPUCompareFunction.GreaterEqual;
  43667. break;
  43668. case GreaterDepth:
  43669. depthCompare = GPUCompareFunction.Greater;
  43670. break;
  43671. case NotEqualDepth:
  43672. depthCompare = GPUCompareFunction.NotEqual;
  43673. break;
  43674. default:
  43675. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  43676. }
  43677. }
  43678. return depthCompare;
  43679. }
  43680. }
  43681. /*// debugger tools
  43682. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  43683. //*/
  43684. //
  43685. class WebGPUBackend extends Backend {
  43686. constructor( parameters = {} ) {
  43687. super( parameters );
  43688. this.isWebGPUBackend = true;
  43689. // some parameters require default values other than "undefined"
  43690. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  43691. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  43692. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43693. this.device = null;
  43694. this.context = null;
  43695. this.colorBuffer = null;
  43696. this.defaultRenderPassdescriptor = null;
  43697. this.utils = new WebGPUUtils( this );
  43698. this.attributeUtils = new WebGPUAttributeUtils( this );
  43699. this.bindingUtils = new WebGPUBindingUtils( this );
  43700. this.pipelineUtils = new WebGPUPipelineUtils( this );
  43701. this.textureUtils = new WebGPUTextureUtils( this );
  43702. this.occludedResolveCache = new Map();
  43703. }
  43704. async init( renderer ) {
  43705. await super.init( renderer );
  43706. //
  43707. const parameters = this.parameters;
  43708. // create the device if it is not passed with parameters
  43709. let device;
  43710. if ( parameters.device === undefined ) {
  43711. const adapterOptions = {
  43712. powerPreference: parameters.powerPreference
  43713. };
  43714. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  43715. if ( adapter === null ) {
  43716. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  43717. }
  43718. // feature support
  43719. const features = Object.values( GPUFeatureName );
  43720. const supportedFeatures = [];
  43721. for ( const name of features ) {
  43722. if ( adapter.features.has( name ) ) {
  43723. supportedFeatures.push( name );
  43724. }
  43725. }
  43726. const deviceDescriptor = {
  43727. requiredFeatures: supportedFeatures,
  43728. requiredLimits: parameters.requiredLimits
  43729. };
  43730. device = await adapter.requestDevice( deviceDescriptor );
  43731. } else {
  43732. device = parameters.device;
  43733. }
  43734. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  43735. this.device = device;
  43736. this.context = context;
  43737. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  43738. this.context.configure( {
  43739. device: this.device,
  43740. format: GPUTextureFormat.BGRA8Unorm,
  43741. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  43742. alphaMode: alphaMode
  43743. } );
  43744. this.updateSize();
  43745. }
  43746. get coordinateSystem() {
  43747. return WebGPUCoordinateSystem;
  43748. }
  43749. async getArrayBufferAsync( attribute ) {
  43750. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43751. }
  43752. getContext() {
  43753. return this.context;
  43754. }
  43755. _getDefaultRenderPassDescriptor() {
  43756. let descriptor = this.defaultRenderPassdescriptor;
  43757. if ( descriptor === null ) {
  43758. const renderer = this.renderer;
  43759. descriptor = {
  43760. colorAttachments: [ {
  43761. view: null
  43762. } ],
  43763. depthStencilAttachment: {
  43764. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  43765. }
  43766. };
  43767. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43768. if ( this.renderer.samples > 0 ) {
  43769. colorAttachment.view = this.colorBuffer.createView();
  43770. } else {
  43771. colorAttachment.resolveTarget = undefined;
  43772. }
  43773. this.defaultRenderPassdescriptor = descriptor;
  43774. }
  43775. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43776. if ( this.renderer.samples > 0 ) {
  43777. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  43778. } else {
  43779. colorAttachment.view = this.context.getCurrentTexture().createView();
  43780. }
  43781. return descriptor;
  43782. }
  43783. _getRenderPassDescriptor( renderContext ) {
  43784. const renderTarget = renderContext.renderTarget;
  43785. const renderTargetData = this.get( renderTarget );
  43786. let descriptors = renderTargetData.descriptors;
  43787. if ( descriptors === undefined ) {
  43788. descriptors = [];
  43789. renderTargetData.descriptors = descriptors;
  43790. }
  43791. if ( renderTargetData.width !== renderTarget.width ||
  43792. renderTargetData.height !== renderTarget.height ||
  43793. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  43794. renderTargetData.samples !== renderTarget.samples ||
  43795. descriptors.length !== renderTarget.textures.length
  43796. ) {
  43797. descriptors.length = 0;
  43798. // dispose
  43799. const onDispose = () => {
  43800. renderTarget.removeEventListener( 'dispose', onDispose );
  43801. this.delete( renderTarget );
  43802. };
  43803. renderTarget.addEventListener( 'dispose', onDispose );
  43804. }
  43805. let descriptor = descriptors[ renderContext.activeCubeFace ];
  43806. if ( descriptor === undefined ) {
  43807. const textures = renderContext.textures;
  43808. const colorAttachments = [];
  43809. for ( let i = 0; i < textures.length; i ++ ) {
  43810. const textureData = this.get( textures[ i ] );
  43811. const textureView = textureData.texture.createView( {
  43812. baseMipLevel: renderContext.activeMipmapLevel,
  43813. mipLevelCount: 1,
  43814. baseArrayLayer: renderContext.activeCubeFace,
  43815. dimension: GPUTextureViewDimension.TwoD
  43816. } );
  43817. let view, resolveTarget;
  43818. if ( textureData.msaaTexture !== undefined ) {
  43819. view = textureData.msaaTexture.createView();
  43820. resolveTarget = textureView;
  43821. } else {
  43822. view = textureView;
  43823. resolveTarget = undefined;
  43824. }
  43825. colorAttachments.push( {
  43826. view,
  43827. resolveTarget,
  43828. loadOp: GPULoadOp.Load,
  43829. storeOp: GPUStoreOp.Store
  43830. } );
  43831. }
  43832. const depthTextureData = this.get( renderContext.depthTexture );
  43833. const depthStencilAttachment = {
  43834. view: depthTextureData.texture.createView()
  43835. };
  43836. descriptor = {
  43837. colorAttachments,
  43838. depthStencilAttachment
  43839. };
  43840. descriptors[ renderContext.activeCubeFace ] = descriptor;
  43841. renderTargetData.width = renderTarget.width;
  43842. renderTargetData.height = renderTarget.height;
  43843. renderTargetData.samples = renderTarget.samples;
  43844. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  43845. }
  43846. return descriptor;
  43847. }
  43848. beginRender( renderContext ) {
  43849. const renderContextData = this.get( renderContext );
  43850. const device = this.device;
  43851. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43852. let occlusionQuerySet;
  43853. if ( occlusionQueryCount > 0 ) {
  43854. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  43855. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  43856. // Get a reference to the array of objects with queries. The renderContextData property
  43857. // can be changed by another render pass before the buffer.mapAsyc() completes.
  43858. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  43859. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  43860. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43861. //
  43862. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  43863. renderContextData.occlusionQuerySet = occlusionQuerySet;
  43864. renderContextData.occlusionQueryIndex = 0;
  43865. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43866. renderContextData.lastOcclusionObject = null;
  43867. }
  43868. let descriptor;
  43869. if ( renderContext.textures === null ) {
  43870. descriptor = this._getDefaultRenderPassDescriptor();
  43871. } else {
  43872. descriptor = this._getRenderPassDescriptor( renderContext );
  43873. }
  43874. this.initTimestampQuery( renderContext, descriptor );
  43875. descriptor.occlusionQuerySet = occlusionQuerySet;
  43876. const depthStencilAttachment = descriptor.depthStencilAttachment;
  43877. if ( renderContext.textures !== null ) {
  43878. const colorAttachments = descriptor.colorAttachments;
  43879. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  43880. const colorAttachment = colorAttachments[ i ];
  43881. if ( renderContext.clearColor ) {
  43882. colorAttachment.clearValue = renderContext.clearColorValue;
  43883. colorAttachment.loadOp = GPULoadOp.Clear;
  43884. colorAttachment.storeOp = GPUStoreOp.Store;
  43885. } else {
  43886. colorAttachment.loadOp = GPULoadOp.Load;
  43887. colorAttachment.storeOp = GPUStoreOp.Store;
  43888. }
  43889. }
  43890. } else {
  43891. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43892. if ( renderContext.clearColor ) {
  43893. colorAttachment.clearValue = renderContext.clearColorValue;
  43894. colorAttachment.loadOp = GPULoadOp.Clear;
  43895. colorAttachment.storeOp = GPUStoreOp.Store;
  43896. } else {
  43897. colorAttachment.loadOp = GPULoadOp.Load;
  43898. colorAttachment.storeOp = GPUStoreOp.Store;
  43899. }
  43900. }
  43901. //
  43902. if ( renderContext.depth ) {
  43903. if ( renderContext.clearDepth ) {
  43904. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  43905. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43906. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43907. } else {
  43908. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43909. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43910. }
  43911. }
  43912. if ( renderContext.stencil ) {
  43913. if ( renderContext.clearStencil ) {
  43914. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  43915. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43916. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43917. } else {
  43918. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43919. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43920. }
  43921. }
  43922. //
  43923. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  43924. const currentPass = encoder.beginRenderPass( descriptor );
  43925. //
  43926. renderContextData.descriptor = descriptor;
  43927. renderContextData.encoder = encoder;
  43928. renderContextData.currentPass = currentPass;
  43929. renderContextData.currentSets = { attributes: {} };
  43930. //
  43931. if ( renderContext.viewport ) {
  43932. this.updateViewport( renderContext );
  43933. }
  43934. if ( renderContext.scissor ) {
  43935. const { x, y, width, height } = renderContext.scissorValue;
  43936. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  43937. }
  43938. }
  43939. finishRender( renderContext ) {
  43940. const renderContextData = this.get( renderContext );
  43941. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43942. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  43943. renderContextData.registerBundlesPhase = false;
  43944. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  43945. }
  43946. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43947. renderContextData.currentPass.endOcclusionQuery();
  43948. }
  43949. renderContextData.currentPass.end();
  43950. if ( occlusionQueryCount > 0 ) {
  43951. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  43952. //
  43953. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  43954. if ( queryResolveBuffer === undefined ) {
  43955. queryResolveBuffer = this.device.createBuffer(
  43956. {
  43957. size: bufferSize,
  43958. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  43959. }
  43960. );
  43961. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  43962. }
  43963. //
  43964. const readBuffer = this.device.createBuffer(
  43965. {
  43966. size: bufferSize,
  43967. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43968. }
  43969. );
  43970. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  43971. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  43972. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  43973. renderContextData.occlusionQueryBuffer = readBuffer;
  43974. //
  43975. this.resolveOccludedAsync( renderContext );
  43976. }
  43977. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  43978. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  43979. //
  43980. if ( renderContext.textures !== null ) {
  43981. const textures = renderContext.textures;
  43982. for ( let i = 0; i < textures.length; i ++ ) {
  43983. const texture = textures[ i ];
  43984. if ( texture.generateMipmaps === true ) {
  43985. this.textureUtils.generateMipmaps( texture );
  43986. }
  43987. }
  43988. }
  43989. }
  43990. isOccluded( renderContext, object ) {
  43991. const renderContextData = this.get( renderContext );
  43992. return renderContextData.occluded && renderContextData.occluded.has( object );
  43993. }
  43994. async resolveOccludedAsync( renderContext ) {
  43995. const renderContextData = this.get( renderContext );
  43996. // handle occlusion query results
  43997. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  43998. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  43999. const occluded = new WeakSet();
  44000. renderContextData.currentOcclusionQueryObjects = null;
  44001. renderContextData.currentOcclusionQueryBuffer = null;
  44002. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44003. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44004. const results = new BigUint64Array( buffer );
  44005. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44006. if ( results[ i ] !== BigInt( 0 ) ) {
  44007. occluded.add( currentOcclusionQueryObjects[ i ] );
  44008. }
  44009. }
  44010. currentOcclusionQueryBuffer.destroy();
  44011. renderContextData.occluded = occluded;
  44012. }
  44013. }
  44014. updateViewport( renderContext ) {
  44015. const { currentPass } = this.get( renderContext );
  44016. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44017. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  44018. }
  44019. clear( color, depth, stencil, renderTargetData = null ) {
  44020. const device = this.device;
  44021. const renderer = this.renderer;
  44022. let colorAttachments = [];
  44023. let depthStencilAttachment;
  44024. let clearValue;
  44025. let supportsDepth;
  44026. let supportsStencil;
  44027. if ( color ) {
  44028. const clearColor = this.getClearColor();
  44029. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44030. }
  44031. if ( renderTargetData === null ) {
  44032. supportsDepth = renderer.depth;
  44033. supportsStencil = renderer.stencil;
  44034. const descriptor = this._getDefaultRenderPassDescriptor();
  44035. if ( color ) {
  44036. colorAttachments = descriptor.colorAttachments;
  44037. const colorAttachment = colorAttachments[ 0 ];
  44038. colorAttachment.clearValue = clearValue;
  44039. colorAttachment.loadOp = GPULoadOp.Clear;
  44040. colorAttachment.storeOp = GPUStoreOp.Store;
  44041. }
  44042. if ( supportsDepth || supportsStencil ) {
  44043. depthStencilAttachment = descriptor.depthStencilAttachment;
  44044. }
  44045. } else {
  44046. supportsDepth = renderTargetData.depth;
  44047. supportsStencil = renderTargetData.stencil;
  44048. if ( color ) {
  44049. for ( const texture of renderTargetData.textures ) {
  44050. const textureData = this.get( texture );
  44051. const textureView = textureData.texture.createView();
  44052. let view, resolveTarget;
  44053. if ( textureData.msaaTexture !== undefined ) {
  44054. view = textureData.msaaTexture.createView();
  44055. resolveTarget = textureView;
  44056. } else {
  44057. view = textureView;
  44058. resolveTarget = undefined;
  44059. }
  44060. colorAttachments.push( {
  44061. view,
  44062. resolveTarget,
  44063. clearValue,
  44064. loadOp: GPULoadOp.Clear,
  44065. storeOp: GPUStoreOp.Store
  44066. } );
  44067. }
  44068. }
  44069. if ( supportsDepth || supportsStencil ) {
  44070. const depthTextureData = this.get( renderTargetData.depthTexture );
  44071. depthStencilAttachment = {
  44072. view: depthTextureData.texture.createView()
  44073. };
  44074. }
  44075. }
  44076. //
  44077. if ( supportsDepth ) {
  44078. if ( depth ) {
  44079. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44080. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44081. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44082. } else {
  44083. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44084. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44085. }
  44086. }
  44087. //
  44088. if ( supportsStencil ) {
  44089. if ( stencil ) {
  44090. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44091. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44092. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44093. } else {
  44094. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44095. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44096. }
  44097. }
  44098. //
  44099. const encoder = device.createCommandEncoder( {} );
  44100. const currentPass = encoder.beginRenderPass( {
  44101. colorAttachments,
  44102. depthStencilAttachment
  44103. } );
  44104. currentPass.end();
  44105. device.queue.submit( [ encoder.finish() ] );
  44106. }
  44107. // compute
  44108. beginCompute( computeGroup ) {
  44109. const groupGPU = this.get( computeGroup );
  44110. const descriptor = {};
  44111. this.initTimestampQuery( computeGroup, descriptor );
  44112. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44113. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44114. }
  44115. compute( computeGroup, computeNode, bindings, pipeline ) {
  44116. const { passEncoderGPU } = this.get( computeGroup );
  44117. // pipeline
  44118. const pipelineGPU = this.get( pipeline ).pipeline;
  44119. passEncoderGPU.setPipeline( pipelineGPU );
  44120. // bind groups
  44121. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44122. const bindGroup = bindings[ i ];
  44123. const bindingsData = this.get( bindGroup );
  44124. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44125. }
  44126. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44127. const computeNodeData = this.get( computeNode );
  44128. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44129. const { dispatchSize } = computeNodeData;
  44130. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44131. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44132. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44133. } else {
  44134. dispatchSize.x = computeNode.dispatchCount;
  44135. }
  44136. passEncoderGPU.dispatchWorkgroups(
  44137. dispatchSize.x,
  44138. dispatchSize.y,
  44139. dispatchSize.z
  44140. );
  44141. }
  44142. finishCompute( computeGroup ) {
  44143. const groupData = this.get( computeGroup );
  44144. groupData.passEncoderGPU.end();
  44145. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44146. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44147. }
  44148. // render object
  44149. draw( renderObject, info ) {
  44150. const { object, geometry, context, pipeline } = renderObject;
  44151. const bindings = renderObject.getBindings();
  44152. const contextData = this.get( context );
  44153. const pipelineGPU = this.get( pipeline ).pipeline;
  44154. const currentSets = contextData.currentSets;
  44155. const renderObjectData = this.get( renderObject );
  44156. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  44157. const renderContextData = this.get( context );
  44158. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  44159. renderContextData.renderBundles.push( renderBundle );
  44160. return;
  44161. }
  44162. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  44163. // pipeline
  44164. if ( currentSets.pipeline !== pipelineGPU ) {
  44165. passEncoderGPU.setPipeline( pipelineGPU );
  44166. currentSets.pipeline = pipelineGPU;
  44167. }
  44168. // bind groups
  44169. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44170. const bindGroup = bindings[ i ];
  44171. const bindingsData = this.get( bindGroup );
  44172. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  44173. }
  44174. // attributes
  44175. const index = renderObject.getIndex();
  44176. const hasIndex = ( index !== null );
  44177. // index
  44178. if ( hasIndex === true ) {
  44179. if ( currentSets.index !== index ) {
  44180. const buffer = this.get( index ).buffer;
  44181. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44182. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44183. currentSets.index = index;
  44184. }
  44185. }
  44186. // vertex buffers
  44187. const vertexBuffers = renderObject.getVertexBuffers();
  44188. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44189. const vertexBuffer = vertexBuffers[ i ];
  44190. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44191. const buffer = this.get( vertexBuffer ).buffer;
  44192. passEncoderGPU.setVertexBuffer( i, buffer );
  44193. currentSets.attributes[ i ] = vertexBuffer;
  44194. }
  44195. }
  44196. // occlusion queries - handle multiple consecutive draw calls for an object
  44197. if ( contextData.occlusionQuerySet !== undefined ) {
  44198. const lastObject = contextData.lastOcclusionObject;
  44199. if ( lastObject !== object ) {
  44200. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44201. passEncoderGPU.endOcclusionQuery();
  44202. contextData.occlusionQueryIndex ++;
  44203. }
  44204. if ( object.occlusionTest === true ) {
  44205. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  44206. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44207. }
  44208. contextData.lastOcclusionObject = object;
  44209. }
  44210. }
  44211. // draw
  44212. const drawRange = renderObject.drawRange;
  44213. const firstVertex = drawRange.start;
  44214. const instanceCount = this.getInstanceCount( renderObject );
  44215. if ( instanceCount === 0 ) return;
  44216. if ( object.isBatchedMesh === true ) {
  44217. const starts = object._multiDrawStarts;
  44218. const counts = object._multiDrawCounts;
  44219. const drawCount = object._multiDrawCount;
  44220. const drawInstances = object._multiDrawInstances;
  44221. const bytesPerElement = index.bytesPerElement || 1;
  44222. for ( let i = 0; i < drawCount; i ++ ) {
  44223. const count = drawInstances ? drawInstances[ i ] : 1;
  44224. const firstInstance = count > 1 ? 0 : i;
  44225. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  44226. }
  44227. } else if ( hasIndex === true ) {
  44228. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  44229. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  44230. info.update( object, indexCount, instanceCount );
  44231. } else {
  44232. const positionAttribute = geometry.attributes.position;
  44233. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  44234. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44235. info.update( object, vertexCount, instanceCount );
  44236. }
  44237. if ( this.renderer._currentRenderBundle ) {
  44238. const renderBundle = passEncoderGPU.finish();
  44239. renderObjectData.lastPipelineGPU = pipelineGPU;
  44240. renderObjectData.renderBundle = renderBundle;
  44241. renderObjectData.bundleEncoder = passEncoderGPU;
  44242. }
  44243. }
  44244. // cache key
  44245. needsRenderUpdate( renderObject ) {
  44246. const data = this.get( renderObject );
  44247. const { object, material } = renderObject;
  44248. const utils = this.utils;
  44249. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44250. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44251. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44252. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44253. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44254. let needsUpdate = false;
  44255. if ( data.material !== material || data.materialVersion !== material.version ||
  44256. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44257. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44258. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44259. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44260. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44261. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44262. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44263. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44264. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44265. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44266. data.primitiveTopology !== primitiveTopology ||
  44267. data.clippingContextVersion !== renderObject.clippingContextVersion
  44268. ) {
  44269. data.material = material; data.materialVersion = material.version;
  44270. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44271. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44272. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44273. data.colorWrite = material.colorWrite;
  44274. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44275. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44276. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44277. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44278. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44279. data.sampleCount = sampleCount;
  44280. data.colorSpace = colorSpace;
  44281. data.colorFormat = colorFormat;
  44282. data.depthStencilFormat = depthStencilFormat;
  44283. data.primitiveTopology = primitiveTopology;
  44284. data.clippingContextVersion = renderObject.clippingContextVersion;
  44285. needsUpdate = true;
  44286. }
  44287. return needsUpdate;
  44288. }
  44289. getRenderCacheKey( renderObject ) {
  44290. const { object, material } = renderObject;
  44291. const utils = this.utils;
  44292. const renderContext = renderObject.context;
  44293. return [
  44294. material.transparent, material.blending, material.premultipliedAlpha,
  44295. material.blendSrc, material.blendDst, material.blendEquation,
  44296. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44297. material.colorWrite,
  44298. material.depthWrite, material.depthTest, material.depthFunc,
  44299. material.stencilWrite, material.stencilFunc,
  44300. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44301. material.stencilFuncMask, material.stencilWriteMask,
  44302. material.side,
  44303. utils.getSampleCountRenderContext( renderContext ),
  44304. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44305. utils.getPrimitiveTopology( object, material ),
  44306. renderObject.clippingContextVersion
  44307. ].join();
  44308. }
  44309. // textures
  44310. createSampler( texture ) {
  44311. this.textureUtils.createSampler( texture );
  44312. }
  44313. destroySampler( texture ) {
  44314. this.textureUtils.destroySampler( texture );
  44315. }
  44316. createDefaultTexture( texture ) {
  44317. this.textureUtils.createDefaultTexture( texture );
  44318. }
  44319. createTexture( texture, options ) {
  44320. this.textureUtils.createTexture( texture, options );
  44321. }
  44322. updateTexture( texture, options ) {
  44323. this.textureUtils.updateTexture( texture, options );
  44324. }
  44325. generateMipmaps( texture ) {
  44326. this.textureUtils.generateMipmaps( texture );
  44327. }
  44328. destroyTexture( texture ) {
  44329. this.textureUtils.destroyTexture( texture );
  44330. }
  44331. copyTextureToBuffer( texture, x, y, width, height ) {
  44332. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  44333. }
  44334. initTimestampQuery( renderContext, descriptor ) {
  44335. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44336. const renderContextData = this.get( renderContext );
  44337. if ( ! renderContextData.timeStampQuerySet ) {
  44338. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44339. // beginning and one for the end of compute pass execution.
  44340. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44341. const timestampWrites = {
  44342. querySet: timeStampQuerySet,
  44343. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44344. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44345. };
  44346. Object.assign( descriptor, {
  44347. timestampWrites,
  44348. } );
  44349. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44350. }
  44351. }
  44352. // timestamp utils
  44353. prepareTimestampBuffer( renderContext, encoder ) {
  44354. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44355. const renderContextData = this.get( renderContext );
  44356. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44357. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44358. renderContextData.currentTimestampQueryBuffers = {
  44359. resolveBuffer: this.device.createBuffer( {
  44360. label: 'timestamp resolve buffer',
  44361. size: size,
  44362. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44363. } ),
  44364. resultBuffer: this.device.createBuffer( {
  44365. label: 'timestamp result buffer',
  44366. size: size,
  44367. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  44368. } ),
  44369. isMappingPending: false,
  44370. };
  44371. }
  44372. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44373. if ( isMappingPending === true ) return;
  44374. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  44375. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  44376. }
  44377. async resolveTimestampAsync( renderContext, type = 'render' ) {
  44378. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44379. const renderContextData = this.get( renderContext );
  44380. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  44381. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44382. if ( isMappingPending === true ) return;
  44383. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  44384. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  44385. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  44386. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  44387. this.renderer.info.updateTimestamp( type, duration );
  44388. resultBuffer.unmap();
  44389. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  44390. } );
  44391. }
  44392. // node builder
  44393. createNodeBuilder( object, renderer ) {
  44394. return new WGSLNodeBuilder( object, renderer );
  44395. }
  44396. // program
  44397. createProgram( program ) {
  44398. const programGPU = this.get( program );
  44399. programGPU.module = {
  44400. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  44401. entryPoint: 'main'
  44402. };
  44403. }
  44404. destroyProgram( program ) {
  44405. this.delete( program );
  44406. }
  44407. // pipelines
  44408. createRenderPipeline( renderObject, promises ) {
  44409. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  44410. }
  44411. createComputePipeline( computePipeline, bindings ) {
  44412. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  44413. }
  44414. createBundleEncoder( renderContext, renderObject ) {
  44415. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  44416. }
  44417. // bindings
  44418. createBindings( bindGroup ) {
  44419. this.bindingUtils.createBindings( bindGroup );
  44420. }
  44421. updateBindings( bindGroup ) {
  44422. this.bindingUtils.createBindings( bindGroup );
  44423. }
  44424. updateBinding( binding ) {
  44425. this.bindingUtils.updateBinding( binding );
  44426. }
  44427. // attributes
  44428. createIndexAttribute( attribute ) {
  44429. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44430. }
  44431. createAttribute( attribute ) {
  44432. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44433. }
  44434. createStorageAttribute( attribute ) {
  44435. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44436. }
  44437. updateAttribute( attribute ) {
  44438. this.attributeUtils.updateAttribute( attribute );
  44439. }
  44440. destroyAttribute( attribute ) {
  44441. this.attributeUtils.destroyAttribute( attribute );
  44442. }
  44443. // canvas
  44444. updateSize() {
  44445. this.colorBuffer = this.textureUtils.getColorBuffer();
  44446. this.defaultRenderPassdescriptor = null;
  44447. }
  44448. // utils public
  44449. getMaxAnisotropy() {
  44450. return 16;
  44451. }
  44452. hasFeature( name ) {
  44453. return this.device.features.has( name );
  44454. }
  44455. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  44456. let dstX = 0;
  44457. let dstY = 0;
  44458. let srcX = 0;
  44459. let srcY = 0;
  44460. let srcWidth = srcTexture.image.width;
  44461. let srcHeight = srcTexture.image.height;
  44462. if ( srcRegion !== null ) {
  44463. srcX = srcRegion.x;
  44464. srcY = srcRegion.y;
  44465. srcWidth = srcRegion.width;
  44466. srcHeight = srcRegion.height;
  44467. }
  44468. if ( dstPosition !== null ) {
  44469. dstX = dstPosition.x;
  44470. dstY = dstPosition.y;
  44471. }
  44472. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  44473. const sourceGPU = this.get( srcTexture ).texture;
  44474. const destinationGPU = this.get( dstTexture ).texture;
  44475. encoder.copyTextureToTexture(
  44476. {
  44477. texture: sourceGPU,
  44478. mipLevel: level,
  44479. origin: { x: srcX, y: srcY, z: 0 }
  44480. },
  44481. {
  44482. texture: destinationGPU,
  44483. mipLevel: level,
  44484. origin: { x: dstX, y: dstY, z: 0 }
  44485. },
  44486. [
  44487. srcWidth,
  44488. srcHeight
  44489. ]
  44490. );
  44491. this.device.queue.submit( [ encoder.finish() ] );
  44492. }
  44493. copyFramebufferToTexture( texture, renderContext ) {
  44494. const renderContextData = this.get( renderContext );
  44495. const { encoder, descriptor } = renderContextData;
  44496. let sourceGPU = null;
  44497. if ( renderContext.renderTarget ) {
  44498. if ( texture.isDepthTexture ) {
  44499. sourceGPU = this.get( renderContext.depthTexture ).texture;
  44500. } else {
  44501. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  44502. }
  44503. } else {
  44504. if ( texture.isDepthTexture ) {
  44505. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  44506. } else {
  44507. sourceGPU = this.context.getCurrentTexture();
  44508. }
  44509. }
  44510. const destinationGPU = this.get( texture ).texture;
  44511. if ( sourceGPU.format !== destinationGPU.format ) {
  44512. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  44513. return;
  44514. }
  44515. renderContextData.currentPass.end();
  44516. encoder.copyTextureToTexture(
  44517. {
  44518. texture: sourceGPU,
  44519. origin: { x: 0, y: 0, z: 0 }
  44520. },
  44521. {
  44522. texture: destinationGPU
  44523. },
  44524. [
  44525. texture.image.width,
  44526. texture.image.height
  44527. ]
  44528. );
  44529. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  44530. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  44531. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  44532. }
  44533. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44534. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44535. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  44536. renderContextData.currentSets = { attributes: {} };
  44537. }
  44538. }
  44539. /*
  44540. const debugHandler = {
  44541. get: function ( target, name ) {
  44542. // Add |update
  44543. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  44544. return target[ name ];
  44545. }
  44546. };
  44547. */
  44548. class WebGPURenderer extends Renderer {
  44549. constructor( parameters = {} ) {
  44550. let BackendClass;
  44551. if ( parameters.forceWebGL ) {
  44552. BackendClass = WebGLBackend;
  44553. } else if ( WebGPU.isAvailable() ) {
  44554. BackendClass = WebGPUBackend;
  44555. } else {
  44556. BackendClass = WebGLBackend;
  44557. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  44558. }
  44559. const backend = new BackendClass( parameters );
  44560. //super( new Proxy( backend, debugHandler ) );
  44561. super( backend, parameters );
  44562. this.isWebGPURenderer = true;
  44563. }
  44564. }
  44565. const _material = /*@__PURE__*/ new NodeMaterial();
  44566. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  44567. class PostProcessing {
  44568. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  44569. this.renderer = renderer;
  44570. this.outputNode = outputNode;
  44571. this.outputColorTransform = true;
  44572. this.needsUpdate = true;
  44573. }
  44574. render() {
  44575. this.update();
  44576. const renderer = this.renderer;
  44577. const toneMapping = renderer.toneMapping;
  44578. const outputColorSpace = renderer.outputColorSpace;
  44579. renderer.toneMapping = NoToneMapping;
  44580. renderer.outputColorSpace = LinearSRGBColorSpace;
  44581. //
  44582. _quadMesh.render( renderer );
  44583. //
  44584. renderer.toneMapping = toneMapping;
  44585. renderer.outputColorSpace = outputColorSpace;
  44586. }
  44587. update() {
  44588. if ( this.needsUpdate === true ) {
  44589. const renderer = this.renderer;
  44590. const toneMapping = renderer.toneMapping;
  44591. const outputColorSpace = renderer.outputColorSpace;
  44592. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  44593. _quadMesh.material.needsUpdate = true;
  44594. this.needsUpdate = false;
  44595. }
  44596. }
  44597. async renderAsync() {
  44598. this.update();
  44599. const renderer = this.renderer;
  44600. const toneMapping = renderer.toneMapping;
  44601. const outputColorSpace = renderer.outputColorSpace;
  44602. renderer.toneMapping = NoToneMapping;
  44603. renderer.outputColorSpace = LinearSRGBColorSpace;
  44604. //
  44605. await _quadMesh.renderAsync( renderer );
  44606. //
  44607. renderer.toneMapping = toneMapping;
  44608. renderer.outputColorSpace = outputColorSpace;
  44609. }
  44610. }
  44611. class StorageTexture extends Texture {
  44612. constructor( width = 1, height = 1 ) {
  44613. super();
  44614. this.image = { width, height };
  44615. this.magFilter = LinearFilter;
  44616. this.minFilter = LinearFilter;
  44617. this.isStorageTexture = true;
  44618. }
  44619. }
  44620. class StorageBufferAttribute extends BufferAttribute {
  44621. constructor( array, itemSize, typeClass = Float32Array ) {
  44622. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44623. super( array, itemSize );
  44624. this.isStorageBufferAttribute = true;
  44625. }
  44626. }
  44627. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  44628. constructor( array, itemSize, typeClass = Float32Array ) {
  44629. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44630. super( array, itemSize );
  44631. this.isStorageInstancedBufferAttribute = true;
  44632. }
  44633. }
  44634. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  44635. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  44636. revision: REVISION,
  44637. } } ) );
  44638. }
  44639. if ( typeof window !== 'undefined' ) {
  44640. if ( window.__THREE__ ) {
  44641. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  44642. } else {
  44643. window.__THREE__ = REVISION;
  44644. }
  44645. }
  44646. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnamorphicNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, BlendModeNode, BloomNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CheckerNode, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorAdjustmentNode, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, CondNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DenoiseNode, DepthFormat, DepthOfFieldNode, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, DiscardNode, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DotScreenNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, FXAANode, F_Schlick, FileLoader, FilmNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GTAONode, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HashNode, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightNode, LightProbe, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeKeywords, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OperatorNode, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, PackingNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, PixelationPassNode, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGBShiftNode, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, SobelOperatorNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureBicubicNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, TransitionNode, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acos, add, addLightNode, addNodeClass, addNodeElement, addNodeMaterial, afterImage, all, alphaT, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, ao, append, arrayBuffer, asin, assign, atan, atan2, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bloom, blur, bmat2, bmat3, bmat4, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToLinear, colorToDirection, compute, cond, context, convert, cos, createCanvasElement, createNodeFromType, createNodeMaterialFromType, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, denoise, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, discard, distance, div, dodge, dof, dot, dotScreen, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, film, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, fxaa, gain, gapSize, gaussianBlur, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, global, glsl, glslFn, greaterThan, greaterThanEqual, hash, hue, imat2, imat3, imat4, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightTargetDirection, lightingContext, lights, lightsNode, linearDepth, linearToColorSpace, linearTosRGB, log, log2, loop, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularStrength, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mod, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, objectDirection, objectGroup, objectNormalMatrix, objectPosition, objectScale, objectViewMatrix, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pixelationPass, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinear, sampler, saturate, saturation, screen, scriptable, scriptableValue, sepia, setCurrentStack, shaderStages, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, sobel, specularColor, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, threshold, timerDelta, timerGlobal, timerLocal, toneMapping, transformDirection, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transition, transpose, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, umat2, umat3, umat4, uniform, uniformArray, uniformGroup, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportBottomRight, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor };
粤ICP备19079148号