three.webgpu.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194
  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. } else if ( builder.environmentNode ) {
  26846. node = builder.environmentNode;
  26847. }
  26848. return node;
  26849. }
  26850. setupLightMap( builder ) {
  26851. let node = null;
  26852. if ( builder.material.lightMap ) {
  26853. node = new IrradianceNode( materialLightMap );
  26854. }
  26855. return node;
  26856. }
  26857. setupLights( builder ) {
  26858. const materialLightsNode = [];
  26859. //
  26860. const envNode = this.setupEnvironment( builder );
  26861. if ( envNode && envNode.isLightingNode ) {
  26862. materialLightsNode.push( envNode );
  26863. }
  26864. const lightMapNode = this.setupLightMap( builder );
  26865. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26866. materialLightsNode.push( lightMapNode );
  26867. }
  26868. if ( this.aoNode !== null || builder.material.aoMap ) {
  26869. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26870. materialLightsNode.push( new AONode( aoNode ) );
  26871. }
  26872. let lightsN = this.lightsNode || builder.lightsNode;
  26873. if ( materialLightsNode.length > 0 ) {
  26874. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  26875. }
  26876. return lightsN;
  26877. }
  26878. setupLightingModel( /*builder*/ ) {
  26879. // Interface function.
  26880. }
  26881. setupLighting( builder ) {
  26882. const { material } = builder;
  26883. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26884. // OUTGOING LIGHT
  26885. const lights = this.lights === true || this.lightsNode !== null;
  26886. const lightsNode = lights ? this.setupLights( builder ) : null;
  26887. let outgoingLightNode = this.setupOutgoingLight( builder );
  26888. if ( lightsNode && lightsNode.hasLight !== false ) {
  26889. const lightingModel = this.setupLightingModel( builder );
  26890. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26891. } else if ( backdropNode !== null ) {
  26892. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26893. }
  26894. // EMISSIVE
  26895. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26896. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26897. outgoingLightNode = outgoingLightNode.add( emissive );
  26898. }
  26899. return outgoingLightNode;
  26900. }
  26901. setupOutput( builder, outputNode ) {
  26902. // FOG
  26903. if ( this.fog === true ) {
  26904. const fogNode = builder.fogNode;
  26905. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26906. }
  26907. return outputNode;
  26908. }
  26909. setDefaultValues( material ) {
  26910. // This approach is to reuse the native refreshUniforms*
  26911. // and turn available the use of features like transmission and environment in core
  26912. for ( const property in material ) {
  26913. const value = material[ property ];
  26914. if ( this[ property ] === undefined ) {
  26915. this[ property ] = value;
  26916. if ( value && value.clone ) this[ property ] = value.clone();
  26917. }
  26918. }
  26919. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26920. for ( const key in descriptors ) {
  26921. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26922. descriptors[ key ].get !== undefined ) {
  26923. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26924. }
  26925. }
  26926. }
  26927. toJSON( meta ) {
  26928. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26929. if ( isRoot ) {
  26930. meta = {
  26931. textures: {},
  26932. images: {},
  26933. nodes: {}
  26934. };
  26935. }
  26936. const data = Material.prototype.toJSON.call( this, meta );
  26937. const nodeChildren = getNodeChildren( this );
  26938. data.inputNodes = {};
  26939. for ( const { property, childNode } of nodeChildren ) {
  26940. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26941. }
  26942. // TODO: Copied from Object3D.toJSON
  26943. function extractFromCache( cache ) {
  26944. const values = [];
  26945. for ( const key in cache ) {
  26946. const data = cache[ key ];
  26947. delete data.metadata;
  26948. values.push( data );
  26949. }
  26950. return values;
  26951. }
  26952. if ( isRoot ) {
  26953. const textures = extractFromCache( meta.textures );
  26954. const images = extractFromCache( meta.images );
  26955. const nodes = extractFromCache( meta.nodes );
  26956. if ( textures.length > 0 ) data.textures = textures;
  26957. if ( images.length > 0 ) data.images = images;
  26958. if ( nodes.length > 0 ) data.nodes = nodes;
  26959. }
  26960. return data;
  26961. }
  26962. copy( source ) {
  26963. this.lightsNode = source.lightsNode;
  26964. this.envNode = source.envNode;
  26965. this.colorNode = source.colorNode;
  26966. this.normalNode = source.normalNode;
  26967. this.opacityNode = source.opacityNode;
  26968. this.backdropNode = source.backdropNode;
  26969. this.backdropAlphaNode = source.backdropAlphaNode;
  26970. this.alphaTestNode = source.alphaTestNode;
  26971. this.positionNode = source.positionNode;
  26972. this.depthNode = source.depthNode;
  26973. this.shadowNode = source.shadowNode;
  26974. this.shadowPositionNode = source.shadowPositionNode;
  26975. this.outputNode = source.outputNode;
  26976. this.mrtNode = source.mrtNode;
  26977. this.fragmentNode = source.fragmentNode;
  26978. this.vertexNode = source.vertexNode;
  26979. return super.copy( source );
  26980. }
  26981. static fromMaterial( material ) {
  26982. if ( material.isNodeMaterial === true ) { // is already a node material
  26983. return material;
  26984. }
  26985. const type = material.type.replace( 'Material', 'NodeMaterial' );
  26986. const nodeMaterial = createNodeMaterialFromType( type );
  26987. if ( nodeMaterial === undefined ) {
  26988. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  26989. }
  26990. for ( const key in material ) {
  26991. nodeMaterial[ key ] = material[ key ];
  26992. }
  26993. return nodeMaterial;
  26994. }
  26995. }
  26996. function addNodeMaterial( type, nodeMaterial ) {
  26997. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  26998. if ( NodeMaterials.has( type ) ) {
  26999. console.warn( `Redefinition of node material ${ type }` );
  27000. return;
  27001. }
  27002. NodeMaterials.set( type, nodeMaterial );
  27003. nodeMaterial.type = type;
  27004. }
  27005. function createNodeMaterialFromType( type ) {
  27006. const Material = NodeMaterials.get( type );
  27007. if ( Material !== undefined ) {
  27008. return new Material();
  27009. }
  27010. }
  27011. addNodeMaterial( 'NodeMaterial', NodeMaterial );
  27012. class Uniform {
  27013. constructor( name, value ) {
  27014. this.name = name;
  27015. this.value = value;
  27016. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  27017. this.itemSize = 0;
  27018. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  27019. }
  27020. setValue( value ) {
  27021. this.value = value;
  27022. }
  27023. getValue() {
  27024. return this.value;
  27025. }
  27026. }
  27027. class NumberUniform extends Uniform {
  27028. constructor( name, value = 0 ) {
  27029. super( name, value );
  27030. this.isNumberUniform = true;
  27031. this.boundary = 4;
  27032. this.itemSize = 1;
  27033. }
  27034. }
  27035. class Vector2Uniform extends Uniform {
  27036. constructor( name, value = new Vector2() ) {
  27037. super( name, value );
  27038. this.isVector2Uniform = true;
  27039. this.boundary = 8;
  27040. this.itemSize = 2;
  27041. }
  27042. }
  27043. class Vector3Uniform extends Uniform {
  27044. constructor( name, value = new Vector3() ) {
  27045. super( name, value );
  27046. this.isVector3Uniform = true;
  27047. this.boundary = 16;
  27048. this.itemSize = 3;
  27049. }
  27050. }
  27051. class Vector4Uniform extends Uniform {
  27052. constructor( name, value = new Vector4() ) {
  27053. super( name, value );
  27054. this.isVector4Uniform = true;
  27055. this.boundary = 16;
  27056. this.itemSize = 4;
  27057. }
  27058. }
  27059. class ColorUniform extends Uniform {
  27060. constructor( name, value = new Color() ) {
  27061. super( name, value );
  27062. this.isColorUniform = true;
  27063. this.boundary = 16;
  27064. this.itemSize = 3;
  27065. }
  27066. }
  27067. class Matrix3Uniform extends Uniform {
  27068. constructor( name, value = new Matrix3() ) {
  27069. super( name, value );
  27070. this.isMatrix3Uniform = true;
  27071. this.boundary = 48;
  27072. this.itemSize = 12;
  27073. }
  27074. }
  27075. class Matrix4Uniform extends Uniform {
  27076. constructor( name, value = new Matrix4() ) {
  27077. super( name, value );
  27078. this.isMatrix4Uniform = true;
  27079. this.boundary = 64;
  27080. this.itemSize = 16;
  27081. }
  27082. }
  27083. class NumberNodeUniform extends NumberUniform {
  27084. constructor( nodeUniform ) {
  27085. super( nodeUniform.name, nodeUniform.value );
  27086. this.nodeUniform = nodeUniform;
  27087. }
  27088. getValue() {
  27089. return this.nodeUniform.value;
  27090. }
  27091. }
  27092. class Vector2NodeUniform extends Vector2Uniform {
  27093. constructor( nodeUniform ) {
  27094. super( nodeUniform.name, nodeUniform.value );
  27095. this.nodeUniform = nodeUniform;
  27096. }
  27097. getValue() {
  27098. return this.nodeUniform.value;
  27099. }
  27100. }
  27101. class Vector3NodeUniform extends Vector3Uniform {
  27102. constructor( nodeUniform ) {
  27103. super( nodeUniform.name, nodeUniform.value );
  27104. this.nodeUniform = nodeUniform;
  27105. }
  27106. getValue() {
  27107. return this.nodeUniform.value;
  27108. }
  27109. }
  27110. class Vector4NodeUniform extends Vector4Uniform {
  27111. constructor( nodeUniform ) {
  27112. super( nodeUniform.name, nodeUniform.value );
  27113. this.nodeUniform = nodeUniform;
  27114. }
  27115. getValue() {
  27116. return this.nodeUniform.value;
  27117. }
  27118. }
  27119. class ColorNodeUniform extends ColorUniform {
  27120. constructor( nodeUniform ) {
  27121. super( nodeUniform.name, nodeUniform.value );
  27122. this.nodeUniform = nodeUniform;
  27123. }
  27124. getValue() {
  27125. return this.nodeUniform.value;
  27126. }
  27127. }
  27128. class Matrix3NodeUniform extends Matrix3Uniform {
  27129. constructor( nodeUniform ) {
  27130. super( nodeUniform.name, nodeUniform.value );
  27131. this.nodeUniform = nodeUniform;
  27132. }
  27133. getValue() {
  27134. return this.nodeUniform.value;
  27135. }
  27136. }
  27137. class Matrix4NodeUniform extends Matrix4Uniform {
  27138. constructor( nodeUniform ) {
  27139. super( nodeUniform.name, nodeUniform.value );
  27140. this.nodeUniform = nodeUniform;
  27141. }
  27142. getValue() {
  27143. return this.nodeUniform.value;
  27144. }
  27145. }
  27146. class CondNode extends Node {
  27147. constructor( condNode, ifNode, elseNode = null ) {
  27148. super();
  27149. this.condNode = condNode;
  27150. this.ifNode = ifNode;
  27151. this.elseNode = elseNode;
  27152. }
  27153. getNodeType( builder ) {
  27154. const ifType = this.ifNode.getNodeType( builder );
  27155. if ( this.elseNode !== null ) {
  27156. const elseType = this.elseNode.getNodeType( builder );
  27157. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  27158. return elseType;
  27159. }
  27160. }
  27161. return ifType;
  27162. }
  27163. setup( builder ) {
  27164. const properties = builder.getNodeProperties( this );
  27165. properties.condNode = this.condNode.cache();
  27166. properties.ifNode = this.ifNode.cache();
  27167. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  27168. }
  27169. generate( builder, output ) {
  27170. const type = this.getNodeType( builder );
  27171. const nodeData = builder.getDataFromNode( this );
  27172. if ( nodeData.nodeProperty !== undefined ) {
  27173. return nodeData.nodeProperty;
  27174. }
  27175. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  27176. const needsOutput = output !== 'void';
  27177. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  27178. nodeData.nodeProperty = nodeProperty;
  27179. const nodeSnippet = condNode.build( builder, 'bool' );
  27180. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  27181. let ifSnippet = ifNode.build( builder, type );
  27182. if ( ifSnippet ) {
  27183. if ( needsOutput ) {
  27184. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  27185. } else {
  27186. ifSnippet = 'return ' + ifSnippet + ';';
  27187. }
  27188. }
  27189. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  27190. if ( elseNode !== null ) {
  27191. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  27192. let elseSnippet = elseNode.build( builder, type );
  27193. if ( elseSnippet ) {
  27194. if ( needsOutput ) {
  27195. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  27196. } else {
  27197. elseSnippet = 'return ' + elseSnippet + ';';
  27198. }
  27199. }
  27200. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  27201. } else {
  27202. builder.addFlowCode( '\n\n' );
  27203. }
  27204. return builder.format( nodeProperty, type, output );
  27205. }
  27206. }
  27207. const cond = nodeProxy( CondNode );
  27208. addNodeElement( 'cond', cond );
  27209. addNodeClass( 'CondNode', CondNode );
  27210. class StackNode extends Node {
  27211. constructor( parent = null ) {
  27212. super();
  27213. this.nodes = [];
  27214. this.outputNode = null;
  27215. this.parent = parent;
  27216. this._currentCond = null;
  27217. this.isStackNode = true;
  27218. }
  27219. getNodeType( builder ) {
  27220. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  27221. }
  27222. add( node ) {
  27223. this.nodes.push( node );
  27224. return this;
  27225. }
  27226. if( boolNode, method ) {
  27227. const methodNode = new ShaderNode( method );
  27228. this._currentCond = cond( boolNode, methodNode );
  27229. return this.add( this._currentCond );
  27230. }
  27231. elseif( boolNode, method ) {
  27232. const methodNode = new ShaderNode( method );
  27233. const ifNode = cond( boolNode, methodNode );
  27234. this._currentCond.elseNode = ifNode;
  27235. this._currentCond = ifNode;
  27236. return this;
  27237. }
  27238. else( method ) {
  27239. this._currentCond.elseNode = new ShaderNode( method );
  27240. return this;
  27241. }
  27242. build( builder, ...params ) {
  27243. const previousStack = getCurrentStack();
  27244. setCurrentStack( this );
  27245. for ( const node of this.nodes ) {
  27246. node.build( builder, 'void' );
  27247. }
  27248. setCurrentStack( previousStack );
  27249. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  27250. }
  27251. }
  27252. const stack = nodeProxy( StackNode );
  27253. addNodeClass( 'StackNode', StackNode );
  27254. class EquirectUVNode extends TempNode {
  27255. constructor( dirNode = positionWorldDirection ) {
  27256. super( 'vec2' );
  27257. this.dirNode = dirNode;
  27258. }
  27259. setup() {
  27260. const dir = this.dirNode;
  27261. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27262. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27263. return vec2( u, v );
  27264. }
  27265. }
  27266. const equirectUV = nodeProxy( EquirectUVNode );
  27267. addNodeClass( 'EquirectUVNode', EquirectUVNode );
  27268. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27269. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27270. constructor( size = 1, options = {} ) {
  27271. super( size, options );
  27272. this.isCubeRenderTarget = true;
  27273. }
  27274. fromEquirectangularTexture( renderer, texture$1 ) {
  27275. const currentMinFilter = texture$1.minFilter;
  27276. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27277. texture$1.generateMipmaps = true;
  27278. this.texture.type = texture$1.type;
  27279. this.texture.colorSpace = texture$1.colorSpace;
  27280. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27281. this.texture.minFilter = texture$1.minFilter;
  27282. this.texture.magFilter = texture$1.magFilter;
  27283. const geometry = new BoxGeometry( 5, 5, 5 );
  27284. const uvNode = equirectUV( positionWorldDirection );
  27285. const material = createNodeMaterialFromType( 'MeshBasicNodeMaterial' );
  27286. material.colorNode = texture( texture$1, uvNode, 0 );
  27287. material.side = BackSide;
  27288. material.blending = NoBlending;
  27289. const mesh = new Mesh( geometry, material );
  27290. const scene = new Scene();
  27291. scene.add( mesh );
  27292. // Avoid blurred poles
  27293. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27294. const camera = new CubeCamera( 1, 10, this );
  27295. camera.update( renderer, scene );
  27296. texture$1.minFilter = currentMinFilter;
  27297. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27298. mesh.geometry.dispose();
  27299. mesh.material.dispose();
  27300. return this;
  27301. }
  27302. }
  27303. // These defines must match with PMREMGenerator
  27304. const cubeUV_r0 = float( 1.0 );
  27305. const cubeUV_m0 = float( - 2.0 );
  27306. const cubeUV_r1 = float( 0.8 );
  27307. const cubeUV_m1 = float( - 1.0 );
  27308. const cubeUV_r4 = float( 0.4 );
  27309. const cubeUV_m4 = float( 2.0 );
  27310. const cubeUV_r5 = float( 0.305 );
  27311. const cubeUV_m5 = float( 3.0 );
  27312. const cubeUV_r6 = float( 0.21 );
  27313. const cubeUV_m6 = float( 4.0 );
  27314. const cubeUV_minMipLevel = float( 4.0 );
  27315. const cubeUV_minTileSize = float( 16.0 );
  27316. // These shader functions convert between the UV coordinates of a single face of
  27317. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  27318. // sampling a textureCube (not generally normalized ).
  27319. const getFace = tslFn( ( [ direction ] ) => {
  27320. const absDirection = vec3( abs( direction ) ).toVar();
  27321. const face = float( - 1.0 ).toVar();
  27322. If( absDirection.x.greaterThan( absDirection.z ), () => {
  27323. If( absDirection.x.greaterThan( absDirection.y ), () => {
  27324. face.assign( cond( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  27325. } ).else( () => {
  27326. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27327. } );
  27328. } ).else( () => {
  27329. If( absDirection.z.greaterThan( absDirection.y ), () => {
  27330. face.assign( cond( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  27331. } ).else( () => {
  27332. face.assign( cond( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  27333. } );
  27334. } );
  27335. return face;
  27336. } ).setLayout( {
  27337. name: 'getFace',
  27338. type: 'float',
  27339. inputs: [
  27340. { name: 'direction', type: 'vec3' }
  27341. ]
  27342. } );
  27343. // RH coordinate system; PMREM face-indexing convention
  27344. const getUV = tslFn( ( [ direction, face ] ) => {
  27345. const uv = vec2().toVar();
  27346. If( face.equal( 0.0 ), () => {
  27347. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  27348. } ).elseif( face.equal( 1.0 ), () => {
  27349. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  27350. } ).elseif( face.equal( 2.0 ), () => {
  27351. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  27352. } ).elseif( face.equal( 3.0 ), () => {
  27353. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  27354. } ).elseif( face.equal( 4.0 ), () => {
  27355. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  27356. } ).else( () => {
  27357. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  27358. } );
  27359. return mul( 0.5, uv.add( 1.0 ) );
  27360. } ).setLayout( {
  27361. name: 'getUV',
  27362. type: 'vec2',
  27363. inputs: [
  27364. { name: 'direction', type: 'vec3' },
  27365. { name: 'face', type: 'float' }
  27366. ]
  27367. } );
  27368. const roughnessToMip = tslFn( ( [ roughness ] ) => {
  27369. const mip = float( 0.0 ).toVar();
  27370. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  27371. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  27372. } ).elseif( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  27373. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  27374. } ).elseif( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  27375. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  27376. } ).elseif( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  27377. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  27378. } ).else( () => {
  27379. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  27380. } );
  27381. return mip;
  27382. } ).setLayout( {
  27383. name: 'roughnessToMip',
  27384. type: 'float',
  27385. inputs: [
  27386. { name: 'roughness', type: 'float' }
  27387. ]
  27388. } );
  27389. // RH coordinate system; PMREM face-indexing convention
  27390. const getDirection = tslFn( ( [ uv_immutable, face ] ) => {
  27391. const uv = uv_immutable.toVar();
  27392. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  27393. const direction = vec3( uv, 1.0 ).toVar();
  27394. If( face.equal( 0.0 ), () => {
  27395. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  27396. } ).elseif( face.equal( 1.0 ), () => {
  27397. direction.assign( direction.xzy );
  27398. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  27399. } ).elseif( face.equal( 2.0 ), () => {
  27400. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  27401. } ).elseif( face.equal( 3.0 ), () => {
  27402. direction.assign( direction.zyx );
  27403. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  27404. } ).elseif( face.equal( 4.0 ), () => {
  27405. direction.assign( direction.xzy );
  27406. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  27407. } ).elseif( face.equal( 5.0 ), () => {
  27408. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  27409. } );
  27410. return direction;
  27411. } ).setLayout( {
  27412. name: 'getDirection',
  27413. type: 'vec3',
  27414. inputs: [
  27415. { name: 'uv', type: 'vec2' },
  27416. { name: 'face', type: 'float' }
  27417. ]
  27418. } );
  27419. //
  27420. const textureCubeUV = tslFn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27421. const roughness = float( roughness_immutable );
  27422. const sampleDir = vec3( sampleDir_immutable );
  27423. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  27424. const mipF = fract( mip );
  27425. const mipInt = floor( mip );
  27426. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27427. If( mipF.notEqual( 0.0 ), () => {
  27428. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  27429. color0.assign( mix( color0, color1, mipF ) );
  27430. } );
  27431. return color0;
  27432. } );
  27433. const bilinearCubeUV = tslFn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  27434. const mipInt = float( mipInt_immutable ).toVar();
  27435. const direction = vec3( direction_immutable );
  27436. const face = float( getFace( direction ) ).toVar();
  27437. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  27438. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  27439. const faceSize = float( exp2( mipInt ) ).toVar();
  27440. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  27441. If( face.greaterThan( 2.0 ), () => {
  27442. uv.y.addAssign( faceSize );
  27443. face.subAssign( 3.0 );
  27444. } );
  27445. uv.x.addAssign( face.mul( faceSize ) );
  27446. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  27447. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  27448. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  27449. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  27450. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  27451. } );
  27452. const getSample = tslFn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27453. const cosTheta = cos( theta );
  27454. // Rodrigues' axis-angle rotation
  27455. const sampleDirection = outputDirection.mul( cosTheta )
  27456. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  27457. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  27458. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  27459. } );
  27460. const blur = tslFn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  27461. const axis = vec3( cond( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  27462. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  27463. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  27464. } );
  27465. axis.assign( normalize( axis ) );
  27466. const gl_FragColor = vec3().toVar();
  27467. 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 } ) ) );
  27468. loop( { start: int( 1 ), end: n }, ( { i } ) => {
  27469. If( i.greaterThanEqual( samples ), () => {
  27470. Break();
  27471. } );
  27472. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  27473. 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 } ) ) );
  27474. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  27475. } );
  27476. return vec4( gl_FragColor, 1 );
  27477. } );
  27478. const LOD_MIN = 4;
  27479. // The standard deviations (radians) associated with the extra mips. These are
  27480. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27481. // geometric shadowing function. These sigma values squared must match the
  27482. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27483. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  27484. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  27485. // samples and exit early, but not recompile the shader.
  27486. const MAX_SAMPLES = 20;
  27487. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27488. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  27489. const _clearColor$2 = /*@__PURE__*/ new Color();
  27490. let _oldTarget = null;
  27491. let _oldActiveCubeFace = 0;
  27492. let _oldActiveMipmapLevel = 0;
  27493. // Golden Ratio
  27494. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  27495. const INV_PHI = 1 / PHI;
  27496. // Vertices of a dodecahedron (except the opposites, which represent the
  27497. // same axis), used as axis directions evenly spread on a sphere.
  27498. const _axisDirections = [
  27499. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  27500. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  27501. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  27502. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  27503. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  27504. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  27505. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  27506. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  27507. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  27508. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  27509. ];
  27510. //
  27511. // WebGPU Face indices
  27512. const _faceLib = [
  27513. 3, 1, 5,
  27514. 0, 4, 2
  27515. ];
  27516. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  27517. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  27518. /**
  27519. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27520. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27521. * blur to be quickly accessed based on material roughness. It is packed into a
  27522. * special CubeUV format that allows us to perform custom interpolation so that
  27523. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27524. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27525. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27526. * higher roughness levels. In this way we maintain resolution to smoothly
  27527. * interpolate diffuse lighting while limiting sampling computation.
  27528. *
  27529. * Paper: Fast, Accurate Image-Based Lighting
  27530. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27531. */
  27532. class PMREMGenerator {
  27533. constructor( renderer ) {
  27534. this._renderer = renderer;
  27535. this._pingPongRenderTarget = null;
  27536. this._lodMax = 0;
  27537. this._cubeSize = 0;
  27538. this._lodPlanes = [];
  27539. this._sizeLods = [];
  27540. this._sigmas = [];
  27541. this._lodMeshes = [];
  27542. this._blurMaterial = null;
  27543. this._cubemapMaterial = null;
  27544. this._equirectMaterial = null;
  27545. this._backgroundBox = null;
  27546. }
  27547. /**
  27548. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27549. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27550. * in radians to be applied to the scene before PMREM generation. Optional near
  27551. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27552. * is placed at the origin).
  27553. */
  27554. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  27555. _oldTarget = this._renderer.getRenderTarget();
  27556. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27557. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27558. this._setSize( 256 );
  27559. const cubeUVRenderTarget = this._allocateTargets();
  27560. cubeUVRenderTarget.depthBuffer = true;
  27561. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  27562. if ( sigma > 0 ) {
  27563. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  27564. }
  27565. this._applyPMREM( cubeUVRenderTarget );
  27566. this._cleanup( cubeUVRenderTarget );
  27567. return cubeUVRenderTarget;
  27568. }
  27569. /**
  27570. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27571. * or HDR. The ideal input image size is 1k (1024 x 512),
  27572. * as this matches best with the 256 x 256 cubemap output.
  27573. */
  27574. fromEquirectangular( equirectangular, renderTarget = null ) {
  27575. return this._fromTexture( equirectangular, renderTarget );
  27576. }
  27577. /**
  27578. * Generates a PMREM from an cubemap texture, which can be either LDR
  27579. * or HDR. The ideal input cube size is 256 x 256,
  27580. * as this matches best with the 256 x 256 cubemap output.
  27581. */
  27582. fromCubemap( cubemap, renderTarget = null ) {
  27583. return this._fromTexture( cubemap, renderTarget );
  27584. }
  27585. /**
  27586. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27587. * your texture's network fetch for increased concurrency.
  27588. */
  27589. compileCubemapShader() {
  27590. if ( this._cubemapMaterial === null ) {
  27591. this._cubemapMaterial = _getCubemapMaterial();
  27592. this._compileMaterial( this._cubemapMaterial );
  27593. }
  27594. }
  27595. /**
  27596. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27597. * your texture's network fetch for increased concurrency.
  27598. */
  27599. compileEquirectangularShader() {
  27600. if ( this._equirectMaterial === null ) {
  27601. this._equirectMaterial = _getEquirectMaterial();
  27602. this._compileMaterial( this._equirectMaterial );
  27603. }
  27604. }
  27605. /**
  27606. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27607. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27608. * one of them will cause any others to also become unusable.
  27609. */
  27610. dispose() {
  27611. this._dispose();
  27612. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  27613. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  27614. if ( this._backgroundBox !== null ) {
  27615. this._backgroundBox.geometry.dispose();
  27616. this._backgroundBox.material.dispose();
  27617. }
  27618. }
  27619. // private interface
  27620. _setSize( cubeSize ) {
  27621. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  27622. this._cubeSize = Math.pow( 2, this._lodMax );
  27623. }
  27624. _dispose() {
  27625. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  27626. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  27627. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  27628. this._lodPlanes[ i ].dispose();
  27629. }
  27630. }
  27631. _cleanup( outputTarget ) {
  27632. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  27633. outputTarget.scissorTest = false;
  27634. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  27635. }
  27636. _fromTexture( texture, renderTarget ) {
  27637. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  27638. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  27639. } else { // Equirectangular
  27640. this._setSize( texture.image.width / 4 );
  27641. }
  27642. _oldTarget = this._renderer.getRenderTarget();
  27643. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  27644. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  27645. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  27646. this._textureToCubeUV( texture, cubeUVRenderTarget );
  27647. this._applyPMREM( cubeUVRenderTarget );
  27648. this._cleanup( cubeUVRenderTarget );
  27649. return cubeUVRenderTarget;
  27650. }
  27651. _allocateTargets() {
  27652. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  27653. const height = 4 * this._cubeSize;
  27654. const params = {
  27655. magFilter: LinearFilter,
  27656. minFilter: LinearFilter,
  27657. generateMipmaps: false,
  27658. type: HalfFloatType,
  27659. format: RGBAFormat,
  27660. colorSpace: LinearSRGBColorSpace,
  27661. //depthBuffer: false
  27662. };
  27663. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  27664. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  27665. if ( this._pingPongRenderTarget !== null ) {
  27666. this._dispose();
  27667. }
  27668. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  27669. const { _lodMax } = this;
  27670. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  27671. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  27672. }
  27673. return cubeUVRenderTarget;
  27674. }
  27675. _compileMaterial( material ) {
  27676. const tmpMesh = this._lodMeshes[ 0 ];
  27677. tmpMesh.material = material;
  27678. this._renderer.compile( tmpMesh, _flatCamera );
  27679. }
  27680. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  27681. const cubeCamera = _cubeCamera;
  27682. cubeCamera.near = near;
  27683. cubeCamera.far = far;
  27684. // px, py, pz, nx, ny, nz
  27685. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  27686. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  27687. const renderer = this._renderer;
  27688. const originalAutoClear = renderer.autoClear;
  27689. renderer.getClearColor( _clearColor$2 );
  27690. renderer.autoClear = false;
  27691. let backgroundBox = this._backgroundBox;
  27692. if ( backgroundBox === null ) {
  27693. const backgroundMaterial = new MeshBasicMaterial( {
  27694. name: 'PMREM.Background',
  27695. side: BackSide,
  27696. depthWrite: false,
  27697. depthTest: false
  27698. } );
  27699. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  27700. }
  27701. let useSolidColor = false;
  27702. const background = scene.background;
  27703. if ( background ) {
  27704. if ( background.isColor ) {
  27705. backgroundBox.material.color.copy( background );
  27706. scene.background = null;
  27707. useSolidColor = true;
  27708. }
  27709. } else {
  27710. backgroundBox.material.color.copy( _clearColor$2 );
  27711. useSolidColor = true;
  27712. }
  27713. renderer.setRenderTarget( cubeUVRenderTarget );
  27714. renderer.clear();
  27715. if ( useSolidColor ) {
  27716. renderer.render( backgroundBox, cubeCamera );
  27717. }
  27718. for ( let i = 0; i < 6; i ++ ) {
  27719. const col = i % 3;
  27720. if ( col === 0 ) {
  27721. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27722. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  27723. } else if ( col === 1 ) {
  27724. cubeCamera.up.set( 0, 0, upSign[ i ] );
  27725. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  27726. } else {
  27727. cubeCamera.up.set( 0, upSign[ i ], 0 );
  27728. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  27729. }
  27730. const size = this._cubeSize;
  27731. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  27732. renderer.render( scene, cubeCamera );
  27733. }
  27734. renderer.autoClear = originalAutoClear;
  27735. scene.background = background;
  27736. }
  27737. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  27738. const renderer = this._renderer;
  27739. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  27740. if ( isCubeTexture ) {
  27741. if ( this._cubemapMaterial === null ) {
  27742. this._cubemapMaterial = _getCubemapMaterial( texture );
  27743. }
  27744. } else {
  27745. if ( this._equirectMaterial === null ) {
  27746. this._equirectMaterial = _getEquirectMaterial( texture );
  27747. }
  27748. }
  27749. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  27750. material.fragmentNode.value = texture;
  27751. const mesh = this._lodMeshes[ 0 ];
  27752. mesh.material = material;
  27753. const size = this._cubeSize;
  27754. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  27755. renderer.setRenderTarget( cubeUVRenderTarget );
  27756. renderer.render( mesh, _flatCamera );
  27757. }
  27758. _applyPMREM( cubeUVRenderTarget ) {
  27759. const renderer = this._renderer;
  27760. const autoClear = renderer.autoClear;
  27761. renderer.autoClear = false;
  27762. const n = this._lodPlanes.length;
  27763. for ( let i = 1; i < n; i ++ ) {
  27764. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  27765. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  27766. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  27767. }
  27768. renderer.autoClear = autoClear;
  27769. }
  27770. /**
  27771. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27772. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27773. * the blur latitudinally (around the poles), and then longitudinally (towards
  27774. * the poles) to approximate the orthogonally-separable blur. It is least
  27775. * accurate at the poles, but still does a decent job.
  27776. */
  27777. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  27778. const pingPongRenderTarget = this._pingPongRenderTarget;
  27779. this._halfBlur(
  27780. cubeUVRenderTarget,
  27781. pingPongRenderTarget,
  27782. lodIn,
  27783. lodOut,
  27784. sigma,
  27785. 'latitudinal',
  27786. poleAxis );
  27787. this._halfBlur(
  27788. pingPongRenderTarget,
  27789. cubeUVRenderTarget,
  27790. lodOut,
  27791. lodOut,
  27792. sigma,
  27793. 'longitudinal',
  27794. poleAxis );
  27795. }
  27796. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  27797. const renderer = this._renderer;
  27798. const blurMaterial = this._blurMaterial;
  27799. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  27800. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  27801. }
  27802. // Number of standard deviations at which to cut off the discrete approximation.
  27803. const STANDARD_DEVIATIONS = 3;
  27804. const blurMesh = this._lodMeshes[ lodOut ];
  27805. blurMesh.material = blurMaterial;
  27806. const blurUniforms = blurMaterial.uniforms;
  27807. const pixels = this._sizeLods[ lodIn ] - 1;
  27808. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  27809. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27810. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  27811. if ( samples > MAX_SAMPLES ) {
  27812. console.warn( `sigmaRadians, ${
  27813. sigmaRadians}, is too large and will clip, as it requested ${
  27814. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  27815. }
  27816. const weights = [];
  27817. let sum = 0;
  27818. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  27819. const x = i / sigmaPixels;
  27820. const weight = Math.exp( - x * x / 2 );
  27821. weights.push( weight );
  27822. if ( i === 0 ) {
  27823. sum += weight;
  27824. } else if ( i < samples ) {
  27825. sum += 2 * weight;
  27826. }
  27827. }
  27828. for ( let i = 0; i < weights.length; i ++ ) {
  27829. weights[ i ] = weights[ i ] / sum;
  27830. }
  27831. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  27832. blurUniforms.envMap.value = targetIn.texture;
  27833. blurUniforms.samples.value = samples;
  27834. blurUniforms.weights.array = weights;
  27835. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  27836. if ( poleAxis ) {
  27837. blurUniforms.poleAxis.value = poleAxis;
  27838. }
  27839. const { _lodMax } = this;
  27840. blurUniforms.dTheta.value = radiansPerPixel;
  27841. blurUniforms.mipInt.value = _lodMax - lodIn;
  27842. const outputSize = this._sizeLods[ lodOut ];
  27843. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  27844. const y = 4 * ( this._cubeSize - outputSize );
  27845. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  27846. renderer.setRenderTarget( targetOut );
  27847. renderer.render( blurMesh, _flatCamera );
  27848. }
  27849. }
  27850. function _createPlanes( lodMax ) {
  27851. const lodPlanes = [];
  27852. const sizeLods = [];
  27853. const sigmas = [];
  27854. const lodMeshes = [];
  27855. let lod = lodMax;
  27856. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  27857. for ( let i = 0; i < totalLods; i ++ ) {
  27858. const sizeLod = Math.pow( 2, lod );
  27859. sizeLods.push( sizeLod );
  27860. let sigma = 1.0 / sizeLod;
  27861. if ( i > lodMax - LOD_MIN ) {
  27862. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  27863. } else if ( i === 0 ) {
  27864. sigma = 0;
  27865. }
  27866. sigmas.push( sigma );
  27867. const texelSize = 1.0 / ( sizeLod - 2 );
  27868. const min = - texelSize;
  27869. const max = 1 + texelSize;
  27870. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  27871. const cubeFaces = 6;
  27872. const vertices = 6;
  27873. const positionSize = 3;
  27874. const uvSize = 2;
  27875. const faceIndexSize = 1;
  27876. const position = new Float32Array( positionSize * vertices * cubeFaces );
  27877. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  27878. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  27879. for ( let face = 0; face < cubeFaces; face ++ ) {
  27880. const x = ( face % 3 ) * 2 / 3 - 1;
  27881. const y = face > 2 ? 0 : - 1;
  27882. const coordinates = [
  27883. x, y, 0,
  27884. x + 2 / 3, y, 0,
  27885. x + 2 / 3, y + 1, 0,
  27886. x, y, 0,
  27887. x + 2 / 3, y + 1, 0,
  27888. x, y + 1, 0
  27889. ];
  27890. const faceIdx = _faceLib[ face ];
  27891. position.set( coordinates, positionSize * vertices * faceIdx );
  27892. uv.set( uv1, uvSize * vertices * faceIdx );
  27893. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  27894. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  27895. }
  27896. const planes = new BufferGeometry();
  27897. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  27898. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  27899. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  27900. lodPlanes.push( planes );
  27901. lodMeshes.push( new Mesh( planes, null ) );
  27902. if ( lod > LOD_MIN ) {
  27903. lod --;
  27904. }
  27905. }
  27906. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  27907. }
  27908. function _createRenderTarget( width, height, params ) {
  27909. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  27910. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27911. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27912. cubeUVRenderTarget.texture.isPMREMTexture = true;
  27913. cubeUVRenderTarget.scissorTest = true;
  27914. return cubeUVRenderTarget;
  27915. }
  27916. function _setViewport( target, x, y, width, height ) {
  27917. const viewY = target.height - height - y;
  27918. target.viewport.set( x, viewY, width, height );
  27919. target.scissor.set( x, viewY, width, height );
  27920. }
  27921. function _getMaterial() {
  27922. const material = new NodeMaterial();
  27923. material.depthTest = false;
  27924. material.depthWrite = false;
  27925. material.blending = NoBlending;
  27926. return material;
  27927. }
  27928. function _getBlurShader( lodMax, width, height ) {
  27929. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  27930. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  27931. const dTheta = uniform( 0 );
  27932. const n = float( MAX_SAMPLES );
  27933. const latitudinal = uniform( 0 ); // false, bool
  27934. const samples = uniform( 1 ); // int
  27935. const envMap = texture( null );
  27936. const mipInt = uniform( 0 ); // int
  27937. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  27938. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  27939. const CUBEUV_MAX_MIP = float( lodMax );
  27940. const materialUniforms = {
  27941. n,
  27942. latitudinal,
  27943. weights,
  27944. poleAxis,
  27945. outputDirection,
  27946. dTheta,
  27947. samples,
  27948. envMap,
  27949. mipInt,
  27950. CUBEUV_TEXEL_WIDTH,
  27951. CUBEUV_TEXEL_HEIGHT,
  27952. CUBEUV_MAX_MIP
  27953. };
  27954. const material = _getMaterial();
  27955. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  27956. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  27957. return material;
  27958. }
  27959. function _getCubemapMaterial( envTexture ) {
  27960. const material = _getMaterial();
  27961. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  27962. return material;
  27963. }
  27964. function _getEquirectMaterial( envTexture ) {
  27965. const material = _getMaterial();
  27966. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  27967. return material;
  27968. }
  27969. let _id$5 = 0;
  27970. class BindGroup {
  27971. constructor( name = '', bindings = [], index = 0 ) {
  27972. this.name = name;
  27973. this.bindings = bindings;
  27974. this.index = index;
  27975. this.id = _id$5 ++;
  27976. }
  27977. }
  27978. const rendererCache = new WeakMap();
  27979. const typeFromLength = new Map( [
  27980. [ 2, 'vec2' ],
  27981. [ 3, 'vec3' ],
  27982. [ 4, 'vec4' ],
  27983. [ 9, 'mat3' ],
  27984. [ 16, 'mat4' ]
  27985. ] );
  27986. const typeFromArray = new Map( [
  27987. [ Int8Array, 'int' ],
  27988. [ Int16Array, 'int' ],
  27989. [ Int32Array, 'int' ],
  27990. [ Uint8Array, 'uint' ],
  27991. [ Uint16Array, 'uint' ],
  27992. [ Uint32Array, 'uint' ],
  27993. [ Float32Array, 'float' ]
  27994. ] );
  27995. const toFloat = ( value ) => {
  27996. value = Number( value );
  27997. return value + ( value % 1 ? '' : '.0' );
  27998. };
  27999. class NodeBuilder {
  28000. constructor( object, renderer, parser ) {
  28001. this.object = object;
  28002. this.material = ( object && object.material ) || null;
  28003. this.geometry = ( object && object.geometry ) || null;
  28004. this.renderer = renderer;
  28005. this.parser = parser;
  28006. this.scene = null;
  28007. this.camera = null;
  28008. this.nodes = [];
  28009. this.updateNodes = [];
  28010. this.updateBeforeNodes = [];
  28011. this.updateAfterNodes = [];
  28012. this.hashNodes = {};
  28013. this.lightsNode = null;
  28014. this.environmentNode = null;
  28015. this.fogNode = null;
  28016. this.clippingContext = null;
  28017. this.vertexShader = null;
  28018. this.fragmentShader = null;
  28019. this.computeShader = null;
  28020. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  28021. this.flowCode = { vertex: '', fragment: '', compute: '' };
  28022. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  28023. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  28024. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  28025. this.bindingsIndexes = {};
  28026. this.bindGroups = null;
  28027. this.attributes = [];
  28028. this.bufferAttributes = [];
  28029. this.varyings = [];
  28030. this.codes = {};
  28031. this.vars = {};
  28032. this.flow = { code: '' };
  28033. this.chaining = [];
  28034. this.stack = stack();
  28035. this.stacks = [];
  28036. this.tab = '\t';
  28037. this.instanceBindGroups = true;
  28038. this.currentFunctionNode = null;
  28039. this.context = {
  28040. keywords: new NodeKeywords(),
  28041. material: this.material
  28042. };
  28043. this.cache = new NodeCache();
  28044. this.globalCache = this.cache;
  28045. this.flowsData = new WeakMap();
  28046. this.shaderStage = null;
  28047. this.buildStage = null;
  28048. }
  28049. getBingGroupsCache() {
  28050. let bindGroupsCache = rendererCache.get( this.renderer );
  28051. if ( bindGroupsCache === undefined ) {
  28052. bindGroupsCache = new ChainMap();
  28053. rendererCache.set( this.renderer, bindGroupsCache );
  28054. }
  28055. return bindGroupsCache;
  28056. }
  28057. createRenderTarget( width, height, options ) {
  28058. return new RenderTarget( width, height, options );
  28059. }
  28060. createCubeRenderTarget( size, options ) {
  28061. return new CubeRenderTarget( size, options );
  28062. }
  28063. createPMREMGenerator() {
  28064. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28065. return new PMREMGenerator( this.renderer );
  28066. }
  28067. includes( node ) {
  28068. return this.nodes.includes( node );
  28069. }
  28070. _getBindGroup( groupName, bindings ) {
  28071. const bindGroupsCache = this.getBingGroupsCache();
  28072. //
  28073. const bindingsArray = [];
  28074. let sharedGroup = true;
  28075. for ( const binding of bindings ) {
  28076. bindingsArray.push( binding );
  28077. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  28078. }
  28079. //
  28080. let bindGroup;
  28081. if ( sharedGroup ) {
  28082. bindGroup = bindGroupsCache.get( bindingsArray );
  28083. if ( bindGroup === undefined ) {
  28084. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group );
  28085. bindGroupsCache.set( bindingsArray, bindGroup );
  28086. }
  28087. } else {
  28088. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group );
  28089. }
  28090. return bindGroup;
  28091. }
  28092. getBindGroupArray( groupName, shaderStage ) {
  28093. const bindings = this.bindings[ shaderStage ];
  28094. let bindGroup = bindings[ groupName ];
  28095. if ( bindGroup === undefined ) {
  28096. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  28097. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  28098. }
  28099. bindings[ groupName ] = bindGroup = [];
  28100. }
  28101. return bindGroup;
  28102. }
  28103. getBindings() {
  28104. let bindingsGroups = this.bindGroups;
  28105. if ( bindingsGroups === null ) {
  28106. const groups = {};
  28107. const bindings = this.bindings;
  28108. for ( const shaderStage of shaderStages ) {
  28109. for ( const groupName in bindings[ shaderStage ] ) {
  28110. const uniforms = bindings[ shaderStage ][ groupName ];
  28111. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  28112. groupUniforms.push( ...uniforms );
  28113. }
  28114. }
  28115. bindingsGroups = [];
  28116. for ( const groupName in groups ) {
  28117. const group = groups[ groupName ];
  28118. const bindingsGroup = this._getBindGroup( groupName, group );
  28119. bindingsGroups.push( bindingsGroup );
  28120. }
  28121. this.bindGroups = bindingsGroups;
  28122. }
  28123. return bindingsGroups;
  28124. }
  28125. setHashNode( node, hash ) {
  28126. this.hashNodes[ hash ] = node;
  28127. }
  28128. addNode( node ) {
  28129. if ( this.nodes.includes( node ) === false ) {
  28130. this.nodes.push( node );
  28131. this.setHashNode( node, node.getHash( this ) );
  28132. }
  28133. }
  28134. buildUpdateNodes() {
  28135. for ( const node of this.nodes ) {
  28136. const updateType = node.getUpdateType();
  28137. const updateBeforeType = node.getUpdateBeforeType();
  28138. const updateAfterType = node.getUpdateAfterType();
  28139. if ( updateType !== NodeUpdateType.NONE ) {
  28140. this.updateNodes.push( node.getSelf() );
  28141. }
  28142. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  28143. this.updateBeforeNodes.push( node );
  28144. }
  28145. if ( updateAfterType !== NodeUpdateType.NONE ) {
  28146. this.updateAfterNodes.push( node );
  28147. }
  28148. }
  28149. }
  28150. get currentNode() {
  28151. return this.chaining[ this.chaining.length - 1 ];
  28152. }
  28153. isFilteredTexture( texture ) {
  28154. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  28155. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  28156. }
  28157. addChain( node ) {
  28158. /*
  28159. if ( this.chaining.indexOf( node ) !== - 1 ) {
  28160. console.warn( 'Recursive node: ', node );
  28161. }
  28162. */
  28163. this.chaining.push( node );
  28164. }
  28165. removeChain( node ) {
  28166. const lastChain = this.chaining.pop();
  28167. if ( lastChain !== node ) {
  28168. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  28169. }
  28170. }
  28171. getMethod( method ) {
  28172. return method;
  28173. }
  28174. getNodeFromHash( hash ) {
  28175. return this.hashNodes[ hash ];
  28176. }
  28177. addFlow( shaderStage, node ) {
  28178. this.flowNodes[ shaderStage ].push( node );
  28179. return node;
  28180. }
  28181. setContext( context ) {
  28182. this.context = context;
  28183. }
  28184. getContext() {
  28185. return this.context;
  28186. }
  28187. getSharedContext() {
  28188. ({ ...this.context });
  28189. return this.context;
  28190. }
  28191. setCache( cache ) {
  28192. this.cache = cache;
  28193. }
  28194. getCache() {
  28195. return this.cache;
  28196. }
  28197. getCacheFromNode( node, parent = true ) {
  28198. const data = this.getDataFromNode( node );
  28199. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  28200. return data.cache;
  28201. }
  28202. isAvailable( /*name*/ ) {
  28203. return false;
  28204. }
  28205. getVertexIndex() {
  28206. console.warn( 'Abstract function.' );
  28207. }
  28208. getInstanceIndex() {
  28209. console.warn( 'Abstract function.' );
  28210. }
  28211. getDrawIndex() {
  28212. console.warn( 'Abstract function.' );
  28213. }
  28214. getFrontFacing() {
  28215. console.warn( 'Abstract function.' );
  28216. }
  28217. getFragCoord() {
  28218. console.warn( 'Abstract function.' );
  28219. }
  28220. isFlipY() {
  28221. return false;
  28222. }
  28223. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  28224. console.warn( 'Abstract function.' );
  28225. }
  28226. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  28227. console.warn( 'Abstract function.' );
  28228. }
  28229. generateConst( type, value = null ) {
  28230. if ( value === null ) {
  28231. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  28232. else if ( type === 'bool' ) value = false;
  28233. else if ( type === 'color' ) value = new Color();
  28234. else if ( type === 'vec2' ) value = new Vector2();
  28235. else if ( type === 'vec3' ) value = new Vector3();
  28236. else if ( type === 'vec4' ) value = new Vector4();
  28237. }
  28238. if ( type === 'float' ) return toFloat( value );
  28239. if ( type === 'int' ) return `${ Math.round( value ) }`;
  28240. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  28241. if ( type === 'bool' ) return value ? 'true' : 'false';
  28242. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  28243. const typeLength = this.getTypeLength( type );
  28244. const componentType = this.getComponentType( type );
  28245. const generateConst = value => this.generateConst( componentType, value );
  28246. if ( typeLength === 2 ) {
  28247. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  28248. } else if ( typeLength === 3 ) {
  28249. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  28250. } else if ( typeLength === 4 ) {
  28251. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  28252. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  28253. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  28254. } else if ( typeLength > 4 ) {
  28255. return `${ this.getType( type ) }()`;
  28256. }
  28257. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  28258. }
  28259. getType( type ) {
  28260. if ( type === 'color' ) return 'vec3';
  28261. return type;
  28262. }
  28263. hasGeometryAttribute( name ) {
  28264. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  28265. }
  28266. getAttribute( name, type ) {
  28267. const attributes = this.attributes;
  28268. // find attribute
  28269. for ( const attribute of attributes ) {
  28270. if ( attribute.name === name ) {
  28271. return attribute;
  28272. }
  28273. }
  28274. // create a new if no exist
  28275. const attribute = new NodeAttribute( name, type );
  28276. attributes.push( attribute );
  28277. return attribute;
  28278. }
  28279. getPropertyName( node/*, shaderStage*/ ) {
  28280. return node.name;
  28281. }
  28282. isVector( type ) {
  28283. return /vec\d/.test( type );
  28284. }
  28285. isMatrix( type ) {
  28286. return /mat\d/.test( type );
  28287. }
  28288. isReference( type ) {
  28289. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  28290. }
  28291. needsColorSpaceToLinear( /*texture*/ ) {
  28292. return false;
  28293. }
  28294. getComponentTypeFromTexture( texture ) {
  28295. const type = texture.type;
  28296. if ( texture.isDataTexture ) {
  28297. if ( type === IntType ) return 'int';
  28298. if ( type === UnsignedIntType ) return 'uint';
  28299. }
  28300. return 'float';
  28301. }
  28302. getElementType( type ) {
  28303. if ( type === 'mat2' ) return 'vec2';
  28304. if ( type === 'mat3' ) return 'vec3';
  28305. if ( type === 'mat4' ) return 'vec4';
  28306. return this.getComponentType( type );
  28307. }
  28308. getComponentType( type ) {
  28309. type = this.getVectorType( type );
  28310. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  28311. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  28312. if ( componentType === null ) return null;
  28313. if ( componentType[ 1 ] === 'b' ) return 'bool';
  28314. if ( componentType[ 1 ] === 'i' ) return 'int';
  28315. if ( componentType[ 1 ] === 'u' ) return 'uint';
  28316. return 'float';
  28317. }
  28318. getVectorType( type ) {
  28319. if ( type === 'color' ) return 'vec3';
  28320. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  28321. return type;
  28322. }
  28323. getTypeFromLength( length, componentType = 'float' ) {
  28324. if ( length === 1 ) return componentType;
  28325. const baseType = typeFromLength.get( length );
  28326. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  28327. return prefix + baseType;
  28328. }
  28329. getTypeFromArray( array ) {
  28330. return typeFromArray.get( array.constructor );
  28331. }
  28332. getTypeFromAttribute( attribute ) {
  28333. let dataAttribute = attribute;
  28334. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  28335. const array = dataAttribute.array;
  28336. const itemSize = attribute.itemSize;
  28337. const normalized = attribute.normalized;
  28338. let arrayType;
  28339. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  28340. arrayType = this.getTypeFromArray( array );
  28341. }
  28342. return this.getTypeFromLength( itemSize, arrayType );
  28343. }
  28344. getTypeLength( type ) {
  28345. const vecType = this.getVectorType( type );
  28346. const vecNum = /vec([2-4])/.exec( vecType );
  28347. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  28348. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  28349. if ( /mat2/.test( type ) === true ) return 4;
  28350. if ( /mat3/.test( type ) === true ) return 9;
  28351. if ( /mat4/.test( type ) === true ) return 16;
  28352. return 0;
  28353. }
  28354. getVectorFromMatrix( type ) {
  28355. return type.replace( 'mat', 'vec' );
  28356. }
  28357. changeComponentType( type, newComponentType ) {
  28358. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  28359. }
  28360. getIntegerType( type ) {
  28361. const componentType = this.getComponentType( type );
  28362. if ( componentType === 'int' || componentType === 'uint' ) return type;
  28363. return this.changeComponentType( type, 'int' );
  28364. }
  28365. addStack() {
  28366. this.stack = stack( this.stack );
  28367. this.stacks.push( getCurrentStack() || this.stack );
  28368. setCurrentStack( this.stack );
  28369. return this.stack;
  28370. }
  28371. removeStack() {
  28372. const lastStack = this.stack;
  28373. this.stack = lastStack.parent;
  28374. setCurrentStack( this.stacks.pop() );
  28375. return lastStack;
  28376. }
  28377. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  28378. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  28379. let nodeData = cache.getData( node );
  28380. if ( nodeData === undefined ) {
  28381. nodeData = {};
  28382. cache.setData( node, nodeData );
  28383. }
  28384. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  28385. return nodeData[ shaderStage ];
  28386. }
  28387. getNodeProperties( node, shaderStage = 'any' ) {
  28388. const nodeData = this.getDataFromNode( node, shaderStage );
  28389. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  28390. }
  28391. getBufferAttributeFromNode( node, type ) {
  28392. const nodeData = this.getDataFromNode( node );
  28393. let bufferAttribute = nodeData.bufferAttribute;
  28394. if ( bufferAttribute === undefined ) {
  28395. const index = this.uniforms.index ++;
  28396. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  28397. this.bufferAttributes.push( bufferAttribute );
  28398. nodeData.bufferAttribute = bufferAttribute;
  28399. }
  28400. return bufferAttribute;
  28401. }
  28402. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  28403. const nodeData = this.getDataFromNode( node, shaderStage );
  28404. if ( nodeData.structType === undefined ) {
  28405. const index = this.structs.index ++;
  28406. node.name = `StructType${ index }`;
  28407. this.structs[ shaderStage ].push( node );
  28408. nodeData.structType = node;
  28409. }
  28410. return node;
  28411. }
  28412. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  28413. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  28414. let nodeUniform = nodeData.uniform;
  28415. if ( nodeUniform === undefined ) {
  28416. const index = this.uniforms.index ++;
  28417. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  28418. this.uniforms[ shaderStage ].push( nodeUniform );
  28419. nodeData.uniform = nodeUniform;
  28420. }
  28421. return nodeUniform;
  28422. }
  28423. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  28424. const nodeData = this.getDataFromNode( node, shaderStage );
  28425. let nodeVar = nodeData.variable;
  28426. if ( nodeVar === undefined ) {
  28427. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  28428. if ( name === null ) name = 'nodeVar' + vars.length;
  28429. nodeVar = new NodeVar( name, type );
  28430. vars.push( nodeVar );
  28431. nodeData.variable = nodeVar;
  28432. }
  28433. return nodeVar;
  28434. }
  28435. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  28436. const nodeData = this.getDataFromNode( node, 'any' );
  28437. let nodeVarying = nodeData.varying;
  28438. if ( nodeVarying === undefined ) {
  28439. const varyings = this.varyings;
  28440. const index = varyings.length;
  28441. if ( name === null ) name = 'nodeVarying' + index;
  28442. nodeVarying = new NodeVarying( name, type );
  28443. varyings.push( nodeVarying );
  28444. nodeData.varying = nodeVarying;
  28445. }
  28446. return nodeVarying;
  28447. }
  28448. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  28449. const nodeData = this.getDataFromNode( node );
  28450. let nodeCode = nodeData.code;
  28451. if ( nodeCode === undefined ) {
  28452. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  28453. const index = codes.length;
  28454. nodeCode = new NodeCode( 'nodeCode' + index, type );
  28455. codes.push( nodeCode );
  28456. nodeData.code = nodeCode;
  28457. }
  28458. return nodeCode;
  28459. }
  28460. addLineFlowCode( code ) {
  28461. if ( code === '' ) return this;
  28462. code = this.tab + code;
  28463. if ( ! /;\s*$/.test( code ) ) {
  28464. code = code + ';\n';
  28465. }
  28466. this.flow.code += code;
  28467. return this;
  28468. }
  28469. addFlowCode( code ) {
  28470. this.flow.code += code;
  28471. return this;
  28472. }
  28473. addFlowTab() {
  28474. this.tab += '\t';
  28475. return this;
  28476. }
  28477. removeFlowTab() {
  28478. this.tab = this.tab.slice( 0, - 1 );
  28479. return this;
  28480. }
  28481. getFlowData( node/*, shaderStage*/ ) {
  28482. return this.flowsData.get( node );
  28483. }
  28484. flowNode( node ) {
  28485. const output = node.getNodeType( this );
  28486. const flowData = this.flowChildNode( node, output );
  28487. this.flowsData.set( node, flowData );
  28488. return flowData;
  28489. }
  28490. buildFunctionNode( shaderNode ) {
  28491. const fn = new FunctionNode();
  28492. const previous = this.currentFunctionNode;
  28493. this.currentFunctionNode = fn;
  28494. fn.code = this.buildFunctionCode( shaderNode );
  28495. this.currentFunctionNode = previous;
  28496. return fn;
  28497. }
  28498. flowShaderNode( shaderNode ) {
  28499. const layout = shaderNode.layout;
  28500. let inputs;
  28501. if ( shaderNode.isArrayInput ) {
  28502. inputs = [];
  28503. for ( const input of layout.inputs ) {
  28504. inputs.push( new ParameterNode( input.type, input.name ) );
  28505. }
  28506. } else {
  28507. inputs = {};
  28508. for ( const input of layout.inputs ) {
  28509. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  28510. }
  28511. }
  28512. //
  28513. shaderNode.layout = null;
  28514. const callNode = shaderNode.call( inputs );
  28515. const flowData = this.flowStagesNode( callNode, layout.type );
  28516. shaderNode.layout = layout;
  28517. return flowData;
  28518. }
  28519. flowStagesNode( node, output = null ) {
  28520. const previousFlow = this.flow;
  28521. const previousVars = this.vars;
  28522. const previousCache = this.cache;
  28523. const previousBuildStage = this.buildStage;
  28524. const previousStack = this.stack;
  28525. const flow = {
  28526. code: ''
  28527. };
  28528. this.flow = flow;
  28529. this.vars = {};
  28530. this.cache = new NodeCache();
  28531. this.stack = stack();
  28532. for ( const buildStage of defaultBuildStages ) {
  28533. this.setBuildStage( buildStage );
  28534. flow.result = node.build( this, output );
  28535. }
  28536. flow.vars = this.getVars( this.shaderStage );
  28537. this.flow = previousFlow;
  28538. this.vars = previousVars;
  28539. this.cache = previousCache;
  28540. this.stack = previousStack;
  28541. this.setBuildStage( previousBuildStage );
  28542. return flow;
  28543. }
  28544. getFunctionOperator() {
  28545. return null;
  28546. }
  28547. flowChildNode( node, output = null ) {
  28548. const previousFlow = this.flow;
  28549. const flow = {
  28550. code: ''
  28551. };
  28552. this.flow = flow;
  28553. flow.result = node.build( this, output );
  28554. this.flow = previousFlow;
  28555. return flow;
  28556. }
  28557. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  28558. const previousShaderStage = this.shaderStage;
  28559. this.setShaderStage( shaderStage );
  28560. const flowData = this.flowChildNode( node, output );
  28561. if ( propertyName !== null ) {
  28562. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  28563. }
  28564. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  28565. this.setShaderStage( previousShaderStage );
  28566. return flowData;
  28567. }
  28568. getAttributesArray() {
  28569. return this.attributes.concat( this.bufferAttributes );
  28570. }
  28571. getAttributes( /*shaderStage*/ ) {
  28572. console.warn( 'Abstract function.' );
  28573. }
  28574. getVaryings( /*shaderStage*/ ) {
  28575. console.warn( 'Abstract function.' );
  28576. }
  28577. getVar( type, name ) {
  28578. return `${ this.getType( type ) } ${ name }`;
  28579. }
  28580. getVars( shaderStage ) {
  28581. let snippet = '';
  28582. const vars = this.vars[ shaderStage ];
  28583. if ( vars !== undefined ) {
  28584. for ( const variable of vars ) {
  28585. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  28586. }
  28587. }
  28588. return snippet;
  28589. }
  28590. getUniforms( /*shaderStage*/ ) {
  28591. console.warn( 'Abstract function.' );
  28592. }
  28593. getCodes( shaderStage ) {
  28594. const codes = this.codes[ shaderStage ];
  28595. let code = '';
  28596. if ( codes !== undefined ) {
  28597. for ( const nodeCode of codes ) {
  28598. code += nodeCode.code + '\n';
  28599. }
  28600. }
  28601. return code;
  28602. }
  28603. getHash() {
  28604. return this.vertexShader + this.fragmentShader + this.computeShader;
  28605. }
  28606. setShaderStage( shaderStage ) {
  28607. this.shaderStage = shaderStage;
  28608. }
  28609. getShaderStage() {
  28610. return this.shaderStage;
  28611. }
  28612. setBuildStage( buildStage ) {
  28613. this.buildStage = buildStage;
  28614. }
  28615. getBuildStage() {
  28616. return this.buildStage;
  28617. }
  28618. buildCode() {
  28619. console.warn( 'Abstract function.' );
  28620. }
  28621. build() {
  28622. const { object, material } = this;
  28623. if ( material !== null ) {
  28624. NodeMaterial.fromMaterial( material ).build( this );
  28625. } else {
  28626. this.addFlow( 'compute', object );
  28627. }
  28628. // setup() -> stage 1: create possible new nodes and returns an output reference node
  28629. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  28630. // generate() -> stage 3: generate shader
  28631. for ( const buildStage of defaultBuildStages ) {
  28632. this.setBuildStage( buildStage );
  28633. if ( this.context.vertex && this.context.vertex.isNode ) {
  28634. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  28635. }
  28636. for ( const shaderStage of shaderStages ) {
  28637. this.setShaderStage( shaderStage );
  28638. const flowNodes = this.flowNodes[ shaderStage ];
  28639. for ( const node of flowNodes ) {
  28640. if ( buildStage === 'generate' ) {
  28641. this.flowNode( node );
  28642. } else {
  28643. node.build( this );
  28644. }
  28645. }
  28646. }
  28647. }
  28648. this.setBuildStage( null );
  28649. this.setShaderStage( null );
  28650. // stage 4: build code for a specific output
  28651. this.buildCode();
  28652. this.buildUpdateNodes();
  28653. return this;
  28654. }
  28655. getNodeUniform( uniformNode, type ) {
  28656. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  28657. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  28658. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  28659. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  28660. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  28661. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  28662. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  28663. throw new Error( `Uniform "${type}" not declared.` );
  28664. }
  28665. createNodeMaterial( type = 'NodeMaterial' ) {
  28666. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  28667. return createNodeMaterialFromType( type );
  28668. }
  28669. format( snippet, fromType, toType ) {
  28670. fromType = this.getVectorType( fromType );
  28671. toType = this.getVectorType( toType );
  28672. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  28673. return snippet;
  28674. }
  28675. const fromTypeLength = this.getTypeLength( fromType );
  28676. const toTypeLength = this.getTypeLength( toType );
  28677. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  28678. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  28679. }
  28680. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  28681. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  28682. }
  28683. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  28684. // @TODO: ignore for now
  28685. return snippet;
  28686. }
  28687. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  28688. // @TODO: ignore for now
  28689. return snippet;
  28690. }
  28691. if ( fromTypeLength === toTypeLength ) {
  28692. return `${ this.getType( toType ) }( ${ snippet } )`;
  28693. }
  28694. if ( fromTypeLength > toTypeLength ) {
  28695. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  28696. }
  28697. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  28698. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  28699. }
  28700. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  28701. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  28702. }
  28703. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  28704. // convert a number value to vector type, e.g:
  28705. // vec3( 1u ) -> vec3( float( 1u ) )
  28706. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  28707. }
  28708. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  28709. }
  28710. getSignature() {
  28711. return `// Three.js r${ REVISION } - Node System\n`;
  28712. }
  28713. }
  28714. class NodeFrame {
  28715. constructor() {
  28716. this.time = 0;
  28717. this.deltaTime = 0;
  28718. this.frameId = 0;
  28719. this.renderId = 0;
  28720. this.startTime = null;
  28721. this.updateMap = new WeakMap();
  28722. this.updateBeforeMap = new WeakMap();
  28723. this.updateAfterMap = new WeakMap();
  28724. this.renderer = null;
  28725. this.material = null;
  28726. this.camera = null;
  28727. this.object = null;
  28728. this.scene = null;
  28729. }
  28730. _getMaps( referenceMap, nodeRef ) {
  28731. let maps = referenceMap.get( nodeRef );
  28732. if ( maps === undefined ) {
  28733. maps = {
  28734. renderMap: new WeakMap(),
  28735. frameMap: new WeakMap()
  28736. };
  28737. referenceMap.set( nodeRef, maps );
  28738. }
  28739. return maps;
  28740. }
  28741. updateBeforeNode( node ) {
  28742. const updateType = node.getUpdateBeforeType();
  28743. const reference = node.updateReference( this );
  28744. if ( updateType === NodeUpdateType.FRAME ) {
  28745. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  28746. if ( frameMap.get( reference ) !== this.frameId ) {
  28747. if ( node.updateBefore( this ) !== false ) {
  28748. frameMap.set( reference, this.frameId );
  28749. }
  28750. }
  28751. } else if ( updateType === NodeUpdateType.RENDER ) {
  28752. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  28753. if ( renderMap.get( reference ) !== this.renderId ) {
  28754. if ( node.updateBefore( this ) !== false ) {
  28755. renderMap.set( reference, this.renderId );
  28756. }
  28757. }
  28758. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28759. node.updateBefore( this );
  28760. }
  28761. }
  28762. updateAfterNode( node ) {
  28763. const updateType = node.getUpdateAfterType();
  28764. const reference = node.updateReference( this );
  28765. if ( updateType === NodeUpdateType.FRAME ) {
  28766. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  28767. if ( frameMap.get( reference ) !== this.frameId ) {
  28768. if ( node.updateAfter( this ) !== false ) {
  28769. frameMap.set( reference, this.frameId );
  28770. }
  28771. }
  28772. } else if ( updateType === NodeUpdateType.RENDER ) {
  28773. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  28774. if ( renderMap.get( reference ) !== this.renderId ) {
  28775. if ( node.updateAfter( this ) !== false ) {
  28776. renderMap.set( reference, this.renderId );
  28777. }
  28778. }
  28779. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28780. node.updateAfter( this );
  28781. }
  28782. }
  28783. updateNode( node ) {
  28784. const updateType = node.getUpdateType();
  28785. const reference = node.updateReference( this );
  28786. if ( updateType === NodeUpdateType.FRAME ) {
  28787. const { frameMap } = this._getMaps( this.updateMap, reference );
  28788. if ( frameMap.get( reference ) !== this.frameId ) {
  28789. if ( node.update( this ) !== false ) {
  28790. frameMap.set( reference, this.frameId );
  28791. }
  28792. }
  28793. } else if ( updateType === NodeUpdateType.RENDER ) {
  28794. const { renderMap } = this._getMaps( this.updateMap, reference );
  28795. if ( renderMap.get( reference ) !== this.renderId ) {
  28796. if ( node.update( this ) !== false ) {
  28797. renderMap.set( reference, this.renderId );
  28798. }
  28799. }
  28800. } else if ( updateType === NodeUpdateType.OBJECT ) {
  28801. node.update( this );
  28802. }
  28803. }
  28804. update() {
  28805. this.frameId ++;
  28806. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  28807. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  28808. this.lastTime = performance.now();
  28809. this.time += this.deltaTime;
  28810. }
  28811. }
  28812. class NodeFunctionInput {
  28813. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  28814. this.type = type;
  28815. this.name = name;
  28816. this.count = count;
  28817. this.qualifier = qualifier;
  28818. this.isConst = isConst;
  28819. }
  28820. }
  28821. NodeFunctionInput.isNodeFunctionInput = true;
  28822. class StructTypeNode extends Node {
  28823. constructor( types ) {
  28824. super();
  28825. this.types = types;
  28826. this.isStructTypeNode = true;
  28827. }
  28828. getMemberTypes() {
  28829. return this.types;
  28830. }
  28831. }
  28832. addNodeClass( 'StructTypeNode', StructTypeNode );
  28833. class OutputStructNode extends Node {
  28834. constructor( ...members ) {
  28835. super();
  28836. this.members = members;
  28837. this.isOutputStructNode = true;
  28838. }
  28839. setup( builder ) {
  28840. super.setup( builder );
  28841. const members = this.members;
  28842. const types = [];
  28843. for ( let i = 0; i < members.length; i ++ ) {
  28844. types.push( members[ i ].getNodeType( builder ) );
  28845. }
  28846. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  28847. }
  28848. generate( builder, output ) {
  28849. const propertyName = builder.getOutputStructName();
  28850. const members = this.members;
  28851. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  28852. for ( let i = 0; i < members.length; i ++ ) {
  28853. const snippet = members[ i ].build( builder, output );
  28854. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  28855. }
  28856. return propertyName;
  28857. }
  28858. }
  28859. const outputStruct = nodeProxy( OutputStructNode );
  28860. addNodeClass( 'OutputStructNode', OutputStructNode );
  28861. function getTextureIndex( textures, name ) {
  28862. for ( let i = 0; i < textures.length; i ++ ) {
  28863. if ( textures[ i ].name === name ) {
  28864. return i;
  28865. }
  28866. }
  28867. return - 1;
  28868. }
  28869. class MRTNode extends OutputStructNode {
  28870. constructor( outputNodes ) {
  28871. super();
  28872. this.outputNodes = outputNodes;
  28873. this.isMRTNode = true;
  28874. }
  28875. getNode( name ) {
  28876. return this.outputNodes[ name ];
  28877. }
  28878. merge( mrtNode ) {
  28879. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  28880. return mrt( outputs );
  28881. }
  28882. setup( builder ) {
  28883. const outputNodes = this.outputNodes;
  28884. const mrt = builder.renderer.getRenderTarget();
  28885. const members = [];
  28886. const textures = mrt.textures;
  28887. for ( const name in outputNodes ) {
  28888. const index = getTextureIndex( textures, name );
  28889. members[ index ] = vec4( outputNodes[ name ] );
  28890. }
  28891. this.members = members;
  28892. return super.setup( builder );
  28893. }
  28894. }
  28895. const mrt = nodeProxy( MRTNode );
  28896. addNodeClass( 'MRTNode', MRTNode );
  28897. class HashNode extends Node {
  28898. constructor( seedNode ) {
  28899. super();
  28900. this.seedNode = seedNode;
  28901. }
  28902. setup( /*builder*/ ) {
  28903. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  28904. const state = this.seedNode.toUint().mul( 747796405 ).add( 2891336453 );
  28905. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  28906. const result = word.shiftRight( 22 ).bitXor( word );
  28907. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  28908. }
  28909. }
  28910. const hash = nodeProxy( HashNode );
  28911. addNodeElement( 'hash', hash );
  28912. addNodeClass( 'HashNode', HashNode );
  28913. // remapping functions https://iquilezles.org/articles/functions/
  28914. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  28915. 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 ) );
  28916. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  28917. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  28918. addNodeElement( 'parabola', parabola );
  28919. addNodeElement( 'gain', gain );
  28920. addNodeElement( 'pcurve', pcurve );
  28921. addNodeElement( 'sinc', sinc );
  28922. // https://github.com/cabbibo/glsl-tri-noise-3d
  28923. const tri = tslFn( ( [ x ] ) => {
  28924. return x.fract().sub( .5 ).abs();
  28925. } );
  28926. const tri3 = tslFn( ( [ p ] ) => {
  28927. 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. ) ) ) ) );
  28928. } );
  28929. const triNoise3D = tslFn( ( [ p_immutable, spd, time ] ) => {
  28930. const p = vec3( p_immutable ).toVar();
  28931. const z = float( 1.4 ).toVar();
  28932. const rz = float( 0.0 ).toVar();
  28933. const bp = vec3( p ).toVar();
  28934. loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  28935. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  28936. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  28937. bp.mulAssign( 1.8 );
  28938. z.mulAssign( 1.5 );
  28939. p.mulAssign( 1.2 );
  28940. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  28941. rz.addAssign( t.div( z ) );
  28942. bp.addAssign( 0.14 );
  28943. } );
  28944. return rz;
  28945. } );
  28946. // layouts
  28947. tri.setLayout( {
  28948. name: 'tri',
  28949. type: 'float',
  28950. inputs: [
  28951. { name: 'x', type: 'float' }
  28952. ]
  28953. } );
  28954. tri3.setLayout( {
  28955. name: 'tri3',
  28956. type: 'vec3',
  28957. inputs: [
  28958. { name: 'p', type: 'vec3' }
  28959. ]
  28960. } );
  28961. triNoise3D.setLayout( {
  28962. name: 'triNoise3D',
  28963. type: 'float',
  28964. inputs: [
  28965. { name: 'p', type: 'vec3' },
  28966. { name: 'spd', type: 'float' },
  28967. { name: 'time', type: 'float' }
  28968. ]
  28969. } );
  28970. let discardExpression;
  28971. class DiscardNode extends CondNode {
  28972. constructor( condNode ) {
  28973. discardExpression = discardExpression || expression( 'discard' );
  28974. super( condNode, discardExpression );
  28975. }
  28976. }
  28977. const inlineDiscard = nodeProxy( DiscardNode );
  28978. const discard = ( condNode ) => inlineDiscard( condNode ).append();
  28979. const Return = () => expression( 'return' ).append();
  28980. addNodeElement( 'discard', discard ); // @TODO: Check... this cause a little confusing using in chaining
  28981. addNodeClass( 'DiscardNode', DiscardNode );
  28982. class FunctionOverloadingNode extends Node {
  28983. constructor( functionNodes = [], ...parametersNodes ) {
  28984. super();
  28985. this.functionNodes = functionNodes;
  28986. this.parametersNodes = parametersNodes;
  28987. this._candidateFnCall = null;
  28988. this.global = true;
  28989. }
  28990. getNodeType() {
  28991. return this.functionNodes[ 0 ].shaderNode.layout.type;
  28992. }
  28993. setup( builder ) {
  28994. const params = this.parametersNodes;
  28995. let candidateFnCall = this._candidateFnCall;
  28996. if ( candidateFnCall === null ) {
  28997. let candidateFn = null;
  28998. let candidateScore = - 1;
  28999. for ( const functionNode of this.functionNodes ) {
  29000. const shaderNode = functionNode.shaderNode;
  29001. const layout = shaderNode.layout;
  29002. if ( layout === null ) {
  29003. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  29004. }
  29005. const inputs = layout.inputs;
  29006. if ( params.length === inputs.length ) {
  29007. let score = 0;
  29008. for ( let i = 0; i < params.length; i ++ ) {
  29009. const param = params[ i ];
  29010. const input = inputs[ i ];
  29011. if ( param.getNodeType( builder ) === input.type ) {
  29012. score ++;
  29013. } else {
  29014. score = 0;
  29015. }
  29016. }
  29017. if ( score > candidateScore ) {
  29018. candidateFn = functionNode;
  29019. candidateScore = score;
  29020. }
  29021. }
  29022. }
  29023. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  29024. }
  29025. return candidateFnCall;
  29026. }
  29027. }
  29028. const overloadingBaseFn = nodeProxy( FunctionOverloadingNode );
  29029. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  29030. addNodeClass( 'FunctionOverloadingNode', FunctionOverloadingNode );
  29031. class MatcapUVNode extends TempNode {
  29032. constructor() {
  29033. super( 'vec2' );
  29034. }
  29035. setup() {
  29036. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29037. const y = positionViewDirection.cross( x );
  29038. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29039. }
  29040. }
  29041. const matcapUV = nodeImmutable( MatcapUVNode );
  29042. addNodeClass( 'MatcapUVNode', MatcapUVNode );
  29043. class TimerNode extends UniformNode {
  29044. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  29045. super( value );
  29046. this.scope = scope;
  29047. this.scale = scale;
  29048. this.updateType = NodeUpdateType.FRAME;
  29049. }
  29050. /*
  29051. @TODO:
  29052. getNodeType( builder ) {
  29053. const scope = this.scope;
  29054. if ( scope === TimerNode.FRAME ) {
  29055. return 'uint';
  29056. }
  29057. return 'float';
  29058. }
  29059. */
  29060. update( frame ) {
  29061. const scope = this.scope;
  29062. const scale = this.scale;
  29063. if ( scope === TimerNode.LOCAL ) {
  29064. this.value += frame.deltaTime * scale;
  29065. } else if ( scope === TimerNode.DELTA ) {
  29066. this.value = frame.deltaTime * scale;
  29067. } else if ( scope === TimerNode.FRAME ) {
  29068. this.value = frame.frameId;
  29069. } else {
  29070. // global
  29071. this.value = frame.time * scale;
  29072. }
  29073. }
  29074. serialize( data ) {
  29075. super.serialize( data );
  29076. data.scope = this.scope;
  29077. data.scale = this.scale;
  29078. }
  29079. deserialize( data ) {
  29080. super.deserialize( data );
  29081. this.scope = data.scope;
  29082. this.scale = data.scale;
  29083. }
  29084. }
  29085. TimerNode.LOCAL = 'local';
  29086. TimerNode.GLOBAL = 'global';
  29087. TimerNode.DELTA = 'delta';
  29088. TimerNode.FRAME = 'frame';
  29089. // @TODO: add support to use node in timeScale
  29090. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  29091. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  29092. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  29093. const frameId = nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  29094. addNodeClass( 'TimerNode', TimerNode );
  29095. class OscNode extends Node {
  29096. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  29097. super();
  29098. this.method = method;
  29099. this.timeNode = timeNode;
  29100. }
  29101. getNodeType( builder ) {
  29102. return this.timeNode.getNodeType( builder );
  29103. }
  29104. setup() {
  29105. const method = this.method;
  29106. const timeNode = nodeObject( this.timeNode );
  29107. let outputNode = null;
  29108. if ( method === OscNode.SINE ) {
  29109. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  29110. } else if ( method === OscNode.SQUARE ) {
  29111. outputNode = timeNode.fract().round();
  29112. } else if ( method === OscNode.TRIANGLE ) {
  29113. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  29114. } else if ( method === OscNode.SAWTOOTH ) {
  29115. outputNode = timeNode.fract();
  29116. }
  29117. return outputNode;
  29118. }
  29119. serialize( data ) {
  29120. super.serialize( data );
  29121. data.method = this.method;
  29122. }
  29123. deserialize( data ) {
  29124. super.deserialize( data );
  29125. this.method = data.method;
  29126. }
  29127. }
  29128. OscNode.SINE = 'sine';
  29129. OscNode.SQUARE = 'square';
  29130. OscNode.TRIANGLE = 'triangle';
  29131. OscNode.SAWTOOTH = 'sawtooth';
  29132. const oscSine = nodeProxy( OscNode, OscNode.SINE );
  29133. const oscSquare = nodeProxy( OscNode, OscNode.SQUARE );
  29134. const oscTriangle = nodeProxy( OscNode, OscNode.TRIANGLE );
  29135. const oscSawtooth = nodeProxy( OscNode, OscNode.SAWTOOTH );
  29136. addNodeClass( 'OscNode', OscNode );
  29137. class PackingNode extends TempNode {
  29138. constructor( scope, node ) {
  29139. super();
  29140. this.scope = scope;
  29141. this.node = node;
  29142. }
  29143. getNodeType( builder ) {
  29144. return this.node.getNodeType( builder );
  29145. }
  29146. setup() {
  29147. const { scope, node } = this;
  29148. let result = null;
  29149. if ( scope === PackingNode.DIRECTION_TO_COLOR ) {
  29150. result = node.mul( 0.5 ).add( 0.5 );
  29151. } else if ( scope === PackingNode.COLOR_TO_DIRECTION ) {
  29152. result = node.mul( 2.0 ).sub( 1 );
  29153. }
  29154. return result;
  29155. }
  29156. }
  29157. PackingNode.DIRECTION_TO_COLOR = 'directionToColor';
  29158. PackingNode.COLOR_TO_DIRECTION = 'colorToDirection';
  29159. const directionToColor = nodeProxy( PackingNode, PackingNode.DIRECTION_TO_COLOR );
  29160. const colorToDirection = nodeProxy( PackingNode, PackingNode.COLOR_TO_DIRECTION );
  29161. addNodeElement( 'directionToColor', directionToColor );
  29162. addNodeElement( 'colorToDirection', colorToDirection );
  29163. addNodeClass( 'PackingNode', PackingNode );
  29164. class RemapNode extends Node {
  29165. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  29166. super();
  29167. this.node = node;
  29168. this.inLowNode = inLowNode;
  29169. this.inHighNode = inHighNode;
  29170. this.outLowNode = outLowNode;
  29171. this.outHighNode = outHighNode;
  29172. this.doClamp = true;
  29173. }
  29174. setup() {
  29175. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  29176. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  29177. if ( doClamp === true ) t = t.clamp();
  29178. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  29179. }
  29180. }
  29181. const remap = nodeProxy( RemapNode, null, null, { doClamp: false } );
  29182. const remapClamp = nodeProxy( RemapNode );
  29183. addNodeElement( 'remap', remap );
  29184. addNodeElement( 'remapClamp', remapClamp );
  29185. addNodeClass( 'RemapNode', RemapNode );
  29186. const rotateUV = tslFn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  29187. return uv.sub( center ).rotate( rotation ).add( center );
  29188. } );
  29189. const spherizeUV = tslFn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  29190. const delta = uv.sub( center );
  29191. const delta2 = delta.dot( delta );
  29192. const delta4 = delta2.mul( delta2 );
  29193. const deltaOffset = delta4.mul( strength );
  29194. return uv.add( delta.mul( deltaOffset ) );
  29195. } );
  29196. addNodeElement( 'rotateUV', rotateUV );
  29197. addNodeElement( 'spherizeUV', spherizeUV );
  29198. const billboarding = tslFn( ( { position = null, horizontal = true, vertical = false } ) => {
  29199. let worldMatrix;
  29200. if ( position !== null ) {
  29201. worldMatrix = modelWorldMatrix.toVar();
  29202. worldMatrix[ 3 ][ 0 ] = position.x;
  29203. worldMatrix[ 3 ][ 1 ] = position.y;
  29204. worldMatrix[ 3 ][ 2 ] = position.z;
  29205. } else {
  29206. worldMatrix = modelWorldMatrix;
  29207. }
  29208. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  29209. if ( defined( horizontal ) ) {
  29210. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  29211. modelViewMatrix[ 0 ][ 1 ] = 0;
  29212. modelViewMatrix[ 0 ][ 2 ] = 0;
  29213. }
  29214. if ( defined( vertical ) ) {
  29215. modelViewMatrix[ 1 ][ 0 ] = 0;
  29216. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  29217. modelViewMatrix[ 1 ][ 2 ] = 0;
  29218. }
  29219. modelViewMatrix[ 2 ][ 0 ] = 0;
  29220. modelViewMatrix[ 2 ][ 1 ] = 0;
  29221. modelViewMatrix[ 2 ][ 2 ] = 1;
  29222. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  29223. } );
  29224. class RotateNode extends TempNode {
  29225. constructor( positionNode, rotationNode ) {
  29226. super();
  29227. this.positionNode = positionNode;
  29228. this.rotationNode = rotationNode;
  29229. }
  29230. getNodeType( builder ) {
  29231. return this.positionNode.getNodeType( builder );
  29232. }
  29233. setup( builder ) {
  29234. const { rotationNode, positionNode } = this;
  29235. const nodeType = this.getNodeType( builder );
  29236. if ( nodeType === 'vec2' ) {
  29237. const cosAngle = rotationNode.cos();
  29238. const sinAngle = rotationNode.sin();
  29239. const rotationMatrix = mat2(
  29240. cosAngle, sinAngle,
  29241. sinAngle.negate(), cosAngle
  29242. );
  29243. return rotationMatrix.mul( positionNode );
  29244. } else {
  29245. const rotation = rotationNode;
  29246. 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 ) );
  29247. 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 ) );
  29248. 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 ) );
  29249. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29250. }
  29251. }
  29252. }
  29253. const rotate = nodeProxy( RotateNode );
  29254. addNodeElement( 'rotate', rotate );
  29255. addNodeClass( 'RotateNode', RotateNode );
  29256. class SpriteSheetUVNode extends Node {
  29257. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  29258. super( 'vec2' );
  29259. this.countNode = countNode;
  29260. this.uvNode = uvNode;
  29261. this.frameNode = frameNode;
  29262. }
  29263. setup() {
  29264. const { frameNode, uvNode, countNode } = this;
  29265. const { width, height } = countNode;
  29266. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  29267. const column = frameNum.mod( width );
  29268. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  29269. const scale = countNode.reciprocal();
  29270. const uvFrameOffset = vec2( column, row );
  29271. return uvNode.add( uvFrameOffset ).mul( scale );
  29272. }
  29273. }
  29274. const spritesheetUV = nodeProxy( SpriteSheetUVNode );
  29275. addNodeClass( 'SpriteSheetUVNode', SpriteSheetUVNode );
  29276. class StorageArrayElementNode extends ArrayElementNode {
  29277. constructor( storageBufferNode, indexNode ) {
  29278. super( storageBufferNode, indexNode );
  29279. this.isStorageArrayElementNode = true;
  29280. }
  29281. set storageBufferNode( value ) {
  29282. this.node = value;
  29283. }
  29284. get storageBufferNode() {
  29285. return this.node;
  29286. }
  29287. setup( builder ) {
  29288. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29289. if ( ! this.node.instanceIndex && this.node.bufferObject === true ) {
  29290. builder.setupPBO( this.node );
  29291. }
  29292. }
  29293. return super.setup( builder );
  29294. }
  29295. generate( builder, output ) {
  29296. let snippet;
  29297. const isAssignContext = builder.context.assign;
  29298. //
  29299. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  29300. const { node } = this;
  29301. if ( ! node.instanceIndex && this.node.bufferObject === true && isAssignContext !== true ) {
  29302. snippet = builder.generatePBO( this );
  29303. } else {
  29304. snippet = node.build( builder );
  29305. }
  29306. } else {
  29307. snippet = super.generate( builder );
  29308. }
  29309. if ( isAssignContext !== true ) {
  29310. const type = this.getNodeType( builder );
  29311. snippet = builder.format( snippet, type, output );
  29312. }
  29313. return snippet;
  29314. }
  29315. }
  29316. const storageElement = nodeProxy( StorageArrayElementNode );
  29317. addNodeElement( 'storageElement', storageElement );
  29318. addNodeClass( 'StorageArrayElementNode', StorageArrayElementNode );
  29319. class TriplanarTexturesNode extends Node {
  29320. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  29321. super( 'vec4' );
  29322. this.textureXNode = textureXNode;
  29323. this.textureYNode = textureYNode;
  29324. this.textureZNode = textureZNode;
  29325. this.scaleNode = scaleNode;
  29326. this.positionNode = positionNode;
  29327. this.normalNode = normalNode;
  29328. }
  29329. setup() {
  29330. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  29331. // Ref: https://github.com/keijiro/StandardTriplanar
  29332. // Blending factor of triplanar mapping
  29333. let bf = normalNode.abs().normalize();
  29334. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  29335. // Triplanar mapping
  29336. const tx = positionNode.yz.mul( scaleNode );
  29337. const ty = positionNode.zx.mul( scaleNode );
  29338. const tz = positionNode.xy.mul( scaleNode );
  29339. // Base color
  29340. const textureX = textureXNode.value;
  29341. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  29342. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  29343. const cx = texture( textureX, tx ).mul( bf.x );
  29344. const cy = texture( textureY, ty ).mul( bf.y );
  29345. const cz = texture( textureZ, tz ).mul( bf.z );
  29346. return add( cx, cy, cz );
  29347. }
  29348. }
  29349. const triplanarTextures = nodeProxy( TriplanarTexturesNode );
  29350. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  29351. addNodeElement( 'triplanarTexture', triplanarTexture );
  29352. addNodeClass( 'TriplanarTexturesNode', TriplanarTexturesNode );
  29353. const _reflectorPlane = new Plane();
  29354. const _normal = new Vector3();
  29355. const _reflectorWorldPosition = new Vector3();
  29356. const _cameraWorldPosition = new Vector3();
  29357. const _rotationMatrix = new Matrix4();
  29358. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  29359. const clipPlane = new Vector4();
  29360. const _view = new Vector3();
  29361. const _target = new Vector3();
  29362. const _q = new Vector4();
  29363. const _size$6 = new Vector2();
  29364. const _defaultRT = new RenderTarget();
  29365. const _defaultUV = vec2( viewportTopLeft.x.oneMinus(), viewportTopLeft.y );
  29366. let _inReflector = false;
  29367. class ReflectorNode extends TextureNode {
  29368. constructor( parameters = {} ) {
  29369. super( _defaultRT.texture, _defaultUV );
  29370. const {
  29371. target = new Object3D(),
  29372. resolution = 1,
  29373. generateMipmaps = false,
  29374. bounces = true
  29375. } = parameters;
  29376. //
  29377. this.target = target;
  29378. this.resolution = resolution;
  29379. this.generateMipmaps = generateMipmaps;
  29380. this.bounces = bounces;
  29381. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  29382. this.virtualCameras = new WeakMap();
  29383. this.renderTargets = new WeakMap();
  29384. }
  29385. _updateResolution( renderTarget, renderer ) {
  29386. const resolution = this.resolution;
  29387. renderer.getDrawingBufferSize( _size$6 );
  29388. renderTarget.setSize( Math.round( _size$6.width * resolution ), Math.round( _size$6.height * resolution ) );
  29389. }
  29390. setup( builder ) {
  29391. this._updateResolution( _defaultRT, builder.renderer );
  29392. return super.setup( builder );
  29393. }
  29394. getTextureNode() {
  29395. return this.textureNode;
  29396. }
  29397. getVirtualCamera( camera ) {
  29398. let virtualCamera = this.virtualCameras.get( camera );
  29399. if ( virtualCamera === undefined ) {
  29400. virtualCamera = camera.clone();
  29401. this.virtualCameras.set( camera, virtualCamera );
  29402. }
  29403. return virtualCamera;
  29404. }
  29405. getRenderTarget( camera ) {
  29406. let renderTarget = this.renderTargets.get( camera );
  29407. if ( renderTarget === undefined ) {
  29408. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  29409. if ( this.generateMipmaps === true ) {
  29410. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  29411. renderTarget.texture.generateMipmaps = true;
  29412. }
  29413. this.renderTargets.set( camera, renderTarget );
  29414. }
  29415. return renderTarget;
  29416. }
  29417. updateBefore( frame ) {
  29418. if ( this.bounces === false && _inReflector ) return false;
  29419. _inReflector = true;
  29420. const { scene, camera, renderer, material } = frame;
  29421. const { target } = this;
  29422. const virtualCamera = this.getVirtualCamera( camera );
  29423. const renderTarget = this.getRenderTarget( virtualCamera );
  29424. renderer.getDrawingBufferSize( _size$6 );
  29425. this._updateResolution( renderTarget, renderer );
  29426. //
  29427. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  29428. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  29429. _rotationMatrix.extractRotation( target.matrixWorld );
  29430. _normal.set( 0, 0, 1 );
  29431. _normal.applyMatrix4( _rotationMatrix );
  29432. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  29433. // Avoid rendering when reflector is facing away
  29434. if ( _view.dot( _normal ) > 0 ) return;
  29435. _view.reflect( _normal ).negate();
  29436. _view.add( _reflectorWorldPosition );
  29437. _rotationMatrix.extractRotation( camera.matrixWorld );
  29438. _lookAtPosition.set( 0, 0, - 1 );
  29439. _lookAtPosition.applyMatrix4( _rotationMatrix );
  29440. _lookAtPosition.add( _cameraWorldPosition );
  29441. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  29442. _target.reflect( _normal ).negate();
  29443. _target.add( _reflectorWorldPosition );
  29444. //
  29445. virtualCamera.coordinateSystem = camera.coordinateSystem;
  29446. virtualCamera.position.copy( _view );
  29447. virtualCamera.up.set( 0, 1, 0 );
  29448. virtualCamera.up.applyMatrix4( _rotationMatrix );
  29449. virtualCamera.up.reflect( _normal );
  29450. virtualCamera.lookAt( _target );
  29451. virtualCamera.near = camera.near;
  29452. virtualCamera.far = camera.far;
  29453. virtualCamera.updateMatrixWorld();
  29454. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  29455. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  29456. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  29457. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  29458. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  29459. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  29460. const projectionMatrix = virtualCamera.projectionMatrix;
  29461. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  29462. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  29463. _q.z = - 1.0;
  29464. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  29465. // Calculate the scaled plane vector
  29466. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  29467. const clipBias = 0;
  29468. // Replacing the third row of the projection matrix
  29469. projectionMatrix.elements[ 2 ] = clipPlane.x;
  29470. projectionMatrix.elements[ 6 ] = clipPlane.y;
  29471. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  29472. projectionMatrix.elements[ 14 ] = clipPlane.w;
  29473. //
  29474. this.value = renderTarget.texture;
  29475. material.visible = false;
  29476. const currentRenderTarget = renderer.getRenderTarget();
  29477. renderer.setRenderTarget( renderTarget );
  29478. renderer.render( scene, virtualCamera );
  29479. renderer.setRenderTarget( currentRenderTarget );
  29480. material.visible = true;
  29481. _inReflector = false;
  29482. }
  29483. }
  29484. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  29485. // Helper for passes that need to fill the viewport with a single quad.
  29486. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29487. // https://github.com/mrdoob/three.js/pull/21358
  29488. class QuadGeometry extends BufferGeometry {
  29489. constructor( flipY = false ) {
  29490. super();
  29491. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  29492. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  29493. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  29494. }
  29495. }
  29496. const _geometry = /*@__PURE__*/ new QuadGeometry();
  29497. class QuadMesh extends Mesh {
  29498. constructor( material = null ) {
  29499. super( _geometry, material );
  29500. this.camera = _camera;
  29501. }
  29502. renderAsync( renderer ) {
  29503. return renderer.renderAsync( this, _camera );
  29504. }
  29505. render( renderer ) {
  29506. renderer.render( this, _camera );
  29507. }
  29508. }
  29509. const _size$5 = /*@__PURE__*/ new Vector2();
  29510. class RTTNode extends TextureNode {
  29511. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  29512. const renderTarget = new RenderTarget( width, height, options );
  29513. super( renderTarget.texture, uv() );
  29514. this.node = node;
  29515. this.width = width;
  29516. this.height = height;
  29517. this.renderTarget = renderTarget;
  29518. this.textureNeedsUpdate = true;
  29519. this.autoUpdate = true;
  29520. this.updateMap = new WeakMap();
  29521. this._rttNode = null;
  29522. this._quadMesh = new QuadMesh( new NodeMaterial() );
  29523. this.updateBeforeType = NodeUpdateType.RENDER;
  29524. }
  29525. get autoSize() {
  29526. return this.width === null;
  29527. }
  29528. setup( builder ) {
  29529. this._rttNode = this.node.context( builder.getSharedContext() );
  29530. this._quadMesh.material.needsUpdate = true;
  29531. return super.setup( builder );
  29532. }
  29533. setSize( width, height ) {
  29534. this.width = width;
  29535. this.height = height;
  29536. const effectiveWidth = width * this.pixelRatio;
  29537. const effectiveHeight = height * this.pixelRatio;
  29538. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  29539. this.textureNeedsUpdate = true;
  29540. }
  29541. setPixelRatio( pixelRatio ) {
  29542. this.pixelRatio = pixelRatio;
  29543. this.setSize( this.width, this.height );
  29544. }
  29545. updateBefore( { renderer } ) {
  29546. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  29547. this.textureNeedsUpdate = false;
  29548. //
  29549. if ( this.autoSize === true ) {
  29550. this.pixelRatio = renderer.getPixelRatio();
  29551. const size = renderer.getSize( _size$5 );
  29552. this.setSize( size.width, size.height );
  29553. }
  29554. //
  29555. this._quadMesh.material.fragmentNode = this._rttNode;
  29556. //
  29557. const currentRenderTarget = renderer.getRenderTarget();
  29558. renderer.setRenderTarget( this.renderTarget );
  29559. this._quadMesh.render( renderer );
  29560. renderer.setRenderTarget( currentRenderTarget );
  29561. }
  29562. clone() {
  29563. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  29564. newNode.sampler = this.sampler;
  29565. newNode.referenceNode = this;
  29566. return newNode;
  29567. }
  29568. }
  29569. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  29570. addNodeElement( 'toTexture', ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params ) );
  29571. addNodeClass( 'RTTNode', RTTNode );
  29572. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  29573. const bitangentGeometry = /*#__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  29574. const bitangentLocal = /*#__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  29575. const bitangentView = /*#__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  29576. const bitangentWorld = /*#__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  29577. const transformedBitangentView = /*#__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  29578. const transformedBitangentWorld = /*#__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  29579. const TBNViewMatrix = mat3( tangentView, bitangentView, normalView );
  29580. const parallaxDirection = positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  29581. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  29582. const transformedBentNormalView = ( () => {
  29583. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  29584. let bentNormal = anisotropyB.cross( positionViewDirection );
  29585. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  29586. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  29587. return bentNormal;
  29588. } )();
  29589. class VertexColorNode extends AttributeNode {
  29590. constructor( index = 0 ) {
  29591. super( null, 'vec4' );
  29592. this.isVertexColorNode = true;
  29593. this.index = index;
  29594. }
  29595. getAttributeName( /*builder*/ ) {
  29596. const index = this.index;
  29597. return 'color' + ( index > 0 ? index : '' );
  29598. }
  29599. generate( builder ) {
  29600. const attributeName = this.getAttributeName( builder );
  29601. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  29602. let result;
  29603. if ( geometryAttribute === true ) {
  29604. result = super.generate( builder );
  29605. } else {
  29606. // Vertex color fallback should be white
  29607. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  29608. }
  29609. return result;
  29610. }
  29611. serialize( data ) {
  29612. super.serialize( data );
  29613. data.index = this.index;
  29614. }
  29615. deserialize( data ) {
  29616. super.deserialize( data );
  29617. this.index = data.index;
  29618. }
  29619. }
  29620. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  29621. addNodeClass( 'VertexColorNode', VertexColorNode );
  29622. class RendererReferenceNode extends ReferenceNode {
  29623. constructor( property, inputType, renderer = null ) {
  29624. super( property, inputType, renderer );
  29625. this.renderer = renderer;
  29626. }
  29627. updateReference( state ) {
  29628. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  29629. return this.reference;
  29630. }
  29631. }
  29632. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  29633. addNodeClass( 'RendererReferenceNode', RendererReferenceNode );
  29634. // Mipped Bicubic Texture Filtering by N8
  29635. // https://www.shadertoy.com/view/Dl2SDW
  29636. const bC = 1.0 / 6.0;
  29637. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  29638. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  29639. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  29640. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  29641. const g0 = ( a ) => w0( a ).add( w1( a ) );
  29642. const g1 = ( a ) => w2( a ).add( w3( a ) );
  29643. // h0 and h1 are the two offset functions
  29644. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  29645. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  29646. const bicubic = ( textureNode, texelSize, lod ) => {
  29647. const uv = textureNode.uvNode;
  29648. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  29649. const iuv = floor( uvScaled );
  29650. const fuv = fract( uvScaled );
  29651. const g0x = g0( fuv.x );
  29652. const g1x = g1( fuv.x );
  29653. const h0x = h0( fuv.x );
  29654. const h1x = h1( fuv.x );
  29655. const h0y = h0( fuv.y );
  29656. const h1y = h1( fuv.y );
  29657. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29658. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  29659. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29660. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  29661. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  29662. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  29663. return a.add( b );
  29664. };
  29665. const textureBicubicMethod = ( textureNode, lodNode ) => {
  29666. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  29667. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  29668. const fLodSizeInv = div( 1.0, fLodSize );
  29669. const cLodSizeInv = div( 1.0, cLodSize );
  29670. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  29671. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  29672. return fract( lodNode ).mix( fSample, cSample );
  29673. };
  29674. class TextureBicubicNode extends TempNode {
  29675. constructor( textureNode, blurNode = float( 3 ) ) {
  29676. super( 'vec4' );
  29677. this.textureNode = textureNode;
  29678. this.blurNode = blurNode;
  29679. }
  29680. setup() {
  29681. return textureBicubicMethod( this.textureNode, this.blurNode );
  29682. }
  29683. }
  29684. const textureBicubic = nodeProxy( TextureBicubicNode );
  29685. addNodeElement( 'bicubic', textureBicubic );
  29686. addNodeClass( 'TextureBicubicNode', TextureBicubicNode );
  29687. class PointUVNode extends Node {
  29688. constructor() {
  29689. super( 'vec2' );
  29690. this.isPointUVNode = true;
  29691. }
  29692. generate( /*builder*/ ) {
  29693. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  29694. }
  29695. }
  29696. const pointUV = nodeImmutable( PointUVNode );
  29697. addNodeClass( 'PointUVNode', PointUVNode );
  29698. class SceneNode extends Node {
  29699. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  29700. super();
  29701. this.scope = scope;
  29702. this.scene = scene;
  29703. }
  29704. setup( builder ) {
  29705. const scope = this.scope;
  29706. const scene = this.scene !== null ? this.scene : builder.scene;
  29707. let output;
  29708. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  29709. output = reference( 'backgroundBlurriness', 'float', scene );
  29710. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  29711. output = reference( 'backgroundIntensity', 'float', scene );
  29712. } else {
  29713. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  29714. }
  29715. return output;
  29716. }
  29717. }
  29718. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  29719. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  29720. const backgroundBlurriness = nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  29721. const backgroundIntensity = nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  29722. addNodeClass( 'SceneNode', SceneNode );
  29723. const GPUPrimitiveTopology = {
  29724. PointList: 'point-list',
  29725. LineList: 'line-list',
  29726. LineStrip: 'line-strip',
  29727. TriangleList: 'triangle-list',
  29728. TriangleStrip: 'triangle-strip',
  29729. };
  29730. const GPUCompareFunction = {
  29731. Never: 'never',
  29732. Less: 'less',
  29733. Equal: 'equal',
  29734. LessEqual: 'less-equal',
  29735. Greater: 'greater',
  29736. NotEqual: 'not-equal',
  29737. GreaterEqual: 'greater-equal',
  29738. Always: 'always'
  29739. };
  29740. const GPUStoreOp = {
  29741. Store: 'store',
  29742. Discard: 'discard'
  29743. };
  29744. const GPULoadOp = {
  29745. Load: 'load',
  29746. Clear: 'clear'
  29747. };
  29748. const GPUFrontFace = {
  29749. CCW: 'ccw',
  29750. CW: 'cw'
  29751. };
  29752. const GPUCullMode = {
  29753. None: 'none',
  29754. Front: 'front',
  29755. Back: 'back'
  29756. };
  29757. const GPUIndexFormat = {
  29758. Uint16: 'uint16',
  29759. Uint32: 'uint32'
  29760. };
  29761. const GPUTextureFormat = {
  29762. // 8-bit formats
  29763. R8Unorm: 'r8unorm',
  29764. R8Snorm: 'r8snorm',
  29765. R8Uint: 'r8uint',
  29766. R8Sint: 'r8sint',
  29767. // 16-bit formats
  29768. R16Uint: 'r16uint',
  29769. R16Sint: 'r16sint',
  29770. R16Float: 'r16float',
  29771. RG8Unorm: 'rg8unorm',
  29772. RG8Snorm: 'rg8snorm',
  29773. RG8Uint: 'rg8uint',
  29774. RG8Sint: 'rg8sint',
  29775. // 32-bit formats
  29776. R32Uint: 'r32uint',
  29777. R32Sint: 'r32sint',
  29778. R32Float: 'r32float',
  29779. RG16Uint: 'rg16uint',
  29780. RG16Sint: 'rg16sint',
  29781. RG16Float: 'rg16float',
  29782. RGBA8Unorm: 'rgba8unorm',
  29783. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  29784. RGBA8Snorm: 'rgba8snorm',
  29785. RGBA8Uint: 'rgba8uint',
  29786. RGBA8Sint: 'rgba8sint',
  29787. BGRA8Unorm: 'bgra8unorm',
  29788. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  29789. // Packed 32-bit formats
  29790. RGB9E5UFloat: 'rgb9e5ufloat',
  29791. RGB10A2Unorm: 'rgb10a2unorm',
  29792. RG11B10uFloat: 'rgb10a2unorm',
  29793. // 64-bit formats
  29794. RG32Uint: 'rg32uint',
  29795. RG32Sint: 'rg32sint',
  29796. RG32Float: 'rg32float',
  29797. RGBA16Uint: 'rgba16uint',
  29798. RGBA16Sint: 'rgba16sint',
  29799. RGBA16Float: 'rgba16float',
  29800. // 128-bit formats
  29801. RGBA32Uint: 'rgba32uint',
  29802. RGBA32Sint: 'rgba32sint',
  29803. RGBA32Float: 'rgba32float',
  29804. // Depth and stencil formats
  29805. Stencil8: 'stencil8',
  29806. Depth16Unorm: 'depth16unorm',
  29807. Depth24Plus: 'depth24plus',
  29808. Depth24PlusStencil8: 'depth24plus-stencil8',
  29809. Depth32Float: 'depth32float',
  29810. // 'depth32float-stencil8' extension
  29811. Depth32FloatStencil8: 'depth32float-stencil8',
  29812. // BC compressed formats usable if 'texture-compression-bc' is both
  29813. // supported by the device/user agent and enabled in requestDevice.
  29814. BC1RGBAUnorm: 'bc1-rgba-unorm',
  29815. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  29816. BC2RGBAUnorm: 'bc2-rgba-unorm',
  29817. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  29818. BC3RGBAUnorm: 'bc3-rgba-unorm',
  29819. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  29820. BC4RUnorm: 'bc4-r-unorm',
  29821. BC4RSnorm: 'bc4-r-snorm',
  29822. BC5RGUnorm: 'bc5-rg-unorm',
  29823. BC5RGSnorm: 'bc5-rg-snorm',
  29824. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  29825. BC6HRGBFloat: 'bc6h-rgb-float',
  29826. BC7RGBAUnorm: 'bc7-rgba-unorm',
  29827. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  29828. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  29829. // supported by the device/user agent and enabled in requestDevice.
  29830. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  29831. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  29832. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  29833. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  29834. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  29835. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  29836. EACR11Unorm: 'eac-r11unorm',
  29837. EACR11Snorm: 'eac-r11snorm',
  29838. EACRG11Unorm: 'eac-rg11unorm',
  29839. EACRG11Snorm: 'eac-rg11snorm',
  29840. // ASTC compressed formats usable if 'texture-compression-astc' is both
  29841. // supported by the device/user agent and enabled in requestDevice.
  29842. ASTC4x4Unorm: 'astc-4x4-unorm',
  29843. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  29844. ASTC5x4Unorm: 'astc-5x4-unorm',
  29845. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  29846. ASTC5x5Unorm: 'astc-5x5-unorm',
  29847. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  29848. ASTC6x5Unorm: 'astc-6x5-unorm',
  29849. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  29850. ASTC6x6Unorm: 'astc-6x6-unorm',
  29851. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  29852. ASTC8x5Unorm: 'astc-8x5-unorm',
  29853. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  29854. ASTC8x6Unorm: 'astc-8x6-unorm',
  29855. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  29856. ASTC8x8Unorm: 'astc-8x8-unorm',
  29857. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  29858. ASTC10x5Unorm: 'astc-10x5-unorm',
  29859. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  29860. ASTC10x6Unorm: 'astc-10x6-unorm',
  29861. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  29862. ASTC10x8Unorm: 'astc-10x8-unorm',
  29863. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  29864. ASTC10x10Unorm: 'astc-10x10-unorm',
  29865. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  29866. ASTC12x10Unorm: 'astc-12x10-unorm',
  29867. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  29868. ASTC12x12Unorm: 'astc-12x12-unorm',
  29869. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  29870. };
  29871. const GPUAddressMode = {
  29872. ClampToEdge: 'clamp-to-edge',
  29873. Repeat: 'repeat',
  29874. MirrorRepeat: 'mirror-repeat'
  29875. };
  29876. const GPUFilterMode = {
  29877. Linear: 'linear',
  29878. Nearest: 'nearest'
  29879. };
  29880. const GPUBlendFactor = {
  29881. Zero: 'zero',
  29882. One: 'one',
  29883. Src: 'src',
  29884. OneMinusSrc: 'one-minus-src',
  29885. SrcAlpha: 'src-alpha',
  29886. OneMinusSrcAlpha: 'one-minus-src-alpha',
  29887. Dst: 'dst',
  29888. OneMinusDstColor: 'one-minus-dst',
  29889. DstAlpha: 'dst-alpha',
  29890. OneMinusDstAlpha: 'one-minus-dst-alpha',
  29891. SrcAlphaSaturated: 'src-alpha-saturated',
  29892. Constant: 'constant',
  29893. OneMinusConstant: 'one-minus-constant'
  29894. };
  29895. const GPUBlendOperation = {
  29896. Add: 'add',
  29897. Subtract: 'subtract',
  29898. ReverseSubtract: 'reverse-subtract',
  29899. Min: 'min',
  29900. Max: 'max'
  29901. };
  29902. const GPUColorWriteFlags = {
  29903. None: 0,
  29904. Red: 0x1,
  29905. Green: 0x2,
  29906. Blue: 0x4,
  29907. Alpha: 0x8,
  29908. All: 0xF
  29909. };
  29910. const GPUStencilOperation = {
  29911. Keep: 'keep',
  29912. Zero: 'zero',
  29913. Replace: 'replace',
  29914. Invert: 'invert',
  29915. IncrementClamp: 'increment-clamp',
  29916. DecrementClamp: 'decrement-clamp',
  29917. IncrementWrap: 'increment-wrap',
  29918. DecrementWrap: 'decrement-wrap'
  29919. };
  29920. const GPUBufferBindingType = {
  29921. Uniform: 'uniform',
  29922. Storage: 'storage',
  29923. ReadOnlyStorage: 'read-only-storage'
  29924. };
  29925. const GPUStorageTextureAccess = {
  29926. WriteOnly: 'write-only',
  29927. ReadOnly: 'read-only',
  29928. ReadWrite: 'read-write',
  29929. };
  29930. const GPUTextureSampleType = {
  29931. Float: 'float',
  29932. UnfilterableFloat: 'unfilterable-float',
  29933. Depth: 'depth',
  29934. SInt: 'sint',
  29935. UInt: 'uint'
  29936. };
  29937. const GPUTextureDimension = {
  29938. OneD: '1d',
  29939. TwoD: '2d',
  29940. ThreeD: '3d'
  29941. };
  29942. const GPUTextureViewDimension = {
  29943. OneD: '1d',
  29944. TwoD: '2d',
  29945. TwoDArray: '2d-array',
  29946. Cube: 'cube',
  29947. CubeArray: 'cube-array',
  29948. ThreeD: '3d'
  29949. };
  29950. const GPUTextureAspect = {
  29951. All: 'all',
  29952. StencilOnly: 'stencil-only',
  29953. DepthOnly: 'depth-only'
  29954. };
  29955. const GPUInputStepMode = {
  29956. Vertex: 'vertex',
  29957. Instance: 'instance'
  29958. };
  29959. const GPUFeatureName = {
  29960. DepthClipControl: 'depth-clip-control',
  29961. Depth32FloatStencil8: 'depth32float-stencil8',
  29962. TextureCompressionBC: 'texture-compression-bc',
  29963. TextureCompressionETC2: 'texture-compression-etc2',
  29964. TextureCompressionASTC: 'texture-compression-astc',
  29965. TimestampQuery: 'timestamp-query',
  29966. IndirectFirstInstance: 'indirect-first-instance',
  29967. ShaderF16: 'shader-f16',
  29968. RG11B10UFloat: 'rg11b10ufloat-renderable',
  29969. BGRA8UNormStorage: 'bgra8unorm-storage',
  29970. Float32Filterable: 'float32-filterable',
  29971. ClipDistances: 'clip-distances',
  29972. DualSourceBlending: 'dual-source-blending'
  29973. };
  29974. class StorageBufferNode extends BufferNode {
  29975. constructor( value, bufferType, bufferCount = 0 ) {
  29976. super( value, bufferType, bufferCount );
  29977. this.isStorageBufferNode = true;
  29978. this.access = GPUBufferBindingType.Storage;
  29979. this.bufferObject = false;
  29980. this.bufferCount = bufferCount;
  29981. this._attribute = null;
  29982. this._varying = null;
  29983. this.global = true;
  29984. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  29985. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  29986. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  29987. else value.isStorageBufferAttribute = true;
  29988. }
  29989. }
  29990. getHash( builder ) {
  29991. if ( this.bufferCount === 0 ) {
  29992. let bufferData = builder.globalCache.getData( this.value );
  29993. if ( bufferData === undefined ) {
  29994. bufferData = {
  29995. node: this
  29996. };
  29997. builder.globalCache.setData( this.value, bufferData );
  29998. }
  29999. return bufferData.node.uuid;
  30000. }
  30001. return this.uuid;
  30002. }
  30003. getInputType( /*builder*/ ) {
  30004. return 'storageBuffer';
  30005. }
  30006. element( indexNode ) {
  30007. return storageElement( this, indexNode );
  30008. }
  30009. setBufferObject( value ) {
  30010. this.bufferObject = value;
  30011. return this;
  30012. }
  30013. setAccess( value ) {
  30014. this.access = value;
  30015. return this;
  30016. }
  30017. toReadOnly() {
  30018. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  30019. }
  30020. generate( builder ) {
  30021. if ( builder.isAvailable( 'storageBuffer' ) ) {
  30022. return super.generate( builder );
  30023. }
  30024. const nodeType = this.getNodeType( builder );
  30025. if ( this._attribute === null ) {
  30026. this._attribute = bufferAttribute( this.value );
  30027. this._varying = varying( this._attribute );
  30028. }
  30029. const output = this._varying.build( builder, nodeType );
  30030. builder.registerTransform( output, this._attribute );
  30031. return output;
  30032. }
  30033. }
  30034. // Read-Write Storage
  30035. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  30036. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  30037. addNodeClass( 'StorageBufferNode', StorageBufferNode );
  30038. class StorageTextureNode extends TextureNode {
  30039. constructor( value, uvNode, storeNode = null ) {
  30040. super( value, uvNode );
  30041. this.storeNode = storeNode;
  30042. this.isStorageTextureNode = true;
  30043. this.access = GPUStorageTextureAccess.WriteOnly;
  30044. }
  30045. getInputType( /*builder*/ ) {
  30046. return 'storageTexture';
  30047. }
  30048. setup( builder ) {
  30049. super.setup( builder );
  30050. const properties = builder.getNodeProperties( this );
  30051. properties.storeNode = this.storeNode;
  30052. }
  30053. setAccess( value ) {
  30054. this.access = value;
  30055. return this;
  30056. }
  30057. generate( builder, output ) {
  30058. let snippet;
  30059. if ( this.storeNode !== null ) {
  30060. snippet = this.generateStore( builder );
  30061. } else {
  30062. snippet = super.generate( builder, output );
  30063. }
  30064. return snippet;
  30065. }
  30066. toReadOnly() {
  30067. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  30068. }
  30069. toWriteOnly() {
  30070. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  30071. }
  30072. generateStore( builder ) {
  30073. const properties = builder.getNodeProperties( this );
  30074. const { uvNode, storeNode } = properties;
  30075. const textureProperty = super.generate( builder, 'property' );
  30076. const uvSnippet = uvNode.build( builder, 'uvec2' );
  30077. const storeSnippet = storeNode.build( builder, 'vec4' );
  30078. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  30079. builder.addLineFlowCode( snippet );
  30080. }
  30081. }
  30082. const storageTexture = nodeProxy( StorageTextureNode );
  30083. const textureStore = ( value, uvNode, storeNode ) => {
  30084. const node = storageTexture( value, uvNode, storeNode );
  30085. if ( storeNode !== null ) node.append();
  30086. return node;
  30087. };
  30088. addNodeClass( 'StorageTextureNode', StorageTextureNode );
  30089. const normal = tslFn( ( { texture, uv } ) => {
  30090. const epsilon = 0.0001;
  30091. const ret = vec3().temp();
  30092. If( uv.x.lessThan( epsilon ), () => {
  30093. ret.assign( vec3( 1, 0, 0 ) );
  30094. } ).elseif( uv.y.lessThan( epsilon ), () => {
  30095. ret.assign( vec3( 0, 1, 0 ) );
  30096. } ).elseif( uv.z.lessThan( epsilon ), () => {
  30097. ret.assign( vec3( 0, 0, 1 ) );
  30098. } ).elseif( uv.x.greaterThan( 1 - epsilon ), () => {
  30099. ret.assign( vec3( - 1, 0, 0 ) );
  30100. } ).elseif( uv.y.greaterThan( 1 - epsilon ), () => {
  30101. ret.assign( vec3( 0, - 1, 0 ) );
  30102. } ).elseif( uv.z.greaterThan( 1 - epsilon ), () => {
  30103. ret.assign( vec3( 0, 0, - 1 ) );
  30104. } ).else( () => {
  30105. const step = 0.01;
  30106. 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 );
  30107. 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 );
  30108. 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 );
  30109. ret.assign( vec3( x, y, z ) );
  30110. } );
  30111. return ret.normalize();
  30112. } );
  30113. class Texture3DNode extends TextureNode {
  30114. constructor( value, uvNode = null, levelNode = null ) {
  30115. super( value, uvNode, levelNode );
  30116. this.isTexture3DNode = true;
  30117. }
  30118. getInputType( /*builder*/ ) {
  30119. return 'texture3D';
  30120. }
  30121. getDefaultUV() {
  30122. return vec3( 0.5, 0.5, 0.5 );
  30123. }
  30124. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  30125. setupUV( builder, uvNode ) {
  30126. return uvNode;
  30127. }
  30128. generateUV( builder, uvNode ) {
  30129. return uvNode.build( builder, 'vec3' );
  30130. }
  30131. normal( uvNode ) {
  30132. return normal( { texture: this, uv: uvNode } );
  30133. }
  30134. }
  30135. const texture3D = nodeProxy( Texture3DNode );
  30136. addNodeClass( 'Texture3DNode', Texture3DNode );
  30137. class UserDataNode extends ReferenceNode {
  30138. constructor( property, inputType, userData = null ) {
  30139. super( property, inputType, userData );
  30140. this.userData = userData;
  30141. }
  30142. update( frame ) {
  30143. this.reference = this.userData !== null ? this.userData : frame.object.userData;
  30144. super.update( frame );
  30145. }
  30146. }
  30147. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  30148. addNodeClass( 'UserDataNode', UserDataNode );
  30149. const BurnNode = tslFn( ( { base, blend } ) => {
  30150. const fn = ( c ) => blend[ c ].lessThan( EPSILON ).cond( blend[ c ], base[ c ].oneMinus().div( blend[ c ] ).oneMinus().max( 0 ) );
  30151. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30152. } ).setLayout( {
  30153. name: 'burnColor',
  30154. type: 'vec3',
  30155. inputs: [
  30156. { name: 'base', type: 'vec3' },
  30157. { name: 'blend', type: 'vec3' }
  30158. ]
  30159. } );
  30160. const DodgeNode = tslFn( ( { base, blend } ) => {
  30161. const fn = ( c ) => blend[ c ].equal( 1.0 ).cond( blend[ c ], base[ c ].div( blend[ c ].oneMinus() ).max( 0 ) );
  30162. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30163. } ).setLayout( {
  30164. name: 'dodgeColor',
  30165. type: 'vec3',
  30166. inputs: [
  30167. { name: 'base', type: 'vec3' },
  30168. { name: 'blend', type: 'vec3' }
  30169. ]
  30170. } );
  30171. const ScreenNode = tslFn( ( { base, blend } ) => {
  30172. const fn = ( c ) => base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus();
  30173. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30174. } ).setLayout( {
  30175. name: 'screenColor',
  30176. type: 'vec3',
  30177. inputs: [
  30178. { name: 'base', type: 'vec3' },
  30179. { name: 'blend', type: 'vec3' }
  30180. ]
  30181. } );
  30182. const OverlayNode = tslFn( ( { base, blend } ) => {
  30183. const fn = ( c ) => base[ c ].lessThan( 0.5 ).cond( base[ c ].mul( blend[ c ], 2.0 ), base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus() );
  30184. //const fn = ( c ) => mix( base[ c ].oneMinus().mul( blend[ c ].oneMinus() ).oneMinus(), base[ c ].mul( blend[ c ], 2.0 ), step( base[ c ], 0.5 ) );
  30185. return vec3( fn( 'x' ), fn( 'y' ), fn( 'z' ) );
  30186. } ).setLayout( {
  30187. name: 'overlayColor',
  30188. type: 'vec3',
  30189. inputs: [
  30190. { name: 'base', type: 'vec3' },
  30191. { name: 'blend', type: 'vec3' }
  30192. ]
  30193. } );
  30194. class BlendModeNode extends TempNode {
  30195. constructor( blendMode, baseNode, blendNode ) {
  30196. super();
  30197. this.blendMode = blendMode;
  30198. this.baseNode = baseNode;
  30199. this.blendNode = blendNode;
  30200. }
  30201. setup() {
  30202. const { blendMode, baseNode, blendNode } = this;
  30203. const params = { base: baseNode, blend: blendNode };
  30204. let outputNode = null;
  30205. if ( blendMode === BlendModeNode.BURN ) {
  30206. outputNode = BurnNode( params );
  30207. } else if ( blendMode === BlendModeNode.DODGE ) {
  30208. outputNode = DodgeNode( params );
  30209. } else if ( blendMode === BlendModeNode.SCREEN ) {
  30210. outputNode = ScreenNode( params );
  30211. } else if ( blendMode === BlendModeNode.OVERLAY ) {
  30212. outputNode = OverlayNode( params );
  30213. }
  30214. return outputNode;
  30215. }
  30216. }
  30217. BlendModeNode.BURN = 'burn';
  30218. BlendModeNode.DODGE = 'dodge';
  30219. BlendModeNode.SCREEN = 'screen';
  30220. BlendModeNode.OVERLAY = 'overlay';
  30221. const burn = nodeProxy( BlendModeNode, BlendModeNode.BURN );
  30222. const dodge = nodeProxy( BlendModeNode, BlendModeNode.DODGE );
  30223. const overlay = nodeProxy( BlendModeNode, BlendModeNode.OVERLAY );
  30224. const screen = nodeProxy( BlendModeNode, BlendModeNode.SCREEN );
  30225. addNodeElement( 'burn', burn );
  30226. addNodeElement( 'dodge', dodge );
  30227. addNodeElement( 'overlay', overlay );
  30228. addNodeElement( 'screen', screen );
  30229. addNodeClass( 'BlendModeNode', BlendModeNode );
  30230. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  30231. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  30232. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  30233. // It's used to preserve the same TextureNode instance
  30234. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  30235. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  30236. return vec2(
  30237. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  30238. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  30239. ).mul( bumpScale );
  30240. } );
  30241. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  30242. const perturbNormalArb = tslFn( ( inputs ) => {
  30243. const { surf_pos, surf_norm, dHdxy } = inputs;
  30244. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  30245. const vSigmaX = surf_pos.dFdx().normalize();
  30246. const vSigmaY = surf_pos.dFdy().normalize();
  30247. const vN = surf_norm; // normalized
  30248. const R1 = vSigmaY.cross( vN );
  30249. const R2 = vN.cross( vSigmaX );
  30250. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  30251. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30252. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  30253. } );
  30254. class BumpMapNode extends TempNode {
  30255. constructor( textureNode, scaleNode = null ) {
  30256. super( 'vec3' );
  30257. this.textureNode = textureNode;
  30258. this.scaleNode = scaleNode;
  30259. }
  30260. setup() {
  30261. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  30262. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  30263. return perturbNormalArb( {
  30264. surf_pos: positionView,
  30265. surf_norm: normalView,
  30266. dHdxy
  30267. } );
  30268. }
  30269. }
  30270. const bumpMap = nodeProxy( BumpMapNode );
  30271. addNodeElement( 'bumpMap', bumpMap );
  30272. addNodeClass( 'BumpMapNode', BumpMapNode );
  30273. const saturationNode = tslFn( ( { color, adjustment } ) => {
  30274. return adjustment.mix( luminance( color.rgb ), color.rgb );
  30275. } );
  30276. const vibranceNode = tslFn( ( { color, adjustment } ) => {
  30277. const average = add( color.r, color.g, color.b ).div( 3.0 );
  30278. const mx = color.r.max( color.g.max( color.b ) );
  30279. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  30280. return mix( color.rgb, mx, amt );
  30281. } );
  30282. const hueNode = tslFn( ( { color, adjustment } ) => {
  30283. const k = vec3( 0.57735, 0.57735, 0.57735 );
  30284. const cosAngle = adjustment.cos();
  30285. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  30286. } );
  30287. class ColorAdjustmentNode extends TempNode {
  30288. constructor( method, colorNode, adjustmentNode = float( 1 ) ) {
  30289. super( 'vec3' );
  30290. this.method = method;
  30291. this.colorNode = colorNode;
  30292. this.adjustmentNode = adjustmentNode;
  30293. }
  30294. setup() {
  30295. const { method, colorNode, adjustmentNode } = this;
  30296. const callParams = { color: colorNode, adjustment: adjustmentNode };
  30297. let outputNode = null;
  30298. if ( method === ColorAdjustmentNode.SATURATION ) {
  30299. outputNode = saturationNode( callParams );
  30300. } else if ( method === ColorAdjustmentNode.VIBRANCE ) {
  30301. outputNode = vibranceNode( callParams );
  30302. } else if ( method === ColorAdjustmentNode.HUE ) {
  30303. outputNode = hueNode( callParams );
  30304. } else {
  30305. console.error( `${ this.type }: Method "${ this.method }" not supported!` );
  30306. }
  30307. return outputNode;
  30308. }
  30309. }
  30310. ColorAdjustmentNode.SATURATION = 'saturation';
  30311. ColorAdjustmentNode.VIBRANCE = 'vibrance';
  30312. ColorAdjustmentNode.HUE = 'hue';
  30313. const saturation = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.SATURATION );
  30314. const vibrance = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.VIBRANCE );
  30315. const hue = nodeProxy( ColorAdjustmentNode, ColorAdjustmentNode.HUE );
  30316. const _luminanceCoefficients = /*#__PURE__*/ new Vector3();
  30317. const luminance = (
  30318. color,
  30319. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  30320. ) => dot( color, luminanceCoefficients );
  30321. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  30322. addNodeElement( 'saturation', saturation );
  30323. addNodeElement( 'vibrance', vibrance );
  30324. addNodeElement( 'hue', hue );
  30325. addNodeElement( 'threshold', threshold );
  30326. addNodeClass( 'ColorAdjustmentNode', ColorAdjustmentNode );
  30327. // Normal Mapping Without Precomputed Tangents
  30328. // http://www.thetenthplanet.de/archives/1180
  30329. const perturbNormal2Arb = tslFn( ( inputs ) => {
  30330. const { eye_pos, surf_norm, mapN, uv } = inputs;
  30331. const q0 = eye_pos.dFdx();
  30332. const q1 = eye_pos.dFdy();
  30333. const st0 = uv.dFdx();
  30334. const st1 = uv.dFdy();
  30335. const N = surf_norm; // normalized
  30336. const q1perp = q1.cross( N );
  30337. const q0perp = N.cross( q0 );
  30338. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  30339. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  30340. const det = T.dot( T ).max( B.dot( B ) );
  30341. const scale = faceDirection.mul( det.inverseSqrt() );
  30342. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  30343. } );
  30344. class NormalMapNode extends TempNode {
  30345. constructor( node, scaleNode = null ) {
  30346. super( 'vec3' );
  30347. this.node = node;
  30348. this.scaleNode = scaleNode;
  30349. this.normalMapType = TangentSpaceNormalMap;
  30350. }
  30351. setup( builder ) {
  30352. const { normalMapType, scaleNode } = this;
  30353. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  30354. if ( scaleNode !== null ) {
  30355. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  30356. }
  30357. let outputNode = null;
  30358. if ( normalMapType === ObjectSpaceNormalMap ) {
  30359. outputNode = modelNormalMatrix.mul( normalMap ).normalize();
  30360. } else if ( normalMapType === TangentSpaceNormalMap ) {
  30361. const tangent = builder.hasGeometryAttribute( 'tangent' );
  30362. if ( tangent === true ) {
  30363. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  30364. } else {
  30365. outputNode = perturbNormal2Arb( {
  30366. eye_pos: positionView,
  30367. surf_norm: normalView,
  30368. mapN: normalMap,
  30369. uv: uv()
  30370. } );
  30371. }
  30372. }
  30373. return outputNode;
  30374. }
  30375. }
  30376. const normalMap = nodeProxy( NormalMapNode );
  30377. addNodeElement( 'normalMap', normalMap );
  30378. addNodeClass( 'NormalMapNode', NormalMapNode );
  30379. class PosterizeNode extends TempNode {
  30380. constructor( sourceNode, stepsNode ) {
  30381. super();
  30382. this.sourceNode = sourceNode;
  30383. this.stepsNode = stepsNode;
  30384. }
  30385. setup() {
  30386. const { sourceNode, stepsNode } = this;
  30387. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  30388. }
  30389. }
  30390. const posterize = nodeProxy( PosterizeNode );
  30391. addNodeElement( 'posterize', posterize );
  30392. addNodeClass( 'PosterizeNode', PosterizeNode );
  30393. // exposure only
  30394. const LinearToneMappingNode = tslFn( ( { color, exposure } ) => {
  30395. return color.mul( exposure ).clamp();
  30396. } );
  30397. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  30398. const ReinhardToneMappingNode = tslFn( ( { color, exposure } ) => {
  30399. color = color.mul( exposure );
  30400. return color.div( color.add( 1.0 ) ).clamp();
  30401. } );
  30402. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  30403. const OptimizedCineonToneMappingNode = tslFn( ( { color, exposure } ) => {
  30404. // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  30405. color = color.mul( exposure );
  30406. color = color.sub( 0.004 ).max( 0.0 );
  30407. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  30408. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  30409. return a.div( b ).pow( 2.2 );
  30410. } );
  30411. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30412. const RRTAndODTFit = tslFn( ( { color } ) => {
  30413. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  30414. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  30415. return a.div( b );
  30416. } );
  30417. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  30418. const ACESFilmicToneMappingNode = tslFn( ( { color, exposure } ) => {
  30419. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  30420. const ACESInputMat = mat3(
  30421. 0.59719, 0.35458, 0.04823,
  30422. 0.07600, 0.90834, 0.01566,
  30423. 0.02840, 0.13383, 0.83777
  30424. );
  30425. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  30426. const ACESOutputMat = mat3(
  30427. 1.60475, - 0.53108, - 0.07367,
  30428. - 0.10208, 1.10813, - 0.00605,
  30429. - 0.00327, - 0.07276, 1.07602
  30430. );
  30431. color = color.mul( exposure ).div( 0.6 );
  30432. color = ACESInputMat.mul( color );
  30433. // Apply RRT and ODT
  30434. color = RRTAndODTFit( { color } );
  30435. color = ACESOutputMat.mul( color );
  30436. // Clamp to [0, 1]
  30437. return color.clamp();
  30438. } );
  30439. 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 ) );
  30440. 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 ) );
  30441. const agxDefaultContrastApprox = tslFn( ( [ x_immutable ] ) => {
  30442. const x = vec3( x_immutable ).toVar();
  30443. const x2 = vec3( x.mul( x ) ).toVar();
  30444. const x4 = vec3( x2.mul( x2 ) ).toVar();
  30445. 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 ) ) ) );
  30446. } );
  30447. const AGXToneMappingNode = tslFn( ( { color, exposure } ) => {
  30448. const colortone = vec3( color ).toVar();
  30449. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  30450. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  30451. const AgxMinEv = float( - 12.47393 );
  30452. const AgxMaxEv = float( 4.026069 );
  30453. colortone.mulAssign( exposure );
  30454. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  30455. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  30456. colortone.assign( max$1( colortone, 1e-10 ) );
  30457. colortone.assign( log2( colortone ) );
  30458. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  30459. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30460. colortone.assign( agxDefaultContrastApprox( colortone ) );
  30461. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  30462. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  30463. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  30464. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  30465. return colortone;
  30466. } );
  30467. // https://modelviewer.dev/examples/tone-mapping
  30468. const NeutralToneMappingNode = tslFn( ( { color, exposure } ) => {
  30469. const StartCompression = float( 0.8 - 0.04 );
  30470. const Desaturation = float( 0.15 );
  30471. color = color.mul( exposure );
  30472. const x = min$1( color.r, min$1( color.g, color.b ) );
  30473. const offset = cond( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  30474. color.subAssign( offset );
  30475. const peak = max$1( color.r, max$1( color.g, color.b ) );
  30476. If( peak.lessThan( StartCompression ), () => {
  30477. return color;
  30478. } );
  30479. const d = sub( 1, StartCompression );
  30480. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  30481. color.mulAssign( newPeak.div( peak ) );
  30482. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  30483. return mix( color, vec3( newPeak ), g );
  30484. } ).setLayout( {
  30485. name: 'NeutralToneMapping',
  30486. type: 'vec3',
  30487. inputs: [
  30488. { name: 'color', type: 'vec3' },
  30489. { name: 'exposure', type: 'float' }
  30490. ]
  30491. } );
  30492. const toneMappingLib = {
  30493. [ LinearToneMapping ]: LinearToneMappingNode,
  30494. [ ReinhardToneMapping ]: ReinhardToneMappingNode,
  30495. [ CineonToneMapping ]: OptimizedCineonToneMappingNode,
  30496. [ ACESFilmicToneMapping ]: ACESFilmicToneMappingNode,
  30497. [ AgXToneMapping ]: AGXToneMappingNode,
  30498. [ NeutralToneMapping ]: NeutralToneMappingNode
  30499. };
  30500. class ToneMappingNode extends TempNode {
  30501. constructor( toneMapping = NoToneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  30502. super( 'vec3' );
  30503. this.toneMapping = toneMapping;
  30504. this.exposureNode = exposureNode;
  30505. this.colorNode = colorNode;
  30506. }
  30507. getCacheKey() {
  30508. let cacheKey = super.getCacheKey();
  30509. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  30510. return cacheKey;
  30511. }
  30512. setup( builder ) {
  30513. const colorNode = this.colorNode || builder.context.color;
  30514. const toneMapping = this.toneMapping;
  30515. if ( toneMapping === NoToneMapping ) return colorNode;
  30516. const toneMappingParams = { exposure: this.exposureNode, color: colorNode };
  30517. const toneMappingNode = toneMappingLib[ toneMapping ];
  30518. let outputNode = null;
  30519. if ( toneMappingNode ) {
  30520. outputNode = toneMappingNode( toneMappingParams );
  30521. } else {
  30522. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  30523. outputNode = colorNode;
  30524. }
  30525. return outputNode;
  30526. }
  30527. }
  30528. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  30529. const toneMappingExposure = rendererReference( 'toneMappingExposure', 'float' );
  30530. addNodeElement( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  30531. addNodeClass( 'ToneMappingNode', ToneMappingNode );
  30532. let _sharedFramebuffer = null;
  30533. class ViewportSharedTextureNode extends ViewportTextureNode {
  30534. constructor( uvNode = viewportTopLeft, levelNode = null ) {
  30535. if ( _sharedFramebuffer === null ) {
  30536. _sharedFramebuffer = new FramebufferTexture();
  30537. }
  30538. super( uvNode, levelNode, _sharedFramebuffer );
  30539. }
  30540. updateReference() {
  30541. return this;
  30542. }
  30543. }
  30544. const viewportSharedTexture = nodeProxy( ViewportSharedTextureNode );
  30545. addNodeElement( 'viewportSharedTexture', viewportSharedTexture );
  30546. addNodeClass( 'ViewportSharedTextureNode', ViewportSharedTextureNode );
  30547. const _size$4 = /*@__PURE__*/ new Vector2();
  30548. class PassTextureNode extends TextureNode {
  30549. constructor( passNode, texture ) {
  30550. super( texture );
  30551. this.passNode = passNode;
  30552. this.setUpdateMatrix( false );
  30553. }
  30554. setup( builder ) {
  30555. this.passNode.build( builder );
  30556. return super.setup( builder );
  30557. }
  30558. clone() {
  30559. return new this.constructor( this.passNode, this.value );
  30560. }
  30561. }
  30562. class PassMultipleTextureNode extends PassTextureNode {
  30563. constructor( passNode, textureName ) {
  30564. super( passNode, null );
  30565. this.textureName = textureName;
  30566. }
  30567. setup( builder ) {
  30568. this.value = this.passNode.getTexture( this.textureName );
  30569. return super.setup( builder );
  30570. }
  30571. clone() {
  30572. return new this.constructor( this.passNode, this.textureName );
  30573. }
  30574. }
  30575. class PassNode extends TempNode {
  30576. constructor( scope, scene, camera, options = {} ) {
  30577. super( 'vec4' );
  30578. this.scope = scope;
  30579. this.scene = scene;
  30580. this.camera = camera;
  30581. this.options = options;
  30582. this._pixelRatio = 1;
  30583. this._width = 1;
  30584. this._height = 1;
  30585. const depthTexture = new DepthTexture();
  30586. depthTexture.isRenderTargetTexture = true;
  30587. //depthTexture.type = FloatType;
  30588. depthTexture.name = 'depth';
  30589. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  30590. renderTarget.texture.name = 'output';
  30591. renderTarget.depthTexture = depthTexture;
  30592. this.renderTarget = renderTarget;
  30593. this.updateBeforeType = NodeUpdateType.FRAME;
  30594. this._textures = {
  30595. output: renderTarget.texture,
  30596. depth: depthTexture
  30597. };
  30598. this._textureNodes = {};
  30599. this._linearDepthNodes = {};
  30600. this._viewZNodes = {};
  30601. this._cameraNear = uniform( 0 );
  30602. this._cameraFar = uniform( 0 );
  30603. this._mrt = null;
  30604. this.isPassNode = true;
  30605. }
  30606. setMRT( mrt ) {
  30607. this._mrt = mrt;
  30608. return this;
  30609. }
  30610. getMRT() {
  30611. return this._mrt;
  30612. }
  30613. isGlobal() {
  30614. return true;
  30615. }
  30616. getTexture( name ) {
  30617. let texture = this._textures[ name ];
  30618. if ( texture === undefined ) {
  30619. const refTexture = this.renderTarget.texture;
  30620. texture = refTexture.clone();
  30621. texture.isRenderTargetTexture = true;
  30622. texture.name = name;
  30623. this._textures[ name ] = texture;
  30624. this.renderTarget.textures.push( texture );
  30625. }
  30626. return texture;
  30627. }
  30628. getTextureNode( name = 'output' ) {
  30629. let textureNode = this._textureNodes[ name ];
  30630. if ( textureNode === undefined ) {
  30631. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  30632. }
  30633. return textureNode;
  30634. }
  30635. getViewZNode( name = 'depth' ) {
  30636. let viewZNode = this._viewZNodes[ name ];
  30637. if ( viewZNode === undefined ) {
  30638. const cameraNear = this._cameraNear;
  30639. const cameraFar = this._cameraFar;
  30640. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  30641. }
  30642. return viewZNode;
  30643. }
  30644. getLinearDepthNode( name = 'depth' ) {
  30645. let linearDepthNode = this._linearDepthNodes[ name ];
  30646. if ( linearDepthNode === undefined ) {
  30647. const cameraNear = this._cameraNear;
  30648. const cameraFar = this._cameraFar;
  30649. const viewZNode = this.getViewZNode( name );
  30650. // TODO: just if ( builder.camera.isPerspectiveCamera )
  30651. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  30652. }
  30653. return linearDepthNode;
  30654. }
  30655. setup( { renderer } ) {
  30656. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  30657. // Disable MSAA for WebGL backend for now
  30658. if ( renderer.backend.isWebGLBackend === true ) {
  30659. this.renderTarget.samples = 0;
  30660. }
  30661. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  30662. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  30663. }
  30664. updateBefore( frame ) {
  30665. const { renderer } = frame;
  30666. const { scene, camera } = this;
  30667. this._pixelRatio = renderer.getPixelRatio();
  30668. const size = renderer.getSize( _size$4 );
  30669. this.setSize( size.width, size.height );
  30670. const currentRenderTarget = renderer.getRenderTarget();
  30671. const currentMRT = renderer.getMRT();
  30672. this._cameraNear.value = camera.near;
  30673. this._cameraFar.value = camera.far;
  30674. renderer.setRenderTarget( this.renderTarget );
  30675. renderer.setMRT( this._mrt );
  30676. renderer.render( scene, camera );
  30677. renderer.setRenderTarget( currentRenderTarget );
  30678. renderer.setMRT( currentMRT );
  30679. }
  30680. setSize( width, height ) {
  30681. this._width = width;
  30682. this._height = height;
  30683. const effectiveWidth = this._width * this._pixelRatio;
  30684. const effectiveHeight = this._height * this._pixelRatio;
  30685. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  30686. }
  30687. setPixelRatio( pixelRatio ) {
  30688. this._pixelRatio = pixelRatio;
  30689. this.setSize( this._width, this._height );
  30690. }
  30691. dispose() {
  30692. this.renderTarget.dispose();
  30693. }
  30694. }
  30695. PassNode.COLOR = 'color';
  30696. PassNode.DEPTH = 'depth';
  30697. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  30698. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  30699. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  30700. addNodeClass( 'PassNode', PassNode );
  30701. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  30702. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  30703. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  30704. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  30705. class GaussianBlurNode extends TempNode {
  30706. constructor( textureNode, directionNode = null, sigma = 2 ) {
  30707. super( 'vec4' );
  30708. this.textureNode = textureNode;
  30709. this.directionNode = directionNode;
  30710. this.sigma = sigma;
  30711. this._invSize = uniform( new Vector2() );
  30712. this._passDirection = uniform( new Vector2() );
  30713. this._horizontalRT = new RenderTarget();
  30714. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  30715. this._verticalRT = new RenderTarget();
  30716. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  30717. this._textureNode = passTexture( this, this._verticalRT.texture );
  30718. this.updateBeforeType = NodeUpdateType.RENDER;
  30719. this.resolution = new Vector2( 1, 1 );
  30720. }
  30721. setSize( width, height ) {
  30722. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30723. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30724. this._invSize.value.set( 1 / width, 1 / height );
  30725. this._horizontalRT.setSize( width, height );
  30726. this._verticalRT.setSize( width, height );
  30727. }
  30728. updateBefore( frame ) {
  30729. const { renderer } = frame;
  30730. const textureNode = this.textureNode;
  30731. const map = textureNode.value;
  30732. const currentRenderTarget = renderer.getRenderTarget();
  30733. const currentMRT = renderer.getMRT();
  30734. const currentTexture = textureNode.value;
  30735. _quadMesh1.material = this._material;
  30736. _quadMesh2.material = this._material;
  30737. this.setSize( map.image.width, map.image.height );
  30738. const textureType = map.type;
  30739. this._horizontalRT.texture.type = textureType;
  30740. this._verticalRT.texture.type = textureType;
  30741. // clear
  30742. renderer.setMRT( null );
  30743. // horizontal
  30744. renderer.setRenderTarget( this._horizontalRT );
  30745. this._passDirection.value.set( 1, 0 );
  30746. _quadMesh1.render( renderer );
  30747. // vertical
  30748. textureNode.value = this._horizontalRT.texture;
  30749. renderer.setRenderTarget( this._verticalRT );
  30750. this._passDirection.value.set( 0, 1 );
  30751. _quadMesh2.render( renderer );
  30752. // restore
  30753. renderer.setRenderTarget( currentRenderTarget );
  30754. renderer.setMRT( currentMRT );
  30755. textureNode.value = currentTexture;
  30756. }
  30757. getTextureNode() {
  30758. return this._textureNode;
  30759. }
  30760. setup( builder ) {
  30761. const textureNode = this.textureNode;
  30762. if ( textureNode.isTextureNode !== true ) {
  30763. console.error( 'GaussianBlurNode requires a TextureNode.' );
  30764. return vec4();
  30765. }
  30766. //
  30767. const uvNode = textureNode.uvNode || uv();
  30768. const directionNode = vec2( this.directionNode || 1 );
  30769. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30770. const blur = tslFn( () => {
  30771. const kernelSize = 3 + ( 2 * this.sigma );
  30772. const gaussianCoefficients = this._getCoefficients( kernelSize );
  30773. const invSize = this._invSize;
  30774. const direction = directionNode.mul( this._passDirection );
  30775. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  30776. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  30777. for ( let i = 1; i < kernelSize; i ++ ) {
  30778. const x = float( i );
  30779. const w = float( gaussianCoefficients[ i ] );
  30780. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  30781. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  30782. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  30783. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  30784. weightSum.addAssign( mul( 2.0, w ) );
  30785. }
  30786. return diffuseSum.div( weightSum );
  30787. } );
  30788. //
  30789. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30790. material.fragmentNode = blur().context( builder.getSharedContext() );
  30791. material.needsUpdate = true;
  30792. //
  30793. const properties = builder.getNodeProperties( this );
  30794. properties.textureNode = textureNode;
  30795. //
  30796. return this._textureNode;
  30797. }
  30798. dispose() {
  30799. this._horizontalRT.dispose();
  30800. this._verticalRT.dispose();
  30801. }
  30802. _getCoefficients( kernelRadius ) {
  30803. const coefficients = [];
  30804. for ( let i = 0; i < kernelRadius; i ++ ) {
  30805. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  30806. }
  30807. return coefficients;
  30808. }
  30809. }
  30810. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( nodeObject( node ).toTexture(), directionNode, sigma ) );
  30811. addNodeElement( 'gaussianBlur', gaussianBlur );
  30812. const _size$3 = /*@__PURE__*/ new Vector2();
  30813. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  30814. class AfterImageNode extends TempNode {
  30815. constructor( textureNode, damp = 0.96 ) {
  30816. super( textureNode );
  30817. this.textureNode = textureNode;
  30818. this.textureNodeOld = texture();
  30819. this.damp = uniform( damp );
  30820. this._compRT = new RenderTarget();
  30821. this._compRT.texture.name = 'AfterImageNode.comp';
  30822. this._oldRT = new RenderTarget();
  30823. this._oldRT.texture.name = 'AfterImageNode.old';
  30824. this._textureNode = passTexture( this, this._compRT.texture );
  30825. this.updateBeforeType = NodeUpdateType.RENDER;
  30826. }
  30827. getTextureNode() {
  30828. return this._textureNode;
  30829. }
  30830. setSize( width, height ) {
  30831. this._compRT.setSize( width, height );
  30832. this._oldRT.setSize( width, height );
  30833. }
  30834. updateBefore( frame ) {
  30835. const { renderer } = frame;
  30836. const textureNode = this.textureNode;
  30837. const map = textureNode.value;
  30838. const textureType = map.type;
  30839. this._compRT.texture.type = textureType;
  30840. this._oldRT.texture.type = textureType;
  30841. renderer.getDrawingBufferSize( _size$3 );
  30842. this.setSize( _size$3.x, _size$3.y );
  30843. const currentRenderTarget = renderer.getRenderTarget();
  30844. const currentTexture = textureNode.value;
  30845. this.textureNodeOld.value = this._oldRT.texture;
  30846. // comp
  30847. renderer.setRenderTarget( this._compRT );
  30848. _quadMeshComp.render( renderer );
  30849. // Swap the textures
  30850. const temp = this._oldRT;
  30851. this._oldRT = this._compRT;
  30852. this._compRT = temp;
  30853. renderer.setRenderTarget( currentRenderTarget );
  30854. textureNode.value = currentTexture;
  30855. }
  30856. setup( builder ) {
  30857. const textureNode = this.textureNode;
  30858. const textureNodeOld = this.textureNodeOld;
  30859. //
  30860. const uvNode = textureNode.uvNode || uv();
  30861. textureNodeOld.uvNode = uvNode;
  30862. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30863. const when_gt = tslFn( ( [ x_immutable, y_immutable ] ) => {
  30864. const y = float( y_immutable ).toVar();
  30865. const x = vec4( x_immutable ).toVar();
  30866. return max$1( sign( x.sub( y ) ), 0.0 );
  30867. } );
  30868. const afterImg = tslFn( () => {
  30869. const texelOld = vec4( textureNodeOld );
  30870. const texelNew = vec4( sampleTexture( uvNode ) );
  30871. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  30872. return max$1( texelNew, texelOld );
  30873. } );
  30874. //
  30875. const materialComposed = this._materialComposed || ( this._materialComposed = builder.createNodeMaterial() );
  30876. materialComposed.fragmentNode = afterImg();
  30877. _quadMeshComp.material = materialComposed;
  30878. //
  30879. const properties = builder.getNodeProperties( this );
  30880. properties.textureNode = textureNode;
  30881. //
  30882. return this._textureNode;
  30883. }
  30884. dispose() {
  30885. this._compRT.dispose();
  30886. this._oldRT.dispose();
  30887. }
  30888. }
  30889. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( nodeObject( node ).toTexture(), damp ) );
  30890. addNodeElement( 'afterImage', afterImage );
  30891. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  30892. class AnamorphicNode extends TempNode {
  30893. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  30894. super( 'vec4' );
  30895. this.textureNode = textureNode;
  30896. this.tresholdNode = tresholdNode;
  30897. this.scaleNode = scaleNode;
  30898. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  30899. this.samples = samples;
  30900. this.resolution = new Vector2( 1, 1 );
  30901. this._renderTarget = new RenderTarget();
  30902. this._renderTarget.texture.name = 'anamorphic';
  30903. this._invSize = uniform( new Vector2() );
  30904. this._textureNode = passTexture( this, this._renderTarget.texture );
  30905. this.updateBeforeType = NodeUpdateType.RENDER;
  30906. }
  30907. getTextureNode() {
  30908. return this._textureNode;
  30909. }
  30910. setSize( width, height ) {
  30911. this._invSize.value.set( 1 / width, 1 / height );
  30912. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  30913. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  30914. this._renderTarget.setSize( width, height );
  30915. }
  30916. updateBefore( frame ) {
  30917. const { renderer } = frame;
  30918. const textureNode = this.textureNode;
  30919. const map = textureNode.value;
  30920. this._renderTarget.texture.type = map.type;
  30921. const currentRenderTarget = renderer.getRenderTarget();
  30922. const currentTexture = textureNode.value;
  30923. _quadMesh$3.material = this._material;
  30924. this.setSize( map.image.width, map.image.height );
  30925. // render
  30926. renderer.setRenderTarget( this._renderTarget );
  30927. _quadMesh$3.render( renderer );
  30928. // restore
  30929. renderer.setRenderTarget( currentRenderTarget );
  30930. textureNode.value = currentTexture;
  30931. }
  30932. setup( builder ) {
  30933. const textureNode = this.textureNode;
  30934. const uvNode = textureNode.uvNode || uv();
  30935. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30936. const anamorph = tslFn( () => {
  30937. const samples = this.samples;
  30938. const halfSamples = Math.floor( samples / 2 );
  30939. const total = vec3( 0 ).toVar();
  30940. loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  30941. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  30942. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  30943. const color = sampleTexture( uv );
  30944. const pass = threshold( color, this.tresholdNode ).mul( softness );
  30945. total.addAssign( pass );
  30946. } );
  30947. return total.mul( this.colorNode );
  30948. } );
  30949. //
  30950. const material = this._material || ( this._material = builder.createNodeMaterial() );
  30951. material.fragmentNode = anamorph();
  30952. //
  30953. const properties = builder.getNodeProperties( this );
  30954. properties.textureNode = textureNode;
  30955. //
  30956. return this._textureNode;
  30957. }
  30958. dispose() {
  30959. this._renderTarget.dispose();
  30960. }
  30961. }
  30962. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( nodeObject( node ).toTexture(), nodeObject( threshold ), nodeObject( scale ), samples ) );
  30963. addNodeElement( 'anamorphic', anamorphic );
  30964. class SobelOperatorNode extends TempNode {
  30965. constructor( textureNode ) {
  30966. super();
  30967. this.textureNode = textureNode;
  30968. this.updateBeforeType = NodeUpdateType.RENDER;
  30969. this._invSize = uniform( new Vector2() );
  30970. }
  30971. updateBefore() {
  30972. const map = this.textureNode.value;
  30973. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  30974. }
  30975. setup() {
  30976. const { textureNode } = this;
  30977. const uvNode = textureNode.uvNode || uv();
  30978. const sampleTexture = ( uv ) => textureNode.uv( uv );
  30979. const sobel = tslFn( () => {
  30980. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  30981. const texel = this._invSize;
  30982. // kernel definition (in glsl matrices are filled in column-major order)
  30983. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  30984. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  30985. // fetch the 3x3 neighbourhood of a fragment
  30986. // first column
  30987. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  30988. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  30989. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  30990. // second column
  30991. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  30992. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  30993. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  30994. // third column
  30995. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  30996. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  30997. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  30998. // gradient value in x direction
  30999. const valueGx = add(
  31000. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  31001. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  31002. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  31003. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  31004. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  31005. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  31006. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  31007. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  31008. Gx[ 2 ][ 2 ].mul( tx2y2 )
  31009. );
  31010. // gradient value in y direction
  31011. const valueGy = add(
  31012. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  31013. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  31014. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  31015. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  31016. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  31017. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  31018. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  31019. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  31020. Gy[ 2 ][ 2 ].mul( tx2y2 )
  31021. );
  31022. // magnitute of the total gradient
  31023. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  31024. return vec4( vec3( G ), 1 );
  31025. } );
  31026. const outputNode = sobel();
  31027. return outputNode;
  31028. }
  31029. }
  31030. const sobel = ( node ) => nodeObject( new SobelOperatorNode( nodeObject( node ).toTexture() ) );
  31031. addNodeElement( 'sobel', sobel );
  31032. class DepthOfFieldNode extends TempNode {
  31033. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  31034. super();
  31035. this.textureNode = textureNode;
  31036. this.viewZNode = viewZNode;
  31037. this.focusNode = focusNode;
  31038. this.apertureNode = apertureNode;
  31039. this.maxblurNode = maxblurNode;
  31040. this._aspect = uniform( 0 );
  31041. this.updateBeforeType = NodeUpdateType.RENDER;
  31042. }
  31043. updateBefore() {
  31044. const map = this.textureNode.value;
  31045. this._aspect.value = map.image.width / map.image.height;
  31046. }
  31047. setup() {
  31048. const textureNode = this.textureNode;
  31049. const uvNode = textureNode.uvNode || uv();
  31050. const sampleTexture = ( uv ) => textureNode.uv( uv );
  31051. const dof = tslFn( () => {
  31052. const aspectcorrect = vec2( 1.0, this._aspect );
  31053. const factor = this.focusNode.add( this.viewZNode );
  31054. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  31055. const dofblur9 = dofblur.mul( 0.9 );
  31056. const dofblur7 = dofblur.mul( 0.7 );
  31057. const dofblur4 = dofblur.mul( 0.4 );
  31058. let col = vec4( 0.0 );
  31059. col = col.add( sampleTexture( uvNode ) );
  31060. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31061. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31062. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31063. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31064. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31065. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).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.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31068. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31069. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).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.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31072. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31073. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).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.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  31076. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31077. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31078. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  31079. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  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.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31085. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31086. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  31087. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  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.4, 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( dofblur4 ) ) ) );
  31093. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31094. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  31095. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  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.div( 41 );
  31101. col.a = 1;
  31102. return vec4( col );
  31103. } );
  31104. const outputNode = dof();
  31105. return outputNode;
  31106. }
  31107. }
  31108. 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 ) ) );
  31109. addNodeElement( 'dof', dof );
  31110. class DotScreenNode extends TempNode {
  31111. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  31112. super( 'vec4' );
  31113. this.inputNode = inputNode;
  31114. this.center = uniform( center );
  31115. this.angle = uniform( angle );
  31116. this.scale = uniform( scale );
  31117. this._size = uniform( new Vector2() );
  31118. this.updateBeforeType = NodeUpdateType.RENDER;
  31119. }
  31120. updateBefore( frame ) {
  31121. const { renderer } = frame;
  31122. renderer.getDrawingBufferSize( this._size.value );
  31123. }
  31124. setup() {
  31125. const inputNode = this.inputNode;
  31126. const pattern = tslFn( () => {
  31127. const s = sin( this.angle );
  31128. const c = cos( this.angle );
  31129. const tex = uv().mul( this._size ).sub( this.center );
  31130. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  31131. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  31132. } );
  31133. const dotScreen = tslFn( () => {
  31134. const color = inputNode;
  31135. const average = add( color.r, color.g, color.b ).div( 3 );
  31136. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  31137. } );
  31138. const outputNode = dotScreen();
  31139. return outputNode;
  31140. }
  31141. }
  31142. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  31143. addNodeElement( 'dotScreen', dotScreen );
  31144. class RGBShiftNode extends TempNode {
  31145. constructor( textureNode, amount = 0.005, angle = 0 ) {
  31146. super( 'vec4' );
  31147. this.textureNode = textureNode;
  31148. this.amount = uniform( amount );
  31149. this.angle = uniform( angle );
  31150. }
  31151. setup() {
  31152. const { textureNode } = this;
  31153. const uvNode = textureNode.uvNode || uv();
  31154. const sampleTexture = ( uv ) => textureNode.uv( uv );
  31155. const rgbShift = tslFn( () => {
  31156. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  31157. const cr = sampleTexture( uvNode.add( offset ) );
  31158. const cga = sampleTexture( uvNode );
  31159. const cb = sampleTexture( uvNode.sub( offset ) );
  31160. return vec4( cr.r, cga.g, cb.b, cga.a );
  31161. } );
  31162. return rgbShift();
  31163. }
  31164. }
  31165. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( nodeObject( node ).toTexture(), amount, angle ) );
  31166. addNodeElement( 'rgbShift', rgbShift );
  31167. class FilmNode extends TempNode {
  31168. constructor( inputNode, intensityNode = null, uvNode = null ) {
  31169. super();
  31170. this.inputNode = inputNode;
  31171. this.intensityNode = intensityNode;
  31172. this.uvNode = uvNode;
  31173. }
  31174. setup() {
  31175. const uvNode = this.uvNode || uv();
  31176. const film = tslFn( () => {
  31177. const base = this.inputNode.rgb;
  31178. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  31179. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  31180. if ( this.intensityNode !== null ) {
  31181. color = mix( base, color, this.intensityNode );
  31182. }
  31183. return vec4( color, this.inputNode.a );
  31184. } );
  31185. const outputNode = film();
  31186. return outputNode;
  31187. }
  31188. }
  31189. const film = nodeProxy( FilmNode );
  31190. addNodeElement( 'film', film );
  31191. class Lut3DNode extends TempNode {
  31192. constructor( inputNode, lutNode, size, intensityNode ) {
  31193. super();
  31194. this.inputNode = inputNode;
  31195. this.lutNode = lutNode;
  31196. this.size = uniform( size );
  31197. this.intensityNode = intensityNode;
  31198. }
  31199. setup() {
  31200. const { inputNode, lutNode } = this;
  31201. const sampleLut = ( uv ) => lutNode.uv( uv );
  31202. const lut3D = tslFn( () => {
  31203. const base = inputNode;
  31204. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  31205. const pixelWidth = float( 1.0 ).div( this.size );
  31206. const halfPixelWidth = float( 0.5 ).div( this.size );
  31207. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  31208. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  31209. return vec4( mix( base, lutValue, this.intensityNode ) );
  31210. } );
  31211. const outputNode = lut3D();
  31212. return outputNode;
  31213. }
  31214. }
  31215. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  31216. addNodeElement( 'lut3D', lut3D );
  31217. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  31218. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  31219. const _size$2 = /*@__PURE__*/ new Vector2();
  31220. class GTAONode extends TempNode {
  31221. constructor( depthNode, normalNode, camera ) {
  31222. super();
  31223. this.depthNode = depthNode;
  31224. this.normalNode = normalNode;
  31225. this.radius = uniform( 0.25 );
  31226. this.resolution = uniform( new Vector2() );
  31227. this.thickness = uniform( 1 );
  31228. this.distanceExponent = uniform( 1 );
  31229. this.distanceFallOff = uniform( 1 );
  31230. this.scale = uniform( 1 );
  31231. this.noiseNode = texture( generateMagicSquareNoise() );
  31232. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  31233. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31234. this.SAMPLES = uniform( 16 );
  31235. this._aoRenderTarget = new RenderTarget();
  31236. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  31237. this._material = null;
  31238. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  31239. this.updateBeforeType = NodeUpdateType.FRAME;
  31240. }
  31241. getTextureNode() {
  31242. return this._textureNode;
  31243. }
  31244. setSize( width, height ) {
  31245. this.resolution.value.set( width, height );
  31246. this._aoRenderTarget.setSize( width, height );
  31247. }
  31248. updateBefore( frame ) {
  31249. const { renderer } = frame;
  31250. const size = renderer.getDrawingBufferSize( _size$2 );
  31251. const currentRenderTarget = renderer.getRenderTarget();
  31252. const currentMRT = renderer.getMRT();
  31253. renderer.getClearColor( _currentClearColor$1 );
  31254. const currentClearAlpha = renderer.getClearAlpha();
  31255. _quadMesh$2.material = this._material;
  31256. this.setSize( size.width, size.height );
  31257. // clear
  31258. renderer.setMRT( null );
  31259. renderer.setClearColor( 0xffffff, 1 );
  31260. // ao
  31261. renderer.setRenderTarget( this._aoRenderTarget );
  31262. _quadMesh$2.render( renderer );
  31263. // restore
  31264. renderer.setRenderTarget( currentRenderTarget );
  31265. renderer.setMRT( currentMRT );
  31266. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  31267. }
  31268. setup( builder ) {
  31269. const uvNode = uv();
  31270. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31271. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31272. const getSceneUvAndDepth = tslFn( ( [ sampleViewPos ] )=> {
  31273. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  31274. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31275. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31276. const sampleSceneDepth = sampleDepth( sampleUv );
  31277. return vec3( sampleUv, sampleSceneDepth );
  31278. } );
  31279. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31280. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31281. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31282. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31283. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31284. } );
  31285. const ao = tslFn( () => {
  31286. const depth = sampleDepth( uvNode );
  31287. depth.greaterThanEqual( 1.0 ).discard();
  31288. const viewPosition = getViewPosition( uvNode, depth );
  31289. const viewNormal = this.normalNode.rgb.normalize();
  31290. const radiusToUse = this.radius;
  31291. const noiseResolution = textureSize( this.noiseNode, 0 );
  31292. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31293. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  31294. const noiseTexel = sampleNoise( noiseUv );
  31295. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  31296. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  31297. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  31298. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  31299. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).cond( 3, 5 );
  31300. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  31301. const ao = float( 0 ).toVar();
  31302. loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  31303. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  31304. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  31305. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  31306. const viewDir = normalize( viewPosition.xyz.negate() );
  31307. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  31308. const sliceTangent = cross( sliceBitangent, viewDir );
  31309. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  31310. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  31311. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  31312. loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  31313. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  31314. // x
  31315. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  31316. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  31317. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  31318. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  31319. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  31320. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31321. } );
  31322. // y
  31323. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  31324. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  31325. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  31326. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  31327. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  31328. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  31329. } );
  31330. } );
  31331. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  31332. const nx = dot( normalInSlice, sliceTangent );
  31333. const ny = dot( normalInSlice, viewDir );
  31334. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  31335. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  31336. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  31337. ao.addAssign( occlusion );
  31338. } );
  31339. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  31340. ao.assign( pow( ao, this.scale ) );
  31341. return vec4( vec3( ao ), 1.0 );
  31342. } );
  31343. const material = this._material || ( this._material = builder.createNodeMaterial() );
  31344. material.fragmentNode = ao().context( builder.getSharedContext() );
  31345. material.needsUpdate = true;
  31346. //
  31347. return this._textureNode;
  31348. }
  31349. dispose() {
  31350. this._aoRenderTarget.dispose();
  31351. }
  31352. }
  31353. function generateMagicSquareNoise( size = 5 ) {
  31354. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31355. const magicSquare = generateMagicSquare( noiseSize );
  31356. const noiseSquareSize = magicSquare.length;
  31357. const data = new Uint8Array( noiseSquareSize * 4 );
  31358. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  31359. const iAng = magicSquare[ inx ];
  31360. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  31361. const randomVec = new Vector3(
  31362. Math.cos( angle ),
  31363. Math.sin( angle ),
  31364. 0
  31365. ).normalize();
  31366. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  31367. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  31368. data[ inx * 4 + 2 ] = 127;
  31369. data[ inx * 4 + 3 ] = 255;
  31370. }
  31371. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  31372. noiseTexture.wrapS = RepeatWrapping;
  31373. noiseTexture.wrapT = RepeatWrapping;
  31374. noiseTexture.needsUpdate = true;
  31375. return noiseTexture;
  31376. }
  31377. function generateMagicSquare( size ) {
  31378. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  31379. const noiseSquareSize = noiseSize * noiseSize;
  31380. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  31381. let i = Math.floor( noiseSize / 2 );
  31382. let j = noiseSize - 1;
  31383. for ( let num = 1; num <= noiseSquareSize; ) {
  31384. if ( i === - 1 && j === noiseSize ) {
  31385. j = noiseSize - 2;
  31386. i = 0;
  31387. } else {
  31388. if ( j === noiseSize ) {
  31389. j = 0;
  31390. }
  31391. if ( i < 0 ) {
  31392. i = noiseSize - 1;
  31393. }
  31394. }
  31395. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  31396. j -= 2;
  31397. i ++;
  31398. continue;
  31399. } else {
  31400. magicSquare[ i * noiseSize + j ] = num ++;
  31401. }
  31402. j ++;
  31403. i --;
  31404. }
  31405. return magicSquare;
  31406. }
  31407. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  31408. addNodeElement( 'ao', ao );
  31409. class DenoiseNode extends TempNode {
  31410. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  31411. super();
  31412. this.textureNode = textureNode;
  31413. this.depthNode = depthNode;
  31414. this.normalNode = normalNode;
  31415. this.noiseNode = noiseNode;
  31416. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  31417. this.lumaPhi = uniform( 5 );
  31418. this.depthPhi = uniform( 5 );
  31419. this.normalPhi = uniform( 5 );
  31420. this.radius = uniform( 5 );
  31421. this.index = uniform( 0 );
  31422. this._resolution = uniform( new Vector2() );
  31423. this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
  31424. this.updateBeforeType = NodeUpdateType.RENDER;
  31425. }
  31426. updateBefore() {
  31427. const map = this.textureNode.value;
  31428. this._resolution.value.set( map.image.width, map.image.height );
  31429. }
  31430. setup() {
  31431. const uvNode = uv();
  31432. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  31433. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  31434. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  31435. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  31436. const getViewPosition = tslFn( ( [ screenPosition, depth ] ) => {
  31437. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31438. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31439. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  31440. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31441. } );
  31442. const denoiseSample = tslFn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  31443. const texel = sampleTexture( sampleUv );
  31444. const depth = sampleDepth( sampleUv );
  31445. const normal = sampleNormal( sampleUv ).rgb.normalize();
  31446. const neighborColor = texel.rgb;
  31447. const viewPos = getViewPosition( sampleUv, depth );
  31448. const normalDiff = dot( viewNormal, normal ).toVar();
  31449. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  31450. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  31451. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  31452. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  31453. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  31454. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  31455. return vec4( neighborColor.mul( w ), w );
  31456. } );
  31457. const denoise = tslFn( ( [ uvNode ] ) => {
  31458. const depth = sampleDepth( uvNode );
  31459. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  31460. const texel = sampleTexture( uvNode );
  31461. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  31462. return texel;
  31463. } );
  31464. const center = vec3( texel.rgb );
  31465. const viewPosition = getViewPosition( uvNode, depth );
  31466. const noiseResolution = textureSize( this.noiseNode, 0 );
  31467. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  31468. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  31469. const noiseTexel = sampleNoise( noiseUv );
  31470. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31471. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  31472. const noiseVec = vec2( x, y );
  31473. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  31474. const totalWeight = float( 1.0 ).toVar();
  31475. const denoised = vec3( texel.rgb ).toVar();
  31476. loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  31477. const sampleDir = this._sampleVectors.element( i ).toVar();
  31478. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  31479. const sampleUv = uvNode.add( offset ).toVar();
  31480. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  31481. denoised.addAssign( result.xyz );
  31482. totalWeight.addAssign( result.w );
  31483. } );
  31484. If( totalWeight.greaterThan( float( 0 ) ), () => {
  31485. denoised.divAssign( totalWeight );
  31486. } );
  31487. return vec4( denoised, texel.a );
  31488. } ).setLayout( {
  31489. name: 'denoise',
  31490. type: 'vec4',
  31491. inputs: [
  31492. { name: 'uv', type: 'vec2' }
  31493. ]
  31494. } );
  31495. const output = tslFn( () => {
  31496. return denoise( uvNode );
  31497. } );
  31498. const outputNode = output();
  31499. return outputNode;
  31500. }
  31501. }
  31502. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  31503. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  31504. const array = [];
  31505. for ( let i = 0; i < samples; i ++ ) {
  31506. const sample = poissonDisk[ i ];
  31507. array.push( sample );
  31508. }
  31509. return array;
  31510. }
  31511. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  31512. const samples = [];
  31513. for ( let i = 0; i < numSamples; i ++ ) {
  31514. const angle = 2 * Math.PI * numRings * i / numSamples;
  31515. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  31516. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  31517. }
  31518. return samples;
  31519. }
  31520. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( nodeObject( node ).toTexture(), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  31521. addNodeElement( 'denoise', denoise );
  31522. class FXAANode extends TempNode {
  31523. constructor( textureNode ) {
  31524. super();
  31525. this.textureNode = textureNode;
  31526. this.updateBeforeType = NodeUpdateType.RENDER;
  31527. this._invSize = uniform( new Vector2() );
  31528. }
  31529. updateBefore() {
  31530. const map = this.textureNode.value;
  31531. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  31532. }
  31533. setup() {
  31534. const textureNode = this.textureNode.bias( - 100 );
  31535. const uvNode = textureNode.uvNode || uv();
  31536. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  31537. //----------------------------------------------------------------------------------
  31538. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  31539. // SDK Version: v3.00
  31540. // Email: gameworks@nvidia.com
  31541. // Site: http://developer.nvidia.com/
  31542. //
  31543. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  31544. //
  31545. // Redistribution and use in source and binary forms, with or without
  31546. // modification, are permitted provided that the following conditions
  31547. // are met:
  31548. // * Redistributions of source code must retain the above copyright
  31549. // notice, this list of conditions and the following disclaimer.
  31550. // * Redistributions in binary form must reproduce the above copyright
  31551. // notice, this list of conditions and the following disclaimer in the
  31552. // documentation and/or other materials provided with the distribution.
  31553. // * Neither the name of NVIDIA CORPORATION nor the names of its
  31554. // contributors may be used to endorse or promote products derived
  31555. // from this software without specific prior written permission.
  31556. //
  31557. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  31558. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  31559. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  31560. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31561. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  31562. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  31563. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  31564. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  31565. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31566. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31567. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31568. //
  31569. //----------------------------------------------------------------------------------
  31570. const FxaaTexTop = ( p ) => textureNode.uv( p );
  31571. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  31572. const NUM_SAMPLES = int( 5 );
  31573. const contrast = tslFn( ( [ a_immutable, b_immutable ] ) => {
  31574. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  31575. const b = vec4( b_immutable ).toVar();
  31576. const a = vec4( a_immutable ).toVar();
  31577. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  31578. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  31579. } );
  31580. // FXAA3 QUALITY - PC
  31581. const FxaaPixelShader = tslFn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  31582. const rgbaM = FxaaTexTop( uv ).toVar();
  31583. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31584. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31585. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31586. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  31587. // . S .
  31588. // W M E
  31589. // . N .
  31590. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  31591. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  31592. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  31593. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  31594. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  31595. // . 0 .
  31596. // 0 0 0
  31597. // . 0 .
  31598. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  31599. return rgbaM; // assuming define FXAA_DISCARD is always 0
  31600. } );
  31601. //
  31602. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  31603. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31604. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  31605. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  31606. // locate the edge
  31607. const x = contrastE.greaterThan( contrastW ).cond( 1, - 1 ).toVar();
  31608. const y = contrastS.greaterThan( contrastN ).cond( 1, - 1 ).toVar();
  31609. const dirToEdge = vec2( x, y ).toVar();
  31610. // . 2 . . 1 .
  31611. // 1 0 2 ~= 0 0 1
  31612. // . 1 . . 0 .
  31613. // tap 2 pixels and see which ones are "outside" the edge, to
  31614. // determine if the edge is vertical or horizontal
  31615. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  31616. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  31617. // . 1 .
  31618. // 0 0 1
  31619. // . 0 H
  31620. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  31621. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  31622. // V 1 .
  31623. // 0 0 1
  31624. // . 0 .
  31625. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  31626. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  31627. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  31628. // 1 1 .
  31629. // 0 0 1
  31630. // . 0 1
  31631. // do a simple blur
  31632. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  31633. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  31634. } );
  31635. } );
  31636. const offNP = vec2().toVar();
  31637. If( relativeVContrast.lessThanEqual( 0 ), () => {
  31638. rgbaN.assign( rgbaW );
  31639. rgbaS.assign( rgbaE );
  31640. // . 0 . 1
  31641. // 1 0 1 -> 0
  31642. // . 0 . 1
  31643. offNP.x.assign( 0 );
  31644. offNP.y.assign( fxaaQualityRcpFrame.y );
  31645. } ).else( () => {
  31646. offNP.x.assign( fxaaQualityRcpFrame.x );
  31647. offNP.y.assign( 0 );
  31648. } );
  31649. const mn = contrast( rgbaM, rgbaN ).toVar();
  31650. const ms = contrast( rgbaM, rgbaS ).toVar();
  31651. If( mn.lessThanEqual( ms ), () => {
  31652. rgbaN.assign( rgbaS );
  31653. } );
  31654. const doneN = int( 0 ).toVar();
  31655. const doneP = int( 0 ).toVar();
  31656. const nDist = float( 0 ).toVar();
  31657. const pDist = float( 0 ).toVar();
  31658. const posN = vec2( uv ).toVar();
  31659. const posP = vec2( uv ).toVar();
  31660. const iterationsUsedN = int( 0 ).toVar();
  31661. const iterationsUsedP = int( 0 ).toVar();
  31662. loop( NUM_SAMPLES, ( { i } ) => {
  31663. const increment = i.add( 1 ).toVar();
  31664. If( doneN.equal( 0 ), () => {
  31665. nDist.addAssign( increment );
  31666. posN.assign( uv.add( offNP.mul( nDist ) ) );
  31667. const rgbaEndN = FxaaTexTop( posN.xy );
  31668. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  31669. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  31670. If( nm.greaterThan( nn ), () => {
  31671. doneN.assign( 1 );
  31672. } );
  31673. iterationsUsedN.assign( i );
  31674. } );
  31675. If( doneP.equal( 0 ), () => {
  31676. pDist.addAssign( increment );
  31677. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  31678. const rgbaEndP = FxaaTexTop( posP.xy );
  31679. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  31680. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  31681. If( pm.greaterThan( pn ), () => {
  31682. doneP.assign( 1 );
  31683. } );
  31684. iterationsUsedP.assign( i );
  31685. } );
  31686. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  31687. Break();
  31688. } );
  31689. } );
  31690. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  31691. return rgbaM; // failed to find end of edge
  31692. } );
  31693. const distN = float( 1 ).toVar();
  31694. const distP = float( 1 ).toVar();
  31695. If( doneN.equal( 1 ), () => {
  31696. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31697. } );
  31698. If( doneP.equal( 1 ), () => {
  31699. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  31700. } );
  31701. const dist = min$1( distN, distP );
  31702. // hacky way of reduces blurriness of mostly diagonal edges
  31703. // but reduces AA quality
  31704. dist.assign( pow( dist, 0.5 ) );
  31705. dist.assign( float( 1 ).sub( dist ) );
  31706. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  31707. } ).setLayout( {
  31708. name: 'FxaaPixelShader',
  31709. type: 'vec4',
  31710. inputs: [
  31711. { name: 'uv', type: 'vec2' },
  31712. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  31713. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  31714. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  31715. ]
  31716. } );
  31717. const fxaa = tslFn( () => {
  31718. const edgeDetectionQuality = float( 0.2 );
  31719. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  31720. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  31721. } );
  31722. const outputNode = fxaa();
  31723. return outputNode;
  31724. }
  31725. }
  31726. const fxaa = ( node ) => nodeObject( new FXAANode( nodeObject( node ).toTexture() ) );
  31727. addNodeElement( 'fxaa', fxaa );
  31728. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  31729. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  31730. const _currentClearColor = /*@__PURE__*/ new Color();
  31731. const _size$1 = /*@__PURE__*/ new Vector2();
  31732. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  31733. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  31734. class BloomNode extends TempNode {
  31735. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  31736. super();
  31737. this.inputNode = inputNode;
  31738. this.strength = uniform( strength );
  31739. this.radius = uniform( radius );
  31740. this.threshold = uniform( threshold );
  31741. this.smoothWidth = uniform( 0.01 );
  31742. //
  31743. this._renderTargetsHorizontal = [];
  31744. this._renderTargetsVertical = [];
  31745. this._nMips = 5;
  31746. // render targets
  31747. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31748. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  31749. this._renderTargetBright.texture.generateMipmaps = false;
  31750. for ( let i = 0; i < this._nMips; i ++ ) {
  31751. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31752. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  31753. renderTargetHorizontal.texture.generateMipmaps = false;
  31754. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  31755. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  31756. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  31757. renderTargetVertical.texture.generateMipmaps = false;
  31758. this._renderTargetsVertical.push( renderTargetVertical );
  31759. }
  31760. // materials
  31761. this._compositeMaterial = null;
  31762. this._highPassFilterMaterial = null;
  31763. this._separableBlurMaterials = [];
  31764. // pass and texture nodes
  31765. this._textureNodeBright = texture( this._renderTargetBright.texture );
  31766. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  31767. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  31768. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  31769. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  31770. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  31771. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  31772. this.updateBeforeType = NodeUpdateType.FRAME;
  31773. }
  31774. getTextureNode() {
  31775. return this._textureOutput;
  31776. }
  31777. setSize( width, height ) {
  31778. let resx = Math.round( width / 2 );
  31779. let resy = Math.round( height / 2 );
  31780. this._renderTargetBright.setSize( resx, resy );
  31781. for ( let i = 0; i < this._nMips; i ++ ) {
  31782. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  31783. this._renderTargetsVertical[ i ].setSize( resx, resy );
  31784. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  31785. resx = Math.round( resx / 2 );
  31786. resy = Math.round( resy / 2 );
  31787. }
  31788. }
  31789. updateBefore( frame ) {
  31790. const { renderer } = frame;
  31791. const size = renderer.getDrawingBufferSize( _size$1 );
  31792. this.setSize( size.width, size.height );
  31793. const currentRenderTarget = renderer.getRenderTarget();
  31794. const currentMRT = renderer.getMRT();
  31795. renderer.getClearColor( _currentClearColor );
  31796. const currentClearAlpha = renderer.getClearAlpha();
  31797. this.setSize( size.width, size.height );
  31798. renderer.setMRT( null );
  31799. renderer.setClearColor( _clearColor$1, 0 );
  31800. // 1. Extract Bright Areas
  31801. renderer.setRenderTarget( this._renderTargetBright );
  31802. _quadMesh$1.material = this._highPassFilterMaterial;
  31803. _quadMesh$1.render( renderer );
  31804. // 2. Blur All the mips progressively
  31805. let inputRenderTarget = this._renderTargetBright;
  31806. for ( let i = 0; i < this._nMips; i ++ ) {
  31807. _quadMesh$1.material = this._separableBlurMaterials[ i ];
  31808. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  31809. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  31810. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  31811. renderer.clear();
  31812. _quadMesh$1.render( renderer );
  31813. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  31814. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  31815. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  31816. renderer.clear();
  31817. _quadMesh$1.render( renderer );
  31818. inputRenderTarget = this._renderTargetsVertical[ i ];
  31819. }
  31820. // 3. Composite All the mips
  31821. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  31822. renderer.clear();
  31823. _quadMesh$1.material = this._compositeMaterial;
  31824. _quadMesh$1.render( renderer );
  31825. // restore
  31826. renderer.setRenderTarget( currentRenderTarget );
  31827. renderer.setMRT( currentMRT );
  31828. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  31829. }
  31830. setup( builder ) {
  31831. // luminosity high pass material
  31832. const luminosityHighPass = tslFn( () => {
  31833. const texel = this.inputNode;
  31834. const v = luminance( texel.rgb );
  31835. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  31836. return mix( vec4( 0 ), texel, alpha );
  31837. } );
  31838. this._highPassFilterMaterial = this._highPassFilterMaterial || builder.createNodeMaterial();
  31839. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  31840. this._highPassFilterMaterial.needsUpdate = true;
  31841. // gaussian blur materials
  31842. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  31843. for ( let i = 0; i < this._nMips; i ++ ) {
  31844. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  31845. }
  31846. // composite material
  31847. const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  31848. 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 ) ] );
  31849. const lerpBloomFactor = tslFn( ( [ factor, radius ] ) => {
  31850. const mirrorFactor = float( 1.2 ).sub( factor );
  31851. return mix( factor, mirrorFactor, radius );
  31852. } ).setLayout( {
  31853. name: 'lerpBloomFactor',
  31854. type: 'float',
  31855. inputs: [
  31856. { name: 'factor', type: 'float' },
  31857. { name: 'radius', type: 'float' },
  31858. ]
  31859. } );
  31860. const compositePass = tslFn( () => {
  31861. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  31862. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  31863. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  31864. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  31865. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  31866. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  31867. return sum.mul( this.strength );
  31868. } );
  31869. this._compositeMaterial = this._compositeMaterial || builder.createNodeMaterial();
  31870. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  31871. this._compositeMaterial.needsUpdate = true;
  31872. //
  31873. return this._textureOutput;
  31874. }
  31875. dispose() {
  31876. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  31877. this._renderTargetsHorizontal[ i ].dispose();
  31878. }
  31879. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  31880. this._renderTargetsVertical[ i ].dispose();
  31881. }
  31882. this._renderTargetBright.dispose();
  31883. }
  31884. _getSeperableBlurMaterial( builder, kernelRadius ) {
  31885. const coefficients = [];
  31886. for ( let i = 0; i < kernelRadius; i ++ ) {
  31887. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  31888. }
  31889. //
  31890. const colorTexture = texture();
  31891. const gaussianCoefficients = uniformArray( coefficients );
  31892. const invSize = uniform( new Vector2() );
  31893. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  31894. const uvNode = uv();
  31895. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  31896. const seperableBlurPass = tslFn( () => {
  31897. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  31898. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  31899. loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  31900. const x = float( i );
  31901. const w = gaussianCoefficients.element( i );
  31902. const uvOffset = direction.mul( invSize ).mul( x );
  31903. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  31904. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  31905. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  31906. weightSum.addAssign( float( 2.0 ).mul( w ) );
  31907. } );
  31908. return vec4( diffuseSum.div( weightSum ), 1.0 );
  31909. } );
  31910. const seperableBlurMaterial = builder.createNodeMaterial();
  31911. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  31912. seperableBlurMaterial.needsUpdate = true;
  31913. // uniforms
  31914. seperableBlurMaterial.colorTexture = colorTexture;
  31915. seperableBlurMaterial.direction = direction;
  31916. seperableBlurMaterial.invSize = invSize;
  31917. return seperableBlurMaterial;
  31918. }
  31919. }
  31920. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  31921. addNodeElement( 'bloom', bloom );
  31922. class TransitionNode extends TempNode {
  31923. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  31924. super();
  31925. // Input textures
  31926. this.textureNodeA = textureNodeA;
  31927. this.textureNodeB = textureNodeB;
  31928. this.mixTextureNode = mixTextureNode;
  31929. // Uniforms
  31930. this.mixRatioNode = mixRatioNode;
  31931. this.thresholdNode = thresholdNode;
  31932. this.useTextureNode = useTextureNode;
  31933. }
  31934. setup() {
  31935. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  31936. const sampleTexture = ( textureNode ) => {
  31937. const uvNodeTexture = textureNode.uvNode || uv();
  31938. return textureNode.uv( uvNodeTexture );
  31939. };
  31940. const transition = tslFn( () => {
  31941. const texelOne = sampleTexture( textureNodeA );
  31942. const texelTwo = sampleTexture( textureNodeB );
  31943. const color = vec4().toVar();
  31944. If( useTextureNode.equal( int( 1 ) ), () => {
  31945. const transitionTexel = sampleTexture( mixTextureNode );
  31946. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  31947. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  31948. color.assign( mix( texelOne, texelTwo, mixf ) );
  31949. } ).else( () => {
  31950. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  31951. } );
  31952. return color;
  31953. } );
  31954. const outputNode = transition();
  31955. return outputNode;
  31956. }
  31957. }
  31958. 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 ) ) );
  31959. addNodeElement( 'transition', transition );
  31960. class RenderOutputNode extends TempNode {
  31961. constructor( colorNode, toneMapping, outputColorSpace ) {
  31962. super( 'vec4' );
  31963. this.colorNode = colorNode;
  31964. this.toneMapping = toneMapping;
  31965. this.outputColorSpace = outputColorSpace;
  31966. this.isRenderOutput = true;
  31967. }
  31968. setup( { context } ) {
  31969. let outputNode = this.colorNode || context.color;
  31970. // tone mapping
  31971. const toneMapping = this.toneMapping !== null ? this.toneMapping : context.toneMapping;
  31972. const outputColorSpace = this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace;
  31973. if ( toneMapping !== NoToneMapping ) {
  31974. outputNode = outputNode.toneMapping( toneMapping );
  31975. }
  31976. // output color space
  31977. if ( outputColorSpace === SRGBColorSpace ) {
  31978. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  31979. }
  31980. return outputNode;
  31981. }
  31982. }
  31983. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  31984. addNodeElement( 'renderOutput', renderOutput );
  31985. addNodeClass( 'RenderOutputNode', RenderOutputNode );
  31986. class PixelationNode extends TempNode {
  31987. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  31988. super();
  31989. // Input textures
  31990. this.textureNode = textureNode;
  31991. this.depthNode = depthNode;
  31992. this.normalNode = normalNode;
  31993. // Input uniforms
  31994. this.pixelSize = pixelSize;
  31995. this.normalEdgeStrength = normalEdgeStrength;
  31996. this.depthEdgeStrength = depthEdgeStrength;
  31997. // Private uniforms
  31998. this._resolution = uniform( new Vector4() );
  31999. this.updateBeforeType = NodeUpdateType.RENDER;
  32000. }
  32001. updateBefore() {
  32002. const map = this.textureNode.value;
  32003. const width = map.image.width;
  32004. const height = map.image.height;
  32005. this._resolution.value.set( width, height, 1 / width, 1 / height );
  32006. }
  32007. setup() {
  32008. const { textureNode, depthNode, normalNode } = this;
  32009. const uvNodeTexture = textureNode.uvNode || uv();
  32010. const uvNodeDepth = depthNode.uvNode || uv();
  32011. const uvNodeNormal = normalNode.uvNode || uv();
  32012. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  32013. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  32014. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  32015. const depthEdgeIndicator = ( depth ) => {
  32016. const diff = property( 'float', 'diff' );
  32017. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  32018. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  32019. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  32020. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  32021. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  32022. };
  32023. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  32024. const depthDiff = sampleDepth( x, y ).sub( depth );
  32025. const neighborNormal = sampleNormal( x, y );
  32026. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  32027. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  32028. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  32029. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  32030. // Only the shallower pixel should detect the normal edge.
  32031. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  32032. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  32033. };
  32034. const normalEdgeIndicator = ( depth, normal ) => {
  32035. const indicator = property( 'float', 'indicator' );
  32036. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  32037. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  32038. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  32039. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  32040. return step( 0.1, indicator );
  32041. };
  32042. const pixelation = tslFn( () => {
  32043. const texel = sampleTexture();
  32044. const depth = property( 'float', 'depth' );
  32045. const normal = property( 'vec3', 'normal' );
  32046. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  32047. depth.assign( sampleDepth( 0, 0 ) );
  32048. normal.assign( sampleNormal( 0, 0 ) );
  32049. } );
  32050. const dei = property( 'float', 'dei' );
  32051. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  32052. dei.assign( depthEdgeIndicator( depth ) );
  32053. } );
  32054. const nei = property( 'float', 'nei' );
  32055. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  32056. nei.assign( normalEdgeIndicator( depth, normal ) );
  32057. } );
  32058. const strength = dei.greaterThan( 0 ).cond( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  32059. return texel.mul( strength );
  32060. } );
  32061. const outputNode = pixelation();
  32062. return outputNode;
  32063. }
  32064. }
  32065. 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 ) ) );
  32066. addNodeElement( 'pixelation', pixelation );
  32067. class PixelationPassNode extends PassNode {
  32068. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  32069. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  32070. this.pixelSize = pixelSize;
  32071. this.normalEdgeStrength = normalEdgeStrength;
  32072. this.depthEdgeStrength = depthEdgeStrength;
  32073. this.isPixelationPassNode = true;
  32074. this._mrt = mrt( {
  32075. output: output,
  32076. normal: normalView
  32077. } );
  32078. }
  32079. setSize( width, height ) {
  32080. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  32081. const adjustedWidth = Math.floor( width / pixelSize );
  32082. const adjustedHeight = Math.floor( height / pixelSize );
  32083. super.setSize( adjustedWidth, adjustedHeight );
  32084. }
  32085. setup() {
  32086. const color = super.getTextureNode( 'output' );
  32087. const depth = super.getTextureNode( 'depth' );
  32088. const normal = super.getTextureNode( 'normal' );
  32089. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  32090. }
  32091. }
  32092. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  32093. const sepia = /*@__PURE__*/ tslFn( ( [ color ] ) => {
  32094. const c = vec3( color );
  32095. // https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
  32096. return vec3(
  32097. dot( c, vec3( 0.393, 0.769, 0.189 ) ),
  32098. dot( c, vec3( 0.349, 0.686, 0.168 ) ),
  32099. dot( c, vec3( 0.272, 0.534, 0.131 ) )
  32100. );
  32101. } );
  32102. addNodeElement( 'sepia', sepia );
  32103. class FunctionCallNode extends TempNode {
  32104. constructor( functionNode = null, parameters = {} ) {
  32105. super();
  32106. this.functionNode = functionNode;
  32107. this.parameters = parameters;
  32108. }
  32109. setParameters( parameters ) {
  32110. this.parameters = parameters;
  32111. return this;
  32112. }
  32113. getParameters() {
  32114. return this.parameters;
  32115. }
  32116. getNodeType( builder ) {
  32117. return this.functionNode.getNodeType( builder );
  32118. }
  32119. generate( builder ) {
  32120. const params = [];
  32121. const functionNode = this.functionNode;
  32122. const inputs = functionNode.getInputs( builder );
  32123. const parameters = this.parameters;
  32124. if ( Array.isArray( parameters ) ) {
  32125. for ( let i = 0; i < parameters.length; i ++ ) {
  32126. const inputNode = inputs[ i ];
  32127. const node = parameters[ i ];
  32128. params.push( node.build( builder, inputNode.type ) );
  32129. }
  32130. } else {
  32131. for ( const inputNode of inputs ) {
  32132. const node = parameters[ inputNode.name ];
  32133. if ( node !== undefined ) {
  32134. params.push( node.build( builder, inputNode.type ) );
  32135. } else {
  32136. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  32137. }
  32138. }
  32139. }
  32140. const functionName = functionNode.build( builder, 'property' );
  32141. return `${functionName}( ${params.join( ', ' )} )`;
  32142. }
  32143. }
  32144. const call = ( func, ...params ) => {
  32145. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  32146. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  32147. };
  32148. addNodeElement( 'call', call );
  32149. addNodeClass( 'FunctionCallNode', FunctionCallNode );
  32150. class ScriptableValueNode extends Node {
  32151. constructor( value = null ) {
  32152. super();
  32153. this._value = value;
  32154. this._cache = null;
  32155. this.inputType = null;
  32156. this.outpuType = null;
  32157. this.events = new EventDispatcher();
  32158. this.isScriptableValueNode = true;
  32159. }
  32160. get isScriptableOutputNode() {
  32161. return this.outputType !== null;
  32162. }
  32163. set value( val ) {
  32164. if ( this._value === val ) return;
  32165. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32166. URL.revokeObjectURL( this._cache );
  32167. this._cache = null;
  32168. }
  32169. this._value = val;
  32170. this.events.dispatchEvent( { type: 'change' } );
  32171. this.refresh();
  32172. }
  32173. get value() {
  32174. return this._value;
  32175. }
  32176. refresh() {
  32177. this.events.dispatchEvent( { type: 'refresh' } );
  32178. }
  32179. getValue() {
  32180. const value = this.value;
  32181. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32182. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32183. } else if ( value && value.value !== null && value.value !== undefined && (
  32184. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32185. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32186. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32187. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32188. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32189. ( this.inputType === 'Color' && value.value.isColor ) ||
  32190. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32191. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32192. ) ) {
  32193. return value.value;
  32194. }
  32195. return this._cache || value;
  32196. }
  32197. getNodeType( builder ) {
  32198. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32199. }
  32200. setup() {
  32201. return this.value && this.value.isNode ? this.value : float();
  32202. }
  32203. serialize( data ) {
  32204. super.serialize( data );
  32205. if ( this.value !== null ) {
  32206. if ( this.inputType === 'ArrayBuffer' ) {
  32207. data.value = arrayBufferToBase64( this.value );
  32208. } else {
  32209. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32210. }
  32211. } else {
  32212. data.value = null;
  32213. }
  32214. data.inputType = this.inputType;
  32215. data.outputType = this.outputType;
  32216. }
  32217. deserialize( data ) {
  32218. super.deserialize( data );
  32219. let value = null;
  32220. if ( data.value !== null ) {
  32221. if ( data.inputType === 'ArrayBuffer' ) {
  32222. value = base64ToArrayBuffer( data.value );
  32223. } else if ( data.inputType === 'Texture' ) {
  32224. value = data.meta.textures[ data.value ];
  32225. } else {
  32226. value = data.meta.nodes[ data.value ] || null;
  32227. }
  32228. }
  32229. this.value = value;
  32230. this.inputType = data.inputType;
  32231. this.outputType = data.outputType;
  32232. }
  32233. }
  32234. const scriptableValue = nodeProxy( ScriptableValueNode );
  32235. addNodeElement( 'scriptableValue', scriptableValue );
  32236. addNodeClass( 'ScriptableValueNode', ScriptableValueNode );
  32237. class Resources extends Map {
  32238. get( key, callback = null, ...params ) {
  32239. if ( this.has( key ) ) return super.get( key );
  32240. if ( callback !== null ) {
  32241. const value = callback( ...params );
  32242. this.set( key, value );
  32243. return value;
  32244. }
  32245. }
  32246. }
  32247. class Parameters {
  32248. constructor( scriptableNode ) {
  32249. this.scriptableNode = scriptableNode;
  32250. }
  32251. get parameters() {
  32252. return this.scriptableNode.parameters;
  32253. }
  32254. get layout() {
  32255. return this.scriptableNode.getLayout();
  32256. }
  32257. getInputLayout( id ) {
  32258. return this.scriptableNode.getInputLayout( id );
  32259. }
  32260. get( name ) {
  32261. const param = this.parameters[ name ];
  32262. const value = param ? param.getValue() : null;
  32263. return value;
  32264. }
  32265. }
  32266. const global = new Resources();
  32267. class ScriptableNode extends Node {
  32268. constructor( codeNode = null, parameters = {} ) {
  32269. super();
  32270. this.codeNode = codeNode;
  32271. this.parameters = parameters;
  32272. this._local = new Resources();
  32273. this._output = scriptableValue();
  32274. this._outputs = {};
  32275. this._source = this.source;
  32276. this._method = null;
  32277. this._object = null;
  32278. this._value = null;
  32279. this._needsOutputUpdate = true;
  32280. this.onRefresh = this.onRefresh.bind( this );
  32281. this.isScriptableNode = true;
  32282. }
  32283. get source() {
  32284. return this.codeNode ? this.codeNode.code : '';
  32285. }
  32286. setLocal( name, value ) {
  32287. return this._local.set( name, value );
  32288. }
  32289. getLocal( name ) {
  32290. return this._local.get( name );
  32291. }
  32292. onRefresh() {
  32293. this._refresh();
  32294. }
  32295. getInputLayout( id ) {
  32296. for ( const element of this.getLayout() ) {
  32297. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32298. return element;
  32299. }
  32300. }
  32301. }
  32302. getOutputLayout( id ) {
  32303. for ( const element of this.getLayout() ) {
  32304. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32305. return element;
  32306. }
  32307. }
  32308. }
  32309. setOutput( name, value ) {
  32310. const outputs = this._outputs;
  32311. if ( outputs[ name ] === undefined ) {
  32312. outputs[ name ] = scriptableValue( value );
  32313. } else {
  32314. outputs[ name ].value = value;
  32315. }
  32316. return this;
  32317. }
  32318. getOutput( name ) {
  32319. return this._outputs[ name ];
  32320. }
  32321. getParameter( name ) {
  32322. return this.parameters[ name ];
  32323. }
  32324. setParameter( name, value ) {
  32325. const parameters = this.parameters;
  32326. if ( value && value.isScriptableNode ) {
  32327. this.deleteParameter( name );
  32328. parameters[ name ] = value;
  32329. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32330. } else if ( value && value.isScriptableValueNode ) {
  32331. this.deleteParameter( name );
  32332. parameters[ name ] = value;
  32333. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32334. } else if ( parameters[ name ] === undefined ) {
  32335. parameters[ name ] = scriptableValue( value );
  32336. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32337. } else {
  32338. parameters[ name ].value = value;
  32339. }
  32340. return this;
  32341. }
  32342. getValue() {
  32343. return this.getDefaultOutput().getValue();
  32344. }
  32345. deleteParameter( name ) {
  32346. let valueNode = this.parameters[ name ];
  32347. if ( valueNode ) {
  32348. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32349. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32350. }
  32351. return this;
  32352. }
  32353. clearParameters() {
  32354. for ( const name of Object.keys( this.parameters ) ) {
  32355. this.deleteParameter( name );
  32356. }
  32357. this.needsUpdate = true;
  32358. return this;
  32359. }
  32360. call( name, ...params ) {
  32361. const object = this.getObject();
  32362. const method = object[ name ];
  32363. if ( typeof method === 'function' ) {
  32364. return method( ...params );
  32365. }
  32366. }
  32367. async callAsync( name, ...params ) {
  32368. const object = this.getObject();
  32369. const method = object[ name ];
  32370. if ( typeof method === 'function' ) {
  32371. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32372. }
  32373. }
  32374. getNodeType( builder ) {
  32375. return this.getDefaultOutputNode().getNodeType( builder );
  32376. }
  32377. refresh( output = null ) {
  32378. if ( output !== null ) {
  32379. this.getOutput( output ).refresh();
  32380. } else {
  32381. this._refresh();
  32382. }
  32383. }
  32384. getObject() {
  32385. if ( this.needsUpdate ) this.dispose();
  32386. if ( this._object !== null ) return this._object;
  32387. //
  32388. const refresh = () => this.refresh();
  32389. const setOutput = ( id, value ) => this.setOutput( id, value );
  32390. const parameters = new Parameters( this );
  32391. const THREE = global.get( 'THREE' );
  32392. const TSL = global.get( 'TSL' );
  32393. const method = this.getMethod( this.codeNode );
  32394. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  32395. this._object = method( ...params );
  32396. const layout = this._object.layout;
  32397. if ( layout ) {
  32398. if ( layout.cache === false ) {
  32399. this._local.clear();
  32400. }
  32401. // default output
  32402. this._output.outputType = layout.outputType || null;
  32403. if ( Array.isArray( layout.elements ) ) {
  32404. for ( const element of layout.elements ) {
  32405. const id = element.id || element.name;
  32406. if ( element.inputType ) {
  32407. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32408. this.getParameter( id ).inputType = element.inputType;
  32409. }
  32410. if ( element.outputType ) {
  32411. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32412. this.getOutput( id ).outputType = element.outputType;
  32413. }
  32414. }
  32415. }
  32416. }
  32417. return this._object;
  32418. }
  32419. deserialize( data ) {
  32420. super.deserialize( data );
  32421. for ( const name in this.parameters ) {
  32422. let valueNode = this.parameters[ name ];
  32423. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32424. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32425. }
  32426. }
  32427. getLayout() {
  32428. return this.getObject().layout;
  32429. }
  32430. getDefaultOutputNode() {
  32431. const output = this.getDefaultOutput().value;
  32432. if ( output && output.isNode ) {
  32433. return output;
  32434. }
  32435. return float();
  32436. }
  32437. getDefaultOutput() {
  32438. return this._exec()._output;
  32439. }
  32440. getMethod() {
  32441. if ( this.needsUpdate ) this.dispose();
  32442. if ( this._method !== null ) return this._method;
  32443. //
  32444. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  32445. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  32446. const properties = interfaceProps.join( ', ' );
  32447. const declarations = 'var ' + properties + '; var output = {};\n';
  32448. const returns = '\nreturn { ...output, ' + properties + ' };';
  32449. const code = declarations + this.codeNode.code + returns;
  32450. //
  32451. this._method = new Function( ...parametersProps, code );
  32452. return this._method;
  32453. }
  32454. dispose() {
  32455. if ( this._method === null ) return;
  32456. if ( this._object && typeof this._object.dispose === 'function' ) {
  32457. this._object.dispose();
  32458. }
  32459. this._method = null;
  32460. this._object = null;
  32461. this._source = null;
  32462. this._value = null;
  32463. this._needsOutputUpdate = true;
  32464. this._output.value = null;
  32465. this._outputs = {};
  32466. }
  32467. setup() {
  32468. return this.getDefaultOutputNode();
  32469. }
  32470. getCacheKey( force ) {
  32471. const cacheKey = [ this.source, this.getDefaultOutputNode().getCacheKey( force ) ];
  32472. for ( const param in this.parameters ) {
  32473. cacheKey.push( this.parameters[ param ].getCacheKey( force ) );
  32474. }
  32475. return cacheKey.join( ',' );
  32476. }
  32477. set needsUpdate( value ) {
  32478. if ( value === true ) this.dispose();
  32479. }
  32480. get needsUpdate() {
  32481. return this.source !== this._source;
  32482. }
  32483. _exec() {
  32484. if ( this.codeNode === null ) return this;
  32485. if ( this._needsOutputUpdate === true ) {
  32486. this._value = this.call( 'main' );
  32487. this._needsOutputUpdate = false;
  32488. }
  32489. this._output.value = this._value;
  32490. return this;
  32491. }
  32492. _refresh() {
  32493. this.needsUpdate = true;
  32494. this._exec();
  32495. this._output.refresh();
  32496. }
  32497. }
  32498. const scriptable = nodeProxy( ScriptableNode );
  32499. addNodeElement( 'scriptable', scriptable );
  32500. addNodeClass( 'ScriptableNode', ScriptableNode );
  32501. class FogNode extends Node {
  32502. constructor( colorNode, factorNode ) {
  32503. super( 'float' );
  32504. this.isFogNode = true;
  32505. this.colorNode = colorNode;
  32506. this.factorNode = factorNode;
  32507. }
  32508. getViewZNode( builder ) {
  32509. let viewZ;
  32510. const getViewZ = builder.context.getViewZ;
  32511. if ( getViewZ !== undefined ) {
  32512. viewZ = getViewZ( this );
  32513. }
  32514. return ( viewZ || positionView.z ).negate();
  32515. }
  32516. setup() {
  32517. return this.factorNode;
  32518. }
  32519. }
  32520. const fog = nodeProxy( FogNode );
  32521. addNodeElement( 'fog', fog );
  32522. addNodeClass( 'FogNode', FogNode );
  32523. class FogRangeNode extends FogNode {
  32524. constructor( colorNode, nearNode, farNode ) {
  32525. super( colorNode );
  32526. this.isFogRangeNode = true;
  32527. this.nearNode = nearNode;
  32528. this.farNode = farNode;
  32529. }
  32530. setup( builder ) {
  32531. const viewZ = this.getViewZNode( builder );
  32532. return smoothstep( this.nearNode, this.farNode, viewZ );
  32533. }
  32534. }
  32535. const rangeFog = nodeProxy( FogRangeNode );
  32536. addNodeElement( 'rangeFog', rangeFog );
  32537. addNodeClass( 'FogRangeNode', FogRangeNode );
  32538. class FogExp2Node extends FogNode {
  32539. constructor( colorNode, densityNode ) {
  32540. super( colorNode );
  32541. this.isFogExp2Node = true;
  32542. this.densityNode = densityNode;
  32543. }
  32544. setup( builder ) {
  32545. const viewZ = this.getViewZNode( builder );
  32546. const density = this.densityNode;
  32547. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  32548. }
  32549. }
  32550. const densityFog = nodeProxy( FogExp2Node );
  32551. addNodeElement( 'densityFog', densityFog );
  32552. addNodeClass( 'FogExp2Node', FogExp2Node );
  32553. let min = null;
  32554. let max = null;
  32555. class RangeNode extends Node {
  32556. constructor( minNode = float(), maxNode = float() ) {
  32557. super();
  32558. this.minNode = minNode;
  32559. this.maxNode = maxNode;
  32560. }
  32561. getVectorLength( builder ) {
  32562. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  32563. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  32564. return minLength > maxLength ? minLength : maxLength;
  32565. }
  32566. getNodeType( builder ) {
  32567. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  32568. }
  32569. setup( builder ) {
  32570. const object = builder.object;
  32571. let output = null;
  32572. if ( object.count > 1 ) {
  32573. const minValue = this.minNode.value;
  32574. const maxValue = this.maxNode.value;
  32575. const minLength = builder.getTypeLength( getValueType( minValue ) );
  32576. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  32577. min = min || new Vector4();
  32578. max = max || new Vector4();
  32579. min.setScalar( 0 );
  32580. max.setScalar( 0 );
  32581. if ( minLength === 1 ) min.setScalar( minValue );
  32582. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  32583. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  32584. if ( maxLength === 1 ) max.setScalar( maxValue );
  32585. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  32586. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  32587. const stride = 4;
  32588. const length = stride * object.count;
  32589. const array = new Float32Array( length );
  32590. for ( let i = 0; i < length; i ++ ) {
  32591. const index = i % stride;
  32592. const minElementValue = min.getComponent( index );
  32593. const maxElementValue = max.getComponent( index );
  32594. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  32595. }
  32596. const nodeType = this.getNodeType( builder );
  32597. if ( object.count <= 4096 ) {
  32598. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  32599. } else {
  32600. // TODO: Improve anonymous buffer attribute creation removing this part
  32601. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  32602. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  32603. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  32604. }
  32605. } else {
  32606. output = float( 0 );
  32607. }
  32608. return output;
  32609. }
  32610. }
  32611. const range = nodeProxy( RangeNode );
  32612. addNodeClass( 'RangeNode', RangeNode );
  32613. class ComputeNode extends Node {
  32614. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  32615. super( 'void' );
  32616. this.isComputeNode = true;
  32617. this.computeNode = computeNode;
  32618. this.count = count;
  32619. this.workgroupSize = workgroupSize;
  32620. this.dispatchCount = 0;
  32621. this.version = 1;
  32622. this.updateBeforeType = NodeUpdateType.OBJECT;
  32623. this.updateDispatchCount();
  32624. }
  32625. dispose() {
  32626. this.dispatchEvent( { type: 'dispose' } );
  32627. }
  32628. set needsUpdate( value ) {
  32629. if ( value === true ) this.version ++;
  32630. }
  32631. updateDispatchCount() {
  32632. const { count, workgroupSize } = this;
  32633. let size = workgroupSize[ 0 ];
  32634. for ( let i = 1; i < workgroupSize.length; i ++ )
  32635. size *= workgroupSize[ i ];
  32636. this.dispatchCount = Math.ceil( count / size );
  32637. }
  32638. onInit() { }
  32639. updateBefore( { renderer } ) {
  32640. renderer.compute( this );
  32641. }
  32642. generate( builder ) {
  32643. const { shaderStage } = builder;
  32644. if ( shaderStage === 'compute' ) {
  32645. const snippet = this.computeNode.build( builder, 'void' );
  32646. if ( snippet !== '' ) {
  32647. builder.addLineFlowCode( snippet );
  32648. }
  32649. }
  32650. }
  32651. }
  32652. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  32653. addNodeElement( 'compute', compute );
  32654. addNodeClass( 'ComputeNode', ComputeNode );
  32655. class LightNode extends Node {
  32656. constructor( scope = LightNode.TARGET_DIRECTION, light = null ) {
  32657. super();
  32658. this.scope = scope;
  32659. this.light = light;
  32660. }
  32661. setup() {
  32662. const { scope, light } = this;
  32663. let output = null;
  32664. if ( scope === LightNode.TARGET_DIRECTION ) {
  32665. output = cameraViewMatrix.transformDirection( objectPosition( light ).sub( objectPosition( light.target ) ) );
  32666. }
  32667. return output;
  32668. }
  32669. serialize( data ) {
  32670. super.serialize( data );
  32671. data.scope = this.scope;
  32672. }
  32673. deserialize( data ) {
  32674. super.deserialize( data );
  32675. this.scope = data.scope;
  32676. }
  32677. }
  32678. LightNode.TARGET_DIRECTION = 'targetDirection';
  32679. const lightTargetDirection = nodeProxy( LightNode, LightNode.TARGET_DIRECTION );
  32680. addNodeClass( 'LightNode', LightNode );
  32681. const getDistanceAttenuation = tslFn( ( inputs ) => {
  32682. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  32683. // based upon Frostbite 3 Moving to Physically-based Rendering
  32684. // page 32, equation 26: E[window1]
  32685. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  32686. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  32687. return cutoffDistance.greaterThan( 0 ).cond(
  32688. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  32689. distanceFalloff
  32690. );
  32691. } ); // validated
  32692. class PointLightNode extends AnalyticLightNode {
  32693. constructor( light = null ) {
  32694. super( light );
  32695. this.cutoffDistanceNode = uniform( 0 );
  32696. this.decayExponentNode = uniform( 0 );
  32697. }
  32698. update( frame ) {
  32699. const { light } = this;
  32700. super.update( frame );
  32701. this.cutoffDistanceNode.value = light.distance;
  32702. this.decayExponentNode.value = light.decay;
  32703. }
  32704. setup( builder ) {
  32705. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32706. const lightingModel = builder.context.lightingModel;
  32707. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32708. const lightDirection = lVector.normalize();
  32709. const lightDistance = lVector.length();
  32710. const lightAttenuation = getDistanceAttenuation( {
  32711. lightDistance,
  32712. cutoffDistance: cutoffDistanceNode,
  32713. decayExponent: decayExponentNode
  32714. } );
  32715. const lightColor = colorNode.mul( lightAttenuation );
  32716. const reflectedLight = builder.context.reflectedLight;
  32717. lightingModel.direct( {
  32718. lightDirection,
  32719. lightColor,
  32720. reflectedLight
  32721. }, builder.stack, builder );
  32722. }
  32723. }
  32724. addNodeClass( 'PointLightNode', PointLightNode );
  32725. addLightNode( PointLight, PointLightNode );
  32726. class DirectionalLightNode extends AnalyticLightNode {
  32727. constructor( light = null ) {
  32728. super( light );
  32729. }
  32730. setup( builder ) {
  32731. super.setup( builder );
  32732. const lightingModel = builder.context.lightingModel;
  32733. const lightColor = this.colorNode;
  32734. const lightDirection = lightTargetDirection( this.light );
  32735. const reflectedLight = builder.context.reflectedLight;
  32736. lightingModel.direct( {
  32737. lightDirection,
  32738. lightColor,
  32739. reflectedLight
  32740. }, builder.stack, builder );
  32741. }
  32742. }
  32743. addNodeClass( 'DirectionalLightNode', DirectionalLightNode );
  32744. addLightNode( DirectionalLight, DirectionalLightNode );
  32745. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32746. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32747. let ltcLib = null;
  32748. class RectAreaLightNode extends AnalyticLightNode {
  32749. constructor( light = null ) {
  32750. super( light );
  32751. this.halfHeight = uniform( new Vector3() );
  32752. this.halfWidth = uniform( new Vector3() );
  32753. }
  32754. update( frame ) {
  32755. super.update( frame );
  32756. const { light } = this;
  32757. const viewMatrix = frame.camera.matrixWorldInverse;
  32758. _matrix42.identity();
  32759. _matrix41.copy( light.matrixWorld );
  32760. _matrix41.premultiply( viewMatrix );
  32761. _matrix42.extractRotation( _matrix41 );
  32762. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32763. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32764. this.halfWidth.value.applyMatrix4( _matrix42 );
  32765. this.halfHeight.value.applyMatrix4( _matrix42 );
  32766. }
  32767. setup( builder ) {
  32768. super.setup( builder );
  32769. let ltc_1, ltc_2;
  32770. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32771. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  32772. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  32773. } else {
  32774. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  32775. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  32776. }
  32777. const { colorNode, light } = this;
  32778. const lightingModel = builder.context.lightingModel;
  32779. const lightPosition = objectViewPosition( light );
  32780. const reflectedLight = builder.context.reflectedLight;
  32781. lightingModel.directRectArea( {
  32782. lightColor: colorNode,
  32783. lightPosition,
  32784. halfWidth: this.halfWidth,
  32785. halfHeight: this.halfHeight,
  32786. reflectedLight,
  32787. ltc_1,
  32788. ltc_2
  32789. }, builder.stack, builder );
  32790. }
  32791. static setLTC( ltc ) {
  32792. ltcLib = ltc;
  32793. }
  32794. }
  32795. addNodeClass( 'RectAreaLightNode', RectAreaLightNode );
  32796. addLightNode( RectAreaLight, RectAreaLightNode );
  32797. class SpotLightNode extends AnalyticLightNode {
  32798. constructor( light = null ) {
  32799. super( light );
  32800. this.coneCosNode = uniform( 0 );
  32801. this.penumbraCosNode = uniform( 0 );
  32802. this.cutoffDistanceNode = uniform( 0 );
  32803. this.decayExponentNode = uniform( 0 );
  32804. }
  32805. update( frame ) {
  32806. super.update( frame );
  32807. const { light } = this;
  32808. this.coneCosNode.value = Math.cos( light.angle );
  32809. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32810. this.cutoffDistanceNode.value = light.distance;
  32811. this.decayExponentNode.value = light.decay;
  32812. }
  32813. getSpotAttenuation( angleCosine ) {
  32814. const { coneCosNode, penumbraCosNode } = this;
  32815. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32816. }
  32817. setup( builder ) {
  32818. super.setup( builder );
  32819. const lightingModel = builder.context.lightingModel;
  32820. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32821. const lVector = objectViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32822. const lightDirection = lVector.normalize();
  32823. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32824. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32825. const lightDistance = lVector.length();
  32826. const lightAttenuation = getDistanceAttenuation( {
  32827. lightDistance,
  32828. cutoffDistance: cutoffDistanceNode,
  32829. decayExponent: decayExponentNode
  32830. } );
  32831. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32832. const reflectedLight = builder.context.reflectedLight;
  32833. lightingModel.direct( {
  32834. lightDirection,
  32835. lightColor,
  32836. reflectedLight
  32837. }, builder.stack, builder );
  32838. }
  32839. }
  32840. addNodeClass( 'SpotLightNode', SpotLightNode );
  32841. addLightNode( SpotLight, SpotLightNode );
  32842. class IESSpotLight extends SpotLight {
  32843. constructor( color, intensity, distance, angle, penumbra, decay ) {
  32844. super( color, intensity, distance, angle, penumbra, decay );
  32845. this.iesMap = null;
  32846. }
  32847. copy( source, recursive ) {
  32848. super.copy( source, recursive );
  32849. this.iesMap = source.iesMap;
  32850. return this;
  32851. }
  32852. }
  32853. class IESSpotLightNode extends SpotLightNode {
  32854. getSpotAttenuation( angleCosine ) {
  32855. const iesMap = this.light.iesMap;
  32856. let spotAttenuation = null;
  32857. if ( iesMap && iesMap.isTexture === true ) {
  32858. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32859. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32860. } else {
  32861. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32862. }
  32863. return spotAttenuation;
  32864. }
  32865. }
  32866. addNodeClass( 'IESSpotLightNode', IESSpotLightNode );
  32867. addLightNode( IESSpotLight, IESSpotLightNode );
  32868. class AmbientLightNode extends AnalyticLightNode {
  32869. constructor( light = null ) {
  32870. super( light );
  32871. }
  32872. setup( { context } ) {
  32873. context.irradiance.addAssign( this.colorNode );
  32874. }
  32875. }
  32876. addNodeClass( 'AmbientLightNode', AmbientLightNode );
  32877. addLightNode( AmbientLight, AmbientLightNode );
  32878. class HemisphereLightNode extends AnalyticLightNode {
  32879. constructor( light = null ) {
  32880. super( light );
  32881. this.lightPositionNode = objectPosition( light );
  32882. this.lightDirectionNode = this.lightPositionNode.normalize();
  32883. this.groundColorNode = uniform( new Color() );
  32884. }
  32885. update( frame ) {
  32886. const { light } = this;
  32887. super.update( frame );
  32888. this.lightPositionNode.object3d = light;
  32889. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32890. }
  32891. setup( builder ) {
  32892. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32893. const dotNL = normalView.dot( lightDirectionNode );
  32894. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32895. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32896. builder.context.irradiance.addAssign( irradiance );
  32897. }
  32898. }
  32899. addNodeClass( 'HemisphereLightNode', HemisphereLightNode );
  32900. addLightNode( HemisphereLight, HemisphereLightNode );
  32901. let _generator = null;
  32902. const _cache = new WeakMap();
  32903. function _generateCubeUVSize( imageHeight ) {
  32904. const maxMip = Math.log2( imageHeight ) - 2;
  32905. const texelHeight = 1.0 / imageHeight;
  32906. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  32907. return { texelWidth, texelHeight, maxMip };
  32908. }
  32909. function _getPMREMFromTexture( texture ) {
  32910. let cacheTexture = _cache.get( texture );
  32911. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  32912. if ( pmremVersion !== texture.pmremVersion ) {
  32913. const image = texture.image;
  32914. if ( texture.isCubeTexture ) {
  32915. if ( isCubeMapReady( image ) ) {
  32916. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  32917. } else {
  32918. return null;
  32919. }
  32920. } else {
  32921. if ( isEquirectangularMapReady( image ) ) {
  32922. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  32923. } else {
  32924. return null;
  32925. }
  32926. }
  32927. cacheTexture.pmremVersion = texture.pmremVersion;
  32928. _cache.set( texture, cacheTexture );
  32929. }
  32930. return cacheTexture.texture;
  32931. }
  32932. class PMREMNode extends TempNode {
  32933. constructor( value, uvNode = null, levelNode = null ) {
  32934. super( 'vec3' );
  32935. this._value = value;
  32936. this._pmrem = null;
  32937. this.uvNode = uvNode;
  32938. this.levelNode = levelNode;
  32939. this._generator = null;
  32940. this._texture = texture( new Texture() );
  32941. this._width = uniform( 0 );
  32942. this._height = uniform( 0 );
  32943. this._maxMip = uniform( 0 );
  32944. this.updateBeforeType = NodeUpdateType.RENDER;
  32945. }
  32946. set value( value ) {
  32947. this._value = value;
  32948. this._pmrem = null;
  32949. }
  32950. get value() {
  32951. return this._value;
  32952. }
  32953. updateFromTexture( texture ) {
  32954. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  32955. this._texture.value = texture;
  32956. this._width.value = cubeUVSize.texelWidth;
  32957. this._height.value = cubeUVSize.texelHeight;
  32958. this._maxMip.value = cubeUVSize.maxMip;
  32959. }
  32960. updateBefore() {
  32961. let pmrem = this._pmrem;
  32962. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  32963. const texture = this._value;
  32964. if ( pmremVersion !== texture.pmremVersion ) {
  32965. if ( texture.isPMREMTexture === true ) {
  32966. pmrem = texture;
  32967. } else {
  32968. pmrem = _getPMREMFromTexture( texture );
  32969. }
  32970. if ( pmrem !== null ) {
  32971. this._pmrem = pmrem;
  32972. this.updateFromTexture( pmrem );
  32973. }
  32974. }
  32975. }
  32976. setup( builder ) {
  32977. if ( _generator === null ) {
  32978. _generator = builder.createPMREMGenerator();
  32979. }
  32980. //
  32981. this.updateBefore( builder );
  32982. //
  32983. let uvNode = this.uvNode;
  32984. if ( uvNode === null && builder.context.getUV ) {
  32985. uvNode = builder.context.getUV( this );
  32986. }
  32987. //
  32988. const texture = this.value;
  32989. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  32990. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  32991. }
  32992. //
  32993. let levelNode = this.levelNode;
  32994. if ( levelNode === null && builder.context.getTextureLevel ) {
  32995. levelNode = builder.context.getTextureLevel( this );
  32996. }
  32997. //
  32998. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  32999. }
  33000. }
  33001. function isCubeMapReady( image ) {
  33002. if ( image === null || image === undefined ) return false;
  33003. let count = 0;
  33004. const length = 6;
  33005. for ( let i = 0; i < length; i ++ ) {
  33006. if ( image[ i ] !== undefined ) count ++;
  33007. }
  33008. return count === length;
  33009. }
  33010. function isEquirectangularMapReady( image ) {
  33011. if ( image === null || image === undefined ) return false;
  33012. return image.height > 0;
  33013. }
  33014. const pmremTexture = nodeProxy( PMREMNode );
  33015. addNodeClass( 'PMREMNode', PMREMNode );
  33016. const _envNodeCache = new WeakMap();
  33017. class EnvironmentNode extends LightingNode {
  33018. constructor( envNode = null ) {
  33019. super();
  33020. this.envNode = envNode;
  33021. }
  33022. setup( builder ) {
  33023. let envNode = this.envNode;
  33024. if ( envNode.isTextureNode ) {
  33025. let cacheEnvNode = _envNodeCache.get( envNode.value );
  33026. if ( cacheEnvNode === undefined ) {
  33027. cacheEnvNode = pmremTexture( envNode.value );
  33028. _envNodeCache.set( envNode.value, cacheEnvNode );
  33029. }
  33030. envNode = cacheEnvNode;
  33031. }
  33032. //
  33033. const { material } = builder;
  33034. const envMap = material.envMap;
  33035. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  33036. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  33037. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  33038. const radiance = context( envNode, createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  33039. const irradiance = context( envNode, createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  33040. const isolateRadiance = cache( radiance );
  33041. const isolateIrradiance = cache( irradiance );
  33042. //
  33043. builder.context.radiance.addAssign( isolateRadiance );
  33044. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  33045. //
  33046. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  33047. if ( clearcoatRadiance ) {
  33048. const clearcoatRadianceContext = context( envNode, createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  33049. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  33050. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  33051. }
  33052. }
  33053. }
  33054. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  33055. let reflectVec = null;
  33056. return {
  33057. getUV: () => {
  33058. if ( reflectVec === null ) {
  33059. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  33060. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  33061. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  33062. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  33063. }
  33064. return reflectVec;
  33065. },
  33066. getTextureLevel: () => {
  33067. return roughnessNode;
  33068. }
  33069. };
  33070. };
  33071. const createIrradianceContext = ( normalWorldNode ) => {
  33072. return {
  33073. getUV: () => {
  33074. return normalWorldNode;
  33075. },
  33076. getTextureLevel: () => {
  33077. return float( 1.0 );
  33078. }
  33079. };
  33080. };
  33081. addNodeClass( 'EnvironmentNode', EnvironmentNode );
  33082. class BasicEnvironmentNode extends LightingNode {
  33083. constructor( envNode = null ) {
  33084. super();
  33085. this.envNode = envNode;
  33086. }
  33087. setup( builder ) {
  33088. // environment property is used in the finish() method of BasicLightingModel
  33089. builder.context.environment = this.envNode;
  33090. }
  33091. }
  33092. addNodeClass( 'BasicEnvironmentNode', BasicEnvironmentNode );
  33093. const checkerShaderNode = tslFn( ( inputs ) => {
  33094. const uv = inputs.uv.mul( 2.0 );
  33095. const cx = uv.x.floor();
  33096. const cy = uv.y.floor();
  33097. const result = cx.add( cy ).mod( 2.0 );
  33098. return result.sign();
  33099. } );
  33100. class CheckerNode extends TempNode {
  33101. constructor( uvNode = uv() ) {
  33102. super( 'float' );
  33103. this.uvNode = uvNode;
  33104. }
  33105. setup() {
  33106. return checkerShaderNode( { uv: this.uvNode } );
  33107. }
  33108. }
  33109. const checker = nodeProxy( CheckerNode );
  33110. addNodeElement( 'checker', checker );
  33111. addNodeClass( 'CheckerNode', CheckerNode );
  33112. class NodeLoader extends Loader {
  33113. constructor( manager ) {
  33114. super( manager );
  33115. this.textures = {};
  33116. }
  33117. load( url, onLoad, onProgress, onError ) {
  33118. const loader = new FileLoader( this.manager );
  33119. loader.setPath( this.path );
  33120. loader.setRequestHeader( this.requestHeader );
  33121. loader.setWithCredentials( this.withCredentials );
  33122. loader.load( url, ( text ) => {
  33123. try {
  33124. onLoad( this.parse( JSON.parse( text ) ) );
  33125. } catch ( e ) {
  33126. if ( onError ) {
  33127. onError( e );
  33128. } else {
  33129. console.error( e );
  33130. }
  33131. this.manager.itemError( url );
  33132. }
  33133. }, onProgress, onError );
  33134. }
  33135. parseNodes( json ) {
  33136. const nodes = {};
  33137. if ( json !== undefined ) {
  33138. for ( const nodeJSON of json ) {
  33139. const { uuid, type } = nodeJSON;
  33140. nodes[ uuid ] = nodeObject( createNodeFromType( type ) ); // @TODO: Maybe nodeObjectify the node in createNodeFromType?
  33141. nodes[ uuid ].uuid = uuid;
  33142. }
  33143. const meta = { nodes, textures: this.textures };
  33144. for ( const nodeJSON of json ) {
  33145. nodeJSON.meta = meta;
  33146. const node = nodes[ nodeJSON.uuid ];
  33147. node.deserialize( nodeJSON );
  33148. delete nodeJSON.meta;
  33149. }
  33150. }
  33151. return nodes;
  33152. }
  33153. parse( json ) {
  33154. const node = nodeObject( createNodeFromType( json.type ) );
  33155. node.uuid = json.uuid;
  33156. const nodes = this.parseNodes( json.nodes );
  33157. const meta = { nodes, textures: this.textures };
  33158. json.meta = meta;
  33159. node.deserialize( json );
  33160. delete json.meta;
  33161. return node;
  33162. }
  33163. setTextures( value ) {
  33164. this.textures = value;
  33165. return this;
  33166. }
  33167. }
  33168. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  33169. class InstancedPointsNodeMaterial extends NodeMaterial {
  33170. constructor( params = {} ) {
  33171. super();
  33172. this.normals = false;
  33173. this.lights = false;
  33174. this.useAlphaToCoverage = true;
  33175. this.useColor = params.vertexColors;
  33176. this.pointWidth = 1;
  33177. this.pointColorNode = null;
  33178. this.setDefaultValues( _defaultValues$e );
  33179. this.setupShaders();
  33180. this.setValues( params );
  33181. }
  33182. setupShaders() {
  33183. const useAlphaToCoverage = this.alphaToCoverage;
  33184. const useColor = this.useColor;
  33185. this.vertexNode = tslFn( () => {
  33186. //vUv = uv;
  33187. varying( vec2(), 'vUv' ).assign( uv() ); // @TODO: Analyze other way to do this
  33188. const instancePosition = attribute( 'instancePosition' );
  33189. // camera space
  33190. const mvPos = property( 'vec4', 'mvPos' );
  33191. mvPos.assign( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  33192. const aspect = viewport.z.div( viewport.w );
  33193. // clip space
  33194. const clipPos = cameraProjectionMatrix.mul( mvPos );
  33195. // offset in ndc space
  33196. const offset = property( 'vec2', 'offset' );
  33197. offset.assign( positionGeometry.xy );
  33198. offset.assign( offset.mul( materialPointWidth ) );
  33199. offset.assign( offset.div( viewport.z ) );
  33200. offset.y.assign( offset.y.mul( aspect ) );
  33201. // back to clip space
  33202. offset.assign( offset.mul( clipPos.w ) );
  33203. //clipPos.xy += offset;
  33204. clipPos.assign( clipPos.add( vec4( offset, 0, 0 ) ) );
  33205. return clipPos;
  33206. //vec4 mvPosition = mvPos; // this was used for somethihng...
  33207. } )();
  33208. this.fragmentNode = tslFn( () => {
  33209. const vUv = varying( vec2(), 'vUv' );
  33210. // force assignment into correct place in flow
  33211. const alpha = property( 'float', 'alpha' );
  33212. alpha.assign( 1 );
  33213. const a = vUv.x;
  33214. const b = vUv.y;
  33215. const len2 = a.mul( a ).add( b.mul( b ) );
  33216. if ( useAlphaToCoverage ) {
  33217. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33218. const dlen = property( 'float', 'dlen' );
  33219. dlen.assign( len2.fwidth() );
  33220. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33221. } else {
  33222. len2.greaterThan( 1.0 ).discard();
  33223. }
  33224. let pointColorNode;
  33225. if ( this.pointColorNode ) {
  33226. pointColorNode = this.pointColorNode;
  33227. } else {
  33228. if ( useColor ) {
  33229. const instanceColor = attribute( 'instanceColor' );
  33230. pointColorNode = instanceColor.mul( materialColor );
  33231. } else {
  33232. pointColorNode = materialColor;
  33233. }
  33234. }
  33235. return vec4( pointColorNode, alpha );
  33236. } )();
  33237. this.needsUpdate = true;
  33238. }
  33239. get alphaToCoverage() {
  33240. return this.useAlphaToCoverage;
  33241. }
  33242. set alphaToCoverage( value ) {
  33243. if ( this.useAlphaToCoverage !== value ) {
  33244. this.useAlphaToCoverage = value;
  33245. this.setupShaders();
  33246. }
  33247. }
  33248. }
  33249. addNodeMaterial( 'InstancedPointsNodeMaterial', InstancedPointsNodeMaterial );
  33250. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  33251. class LineBasicNodeMaterial extends NodeMaterial {
  33252. constructor( parameters ) {
  33253. super();
  33254. this.isLineBasicNodeMaterial = true;
  33255. this.lights = false;
  33256. this.normals = false;
  33257. this.setDefaultValues( _defaultValues$d );
  33258. this.setValues( parameters );
  33259. }
  33260. }
  33261. addNodeMaterial( 'LineBasicNodeMaterial', LineBasicNodeMaterial );
  33262. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  33263. class LineDashedNodeMaterial extends NodeMaterial {
  33264. constructor( parameters ) {
  33265. super();
  33266. this.isLineDashedNodeMaterial = true;
  33267. this.lights = false;
  33268. this.normals = false;
  33269. this.setDefaultValues( _defaultValues$c );
  33270. this.offsetNode = null;
  33271. this.dashScaleNode = null;
  33272. this.dashSizeNode = null;
  33273. this.gapSizeNode = null;
  33274. this.setValues( parameters );
  33275. }
  33276. setupVariants() {
  33277. const offsetNode = this.offsetNode;
  33278. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33279. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33280. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33281. dashSize.assign( dashSizeNode );
  33282. gapSize.assign( gapSizeNode );
  33283. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  33284. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33285. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  33286. }
  33287. }
  33288. addNodeMaterial( 'LineDashedNodeMaterial', LineDashedNodeMaterial );
  33289. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  33290. class Line2NodeMaterial extends NodeMaterial {
  33291. constructor( params = {} ) {
  33292. super();
  33293. this.normals = false;
  33294. this.lights = false;
  33295. this.setDefaultValues( _defaultValues$b );
  33296. this.useAlphaToCoverage = true;
  33297. this.useColor = params.vertexColors;
  33298. this.useDash = params.dashed;
  33299. this.useWorldUnits = false;
  33300. this.dashOffset = 0;
  33301. this.lineWidth = 1;
  33302. this.lineColorNode = null;
  33303. this.offsetNode = null;
  33304. this.dashScaleNode = null;
  33305. this.dashSizeNode = null;
  33306. this.gapSizeNode = null;
  33307. this.setValues( params );
  33308. }
  33309. setup( builder ) {
  33310. this.setupShaders();
  33311. super.setup( builder );
  33312. }
  33313. setupShaders() {
  33314. const useAlphaToCoverage = this.alphaToCoverage;
  33315. const useColor = this.useColor;
  33316. const useDash = this.dashed;
  33317. const useWorldUnits = this.worldUnits;
  33318. const trimSegment = tslFn( ( { start, end } ) => {
  33319. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  33320. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  33321. const nearEstimate = b.mul( - 0.5 ).div( a );
  33322. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  33323. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  33324. } );
  33325. this.vertexNode = tslFn( () => {
  33326. varyingProperty( 'vec2', 'vUv' ).assign( uv() );
  33327. const instanceStart = attribute( 'instanceStart' );
  33328. const instanceEnd = attribute( 'instanceEnd' );
  33329. // camera space
  33330. const start = property( 'vec4', 'start' );
  33331. const end = property( 'vec4', 'end' );
  33332. start.assign( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ); // force assignment into correct place in flow
  33333. end.assign( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) );
  33334. if ( useWorldUnits ) {
  33335. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  33336. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  33337. }
  33338. const aspect = viewport.z.div( viewport.w );
  33339. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  33340. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  33341. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  33342. // perhaps there is a more elegant solution -- WestLangley
  33343. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  33344. If( perspective, () => {
  33345. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  33346. end.assign( trimSegment( { start: start, end: end } ) );
  33347. } ).elseif( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  33348. start.assign( trimSegment( { start: end, end: start } ) );
  33349. } );
  33350. } );
  33351. // clip space
  33352. const clipStart = cameraProjectionMatrix.mul( start );
  33353. const clipEnd = cameraProjectionMatrix.mul( end );
  33354. // ndc space
  33355. const ndcStart = clipStart.xyz.div( clipStart.w );
  33356. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  33357. // direction
  33358. const dir = ndcEnd.xy.sub( ndcStart.xy ).temp();
  33359. // account for clip-space aspect ratio
  33360. dir.x.assign( dir.x.mul( aspect ) );
  33361. dir.assign( dir.normalize() );
  33362. const clip = temp( vec4() );
  33363. if ( useWorldUnits ) {
  33364. // get the offset direction as perpendicular to the view vector
  33365. const worldDir = end.xyz.sub( start.xyz ).normalize();
  33366. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  33367. const worldUp = worldDir.cross( tmpFwd ).normalize();
  33368. const worldFwd = worldDir.cross( worldUp );
  33369. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  33370. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).cond( start, end ) );
  33371. // height offset
  33372. const hw = materialLineWidth.mul( 0.5 );
  33373. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).cond( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  33374. // don't extend the line if we're rendering dashes because we
  33375. // won't be rendering the endcaps
  33376. if ( ! useDash ) {
  33377. // cap extension
  33378. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).cond( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  33379. // add width to the box
  33380. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  33381. // endcaps
  33382. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  33383. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  33384. } );
  33385. }
  33386. // project the worldpos
  33387. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  33388. // shift the depth of the projected points so the line
  33389. // segments overlap neatly
  33390. const clipPose = temp( vec3() );
  33391. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).cond( ndcStart, ndcEnd ) );
  33392. clip.z.assign( clipPose.z.mul( clip.w ) );
  33393. } else {
  33394. const offset = property( 'vec2', 'offset' );
  33395. offset.assign( vec2( dir.y, dir.x.negate() ) );
  33396. // undo aspect ratio adjustment
  33397. dir.x.assign( dir.x.div( aspect ) );
  33398. offset.x.assign( offset.x.div( aspect ) );
  33399. // sign flip
  33400. offset.assign( positionGeometry.x.lessThan( 0.0 ).cond( offset.negate(), offset ) );
  33401. // endcaps
  33402. If( positionGeometry.y.lessThan( 0.0 ), () => {
  33403. offset.assign( offset.sub( dir ) );
  33404. } ).elseif( positionGeometry.y.greaterThan( 1.0 ), () => {
  33405. offset.assign( offset.add( dir ) );
  33406. } );
  33407. // adjust for linewidth
  33408. offset.assign( offset.mul( materialLineWidth ) );
  33409. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  33410. offset.assign( offset.div( viewport.w ) );
  33411. // select end
  33412. clip.assign( positionGeometry.y.lessThan( 0.5 ).cond( clipStart, clipEnd ) );
  33413. // back to clip space
  33414. offset.assign( offset.mul( clip.w ) );
  33415. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  33416. }
  33417. return clip;
  33418. } )();
  33419. const closestLineToLine = tslFn( ( { p1, p2, p3, p4 } ) => {
  33420. const p13 = p1.sub( p3 );
  33421. const p43 = p4.sub( p3 );
  33422. const p21 = p2.sub( p1 );
  33423. const d1343 = p13.dot( p43 );
  33424. const d4321 = p43.dot( p21 );
  33425. const d1321 = p13.dot( p21 );
  33426. const d4343 = p43.dot( p43 );
  33427. const d2121 = p21.dot( p21 );
  33428. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  33429. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  33430. const mua = numer.div( denom ).clamp();
  33431. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  33432. return vec2( mua, mub );
  33433. } );
  33434. this.fragmentNode = tslFn( () => {
  33435. const vUv = varyingProperty( 'vec2', 'vUv' );
  33436. if ( useDash ) {
  33437. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  33438. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  33439. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  33440. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  33441. dashSize.assign( dashSizeNode );
  33442. gapSize.assign( gapSizeNode );
  33443. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  33444. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  33445. const lineDistance = positionGeometry.y.lessThan( 0.5 ).cond( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  33446. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  33447. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  33448. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  33449. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  33450. }
  33451. // force assignment into correct place in flow
  33452. const alpha = property( 'float', 'alpha' );
  33453. alpha.assign( 1 );
  33454. if ( useWorldUnits ) {
  33455. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  33456. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  33457. // Find the closest points on the view ray and the line segment
  33458. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  33459. const lineDir = worldEnd.sub( worldStart );
  33460. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  33461. const p1 = worldStart.add( lineDir.mul( params.x ) );
  33462. const p2 = rayEnd.mul( params.y );
  33463. const delta = p1.sub( p2 );
  33464. const len = delta.length();
  33465. const norm = len.div( materialLineWidth );
  33466. if ( ! useDash ) {
  33467. if ( useAlphaToCoverage ) {
  33468. const dnorm = norm.fwidth();
  33469. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  33470. } else {
  33471. norm.greaterThan( 0.5 ).discard();
  33472. }
  33473. }
  33474. } else {
  33475. // round endcaps
  33476. if ( useAlphaToCoverage ) {
  33477. const a = vUv.x;
  33478. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33479. const len2 = a.mul( a ).add( b.mul( b ) );
  33480. // force assignment out of following 'if' statement - to avoid uniform control flow errors
  33481. const dlen = property( 'float', 'dlen' );
  33482. dlen.assign( len2.fwidth() );
  33483. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33484. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  33485. } );
  33486. } else {
  33487. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  33488. const a = vUv.x;
  33489. const b = vUv.y.greaterThan( 0.0 ).cond( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  33490. const len2 = a.mul( a ).add( b.mul( b ) );
  33491. len2.greaterThan( 1.0 ).discard();
  33492. } );
  33493. }
  33494. }
  33495. let lineColorNode;
  33496. if ( this.lineColorNode ) {
  33497. lineColorNode = this.lineColorNode;
  33498. } else {
  33499. if ( useColor ) {
  33500. const instanceColorStart = attribute( 'instanceColorStart' );
  33501. const instanceColorEnd = attribute( 'instanceColorEnd' );
  33502. const instanceColor = positionGeometry.y.lessThan( 0.5 ).cond( instanceColorStart, instanceColorEnd );
  33503. lineColorNode = instanceColor.mul( materialColor );
  33504. } else {
  33505. lineColorNode = materialColor;
  33506. }
  33507. }
  33508. return vec4( lineColorNode, alpha );
  33509. } )();
  33510. }
  33511. get worldUnits() {
  33512. return this.useWorldUnits;
  33513. }
  33514. set worldUnits( value ) {
  33515. if ( this.useWorldUnits !== value ) {
  33516. this.useWorldUnits = value;
  33517. this.needsUpdate = true;
  33518. }
  33519. }
  33520. get dashed() {
  33521. return this.useDash;
  33522. }
  33523. set dashed( value ) {
  33524. if ( this.useDash !== value ) {
  33525. this.useDash = value;
  33526. this.needsUpdate = true;
  33527. }
  33528. }
  33529. get alphaToCoverage() {
  33530. return this.useAlphaToCoverage;
  33531. }
  33532. set alphaToCoverage( value ) {
  33533. if ( this.useAlphaToCoverage !== value ) {
  33534. this.useAlphaToCoverage = value;
  33535. this.needsUpdate = true;
  33536. }
  33537. }
  33538. }
  33539. addNodeMaterial( 'Line2NodeMaterial', Line2NodeMaterial );
  33540. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  33541. class MeshNormalNodeMaterial extends NodeMaterial {
  33542. constructor( parameters ) {
  33543. super();
  33544. this.lights = false;
  33545. this.isMeshNormalNodeMaterial = true;
  33546. this.setDefaultValues( _defaultValues$a );
  33547. this.setValues( parameters );
  33548. }
  33549. setupDiffuseColor() {
  33550. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  33551. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  33552. }
  33553. }
  33554. addNodeMaterial( 'MeshNormalNodeMaterial', MeshNormalNodeMaterial );
  33555. class BasicLightMapNode extends LightingNode {
  33556. constructor( lightMapNode = null ) {
  33557. super();
  33558. this.lightMapNode = lightMapNode;
  33559. }
  33560. setup( builder ) {
  33561. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  33562. const RECIPROCAL_PI = float( 1 / Math.PI );
  33563. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  33564. }
  33565. }
  33566. addNodeClass( 'BasicLightMapNode', BasicLightMapNode );
  33567. class BasicLightingModel extends LightingModel {
  33568. constructor() {
  33569. super();
  33570. }
  33571. indirect( context, stack, builder ) {
  33572. const ambientOcclusion = context.ambientOcclusion;
  33573. const reflectedLight = context.reflectedLight;
  33574. const irradianceLightMap = builder.context.irradianceLightMap;
  33575. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  33576. // accumulation (baked indirect lighting only)
  33577. if ( irradianceLightMap ) {
  33578. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  33579. } else {
  33580. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  33581. }
  33582. // modulation
  33583. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33584. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  33585. }
  33586. finish( context, stack, builder ) {
  33587. const material = builder.material;
  33588. const outgoingLight = context.outgoingLight;
  33589. const envNode = builder.context.environment;
  33590. if ( envNode ) {
  33591. switch ( material.combine ) {
  33592. case MultiplyOperation:
  33593. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  33594. break;
  33595. case MixOperation:
  33596. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  33597. break;
  33598. case AddOperation:
  33599. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  33600. break;
  33601. default:
  33602. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  33603. break;
  33604. }
  33605. }
  33606. }
  33607. }
  33608. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  33609. class MeshBasicNodeMaterial extends NodeMaterial {
  33610. constructor( parameters ) {
  33611. super();
  33612. this.isMeshBasicNodeMaterial = true;
  33613. this.lights = true;
  33614. //this.normals = false; @TODO: normals usage by context
  33615. this.setDefaultValues( _defaultValues$9 );
  33616. this.setValues( parameters );
  33617. }
  33618. setupNormal() {
  33619. transformedNormalView.assign( normalView ); // see #28839
  33620. }
  33621. setupEnvironment( builder ) {
  33622. const envNode = super.setupEnvironment( builder );
  33623. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33624. }
  33625. setupLightMap( builder ) {
  33626. let node = null;
  33627. if ( builder.material.lightMap ) {
  33628. node = new BasicLightMapNode( materialLightMap );
  33629. }
  33630. return node;
  33631. }
  33632. setupOutgoingLight() {
  33633. return diffuseColor.rgb;
  33634. }
  33635. setupLightingModel() {
  33636. return new BasicLightingModel();
  33637. }
  33638. }
  33639. addNodeMaterial( 'MeshBasicNodeMaterial', MeshBasicNodeMaterial );
  33640. const F_Schlick = tslFn( ( { f0, f90, dotVH } ) => {
  33641. // Original approximation by Christophe Schlick '94
  33642. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  33643. // Optimized variant (presented by Epic at SIGGRAPH '13)
  33644. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  33645. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  33646. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  33647. } ); // validated
  33648. const BRDF_Lambert = tslFn( ( inputs ) => {
  33649. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  33650. } ); // validated
  33651. const G_BlinnPhong_Implicit = () => float( 0.25 );
  33652. const D_BlinnPhong = tslFn( ( { dotNH } ) => {
  33653. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  33654. } );
  33655. const BRDF_BlinnPhong = tslFn( ( { lightDirection } ) => {
  33656. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33657. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33658. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33659. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  33660. const G = G_BlinnPhong_Implicit();
  33661. const D = D_BlinnPhong( { dotNH } );
  33662. return F.mul( G ).mul( D );
  33663. } );
  33664. class PhongLightingModel extends BasicLightingModel {
  33665. constructor( specular = true ) {
  33666. super();
  33667. this.specular = specular;
  33668. }
  33669. direct( { lightDirection, lightColor, reflectedLight } ) {
  33670. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33671. const irradiance = dotNL.mul( lightColor );
  33672. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  33673. if ( this.specular === true ) {
  33674. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  33675. }
  33676. }
  33677. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  33678. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  33679. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  33680. }
  33681. }
  33682. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  33683. class MeshLambertNodeMaterial extends NodeMaterial {
  33684. constructor( parameters ) {
  33685. super();
  33686. this.isMeshLambertNodeMaterial = true;
  33687. this.lights = true;
  33688. this.setDefaultValues( _defaultValues$8 );
  33689. this.setValues( parameters );
  33690. }
  33691. setupEnvironment( builder ) {
  33692. const envNode = super.setupEnvironment( builder );
  33693. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33694. }
  33695. setupLightingModel( /*builder*/ ) {
  33696. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  33697. }
  33698. }
  33699. addNodeMaterial( 'MeshLambertNodeMaterial', MeshLambertNodeMaterial );
  33700. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  33701. class MeshPhongNodeMaterial extends NodeMaterial {
  33702. constructor( parameters ) {
  33703. super();
  33704. this.isMeshPhongNodeMaterial = true;
  33705. this.lights = true;
  33706. this.shininessNode = null;
  33707. this.specularNode = null;
  33708. this.setDefaultValues( _defaultValues$7 );
  33709. this.setValues( parameters );
  33710. }
  33711. setupEnvironment( builder ) {
  33712. const envNode = super.setupEnvironment( builder );
  33713. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  33714. }
  33715. setupLightingModel( /*builder*/ ) {
  33716. return new PhongLightingModel();
  33717. }
  33718. setupVariants() {
  33719. // SHININESS
  33720. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  33721. shininess.assign( shininessNode );
  33722. // SPECULAR COLOR
  33723. const specularNode = this.specularNode || materialSpecular;
  33724. specularColor.assign( specularNode );
  33725. }
  33726. copy( source ) {
  33727. this.shininessNode = source.shininessNode;
  33728. this.specularNode = source.specularNode;
  33729. return super.copy( source );
  33730. }
  33731. }
  33732. addNodeMaterial( 'MeshPhongNodeMaterial', MeshPhongNodeMaterial );
  33733. const getGeometryRoughness = tslFn( () => {
  33734. const dxy = normalGeometry.dFdx().abs().max( normalGeometry.dFdy().abs() );
  33735. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  33736. return geometryRoughness;
  33737. } );
  33738. const getRoughness = tslFn( ( inputs ) => {
  33739. const { roughness } = inputs;
  33740. const geometryRoughness = getGeometryRoughness();
  33741. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  33742. roughnessFactor = roughnessFactor.add( geometryRoughness );
  33743. roughnessFactor = roughnessFactor.min( 1.0 );
  33744. return roughnessFactor;
  33745. } );
  33746. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  33747. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33748. const V_GGX_SmithCorrelated = tslFn( ( { alpha, dotNL, dotNV } ) => {
  33749. const a2 = alpha.pow2();
  33750. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  33751. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  33752. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  33753. } ).setLayout( {
  33754. name: 'V_GGX_SmithCorrelated',
  33755. type: 'float',
  33756. inputs: [
  33757. { name: 'alpha', type: 'float' },
  33758. { name: 'dotNL', type: 'float' },
  33759. { name: 'dotNV', type: 'float' }
  33760. ]
  33761. } ); // validated
  33762. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33763. const V_GGX_SmithCorrelated_Anisotropic = tslFn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  33764. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  33765. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  33766. const v = div( 0.5, gv.add( gl ) );
  33767. return v.saturate();
  33768. } ).setLayout( {
  33769. name: 'V_GGX_SmithCorrelated_Anisotropic',
  33770. type: 'float',
  33771. inputs: [
  33772. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33773. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33774. { name: 'dotTV', type: 'float', qualifier: 'in' },
  33775. { name: 'dotBV', type: 'float', qualifier: 'in' },
  33776. { name: 'dotTL', type: 'float', qualifier: 'in' },
  33777. { name: 'dotBL', type: 'float', qualifier: 'in' },
  33778. { name: 'dotNV', type: 'float', qualifier: 'in' },
  33779. { name: 'dotNL', type: 'float', qualifier: 'in' }
  33780. ]
  33781. } );
  33782. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  33783. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  33784. // alpha is "roughness squared" in Disney’s reparameterization
  33785. const D_GGX = tslFn( ( { alpha, dotNH } ) => {
  33786. const a2 = alpha.pow2();
  33787. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  33788. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  33789. } ).setLayout( {
  33790. name: 'D_GGX',
  33791. type: 'float',
  33792. inputs: [
  33793. { name: 'alpha', type: 'float' },
  33794. { name: 'dotNH', type: 'float' }
  33795. ]
  33796. } ); // validated
  33797. const RECIPROCAL_PI = float( 1 / Math.PI );
  33798. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  33799. const D_GGX_Anisotropic = tslFn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  33800. const a2 = alphaT.mul( alphaB );
  33801. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  33802. const v2 = v.dot( v );
  33803. const w2 = a2.div( v2 );
  33804. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  33805. } ).setLayout( {
  33806. name: 'D_GGX_Anisotropic',
  33807. type: 'float',
  33808. inputs: [
  33809. { name: 'alphaT', type: 'float', qualifier: 'in' },
  33810. { name: 'alphaB', type: 'float', qualifier: 'in' },
  33811. { name: 'dotNH', type: 'float', qualifier: 'in' },
  33812. { name: 'dotTH', type: 'float', qualifier: 'in' },
  33813. { name: 'dotBH', type: 'float', qualifier: 'in' }
  33814. ]
  33815. } );
  33816. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  33817. const BRDF_GGX = tslFn( ( inputs ) => {
  33818. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  33819. const normalView = inputs.normalView || transformedNormalView;
  33820. const alpha = roughness.pow2(); // UE4's roughness
  33821. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33822. const dotNL = normalView.dot( lightDirection ).clamp();
  33823. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  33824. const dotNH = normalView.dot( halfDir ).clamp();
  33825. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  33826. let F = F_Schlick( { f0, f90, dotVH } );
  33827. let V, D;
  33828. if ( defined( USE_IRIDESCENCE ) ) {
  33829. F = iridescence.mix( F, f );
  33830. }
  33831. if ( defined( USE_ANISOTROPY ) ) {
  33832. const dotTL = anisotropyT.dot( lightDirection );
  33833. const dotTV = anisotropyT.dot( positionViewDirection );
  33834. const dotTH = anisotropyT.dot( halfDir );
  33835. const dotBL = anisotropyB.dot( lightDirection );
  33836. const dotBV = anisotropyB.dot( positionViewDirection );
  33837. const dotBH = anisotropyB.dot( halfDir );
  33838. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  33839. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  33840. } else {
  33841. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  33842. D = D_GGX( { alpha, dotNH } );
  33843. }
  33844. return F.mul( V ).mul( D );
  33845. } ); // validated
  33846. // Analytical approximation of the DFG LUT, one half of the
  33847. // split-sum approximation used in indirect specular lighting.
  33848. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  33849. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  33850. const DFGApprox = tslFn( ( { roughness, dotNV } ) => {
  33851. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  33852. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  33853. const r = roughness.mul( c0 ).add( c1 );
  33854. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  33855. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  33856. return fab;
  33857. } ).setLayout( {
  33858. name: 'DFGApprox',
  33859. type: 'vec2',
  33860. inputs: [
  33861. { name: 'roughness', type: 'float' },
  33862. { name: 'dotNV', type: 'vec3' }
  33863. ]
  33864. } );
  33865. const EnvironmentBRDF = tslFn( ( inputs ) => {
  33866. const { dotNV, specularColor, specularF90, roughness } = inputs;
  33867. const fab = DFGApprox( { dotNV, roughness } );
  33868. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  33869. } );
  33870. const Schlick_to_F0 = tslFn( ( { f, f90, dotVH } ) => {
  33871. const x = dotVH.oneMinus().saturate();
  33872. const x2 = x.mul( x );
  33873. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  33874. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  33875. } ).setLayout( {
  33876. name: 'Schlick_to_F0',
  33877. type: 'vec3',
  33878. inputs: [
  33879. { name: 'f', type: 'vec3' },
  33880. { name: 'f90', type: 'float' },
  33881. { name: 'dotVH', type: 'float' }
  33882. ]
  33883. } );
  33884. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33885. const D_Charlie = tslFn( ( { roughness, dotNH } ) => {
  33886. const alpha = roughness.pow2();
  33887. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  33888. const invAlpha = float( 1.0 ).div( alpha );
  33889. const cos2h = dotNH.pow2();
  33890. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  33891. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  33892. } ).setLayout( {
  33893. name: 'D_Charlie',
  33894. type: 'float',
  33895. inputs: [
  33896. { name: 'roughness', type: 'float' },
  33897. { name: 'dotNH', type: 'float' }
  33898. ]
  33899. } );
  33900. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  33901. const V_Neubelt = tslFn( ( { dotNV, dotNL } ) => {
  33902. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  33903. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  33904. } ).setLayout( {
  33905. name: 'V_Neubelt',
  33906. type: 'float',
  33907. inputs: [
  33908. { name: 'dotNV', type: 'float' },
  33909. { name: 'dotNL', type: 'float' }
  33910. ]
  33911. } );
  33912. const BRDF_Sheen = tslFn( ( { lightDirection } ) => {
  33913. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  33914. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  33915. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  33916. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  33917. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  33918. const V = V_Neubelt( { dotNV, dotNL } );
  33919. return sheen.mul( D ).mul( V );
  33920. } );
  33921. // Rect Area Light
  33922. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  33923. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  33924. // code: https://github.com/selfshadow/ltc_code/
  33925. const LTC_Uv = tslFn( ( { N, V, roughness } ) => {
  33926. const LUT_SIZE = 64.0;
  33927. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  33928. const LUT_BIAS = 0.5 / LUT_SIZE;
  33929. const dotNV = N.dot( V ).saturate();
  33930. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  33931. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  33932. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  33933. return uv;
  33934. } ).setLayout( {
  33935. name: 'LTC_Uv',
  33936. type: 'vec2',
  33937. inputs: [
  33938. { name: 'N', type: 'vec3' },
  33939. { name: 'V', type: 'vec3' },
  33940. { name: 'roughness', type: 'float' }
  33941. ]
  33942. } );
  33943. const LTC_ClippedSphereFormFactor = tslFn( ( { f } ) => {
  33944. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  33945. // An approximation of the form factor of a horizon-clipped rectangle.
  33946. const l = f.length();
  33947. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  33948. } ).setLayout( {
  33949. name: 'LTC_ClippedSphereFormFactor',
  33950. type: 'float',
  33951. inputs: [
  33952. { name: 'f', type: 'vec3' }
  33953. ]
  33954. } );
  33955. const LTC_EdgeVectorFormFactor = tslFn( ( { v1, v2 } ) => {
  33956. const x = v1.dot( v2 );
  33957. const y = x.abs().toVar();
  33958. // rational polynomial approximation to theta / sin( theta ) / 2PI
  33959. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  33960. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  33961. const v = a.div( b );
  33962. const theta_sintheta = x.greaterThan( 0.0 ).cond( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  33963. return v1.cross( v2 ).mul( theta_sintheta );
  33964. } ).setLayout( {
  33965. name: 'LTC_EdgeVectorFormFactor',
  33966. type: 'vec3',
  33967. inputs: [
  33968. { name: 'v1', type: 'vec3' },
  33969. { name: 'v2', type: 'vec3' }
  33970. ]
  33971. } );
  33972. const LTC_Evaluate = tslFn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  33973. // bail if point is on back side of plane of light
  33974. // assumes ccw winding order of light vertices
  33975. const v1 = p1.sub( p0 ).toVar();
  33976. const v2 = p3.sub( p0 ).toVar();
  33977. const lightNormal = v1.cross( v2 );
  33978. const result = vec3().toVar();
  33979. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  33980. // construct orthonormal basis around N
  33981. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  33982. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  33983. // compute transform
  33984. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  33985. // transform rect
  33986. // & project rect onto sphere
  33987. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  33988. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  33989. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  33990. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  33991. // calculate vector form factor
  33992. const vectorFormFactor = vec3( 0 ).toVar();
  33993. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  33994. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  33995. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  33996. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  33997. // adjust for horizon clipping
  33998. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  33999. } );
  34000. return result;
  34001. } ).setLayout( {
  34002. name: 'LTC_Evaluate',
  34003. type: 'vec3',
  34004. inputs: [
  34005. { name: 'N', type: 'vec3' },
  34006. { name: 'V', type: 'vec3' },
  34007. { name: 'P', type: 'vec3' },
  34008. { name: 'mInv', type: 'mat3' },
  34009. { name: 'p0', type: 'vec3' },
  34010. { name: 'p1', type: 'vec3' },
  34011. { name: 'p2', type: 'vec3' },
  34012. { name: 'p3', type: 'vec3' }
  34013. ]
  34014. } );
  34015. //
  34016. // Transmission
  34017. //
  34018. const getVolumeTransmissionRay = tslFn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  34019. // Direction of refracted light.
  34020. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  34021. // Compute rotation-independant scaling of the model matrix.
  34022. const modelScale = vec3(
  34023. length( modelMatrix[ 0 ].xyz ),
  34024. length( modelMatrix[ 1 ].xyz ),
  34025. length( modelMatrix[ 2 ].xyz )
  34026. );
  34027. // The thickness is specified in local space.
  34028. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  34029. } ).setLayout( {
  34030. name: 'getVolumeTransmissionRay',
  34031. type: 'vec3',
  34032. inputs: [
  34033. { name: 'n', type: 'vec3' },
  34034. { name: 'v', type: 'vec3' },
  34035. { name: 'thickness', type: 'float' },
  34036. { name: 'ior', type: 'float' },
  34037. { name: 'modelMatrix', type: 'mat4' }
  34038. ]
  34039. } );
  34040. const applyIorToRoughness = tslFn( ( [ roughness, ior ] ) => {
  34041. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  34042. // an IOR of 1.5 results in the default amount of microfacet refraction.
  34043. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  34044. } ).setLayout( {
  34045. name: 'applyIorToRoughness',
  34046. type: 'float',
  34047. inputs: [
  34048. { name: 'roughness', type: 'float' },
  34049. { name: 'ior', type: 'float' }
  34050. ]
  34051. } );
  34052. const singleViewportMipTexture = viewportMipTexture();
  34053. const getTransmissionSample = tslFn( ( [ fragCoord, roughness, ior ] ) => {
  34054. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  34055. //const transmissionSample = viewportMipTexture( fragCoord );
  34056. const lod = log2( float( viewportResolution.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  34057. return transmissionSample.bicubic( lod );
  34058. } );
  34059. const volumeAttenuation = tslFn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  34060. If( attenuationDistance.notEqual( 0 ), () => {
  34061. // Compute light attenuation using Beer's law.
  34062. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  34063. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  34064. return transmittance;
  34065. } );
  34066. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  34067. return vec3( 1.0 );
  34068. } ).setLayout( {
  34069. name: 'volumeAttenuation',
  34070. type: 'vec3',
  34071. inputs: [
  34072. { name: 'transmissionDistance', type: 'float' },
  34073. { name: 'attenuationColor', type: 'vec3' },
  34074. { name: 'attenuationDistance', type: 'float' }
  34075. ]
  34076. } );
  34077. const getIBLVolumeRefraction = tslFn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  34078. let transmittedLight, transmittance;
  34079. if ( dispersion ) {
  34080. transmittedLight = vec4().toVar();
  34081. transmittance = vec3().toVar();
  34082. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  34083. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  34084. loop( { start: 0, end: 3 }, ( { i } ) => {
  34085. const ior = iors.element( i );
  34086. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  34087. const refractedRayExit = position.add( transmissionRay );
  34088. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  34089. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  34090. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  34091. refractionCoords.addAssign( 1.0 );
  34092. refractionCoords.divAssign( 2.0 );
  34093. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  34094. // Sample framebuffer to get pixel the refracted ray hits.
  34095. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  34096. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  34097. transmittedLight.a.addAssign( transmissionSample.a );
  34098. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  34099. } );
  34100. transmittedLight.a.divAssign( 3.0 );
  34101. } else {
  34102. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  34103. const refractedRayExit = position.add( transmissionRay );
  34104. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  34105. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  34106. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  34107. refractionCoords.addAssign( 1.0 );
  34108. refractionCoords.divAssign( 2.0 );
  34109. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  34110. // Sample framebuffer to get pixel the refracted ray hits.
  34111. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  34112. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  34113. }
  34114. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  34115. const dotNV = n.dot( v ).clamp();
  34116. // Get the specular component.
  34117. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  34118. dotNV,
  34119. specularColor,
  34120. specularF90,
  34121. roughness
  34122. } ) );
  34123. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  34124. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  34125. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  34126. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  34127. } );
  34128. //
  34129. // Iridescence
  34130. //
  34131. // XYZ to linear-sRGB color space
  34132. const XYZ_TO_REC709 = mat3(
  34133. 3.2404542, - 0.9692660, 0.0556434,
  34134. - 1.5371385, 1.8760108, - 0.2040259,
  34135. - 0.4985314, 0.0415560, 1.0572252
  34136. );
  34137. // Assume air interface for top
  34138. // Note: We don't handle the case fresnel0 == 1
  34139. const Fresnel0ToIor = ( fresnel0 ) => {
  34140. const sqrtF0 = fresnel0.sqrt();
  34141. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  34142. };
  34143. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  34144. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  34145. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  34146. };
  34147. // Fresnel equations for dielectric/dielectric interfaces.
  34148. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  34149. // Evaluation XYZ sensitivity curves in Fourier space
  34150. const evalSensitivity = ( OPD, shift ) => {
  34151. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  34152. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  34153. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  34154. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  34155. 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() );
  34156. 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() );
  34157. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  34158. const rgb = XYZ_TO_REC709.mul( xyz );
  34159. return rgb;
  34160. };
  34161. const evalIridescence = tslFn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  34162. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  34163. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  34164. // Evaluate the cosTheta on the base layer (Snell law)
  34165. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  34166. // Handle TIR:
  34167. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  34168. /*if ( cosTheta2Sq < 0.0 ) {
  34169. return vec3( 1.0 );
  34170. }*/
  34171. const cosTheta2 = cosTheta2Sq.sqrt();
  34172. // First interface
  34173. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  34174. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  34175. //const R21 = R12;
  34176. const T121 = R12.oneMinus();
  34177. const phi12 = iridescenceIOR.lessThan( outsideIOR ).cond( Math.PI, 0.0 );
  34178. const phi21 = float( Math.PI ).sub( phi12 );
  34179. // Second interface
  34180. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  34181. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  34182. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  34183. const phi23 = vec3(
  34184. baseIOR.x.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34185. baseIOR.y.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 ),
  34186. baseIOR.z.lessThan( iridescenceIOR ).cond( Math.PI, 0.0 )
  34187. );
  34188. // Phase shift
  34189. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  34190. const phi = vec3( phi21 ).add( phi23 );
  34191. // Compound terms
  34192. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  34193. const r123 = R123.sqrt();
  34194. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  34195. // Reflectance term for m = 0 (DC term amplitude)
  34196. const C0 = R12.add( Rs );
  34197. let I = C0;
  34198. // Reflectance term for m > 0 (pairs of diracs)
  34199. let Cm = Rs.sub( T121 );
  34200. for ( let m = 1; m <= 2; ++ m ) {
  34201. Cm = Cm.mul( r123 );
  34202. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  34203. I = I.add( Cm.mul( Sm ) );
  34204. }
  34205. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  34206. return I.max( vec3( 0.0 ) );
  34207. } ).setLayout( {
  34208. name: 'evalIridescence',
  34209. type: 'vec3',
  34210. inputs: [
  34211. { name: 'outsideIOR', type: 'float' },
  34212. { name: 'eta2', type: 'float' },
  34213. { name: 'cosTheta1', type: 'float' },
  34214. { name: 'thinFilmThickness', type: 'float' },
  34215. { name: 'baseF0', type: 'vec3' }
  34216. ]
  34217. } );
  34218. //
  34219. // Sheen
  34220. //
  34221. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  34222. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  34223. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  34224. const IBLSheenBRDF = tslFn( ( { normal, viewDir, roughness } ) => {
  34225. const dotNV = normal.dot( viewDir ).saturate();
  34226. const r2 = roughness.pow2();
  34227. const a = cond(
  34228. roughness.lessThan( 0.25 ),
  34229. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  34230. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  34231. );
  34232. const b = cond(
  34233. roughness.lessThan( 0.25 ),
  34234. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  34235. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  34236. );
  34237. const DG = cond( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  34238. return DG.mul( 1.0 / Math.PI ).saturate();
  34239. } );
  34240. const clearcoatF0 = vec3( 0.04 );
  34241. const clearcoatF90 = float( 1 );
  34242. //
  34243. class PhysicalLightingModel extends LightingModel {
  34244. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  34245. super();
  34246. this.clearcoat = clearcoat;
  34247. this.sheen = sheen;
  34248. this.iridescence = iridescence;
  34249. this.anisotropy = anisotropy;
  34250. this.transmission = transmission;
  34251. this.dispersion = dispersion;
  34252. this.clearcoatRadiance = null;
  34253. this.clearcoatSpecularDirect = null;
  34254. this.clearcoatSpecularIndirect = null;
  34255. this.sheenSpecularDirect = null;
  34256. this.sheenSpecularIndirect = null;
  34257. this.iridescenceFresnel = null;
  34258. this.iridescenceF0 = null;
  34259. }
  34260. start( context ) {
  34261. if ( this.clearcoat === true ) {
  34262. this.clearcoatRadiance = vec3().temp( 'clearcoatRadiance' );
  34263. this.clearcoatSpecularDirect = vec3().temp( 'clearcoatSpecularDirect' );
  34264. this.clearcoatSpecularIndirect = vec3().temp( 'clearcoatSpecularIndirect' );
  34265. }
  34266. if ( this.sheen === true ) {
  34267. this.sheenSpecularDirect = vec3().temp( 'sheenSpecularDirect' );
  34268. this.sheenSpecularIndirect = vec3().temp( 'sheenSpecularIndirect' );
  34269. }
  34270. if ( this.iridescence === true ) {
  34271. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  34272. this.iridescenceFresnel = evalIridescence( {
  34273. outsideIOR: float( 1.0 ),
  34274. eta2: iridescenceIOR,
  34275. cosTheta1: dotNVi,
  34276. thinFilmThickness: iridescenceThickness,
  34277. baseF0: specularColor
  34278. } );
  34279. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  34280. }
  34281. if ( this.transmission === true ) {
  34282. const position = positionWorld;
  34283. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  34284. const n = transformedNormalWorld;
  34285. context.backdrop = getIBLVolumeRefraction(
  34286. n,
  34287. v,
  34288. roughness,
  34289. diffuseColor,
  34290. specularColor,
  34291. specularF90, // specularF90
  34292. position, // positionWorld
  34293. modelWorldMatrix, // modelMatrix
  34294. cameraViewMatrix, // viewMatrix
  34295. cameraProjectionMatrix, // projMatrix
  34296. ior,
  34297. thickness,
  34298. attenuationColor,
  34299. attenuationDistance,
  34300. this.dispersion ? dispersion : null
  34301. );
  34302. context.backdropAlpha = transmission;
  34303. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  34304. }
  34305. }
  34306. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  34307. // Approximates multiscattering in order to preserve energy.
  34308. // http://www.jcgt.org/published/0008/01/03/
  34309. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  34310. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34311. const fab = DFGApprox( { roughness, dotNV } );
  34312. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  34313. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  34314. const Ess = fab.x.add( fab.y );
  34315. const Ems = Ess.oneMinus();
  34316. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  34317. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  34318. singleScatter.addAssign( FssEss );
  34319. multiScatter.addAssign( Fms.mul( Ems ) );
  34320. }
  34321. direct( { lightDirection, lightColor, reflectedLight } ) {
  34322. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  34323. const irradiance = dotNL.mul( lightColor );
  34324. if ( this.sheen === true ) {
  34325. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  34326. }
  34327. if ( this.clearcoat === true ) {
  34328. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  34329. const ccIrradiance = dotNLcc.mul( lightColor );
  34330. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  34331. }
  34332. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34333. 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 } ) ) );
  34334. }
  34335. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  34336. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  34337. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  34338. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  34339. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  34340. const N = transformedNormalView;
  34341. const V = positionViewDirection;
  34342. const P = positionView.toVar();
  34343. const uv = LTC_Uv( { N, V, roughness } );
  34344. const t1 = ltc_1.uv( uv ).toVar();
  34345. const t2 = ltc_2.uv( uv ).toVar();
  34346. const mInv = mat3(
  34347. vec3( t1.x, 0, t1.y ),
  34348. vec3( 0, 1, 0 ),
  34349. vec3( t1.z, 0, t1.w )
  34350. ).toVar();
  34351. // LTC Fresnel Approximation by Stephen Hill
  34352. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  34353. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  34354. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  34355. 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 } ) ) );
  34356. }
  34357. indirect( context, stack, builder ) {
  34358. this.indirectDiffuse( context, stack, builder );
  34359. this.indirectSpecular( context, stack, builder );
  34360. this.ambientOcclusion( context, stack, builder );
  34361. }
  34362. indirectDiffuse( { irradiance, reflectedLight } ) {
  34363. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34364. }
  34365. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  34366. if ( this.sheen === true ) {
  34367. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  34368. sheen,
  34369. IBLSheenBRDF( {
  34370. normal: transformedNormalView,
  34371. viewDir: positionViewDirection,
  34372. roughness: sheenRoughness
  34373. } )
  34374. ) );
  34375. }
  34376. if ( this.clearcoat === true ) {
  34377. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34378. const clearcoatEnv = EnvironmentBRDF( {
  34379. dotNV: dotNVcc,
  34380. specularColor: clearcoatF0,
  34381. specularF90: clearcoatF90,
  34382. roughness: clearcoatRoughness
  34383. } );
  34384. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  34385. }
  34386. // Both indirect specular and indirect diffuse light accumulate here
  34387. const singleScattering = vec3().temp( 'singleScattering' );
  34388. const multiScattering = vec3().temp( 'multiScattering' );
  34389. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  34390. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  34391. const totalScattering = singleScattering.add( multiScattering );
  34392. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  34393. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  34394. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  34395. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  34396. }
  34397. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  34398. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  34399. const aoNV = dotNV.add( ambientOcclusion );
  34400. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  34401. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  34402. if ( this.clearcoat === true ) {
  34403. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  34404. }
  34405. if ( this.sheen === true ) {
  34406. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  34407. }
  34408. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34409. reflectedLight.indirectSpecular.mulAssign( aoNode );
  34410. }
  34411. finish( context ) {
  34412. const { outgoingLight } = context;
  34413. if ( this.clearcoat === true ) {
  34414. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  34415. const Fcc = F_Schlick( {
  34416. dotVH: dotNVcc,
  34417. f0: clearcoatF0,
  34418. f90: clearcoatF90
  34419. } );
  34420. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  34421. outgoingLight.assign( clearcoatLight );
  34422. }
  34423. if ( this.sheen === true ) {
  34424. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  34425. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  34426. outgoingLight.assign( sheenLight );
  34427. }
  34428. }
  34429. }
  34430. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  34431. class MeshStandardNodeMaterial extends NodeMaterial {
  34432. constructor( parameters ) {
  34433. super();
  34434. this.isMeshStandardNodeMaterial = true;
  34435. this.lights = true;
  34436. this.emissiveNode = null;
  34437. this.metalnessNode = null;
  34438. this.roughnessNode = null;
  34439. this.setDefaultValues( _defaultValues$6 );
  34440. this.setValues( parameters );
  34441. }
  34442. setupEnvironment( builder ) {
  34443. const envNode = super.setupEnvironment( builder );
  34444. return envNode ? new EnvironmentNode( envNode ) : null;
  34445. }
  34446. setupLightingModel( /*builder*/ ) {
  34447. return new PhysicalLightingModel();
  34448. }
  34449. setupSpecular() {
  34450. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  34451. specularColor.assign( specularColorNode );
  34452. specularF90.assign( 1.0 );
  34453. }
  34454. setupVariants() {
  34455. // METALNESS
  34456. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  34457. metalness.assign( metalnessNode );
  34458. // ROUGHNESS
  34459. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  34460. roughnessNode = getRoughness( { roughness: roughnessNode } );
  34461. roughness.assign( roughnessNode );
  34462. // SPECULAR COLOR
  34463. this.setupSpecular();
  34464. // DIFFUSE COLOR
  34465. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  34466. }
  34467. copy( source ) {
  34468. this.emissiveNode = source.emissiveNode;
  34469. this.metalnessNode = source.metalnessNode;
  34470. this.roughnessNode = source.roughnessNode;
  34471. return super.copy( source );
  34472. }
  34473. }
  34474. addNodeMaterial( 'MeshStandardNodeMaterial', MeshStandardNodeMaterial );
  34475. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  34476. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  34477. constructor( parameters ) {
  34478. super();
  34479. this.isMeshPhysicalNodeMaterial = true;
  34480. this.clearcoatNode = null;
  34481. this.clearcoatRoughnessNode = null;
  34482. this.clearcoatNormalNode = null;
  34483. this.sheenNode = null;
  34484. this.sheenRoughnessNode = null;
  34485. this.iridescenceNode = null;
  34486. this.iridescenceIORNode = null;
  34487. this.iridescenceThicknessNode = null;
  34488. this.specularIntensityNode = null;
  34489. this.specularColorNode = null;
  34490. this.iorNode = null;
  34491. this.transmissionNode = null;
  34492. this.thicknessNode = null;
  34493. this.attenuationDistanceNode = null;
  34494. this.attenuationColorNode = null;
  34495. this.dispersionNode = null;
  34496. this.anisotropyNode = null;
  34497. this.setDefaultValues( _defaultValues$5 );
  34498. this.setValues( parameters );
  34499. }
  34500. get useClearcoat() {
  34501. return this.clearcoat > 0 || this.clearcoatNode !== null;
  34502. }
  34503. get useIridescence() {
  34504. return this.iridescence > 0 || this.iridescenceNode !== null;
  34505. }
  34506. get useSheen() {
  34507. return this.sheen > 0 || this.sheenNode !== null;
  34508. }
  34509. get useAnisotropy() {
  34510. return this.anisotropy > 0 || this.anisotropyNode !== null;
  34511. }
  34512. get useTransmission() {
  34513. return this.transmission > 0 || this.transmissionNode !== null;
  34514. }
  34515. get useDispersion() {
  34516. return this.dispersion > 0 || this.dispersionNode !== null;
  34517. }
  34518. setupSpecular() {
  34519. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  34520. ior.assign( iorNode );
  34521. 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 ) );
  34522. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  34523. }
  34524. setupLightingModel( /*builder*/ ) {
  34525. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  34526. }
  34527. setupVariants( builder ) {
  34528. super.setupVariants( builder );
  34529. // CLEARCOAT
  34530. if ( this.useClearcoat ) {
  34531. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  34532. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  34533. clearcoat.assign( clearcoatNode );
  34534. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  34535. }
  34536. // SHEEN
  34537. if ( this.useSheen ) {
  34538. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  34539. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  34540. sheen.assign( sheenNode );
  34541. sheenRoughness.assign( sheenRoughnessNode );
  34542. }
  34543. // IRIDESCENCE
  34544. if ( this.useIridescence ) {
  34545. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  34546. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  34547. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  34548. iridescence.assign( iridescenceNode );
  34549. iridescenceIOR.assign( iridescenceIORNode );
  34550. iridescenceThickness.assign( iridescenceThicknessNode );
  34551. }
  34552. // ANISOTROPY
  34553. if ( this.useAnisotropy ) {
  34554. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  34555. anisotropy.assign( anisotropyV.length() );
  34556. If( anisotropy.equal( 0.0 ), () => {
  34557. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  34558. } ).else( () => {
  34559. anisotropyV.divAssign( vec2( anisotropy ) );
  34560. anisotropy.assign( anisotropy.saturate() );
  34561. } );
  34562. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  34563. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  34564. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  34565. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  34566. }
  34567. // TRANSMISSION
  34568. if ( this.useTransmission ) {
  34569. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  34570. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  34571. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  34572. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  34573. transmission.assign( transmissionNode );
  34574. thickness.assign( thicknessNode );
  34575. attenuationDistance.assign( attenuationDistanceNode );
  34576. attenuationColor.assign( attenuationColorNode );
  34577. if ( this.useDispersion ) {
  34578. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  34579. dispersion.assign( dispersionNode );
  34580. }
  34581. }
  34582. }
  34583. setupNormal( builder ) {
  34584. super.setupNormal( builder );
  34585. // CLEARCOAT NORMAL
  34586. const clearcoatNormalNode = this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  34587. transformedClearcoatNormalView.assign( clearcoatNormalNode );
  34588. }
  34589. copy( source ) {
  34590. this.clearcoatNode = source.clearcoatNode;
  34591. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  34592. this.clearcoatNormalNode = source.clearcoatNormalNode;
  34593. this.sheenNode = source.sheenNode;
  34594. this.sheenRoughnessNode = source.sheenRoughnessNode;
  34595. this.iridescenceNode = source.iridescenceNode;
  34596. this.iridescenceIORNode = source.iridescenceIORNode;
  34597. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  34598. this.specularIntensityNode = source.specularIntensityNode;
  34599. this.specularColorNode = source.specularColorNode;
  34600. this.transmissionNode = source.transmissionNode;
  34601. this.thicknessNode = source.thicknessNode;
  34602. this.attenuationDistanceNode = source.attenuationDistanceNode;
  34603. this.attenuationColorNode = source.attenuationColorNode;
  34604. this.dispersionNode = source.dispersionNode;
  34605. this.anisotropyNode = source.anisotropyNode;
  34606. return super.copy( source );
  34607. }
  34608. }
  34609. addNodeMaterial( 'MeshPhysicalNodeMaterial', MeshPhysicalNodeMaterial );
  34610. class SSSLightingModel extends PhysicalLightingModel {
  34611. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  34612. super( useClearcoat, useSheen, useIridescence );
  34613. this.useSSS = useSSS;
  34614. }
  34615. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34616. if ( this.useSSS === true ) {
  34617. const material = builder.material;
  34618. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  34619. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  34620. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  34621. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  34622. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  34623. }
  34624. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  34625. }
  34626. }
  34627. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  34628. constructor( parameters ) {
  34629. super( parameters );
  34630. this.thicknessColorNode = null;
  34631. this.thicknessDistortionNode = float( 0.1 );
  34632. this.thicknessAmbientNode = float( 0.0 );
  34633. this.thicknessAttenuationNode = float( .1 );
  34634. this.thicknessPowerNode = float( 2.0 );
  34635. this.thicknessScaleNode = float( 10.0 );
  34636. }
  34637. get useSSS() {
  34638. return this.thicknessColorNode !== null;
  34639. }
  34640. setupLightingModel( /*builder*/ ) {
  34641. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  34642. }
  34643. copy( source ) {
  34644. this.thicknessColorNode = source.thicknessColorNode;
  34645. this.thicknessDistortionNode = source.thicknessDistortionNode;
  34646. this.thicknessAmbientNode = source.thicknessAmbientNode;
  34647. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  34648. this.thicknessPowerNode = source.thicknessPowerNode;
  34649. this.thicknessScaleNode = source.thicknessScaleNode;
  34650. return super.copy( source );
  34651. }
  34652. }
  34653. addNodeMaterial( 'MeshSSSNodeMaterial', MeshSSSNodeMaterial );
  34654. const getGradientIrradiance = tslFn( ( { normal, lightDirection, builder } ) => {
  34655. // dotNL will be from -1.0 to 1.0
  34656. const dotNL = normal.dot( lightDirection );
  34657. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  34658. if ( builder.material.gradientMap ) {
  34659. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  34660. return vec3( gradientMap.r );
  34661. } else {
  34662. const fw = coord.fwidth().mul( 0.5 );
  34663. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  34664. }
  34665. } );
  34666. class ToonLightingModel extends LightingModel {
  34667. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  34668. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  34669. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  34670. }
  34671. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  34672. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  34673. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  34674. }
  34675. }
  34676. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  34677. class MeshToonNodeMaterial extends NodeMaterial {
  34678. constructor( parameters ) {
  34679. super();
  34680. this.isMeshToonNodeMaterial = true;
  34681. this.lights = true;
  34682. this.setDefaultValues( _defaultValues$4 );
  34683. this.setValues( parameters );
  34684. }
  34685. setupLightingModel( /*builder*/ ) {
  34686. return new ToonLightingModel();
  34687. }
  34688. }
  34689. addNodeMaterial( 'MeshToonNodeMaterial', MeshToonNodeMaterial );
  34690. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  34691. class MeshMatcapNodeMaterial extends NodeMaterial {
  34692. constructor( parameters ) {
  34693. super();
  34694. this.lights = false;
  34695. this.isMeshMatcapNodeMaterial = true;
  34696. this.setDefaultValues( _defaultValues$3 );
  34697. this.setValues( parameters );
  34698. }
  34699. setupVariants( builder ) {
  34700. const uv = matcapUV;
  34701. let matcapColor;
  34702. if ( builder.material.matcap ) {
  34703. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  34704. } else {
  34705. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  34706. }
  34707. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  34708. }
  34709. }
  34710. addNodeMaterial( 'MeshMatcapNodeMaterial', MeshMatcapNodeMaterial );
  34711. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  34712. class PointsNodeMaterial extends NodeMaterial {
  34713. constructor( parameters ) {
  34714. super();
  34715. this.isPointsNodeMaterial = true;
  34716. this.lights = false;
  34717. this.normals = false;
  34718. this.transparent = true;
  34719. this.sizeNode = null;
  34720. this.setDefaultValues( _defaultValues$2 );
  34721. this.setValues( parameters );
  34722. }
  34723. copy( source ) {
  34724. this.sizeNode = source.sizeNode;
  34725. return super.copy( source );
  34726. }
  34727. }
  34728. addNodeMaterial( 'PointsNodeMaterial', PointsNodeMaterial );
  34729. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  34730. class SpriteNodeMaterial extends NodeMaterial {
  34731. constructor( parameters ) {
  34732. super();
  34733. this.isSpriteNodeMaterial = true;
  34734. this.lights = false;
  34735. this.normals = false;
  34736. this.positionNode = null;
  34737. this.rotationNode = null;
  34738. this.scaleNode = null;
  34739. this.setDefaultValues( _defaultValues$1 );
  34740. this.setValues( parameters );
  34741. }
  34742. setupPosition( { object, context } ) {
  34743. // < VERTEX STAGE >
  34744. const { positionNode, rotationNode, scaleNode } = this;
  34745. const vertex = positionLocal;
  34746. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  34747. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  34748. if ( scaleNode !== null ) {
  34749. scale = scale.mul( scaleNode );
  34750. }
  34751. let alignedPosition = vertex.xy;
  34752. if ( object.center && object.center.isVector2 === true ) {
  34753. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  34754. }
  34755. alignedPosition = alignedPosition.mul( scale );
  34756. const rotation = float( rotationNode || materialRotation );
  34757. const rotatedPosition = alignedPosition.rotate( rotation );
  34758. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  34759. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  34760. context.vertex = vertex;
  34761. return modelViewProjection;
  34762. }
  34763. copy( source ) {
  34764. this.positionNode = source.positionNode;
  34765. this.rotationNode = source.rotationNode;
  34766. this.scaleNode = source.scaleNode;
  34767. return super.copy( source );
  34768. }
  34769. }
  34770. addNodeMaterial( 'SpriteNodeMaterial', SpriteNodeMaterial );
  34771. class ShadowMaskModel extends LightingModel {
  34772. constructor() {
  34773. super();
  34774. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  34775. }
  34776. direct( { shadowMask } ) {
  34777. this.shadowNode.mulAssign( shadowMask );
  34778. }
  34779. finish( context ) {
  34780. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  34781. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  34782. }
  34783. }
  34784. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  34785. class ShadowNodeMaterial extends NodeMaterial {
  34786. constructor( parameters ) {
  34787. super();
  34788. this.isShadowNodeMaterial = true;
  34789. this.lights = true;
  34790. this.setDefaultValues( _defaultValues );
  34791. this.setValues( parameters );
  34792. }
  34793. setupLightingModel( /*builder*/ ) {
  34794. return new ShadowMaskModel();
  34795. }
  34796. }
  34797. addNodeMaterial( 'ShadowNodeMaterial', ShadowNodeMaterial );
  34798. class VolumeNodeMaterial extends NodeMaterial {
  34799. constructor( params = {} ) {
  34800. super();
  34801. this.normals = false;
  34802. this.lights = false;
  34803. this.isVolumeNodeMaterial = true;
  34804. this.testNode = null;
  34805. this.setValues( params );
  34806. }
  34807. setup( builder ) {
  34808. const map = texture3D( this.map, null, 0 );
  34809. const hitBox = tslFn( ( { orig, dir } ) => {
  34810. const box_min = vec3( - 0.5 );
  34811. const box_max = vec3( 0.5 );
  34812. const inv_dir = dir.reciprocal();
  34813. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  34814. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  34815. const tmin = min$1( tmin_tmp, tmax_tmp );
  34816. const tmax = max$1( tmin_tmp, tmax_tmp );
  34817. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  34818. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  34819. return vec2( t0, t1 );
  34820. } );
  34821. this.fragmentNode = tslFn( () => {
  34822. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  34823. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  34824. const rayDir = vDirection.normalize();
  34825. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  34826. bounds.x.greaterThan( bounds.y ).discard();
  34827. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  34828. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  34829. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  34830. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  34831. delta.divAssign( materialReference( 'steps', 'float' ) );
  34832. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  34833. loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  34834. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  34835. if ( this.testNode !== null ) {
  34836. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  34837. } else {
  34838. // default to show surface of mesh
  34839. ac.a.assign( 1 );
  34840. Break();
  34841. }
  34842. p.addAssign( rayDir.mul( delta ) );
  34843. } );
  34844. ac.a.equal( 0 ).discard();
  34845. return vec4( ac );
  34846. } )();
  34847. super.setup( builder );
  34848. }
  34849. }
  34850. addNodeMaterial( 'VolumeNodeMaterial', VolumeNodeMaterial );
  34851. const superFromTypeFunction = MaterialLoader.createMaterialFromType;
  34852. MaterialLoader.createMaterialFromType = function ( type ) {
  34853. const material = createNodeMaterialFromType( type );
  34854. if ( material !== undefined ) {
  34855. return material;
  34856. }
  34857. return superFromTypeFunction.call( this, type );
  34858. };
  34859. class NodeMaterialLoader extends MaterialLoader {
  34860. constructor( manager ) {
  34861. super( manager );
  34862. this.nodes = {};
  34863. }
  34864. parse( json ) {
  34865. const material = super.parse( json );
  34866. const nodes = this.nodes;
  34867. const inputNodes = json.inputNodes;
  34868. for ( const property in inputNodes ) {
  34869. const uuid = inputNodes[ property ];
  34870. material[ property ] = nodes[ uuid ];
  34871. }
  34872. return material;
  34873. }
  34874. setNodes( value ) {
  34875. this.nodes = value;
  34876. return this;
  34877. }
  34878. }
  34879. class NodeObjectLoader extends ObjectLoader {
  34880. constructor( manager ) {
  34881. super( manager );
  34882. this._nodesJSON = null;
  34883. }
  34884. parse( json, onLoad ) {
  34885. this._nodesJSON = json.nodes;
  34886. const data = super.parse( json, onLoad );
  34887. this._nodesJSON = null; // dispose
  34888. return data;
  34889. }
  34890. parseNodes( json, textures ) {
  34891. if ( json !== undefined ) {
  34892. const loader = new NodeLoader();
  34893. loader.setTextures( textures );
  34894. return loader.parseNodes( json );
  34895. }
  34896. return {};
  34897. }
  34898. parseMaterials( json, textures ) {
  34899. const materials = {};
  34900. if ( json !== undefined ) {
  34901. const nodes = this.parseNodes( this._nodesJSON, textures );
  34902. const loader = new NodeMaterialLoader();
  34903. loader.setTextures( textures );
  34904. loader.setNodes( nodes );
  34905. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34906. const data = json[ i ];
  34907. materials[ data.uuid ] = loader.parse( data );
  34908. }
  34909. }
  34910. return materials;
  34911. }
  34912. }
  34913. class NodeParser {
  34914. parseFunction( /*source*/ ) {
  34915. console.warn( 'Abstract function.' );
  34916. }
  34917. }
  34918. class NodeFunction {
  34919. constructor( type, inputs, name = '', precision = '' ) {
  34920. this.type = type;
  34921. this.inputs = inputs;
  34922. this.name = name;
  34923. this.precision = precision;
  34924. }
  34925. getCode( /*name = this.name*/ ) {
  34926. console.warn( 'Abstract function.' );
  34927. }
  34928. }
  34929. NodeFunction.isNodeFunction = true;
  34930. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34931. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34932. const pragmaMain = '#pragma main';
  34933. const parse$1 = ( source ) => {
  34934. source = source.trim();
  34935. const pragmaMainIndex = source.indexOf( pragmaMain );
  34936. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34937. const declaration = mainCode.match( declarationRegexp$1 );
  34938. if ( declaration !== null && declaration.length === 5 ) {
  34939. // tokenizer
  34940. const inputsCode = declaration[ 4 ];
  34941. const propsMatches = [];
  34942. let nameMatch = null;
  34943. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34944. propsMatches.push( nameMatch );
  34945. }
  34946. // parser
  34947. const inputs = [];
  34948. let i = 0;
  34949. while ( i < propsMatches.length ) {
  34950. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34951. if ( isConst === true ) {
  34952. i ++;
  34953. }
  34954. let qualifier = propsMatches[ i ][ 0 ];
  34955. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34956. i ++;
  34957. } else {
  34958. qualifier = '';
  34959. }
  34960. const type = propsMatches[ i ++ ][ 0 ];
  34961. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34962. if ( Number.isNaN( count ) === false ) i ++;
  34963. else count = null;
  34964. const name = propsMatches[ i ++ ][ 0 ];
  34965. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34966. }
  34967. //
  34968. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34969. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34970. const type = declaration[ 2 ];
  34971. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34972. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  34973. return {
  34974. type,
  34975. inputs,
  34976. name,
  34977. precision,
  34978. inputsCode,
  34979. blockCode,
  34980. headerCode
  34981. };
  34982. } else {
  34983. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34984. }
  34985. };
  34986. class GLSLNodeFunction extends NodeFunction {
  34987. constructor( source ) {
  34988. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34989. super( type, inputs, name, precision );
  34990. this.inputsCode = inputsCode;
  34991. this.blockCode = blockCode;
  34992. this.headerCode = headerCode;
  34993. }
  34994. getCode( name = this.name ) {
  34995. let code;
  34996. const blockCode = this.blockCode;
  34997. if ( blockCode !== '' ) {
  34998. const { type, inputsCode, headerCode, precision } = this;
  34999. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35000. if ( precision !== '' ) {
  35001. declarationCode = `${ precision } ${ declarationCode }`;
  35002. }
  35003. code = headerCode + declarationCode + blockCode;
  35004. } else {
  35005. // interface function
  35006. code = '';
  35007. }
  35008. return code;
  35009. }
  35010. }
  35011. class GLSLNodeParser extends NodeParser {
  35012. parseFunction( source ) {
  35013. return new GLSLNodeFunction( source );
  35014. }
  35015. }
  35016. // Three.js Transpiler
  35017. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  35018. const mx_select = /*#__PURE__*/ tslFn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  35019. const f = float( f_immutable ).toVar();
  35020. const t = float( t_immutable ).toVar();
  35021. const b = bool( b_immutable ).toVar();
  35022. return cond( b, t, f );
  35023. } ).setLayout( {
  35024. name: 'mx_select',
  35025. type: 'float',
  35026. inputs: [
  35027. { name: 'b', type: 'bool' },
  35028. { name: 't', type: 'float' },
  35029. { name: 'f', type: 'float' }
  35030. ]
  35031. } );
  35032. const mx_negate_if = /*#__PURE__*/ tslFn( ( [ val_immutable, b_immutable ] ) => {
  35033. const b = bool( b_immutable ).toVar();
  35034. const val = float( val_immutable ).toVar();
  35035. return cond( b, val.negate(), val );
  35036. } ).setLayout( {
  35037. name: 'mx_negate_if',
  35038. type: 'float',
  35039. inputs: [
  35040. { name: 'val', type: 'float' },
  35041. { name: 'b', type: 'bool' }
  35042. ]
  35043. } );
  35044. const mx_floor = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  35045. const x = float( x_immutable ).toVar();
  35046. return int( floor( x ) );
  35047. } ).setLayout( {
  35048. name: 'mx_floor',
  35049. type: 'int',
  35050. inputs: [
  35051. { name: 'x', type: 'float' }
  35052. ]
  35053. } );
  35054. const mx_floorfrac = /*#__PURE__*/ tslFn( ( [ x_immutable, i ] ) => {
  35055. const x = float( x_immutable ).toVar();
  35056. i.assign( mx_floor( x ) );
  35057. return x.sub( float( i ) );
  35058. } );
  35059. const mx_bilerp_0 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  35060. const t = float( t_immutable ).toVar();
  35061. const s = float( s_immutable ).toVar();
  35062. const v3 = float( v3_immutable ).toVar();
  35063. const v2 = float( v2_immutable ).toVar();
  35064. const v1 = float( v1_immutable ).toVar();
  35065. const v0 = float( v0_immutable ).toVar();
  35066. const s1 = float( sub( 1.0, s ) ).toVar();
  35067. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  35068. } ).setLayout( {
  35069. name: 'mx_bilerp_0',
  35070. type: 'float',
  35071. inputs: [
  35072. { name: 'v0', type: 'float' },
  35073. { name: 'v1', type: 'float' },
  35074. { name: 'v2', type: 'float' },
  35075. { name: 'v3', type: 'float' },
  35076. { name: 's', type: 'float' },
  35077. { name: 't', type: 'float' }
  35078. ]
  35079. } );
  35080. const mx_bilerp_1 = /*#__PURE__*/ tslFn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  35081. const t = float( t_immutable ).toVar();
  35082. const s = float( s_immutable ).toVar();
  35083. const v3 = vec3( v3_immutable ).toVar();
  35084. const v2 = vec3( v2_immutable ).toVar();
  35085. const v1 = vec3( v1_immutable ).toVar();
  35086. const v0 = vec3( v0_immutable ).toVar();
  35087. const s1 = float( sub( 1.0, s ) ).toVar();
  35088. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  35089. } ).setLayout( {
  35090. name: 'mx_bilerp_1',
  35091. type: 'vec3',
  35092. inputs: [
  35093. { name: 'v0', type: 'vec3' },
  35094. { name: 'v1', type: 'vec3' },
  35095. { name: 'v2', type: 'vec3' },
  35096. { name: 'v3', type: 'vec3' },
  35097. { name: 's', type: 'float' },
  35098. { name: 't', type: 'float' }
  35099. ]
  35100. } );
  35101. const mx_bilerp = /*#__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  35102. 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 ] ) => {
  35103. const r = float( r_immutable ).toVar();
  35104. const t = float( t_immutable ).toVar();
  35105. const s = float( s_immutable ).toVar();
  35106. const v7 = float( v7_immutable ).toVar();
  35107. const v6 = float( v6_immutable ).toVar();
  35108. const v5 = float( v5_immutable ).toVar();
  35109. const v4 = float( v4_immutable ).toVar();
  35110. const v3 = float( v3_immutable ).toVar();
  35111. const v2 = float( v2_immutable ).toVar();
  35112. const v1 = float( v1_immutable ).toVar();
  35113. const v0 = float( v0_immutable ).toVar();
  35114. const s1 = float( sub( 1.0, s ) ).toVar();
  35115. const t1 = float( sub( 1.0, t ) ).toVar();
  35116. const r1 = float( sub( 1.0, r ) ).toVar();
  35117. 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 ) ) ) ) ) );
  35118. } ).setLayout( {
  35119. name: 'mx_trilerp_0',
  35120. type: 'float',
  35121. inputs: [
  35122. { name: 'v0', type: 'float' },
  35123. { name: 'v1', type: 'float' },
  35124. { name: 'v2', type: 'float' },
  35125. { name: 'v3', type: 'float' },
  35126. { name: 'v4', type: 'float' },
  35127. { name: 'v5', type: 'float' },
  35128. { name: 'v6', type: 'float' },
  35129. { name: 'v7', type: 'float' },
  35130. { name: 's', type: 'float' },
  35131. { name: 't', type: 'float' },
  35132. { name: 'r', type: 'float' }
  35133. ]
  35134. } );
  35135. 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 ] ) => {
  35136. const r = float( r_immutable ).toVar();
  35137. const t = float( t_immutable ).toVar();
  35138. const s = float( s_immutable ).toVar();
  35139. const v7 = vec3( v7_immutable ).toVar();
  35140. const v6 = vec3( v6_immutable ).toVar();
  35141. const v5 = vec3( v5_immutable ).toVar();
  35142. const v4 = vec3( v4_immutable ).toVar();
  35143. const v3 = vec3( v3_immutable ).toVar();
  35144. const v2 = vec3( v2_immutable ).toVar();
  35145. const v1 = vec3( v1_immutable ).toVar();
  35146. const v0 = vec3( v0_immutable ).toVar();
  35147. const s1 = float( sub( 1.0, s ) ).toVar();
  35148. const t1 = float( sub( 1.0, t ) ).toVar();
  35149. const r1 = float( sub( 1.0, r ) ).toVar();
  35150. 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 ) ) ) ) ) );
  35151. } ).setLayout( {
  35152. name: 'mx_trilerp_1',
  35153. type: 'vec3',
  35154. inputs: [
  35155. { name: 'v0', type: 'vec3' },
  35156. { name: 'v1', type: 'vec3' },
  35157. { name: 'v2', type: 'vec3' },
  35158. { name: 'v3', type: 'vec3' },
  35159. { name: 'v4', type: 'vec3' },
  35160. { name: 'v5', type: 'vec3' },
  35161. { name: 'v6', type: 'vec3' },
  35162. { name: 'v7', type: 'vec3' },
  35163. { name: 's', type: 'float' },
  35164. { name: 't', type: 'float' },
  35165. { name: 'r', type: 'float' }
  35166. ]
  35167. } );
  35168. const mx_trilerp = /*#__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  35169. const mx_gradient_float_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35170. const y = float( y_immutable ).toVar();
  35171. const x = float( x_immutable ).toVar();
  35172. const hash = uint( hash_immutable ).toVar();
  35173. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  35174. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  35175. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  35176. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35177. } ).setLayout( {
  35178. name: 'mx_gradient_float_0',
  35179. type: 'float',
  35180. inputs: [
  35181. { name: 'hash', type: 'uint' },
  35182. { name: 'x', type: 'float' },
  35183. { name: 'y', type: 'float' }
  35184. ]
  35185. } );
  35186. const mx_gradient_float_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35187. const z = float( z_immutable ).toVar();
  35188. const y = float( y_immutable ).toVar();
  35189. const x = float( x_immutable ).toVar();
  35190. const hash = uint( hash_immutable ).toVar();
  35191. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  35192. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  35193. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  35194. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35195. } ).setLayout( {
  35196. name: 'mx_gradient_float_1',
  35197. type: 'float',
  35198. inputs: [
  35199. { name: 'hash', type: 'uint' },
  35200. { name: 'x', type: 'float' },
  35201. { name: 'y', type: 'float' },
  35202. { name: 'z', type: 'float' }
  35203. ]
  35204. } );
  35205. const mx_gradient_float = /*#__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  35206. const mx_gradient_vec3_0 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35207. const y = float( y_immutable ).toVar();
  35208. const x = float( x_immutable ).toVar();
  35209. const hash = uvec3( hash_immutable ).toVar();
  35210. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  35211. } ).setLayout( {
  35212. name: 'mx_gradient_vec3_0',
  35213. type: 'vec3',
  35214. inputs: [
  35215. { name: 'hash', type: 'uvec3' },
  35216. { name: 'x', type: 'float' },
  35217. { name: 'y', type: 'float' }
  35218. ]
  35219. } );
  35220. const mx_gradient_vec3_1 = /*#__PURE__*/ tslFn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35221. const z = float( z_immutable ).toVar();
  35222. const y = float( y_immutable ).toVar();
  35223. const x = float( x_immutable ).toVar();
  35224. const hash = uvec3( hash_immutable ).toVar();
  35225. 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 ) );
  35226. } ).setLayout( {
  35227. name: 'mx_gradient_vec3_1',
  35228. type: 'vec3',
  35229. inputs: [
  35230. { name: 'hash', type: 'uvec3' },
  35231. { name: 'x', type: 'float' },
  35232. { name: 'y', type: 'float' },
  35233. { name: 'z', type: 'float' }
  35234. ]
  35235. } );
  35236. const mx_gradient_vec3 = /*#__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  35237. const mx_gradient_scale2d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35238. const v = float( v_immutable ).toVar();
  35239. return mul( 0.6616, v );
  35240. } ).setLayout( {
  35241. name: 'mx_gradient_scale2d_0',
  35242. type: 'float',
  35243. inputs: [
  35244. { name: 'v', type: 'float' }
  35245. ]
  35246. } );
  35247. const mx_gradient_scale3d_0 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35248. const v = float( v_immutable ).toVar();
  35249. return mul( 0.9820, v );
  35250. } ).setLayout( {
  35251. name: 'mx_gradient_scale3d_0',
  35252. type: 'float',
  35253. inputs: [
  35254. { name: 'v', type: 'float' }
  35255. ]
  35256. } );
  35257. const mx_gradient_scale2d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35258. const v = vec3( v_immutable ).toVar();
  35259. return mul( 0.6616, v );
  35260. } ).setLayout( {
  35261. name: 'mx_gradient_scale2d_1',
  35262. type: 'vec3',
  35263. inputs: [
  35264. { name: 'v', type: 'vec3' }
  35265. ]
  35266. } );
  35267. const mx_gradient_scale2d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  35268. const mx_gradient_scale3d_1 = /*#__PURE__*/ tslFn( ( [ v_immutable ] ) => {
  35269. const v = vec3( v_immutable ).toVar();
  35270. return mul( 0.9820, v );
  35271. } ).setLayout( {
  35272. name: 'mx_gradient_scale3d_1',
  35273. type: 'vec3',
  35274. inputs: [
  35275. { name: 'v', type: 'vec3' }
  35276. ]
  35277. } );
  35278. const mx_gradient_scale3d = /*#__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  35279. const mx_rotl32 = /*#__PURE__*/ tslFn( ( [ x_immutable, k_immutable ] ) => {
  35280. const k = int( k_immutable ).toVar();
  35281. const x = uint( x_immutable ).toVar();
  35282. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  35283. } ).setLayout( {
  35284. name: 'mx_rotl32',
  35285. type: 'uint',
  35286. inputs: [
  35287. { name: 'x', type: 'uint' },
  35288. { name: 'k', type: 'int' }
  35289. ]
  35290. } );
  35291. const mx_bjmix = /*#__PURE__*/ tslFn( ( [ a, b, c ] ) => {
  35292. a.subAssign( c );
  35293. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  35294. c.addAssign( b );
  35295. b.subAssign( a );
  35296. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  35297. a.addAssign( c );
  35298. c.subAssign( b );
  35299. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  35300. b.addAssign( a );
  35301. a.subAssign( c );
  35302. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  35303. c.addAssign( b );
  35304. b.subAssign( a );
  35305. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  35306. a.addAssign( c );
  35307. c.subAssign( b );
  35308. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  35309. b.addAssign( a );
  35310. } );
  35311. const mx_bjfinal = /*#__PURE__*/ tslFn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  35312. const c = uint( c_immutable ).toVar();
  35313. const b = uint( b_immutable ).toVar();
  35314. const a = uint( a_immutable ).toVar();
  35315. c.bitXorAssign( b );
  35316. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  35317. a.bitXorAssign( c );
  35318. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  35319. b.bitXorAssign( a );
  35320. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  35321. c.bitXorAssign( b );
  35322. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  35323. a.bitXorAssign( c );
  35324. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  35325. b.bitXorAssign( a );
  35326. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  35327. c.bitXorAssign( b );
  35328. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  35329. return c;
  35330. } ).setLayout( {
  35331. name: 'mx_bjfinal',
  35332. type: 'uint',
  35333. inputs: [
  35334. { name: 'a', type: 'uint' },
  35335. { name: 'b', type: 'uint' },
  35336. { name: 'c', type: 'uint' }
  35337. ]
  35338. } );
  35339. const mx_bits_to_01 = /*#__PURE__*/ tslFn( ( [ bits_immutable ] ) => {
  35340. const bits = uint( bits_immutable ).toVar();
  35341. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  35342. } ).setLayout( {
  35343. name: 'mx_bits_to_01',
  35344. type: 'float',
  35345. inputs: [
  35346. { name: 'bits', type: 'uint' }
  35347. ]
  35348. } );
  35349. const mx_fade = /*#__PURE__*/ tslFn( ( [ t_immutable ] ) => {
  35350. const t = float( t_immutable ).toVar();
  35351. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  35352. } ).setLayout( {
  35353. name: 'mx_fade',
  35354. type: 'float',
  35355. inputs: [
  35356. { name: 't', type: 'float' }
  35357. ]
  35358. } );
  35359. const mx_hash_int_0 = /*#__PURE__*/ tslFn( ( [ x_immutable ] ) => {
  35360. const x = int( x_immutable ).toVar();
  35361. const len = uint( uint( 1 ) ).toVar();
  35362. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  35363. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  35364. } ).setLayout( {
  35365. name: 'mx_hash_int_0',
  35366. type: 'uint',
  35367. inputs: [
  35368. { name: 'x', type: 'int' }
  35369. ]
  35370. } );
  35371. const mx_hash_int_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35372. const y = int( y_immutable ).toVar();
  35373. const x = int( x_immutable ).toVar();
  35374. const len = uint( uint( 2 ) ).toVar();
  35375. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35376. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35377. a.addAssign( uint( x ) );
  35378. b.addAssign( uint( y ) );
  35379. return mx_bjfinal( a, b, c );
  35380. } ).setLayout( {
  35381. name: 'mx_hash_int_1',
  35382. type: 'uint',
  35383. inputs: [
  35384. { name: 'x', type: 'int' },
  35385. { name: 'y', type: 'int' }
  35386. ]
  35387. } );
  35388. const mx_hash_int_2 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35389. const z = int( z_immutable ).toVar();
  35390. const y = int( y_immutable ).toVar();
  35391. const x = int( x_immutable ).toVar();
  35392. const len = uint( uint( 3 ) ).toVar();
  35393. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35394. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35395. a.addAssign( uint( x ) );
  35396. b.addAssign( uint( y ) );
  35397. c.addAssign( uint( z ) );
  35398. return mx_bjfinal( a, b, c );
  35399. } ).setLayout( {
  35400. name: 'mx_hash_int_2',
  35401. type: 'uint',
  35402. inputs: [
  35403. { name: 'x', type: 'int' },
  35404. { name: 'y', type: 'int' },
  35405. { name: 'z', type: 'int' }
  35406. ]
  35407. } );
  35408. const mx_hash_int_3 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  35409. const xx = int( xx_immutable ).toVar();
  35410. const z = int( z_immutable ).toVar();
  35411. const y = int( y_immutable ).toVar();
  35412. const x = int( x_immutable ).toVar();
  35413. const len = uint( uint( 4 ) ).toVar();
  35414. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35415. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35416. a.addAssign( uint( x ) );
  35417. b.addAssign( uint( y ) );
  35418. c.addAssign( uint( z ) );
  35419. mx_bjmix( a, b, c );
  35420. a.addAssign( uint( xx ) );
  35421. return mx_bjfinal( a, b, c );
  35422. } ).setLayout( {
  35423. name: 'mx_hash_int_3',
  35424. type: 'uint',
  35425. inputs: [
  35426. { name: 'x', type: 'int' },
  35427. { name: 'y', type: 'int' },
  35428. { name: 'z', type: 'int' },
  35429. { name: 'xx', type: 'int' }
  35430. ]
  35431. } );
  35432. const mx_hash_int_4 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  35433. const yy = int( yy_immutable ).toVar();
  35434. const xx = int( xx_immutable ).toVar();
  35435. const z = int( z_immutable ).toVar();
  35436. const y = int( y_immutable ).toVar();
  35437. const x = int( x_immutable ).toVar();
  35438. const len = uint( uint( 5 ) ).toVar();
  35439. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35440. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35441. a.addAssign( uint( x ) );
  35442. b.addAssign( uint( y ) );
  35443. c.addAssign( uint( z ) );
  35444. mx_bjmix( a, b, c );
  35445. a.addAssign( uint( xx ) );
  35446. b.addAssign( uint( yy ) );
  35447. return mx_bjfinal( a, b, c );
  35448. } ).setLayout( {
  35449. name: 'mx_hash_int_4',
  35450. type: 'uint',
  35451. inputs: [
  35452. { name: 'x', type: 'int' },
  35453. { name: 'y', type: 'int' },
  35454. { name: 'z', type: 'int' },
  35455. { name: 'xx', type: 'int' },
  35456. { name: 'yy', type: 'int' }
  35457. ]
  35458. } );
  35459. 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 ] );
  35460. const mx_hash_vec3_0 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable ] ) => {
  35461. const y = int( y_immutable ).toVar();
  35462. const x = int( x_immutable ).toVar();
  35463. const h = uint( mx_hash_int( x, y ) ).toVar();
  35464. const result = uvec3().toVar();
  35465. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35466. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35467. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35468. return result;
  35469. } ).setLayout( {
  35470. name: 'mx_hash_vec3_0',
  35471. type: 'uvec3',
  35472. inputs: [
  35473. { name: 'x', type: 'int' },
  35474. { name: 'y', type: 'int' }
  35475. ]
  35476. } );
  35477. const mx_hash_vec3_1 = /*#__PURE__*/ tslFn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35478. const z = int( z_immutable ).toVar();
  35479. const y = int( y_immutable ).toVar();
  35480. const x = int( x_immutable ).toVar();
  35481. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  35482. const result = uvec3().toVar();
  35483. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35484. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35485. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35486. return result;
  35487. } ).setLayout( {
  35488. name: 'mx_hash_vec3_1',
  35489. type: 'uvec3',
  35490. inputs: [
  35491. { name: 'x', type: 'int' },
  35492. { name: 'y', type: 'int' },
  35493. { name: 'z', type: 'int' }
  35494. ]
  35495. } );
  35496. const mx_hash_vec3 = /*#__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  35497. const mx_perlin_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35498. const p = vec2( p_immutable ).toVar();
  35499. const X = int().toVar(), Y = int().toVar();
  35500. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35501. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35502. const u = float( mx_fade( fx ) ).toVar();
  35503. const v = float( mx_fade( fy ) ).toVar();
  35504. 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();
  35505. return mx_gradient_scale2d( result );
  35506. } ).setLayout( {
  35507. name: 'mx_perlin_noise_float_0',
  35508. type: 'float',
  35509. inputs: [
  35510. { name: 'p', type: 'vec2' }
  35511. ]
  35512. } );
  35513. const mx_perlin_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35514. const p = vec3( p_immutable ).toVar();
  35515. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35516. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35517. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35518. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35519. const u = float( mx_fade( fx ) ).toVar();
  35520. const v = float( mx_fade( fy ) ).toVar();
  35521. const w = float( mx_fade( fz ) ).toVar();
  35522. 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();
  35523. return mx_gradient_scale3d( result );
  35524. } ).setLayout( {
  35525. name: 'mx_perlin_noise_float_1',
  35526. type: 'float',
  35527. inputs: [
  35528. { name: 'p', type: 'vec3' }
  35529. ]
  35530. } );
  35531. const mx_perlin_noise_float = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  35532. const mx_perlin_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35533. const p = vec2( p_immutable ).toVar();
  35534. const X = int().toVar(), Y = int().toVar();
  35535. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35536. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35537. const u = float( mx_fade( fx ) ).toVar();
  35538. const v = float( mx_fade( fy ) ).toVar();
  35539. 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();
  35540. return mx_gradient_scale2d( result );
  35541. } ).setLayout( {
  35542. name: 'mx_perlin_noise_vec3_0',
  35543. type: 'vec3',
  35544. inputs: [
  35545. { name: 'p', type: 'vec2' }
  35546. ]
  35547. } );
  35548. const mx_perlin_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35549. const p = vec3( p_immutable ).toVar();
  35550. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35551. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35552. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35553. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35554. const u = float( mx_fade( fx ) ).toVar();
  35555. const v = float( mx_fade( fy ) ).toVar();
  35556. const w = float( mx_fade( fz ) ).toVar();
  35557. 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();
  35558. return mx_gradient_scale3d( result );
  35559. } ).setLayout( {
  35560. name: 'mx_perlin_noise_vec3_1',
  35561. type: 'vec3',
  35562. inputs: [
  35563. { name: 'p', type: 'vec3' }
  35564. ]
  35565. } );
  35566. const mx_perlin_noise_vec3 = /*#__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  35567. const mx_cell_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35568. const p = float( p_immutable ).toVar();
  35569. const ix = int( mx_floor( p ) ).toVar();
  35570. return mx_bits_to_01( mx_hash_int( ix ) );
  35571. } ).setLayout( {
  35572. name: 'mx_cell_noise_float_0',
  35573. type: 'float',
  35574. inputs: [
  35575. { name: 'p', type: 'float' }
  35576. ]
  35577. } );
  35578. const mx_cell_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35579. const p = vec2( p_immutable ).toVar();
  35580. const ix = int( mx_floor( p.x ) ).toVar();
  35581. const iy = int( mx_floor( p.y ) ).toVar();
  35582. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  35583. } ).setLayout( {
  35584. name: 'mx_cell_noise_float_1',
  35585. type: 'float',
  35586. inputs: [
  35587. { name: 'p', type: 'vec2' }
  35588. ]
  35589. } );
  35590. const mx_cell_noise_float_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35591. const p = vec3( p_immutable ).toVar();
  35592. const ix = int( mx_floor( p.x ) ).toVar();
  35593. const iy = int( mx_floor( p.y ) ).toVar();
  35594. const iz = int( mx_floor( p.z ) ).toVar();
  35595. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  35596. } ).setLayout( {
  35597. name: 'mx_cell_noise_float_2',
  35598. type: 'float',
  35599. inputs: [
  35600. { name: 'p', type: 'vec3' }
  35601. ]
  35602. } );
  35603. const mx_cell_noise_float_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35604. const p = vec4( p_immutable ).toVar();
  35605. const ix = int( mx_floor( p.x ) ).toVar();
  35606. const iy = int( mx_floor( p.y ) ).toVar();
  35607. const iz = int( mx_floor( p.z ) ).toVar();
  35608. const iw = int( mx_floor( p.w ) ).toVar();
  35609. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  35610. } ).setLayout( {
  35611. name: 'mx_cell_noise_float_3',
  35612. type: 'float',
  35613. inputs: [
  35614. { name: 'p', type: 'vec4' }
  35615. ]
  35616. } );
  35617. 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 ] );
  35618. const mx_cell_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35619. const p = float( p_immutable ).toVar();
  35620. const ix = int( mx_floor( p ) ).toVar();
  35621. 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 ) ) ) );
  35622. } ).setLayout( {
  35623. name: 'mx_cell_noise_vec3_0',
  35624. type: 'vec3',
  35625. inputs: [
  35626. { name: 'p', type: 'float' }
  35627. ]
  35628. } );
  35629. const mx_cell_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35630. const p = vec2( p_immutable ).toVar();
  35631. const ix = int( mx_floor( p.x ) ).toVar();
  35632. const iy = int( mx_floor( p.y ) ).toVar();
  35633. 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 ) ) ) );
  35634. } ).setLayout( {
  35635. name: 'mx_cell_noise_vec3_1',
  35636. type: 'vec3',
  35637. inputs: [
  35638. { name: 'p', type: 'vec2' }
  35639. ]
  35640. } );
  35641. const mx_cell_noise_vec3_2 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35642. const p = vec3( p_immutable ).toVar();
  35643. const ix = int( mx_floor( p.x ) ).toVar();
  35644. const iy = int( mx_floor( p.y ) ).toVar();
  35645. const iz = int( mx_floor( p.z ) ).toVar();
  35646. 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 ) ) ) );
  35647. } ).setLayout( {
  35648. name: 'mx_cell_noise_vec3_2',
  35649. type: 'vec3',
  35650. inputs: [
  35651. { name: 'p', type: 'vec3' }
  35652. ]
  35653. } );
  35654. const mx_cell_noise_vec3_3 = /*#__PURE__*/ tslFn( ( [ p_immutable ] ) => {
  35655. const p = vec4( p_immutable ).toVar();
  35656. const ix = int( mx_floor( p.x ) ).toVar();
  35657. const iy = int( mx_floor( p.y ) ).toVar();
  35658. const iz = int( mx_floor( p.z ) ).toVar();
  35659. const iw = int( mx_floor( p.w ) ).toVar();
  35660. 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 ) ) ) );
  35661. } ).setLayout( {
  35662. name: 'mx_cell_noise_vec3_3',
  35663. type: 'vec3',
  35664. inputs: [
  35665. { name: 'p', type: 'vec4' }
  35666. ]
  35667. } );
  35668. 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 ] );
  35669. const mx_fractal_noise_float$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35670. const diminish = float( diminish_immutable ).toVar();
  35671. const lacunarity = float( lacunarity_immutable ).toVar();
  35672. const octaves = int( octaves_immutable ).toVar();
  35673. const p = vec3( p_immutable ).toVar();
  35674. const result = float( 0.0 ).toVar();
  35675. const amplitude = float( 1.0 ).toVar();
  35676. loop( octaves, () => {
  35677. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  35678. amplitude.mulAssign( diminish );
  35679. p.mulAssign( lacunarity );
  35680. } );
  35681. return result;
  35682. } ).setLayout( {
  35683. name: 'mx_fractal_noise_float',
  35684. type: 'float',
  35685. inputs: [
  35686. { name: 'p', type: 'vec3' },
  35687. { name: 'octaves', type: 'int' },
  35688. { name: 'lacunarity', type: 'float' },
  35689. { name: 'diminish', type: 'float' }
  35690. ]
  35691. } );
  35692. const mx_fractal_noise_vec3$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35693. const diminish = float( diminish_immutable ).toVar();
  35694. const lacunarity = float( lacunarity_immutable ).toVar();
  35695. const octaves = int( octaves_immutable ).toVar();
  35696. const p = vec3( p_immutable ).toVar();
  35697. const result = vec3( 0.0 ).toVar();
  35698. const amplitude = float( 1.0 ).toVar();
  35699. loop( octaves, () => {
  35700. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  35701. amplitude.mulAssign( diminish );
  35702. p.mulAssign( lacunarity );
  35703. } );
  35704. return result;
  35705. } ).setLayout( {
  35706. name: 'mx_fractal_noise_vec3',
  35707. type: 'vec3',
  35708. inputs: [
  35709. { name: 'p', type: 'vec3' },
  35710. { name: 'octaves', type: 'int' },
  35711. { name: 'lacunarity', type: 'float' },
  35712. { name: 'diminish', type: 'float' }
  35713. ]
  35714. } );
  35715. const mx_fractal_noise_vec2$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35716. const diminish = float( diminish_immutable ).toVar();
  35717. const lacunarity = float( lacunarity_immutable ).toVar();
  35718. const octaves = int( octaves_immutable ).toVar();
  35719. const p = vec3( p_immutable ).toVar();
  35720. 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 ) );
  35721. } ).setLayout( {
  35722. name: 'mx_fractal_noise_vec2',
  35723. type: 'vec2',
  35724. inputs: [
  35725. { name: 'p', type: 'vec3' },
  35726. { name: 'octaves', type: 'int' },
  35727. { name: 'lacunarity', type: 'float' },
  35728. { name: 'diminish', type: 'float' }
  35729. ]
  35730. } );
  35731. const mx_fractal_noise_vec4$1 = /*#__PURE__*/ tslFn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35732. const diminish = float( diminish_immutable ).toVar();
  35733. const lacunarity = float( lacunarity_immutable ).toVar();
  35734. const octaves = int( octaves_immutable ).toVar();
  35735. const p = vec3( p_immutable ).toVar();
  35736. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  35737. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  35738. return vec4( c, f );
  35739. } ).setLayout( {
  35740. name: 'mx_fractal_noise_vec4',
  35741. type: 'vec4',
  35742. inputs: [
  35743. { name: 'p', type: 'vec3' },
  35744. { name: 'octaves', type: 'int' },
  35745. { name: 'lacunarity', type: 'float' },
  35746. { name: 'diminish', type: 'float' }
  35747. ]
  35748. } );
  35749. const mx_worley_distance_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35750. const metric = int( metric_immutable ).toVar();
  35751. const jitter = float( jitter_immutable ).toVar();
  35752. const yoff = int( yoff_immutable ).toVar();
  35753. const xoff = int( xoff_immutable ).toVar();
  35754. const y = int( y_immutable ).toVar();
  35755. const x = int( x_immutable ).toVar();
  35756. const p = vec2( p_immutable ).toVar();
  35757. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  35758. const off = vec2( tmp.x, tmp.y ).toVar();
  35759. off.subAssign( 0.5 );
  35760. off.mulAssign( jitter );
  35761. off.addAssign( 0.5 );
  35762. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  35763. const diff = vec2( cellpos.sub( p ) ).toVar();
  35764. If( metric.equal( int( 2 ) ), () => {
  35765. return abs( diff.x ).add( abs( diff.y ) );
  35766. } );
  35767. If( metric.equal( int( 3 ) ), () => {
  35768. return max$1( abs( diff.x ), abs( diff.y ) );
  35769. } );
  35770. return dot( diff, diff );
  35771. } ).setLayout( {
  35772. name: 'mx_worley_distance_0',
  35773. type: 'float',
  35774. inputs: [
  35775. { name: 'p', type: 'vec2' },
  35776. { name: 'x', type: 'int' },
  35777. { name: 'y', type: 'int' },
  35778. { name: 'xoff', type: 'int' },
  35779. { name: 'yoff', type: 'int' },
  35780. { name: 'jitter', type: 'float' },
  35781. { name: 'metric', type: 'int' }
  35782. ]
  35783. } );
  35784. 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 ] ) => {
  35785. const metric = int( metric_immutable ).toVar();
  35786. const jitter = float( jitter_immutable ).toVar();
  35787. const zoff = int( zoff_immutable ).toVar();
  35788. const yoff = int( yoff_immutable ).toVar();
  35789. const xoff = int( xoff_immutable ).toVar();
  35790. const z = int( z_immutable ).toVar();
  35791. const y = int( y_immutable ).toVar();
  35792. const x = int( x_immutable ).toVar();
  35793. const p = vec3( p_immutable ).toVar();
  35794. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  35795. off.subAssign( 0.5 );
  35796. off.mulAssign( jitter );
  35797. off.addAssign( 0.5 );
  35798. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  35799. const diff = vec3( cellpos.sub( p ) ).toVar();
  35800. If( metric.equal( int( 2 ) ), () => {
  35801. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  35802. } );
  35803. If( metric.equal( int( 3 ) ), () => {
  35804. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  35805. } );
  35806. return dot( diff, diff );
  35807. } ).setLayout( {
  35808. name: 'mx_worley_distance_1',
  35809. type: 'float',
  35810. inputs: [
  35811. { name: 'p', type: 'vec3' },
  35812. { name: 'x', type: 'int' },
  35813. { name: 'y', type: 'int' },
  35814. { name: 'z', type: 'int' },
  35815. { name: 'xoff', type: 'int' },
  35816. { name: 'yoff', type: 'int' },
  35817. { name: 'zoff', type: 'int' },
  35818. { name: 'jitter', type: 'float' },
  35819. { name: 'metric', type: 'int' }
  35820. ]
  35821. } );
  35822. const mx_worley_distance = /*#__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  35823. const mx_worley_noise_float_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35824. const metric = int( metric_immutable ).toVar();
  35825. const jitter = float( jitter_immutable ).toVar();
  35826. const p = vec2( p_immutable ).toVar();
  35827. const X = int().toVar(), Y = int().toVar();
  35828. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35829. const sqdist = float( 1e6 ).toVar();
  35830. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35831. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35832. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35833. sqdist.assign( min$1( sqdist, dist ) );
  35834. } );
  35835. } );
  35836. If( metric.equal( int( 0 ) ), () => {
  35837. sqdist.assign( sqrt( sqdist ) );
  35838. } );
  35839. return sqdist;
  35840. } ).setLayout( {
  35841. name: 'mx_worley_noise_float_0',
  35842. type: 'float',
  35843. inputs: [
  35844. { name: 'p', type: 'vec2' },
  35845. { name: 'jitter', type: 'float' },
  35846. { name: 'metric', type: 'int' }
  35847. ]
  35848. } );
  35849. const mx_worley_noise_vec2_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35850. const metric = int( metric_immutable ).toVar();
  35851. const jitter = float( jitter_immutable ).toVar();
  35852. const p = vec2( p_immutable ).toVar();
  35853. const X = int().toVar(), Y = int().toVar();
  35854. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35855. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35856. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35857. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35858. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35859. If( dist.lessThan( sqdist.x ), () => {
  35860. sqdist.y.assign( sqdist.x );
  35861. sqdist.x.assign( dist );
  35862. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35863. sqdist.y.assign( dist );
  35864. } );
  35865. } );
  35866. } );
  35867. If( metric.equal( int( 0 ) ), () => {
  35868. sqdist.assign( sqrt( sqdist ) );
  35869. } );
  35870. return sqdist;
  35871. } ).setLayout( {
  35872. name: 'mx_worley_noise_vec2_0',
  35873. type: 'vec2',
  35874. inputs: [
  35875. { name: 'p', type: 'vec2' },
  35876. { name: 'jitter', type: 'float' },
  35877. { name: 'metric', type: 'int' }
  35878. ]
  35879. } );
  35880. const mx_worley_noise_vec3_0 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35881. const metric = int( metric_immutable ).toVar();
  35882. const jitter = float( jitter_immutable ).toVar();
  35883. const p = vec2( p_immutable ).toVar();
  35884. const X = int().toVar(), Y = int().toVar();
  35885. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35886. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35887. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35888. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35889. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35890. If( dist.lessThan( sqdist.x ), () => {
  35891. sqdist.z.assign( sqdist.y );
  35892. sqdist.y.assign( sqdist.x );
  35893. sqdist.x.assign( dist );
  35894. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35895. sqdist.z.assign( sqdist.y );
  35896. sqdist.y.assign( dist );
  35897. } ).elseif( dist.lessThan( sqdist.z ), () => {
  35898. sqdist.z.assign( dist );
  35899. } );
  35900. } );
  35901. } );
  35902. If( metric.equal( int( 0 ) ), () => {
  35903. sqdist.assign( sqrt( sqdist ) );
  35904. } );
  35905. return sqdist;
  35906. } ).setLayout( {
  35907. name: 'mx_worley_noise_vec3_0',
  35908. type: 'vec3',
  35909. inputs: [
  35910. { name: 'p', type: 'vec2' },
  35911. { name: 'jitter', type: 'float' },
  35912. { name: 'metric', type: 'int' }
  35913. ]
  35914. } );
  35915. const mx_worley_noise_float_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35916. const metric = int( metric_immutable ).toVar();
  35917. const jitter = float( jitter_immutable ).toVar();
  35918. const p = vec3( p_immutable ).toVar();
  35919. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35920. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35921. const sqdist = float( 1e6 ).toVar();
  35922. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35923. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35924. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35925. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35926. sqdist.assign( min$1( sqdist, dist ) );
  35927. } );
  35928. } );
  35929. } );
  35930. If( metric.equal( int( 0 ) ), () => {
  35931. sqdist.assign( sqrt( sqdist ) );
  35932. } );
  35933. return sqdist;
  35934. } ).setLayout( {
  35935. name: 'mx_worley_noise_float_1',
  35936. type: 'float',
  35937. inputs: [
  35938. { name: 'p', type: 'vec3' },
  35939. { name: 'jitter', type: 'float' },
  35940. { name: 'metric', type: 'int' }
  35941. ]
  35942. } );
  35943. const mx_worley_noise_float$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  35944. const mx_worley_noise_vec2_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35945. const metric = int( metric_immutable ).toVar();
  35946. const jitter = float( jitter_immutable ).toVar();
  35947. const p = vec3( p_immutable ).toVar();
  35948. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35949. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35950. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35951. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35952. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35953. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35954. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35955. If( dist.lessThan( sqdist.x ), () => {
  35956. sqdist.y.assign( sqdist.x );
  35957. sqdist.x.assign( dist );
  35958. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35959. sqdist.y.assign( dist );
  35960. } );
  35961. } );
  35962. } );
  35963. } );
  35964. If( metric.equal( int( 0 ) ), () => {
  35965. sqdist.assign( sqrt( sqdist ) );
  35966. } );
  35967. return sqdist;
  35968. } ).setLayout( {
  35969. name: 'mx_worley_noise_vec2_1',
  35970. type: 'vec2',
  35971. inputs: [
  35972. { name: 'p', type: 'vec3' },
  35973. { name: 'jitter', type: 'float' },
  35974. { name: 'metric', type: 'int' }
  35975. ]
  35976. } );
  35977. const mx_worley_noise_vec2$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  35978. const mx_worley_noise_vec3_1 = /*#__PURE__*/ tslFn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35979. const metric = int( metric_immutable ).toVar();
  35980. const jitter = float( jitter_immutable ).toVar();
  35981. const p = vec3( p_immutable ).toVar();
  35982. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35983. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35984. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35985. loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35986. loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35987. loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35988. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35989. If( dist.lessThan( sqdist.x ), () => {
  35990. sqdist.z.assign( sqdist.y );
  35991. sqdist.y.assign( sqdist.x );
  35992. sqdist.x.assign( dist );
  35993. } ).elseif( dist.lessThan( sqdist.y ), () => {
  35994. sqdist.z.assign( sqdist.y );
  35995. sqdist.y.assign( dist );
  35996. } ).elseif( dist.lessThan( sqdist.z ), () => {
  35997. sqdist.z.assign( dist );
  35998. } );
  35999. } );
  36000. } );
  36001. } );
  36002. If( metric.equal( int( 0 ) ), () => {
  36003. sqdist.assign( sqrt( sqdist ) );
  36004. } );
  36005. return sqdist;
  36006. } ).setLayout( {
  36007. name: 'mx_worley_noise_vec3_1',
  36008. type: 'vec3',
  36009. inputs: [
  36010. { name: 'p', type: 'vec3' },
  36011. { name: 'jitter', type: 'float' },
  36012. { name: 'metric', type: 'int' }
  36013. ]
  36014. } );
  36015. const mx_worley_noise_vec3$1 = /*#__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  36016. // Three.js Transpiler
  36017. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  36018. const mx_hsvtorgb = /*#__PURE__*/ tslFn( ( [ hsv_immutable ] ) => {
  36019. const hsv = vec3( hsv_immutable ).toVar();
  36020. const h = float( hsv.x ).toVar();
  36021. const s = float( hsv.y ).toVar();
  36022. const v = float( hsv.z ).toVar();
  36023. If( s.lessThan( 0.0001 ), () => {
  36024. return vec3( v, v, v );
  36025. } ).else( () => {
  36026. h.assign( mul( 6.0, h.sub( floor( h ) ) ) );
  36027. const hi = int( trunc( h ) ).toVar();
  36028. const f = float( h.sub( float( hi ) ) ).toVar();
  36029. const p = float( v.mul( sub( 1.0, s ) ) ).toVar();
  36030. const q = float( v.mul( sub( 1.0, s.mul( f ) ) ) ).toVar();
  36031. const t = float( v.mul( sub( 1.0, s.mul( sub( 1.0, f ) ) ) ) ).toVar();
  36032. If( hi.equal( int( 0 ) ), () => {
  36033. return vec3( v, t, p );
  36034. } ).elseif( hi.equal( int( 1 ) ), () => {
  36035. return vec3( q, v, p );
  36036. } ).elseif( hi.equal( int( 2 ) ), () => {
  36037. return vec3( p, v, t );
  36038. } ).elseif( hi.equal( int( 3 ) ), () => {
  36039. return vec3( p, q, v );
  36040. } ).elseif( hi.equal( int( 4 ) ), () => {
  36041. return vec3( t, p, v );
  36042. } );
  36043. return vec3( v, p, q );
  36044. } );
  36045. } ).setLayout( {
  36046. name: 'mx_hsvtorgb',
  36047. type: 'vec3',
  36048. inputs: [
  36049. { name: 'hsv', type: 'vec3' }
  36050. ]
  36051. } );
  36052. const mx_rgbtohsv = /*#__PURE__*/ tslFn( ( [ c_immutable ] ) => {
  36053. const c = vec3( c_immutable ).toVar();
  36054. const r = float( c.x ).toVar();
  36055. const g = float( c.y ).toVar();
  36056. const b = float( c.z ).toVar();
  36057. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  36058. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  36059. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  36060. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  36061. v.assign( maxcomp );
  36062. If( maxcomp.greaterThan( 0.0 ), () => {
  36063. s.assign( delta.div( maxcomp ) );
  36064. } ).else( () => {
  36065. s.assign( 0.0 );
  36066. } );
  36067. If( s.lessThanEqual( 0.0 ), () => {
  36068. h.assign( 0.0 );
  36069. } ).else( () => {
  36070. If( r.greaterThanEqual( maxcomp ), () => {
  36071. h.assign( g.sub( b ).div( delta ) );
  36072. } ).elseif( g.greaterThanEqual( maxcomp ), () => {
  36073. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  36074. } ).else( () => {
  36075. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  36076. } );
  36077. h.mulAssign( 1.0 / 6.0 );
  36078. If( h.lessThan( 0.0 ), () => {
  36079. h.addAssign( 1.0 );
  36080. } );
  36081. } );
  36082. return vec3( h, s, v );
  36083. } ).setLayout( {
  36084. name: 'mx_rgbtohsv',
  36085. type: 'vec3',
  36086. inputs: [
  36087. { name: 'c', type: 'vec3' }
  36088. ]
  36089. } );
  36090. // Three.js Transpiler
  36091. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  36092. const mx_srgb_texture_to_lin_rec709 = /*#__PURE__*/ tslFn( ( [ color_immutable ] ) => {
  36093. const color = vec3( color_immutable ).toVar();
  36094. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  36095. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  36096. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  36097. return mix( linSeg, powSeg, isAbove );
  36098. } ).setLayout( {
  36099. name: 'mx_srgb_texture_to_lin_rec709',
  36100. type: 'vec3',
  36101. inputs: [
  36102. { name: 'color', type: 'vec3' }
  36103. ]
  36104. } );
  36105. const mx_aastep = ( threshold, value ) => {
  36106. threshold = float( threshold );
  36107. value = float( value );
  36108. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  36109. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  36110. };
  36111. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  36112. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  36113. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  36114. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  36115. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  36116. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  36117. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  36118. const mx_safepower = ( in1, in2 = 1 ) => {
  36119. in1 = float( in1 );
  36120. return in1.abs().pow( in2 ).mul( in1.sign() );
  36121. };
  36122. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  36123. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36124. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36125. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36126. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  36127. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  36128. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  36129. return noise_vec4.mul( amplitude ).add( pivot );
  36130. };
  36131. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36132. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36133. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36134. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  36135. 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 );
  36136. 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 );
  36137. 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 );
  36138. 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 );
  36139. function painterSortStable( a, b ) {
  36140. if ( a.groupOrder !== b.groupOrder ) {
  36141. return a.groupOrder - b.groupOrder;
  36142. } else if ( a.renderOrder !== b.renderOrder ) {
  36143. return a.renderOrder - b.renderOrder;
  36144. } else if ( a.material.id !== b.material.id ) {
  36145. return a.material.id - b.material.id;
  36146. } else if ( a.z !== b.z ) {
  36147. return a.z - b.z;
  36148. } else {
  36149. return a.id - b.id;
  36150. }
  36151. }
  36152. function reversePainterSortStable( a, b ) {
  36153. if ( a.groupOrder !== b.groupOrder ) {
  36154. return a.groupOrder - b.groupOrder;
  36155. } else if ( a.renderOrder !== b.renderOrder ) {
  36156. return a.renderOrder - b.renderOrder;
  36157. } else if ( a.z !== b.z ) {
  36158. return b.z - a.z;
  36159. } else {
  36160. return a.id - b.id;
  36161. }
  36162. }
  36163. class RenderList {
  36164. constructor() {
  36165. this.renderItems = [];
  36166. this.renderItemsIndex = 0;
  36167. this.opaque = [];
  36168. this.transparent = [];
  36169. this.bundles = [];
  36170. this.lightsNode = new LightsNode( [] );
  36171. this.lightsArray = [];
  36172. this.occlusionQueryCount = 0;
  36173. }
  36174. begin() {
  36175. this.renderItemsIndex = 0;
  36176. this.opaque.length = 0;
  36177. this.transparent.length = 0;
  36178. this.bundles.length = 0;
  36179. this.lightsArray.length = 0;
  36180. this.occlusionQueryCount = 0;
  36181. return this;
  36182. }
  36183. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  36184. let renderItem = this.renderItems[ this.renderItemsIndex ];
  36185. if ( renderItem === undefined ) {
  36186. renderItem = {
  36187. id: object.id,
  36188. object: object,
  36189. geometry: geometry,
  36190. material: material,
  36191. groupOrder: groupOrder,
  36192. renderOrder: object.renderOrder,
  36193. z: z,
  36194. group: group
  36195. };
  36196. this.renderItems[ this.renderItemsIndex ] = renderItem;
  36197. } else {
  36198. renderItem.id = object.id;
  36199. renderItem.object = object;
  36200. renderItem.geometry = geometry;
  36201. renderItem.material = material;
  36202. renderItem.groupOrder = groupOrder;
  36203. renderItem.renderOrder = object.renderOrder;
  36204. renderItem.z = z;
  36205. renderItem.group = group;
  36206. }
  36207. this.renderItemsIndex ++;
  36208. return renderItem;
  36209. }
  36210. push( object, geometry, material, groupOrder, z, group ) {
  36211. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36212. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  36213. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  36214. }
  36215. unshift( object, geometry, material, groupOrder, z, group ) {
  36216. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36217. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  36218. }
  36219. pushBundle( group ) {
  36220. this.bundles.push( group );
  36221. }
  36222. pushLight( light ) {
  36223. this.lightsArray.push( light );
  36224. }
  36225. getLightsNode() {
  36226. return this.lightsNode.fromLights( this.lightsArray );
  36227. }
  36228. sort( customOpaqueSort, customTransparentSort ) {
  36229. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  36230. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  36231. }
  36232. finish() {
  36233. // update lights
  36234. this.lightsNode.fromLights( this.lightsArray );
  36235. // Clear references from inactive renderItems in the list
  36236. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  36237. const renderItem = this.renderItems[ i ];
  36238. if ( renderItem.id === null ) break;
  36239. renderItem.id = null;
  36240. renderItem.object = null;
  36241. renderItem.geometry = null;
  36242. renderItem.material = null;
  36243. renderItem.groupOrder = null;
  36244. renderItem.renderOrder = null;
  36245. renderItem.z = null;
  36246. renderItem.group = null;
  36247. }
  36248. }
  36249. }
  36250. class RenderLists {
  36251. constructor() {
  36252. this.lists = new ChainMap();
  36253. }
  36254. get( scene, camera ) {
  36255. const lists = this.lists;
  36256. const keys = [ scene, camera ];
  36257. let list = lists.get( keys );
  36258. if ( list === undefined ) {
  36259. list = new RenderList();
  36260. lists.set( keys, list );
  36261. }
  36262. return list;
  36263. }
  36264. dispose() {
  36265. this.lists = new ChainMap();
  36266. }
  36267. }
  36268. let id = 0;
  36269. class RenderContext {
  36270. constructor() {
  36271. this.id = id ++;
  36272. this.color = true;
  36273. this.clearColor = true;
  36274. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  36275. this.depth = true;
  36276. this.clearDepth = true;
  36277. this.clearDepthValue = 1;
  36278. this.stencil = false;
  36279. this.clearStencil = true;
  36280. this.clearStencilValue = 1;
  36281. this.viewport = false;
  36282. this.viewportValue = new Vector4();
  36283. this.scissor = false;
  36284. this.scissorValue = new Vector4();
  36285. this.textures = null;
  36286. this.depthTexture = null;
  36287. this.activeCubeFace = 0;
  36288. this.sampleCount = 1;
  36289. this.width = 0;
  36290. this.height = 0;
  36291. this.isRenderContext = true;
  36292. }
  36293. }
  36294. class RenderContexts {
  36295. constructor() {
  36296. this.chainMaps = {};
  36297. }
  36298. get( scene, camera, renderTarget = null ) {
  36299. const chainKey = [ scene, camera ];
  36300. let attachmentState;
  36301. if ( renderTarget === null ) {
  36302. attachmentState = 'default';
  36303. } else {
  36304. const format = renderTarget.texture.format;
  36305. const count = renderTarget.textures.length;
  36306. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  36307. }
  36308. const chainMap = this.getChainMap( attachmentState );
  36309. let renderState = chainMap.get( chainKey );
  36310. if ( renderState === undefined ) {
  36311. renderState = new RenderContext();
  36312. chainMap.set( chainKey, renderState );
  36313. }
  36314. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36315. return renderState;
  36316. }
  36317. getChainMap( attachmentState ) {
  36318. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  36319. }
  36320. dispose() {
  36321. this.chainMaps = {};
  36322. }
  36323. }
  36324. const _size = /*@__PURE__*/ new Vector3();
  36325. class Textures extends DataMap {
  36326. constructor( renderer, backend, info ) {
  36327. super();
  36328. this.renderer = renderer;
  36329. this.backend = backend;
  36330. this.info = info;
  36331. }
  36332. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  36333. const renderTargetData = this.get( renderTarget );
  36334. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36335. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  36336. const texture = renderTarget.texture;
  36337. const textures = renderTarget.textures;
  36338. const size = this.getSize( texture );
  36339. const mipWidth = size.width >> activeMipmapLevel;
  36340. const mipHeight = size.height >> activeMipmapLevel;
  36341. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  36342. let textureNeedsUpdate = false;
  36343. if ( depthTexture === undefined ) {
  36344. depthTexture = new DepthTexture();
  36345. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  36346. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  36347. depthTexture.image.width = mipWidth;
  36348. depthTexture.image.height = mipHeight;
  36349. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  36350. }
  36351. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  36352. textureNeedsUpdate = true;
  36353. depthTexture.needsUpdate = true;
  36354. depthTexture.image.width = mipWidth;
  36355. depthTexture.image.height = mipHeight;
  36356. }
  36357. renderTargetData.width = size.width;
  36358. renderTargetData.height = size.height;
  36359. renderTargetData.textures = textures;
  36360. renderTargetData.depthTexture = depthTexture;
  36361. renderTargetData.depth = renderTarget.depthBuffer;
  36362. renderTargetData.stencil = renderTarget.stencilBuffer;
  36363. renderTargetData.renderTarget = renderTarget;
  36364. if ( renderTargetData.sampleCount !== sampleCount ) {
  36365. textureNeedsUpdate = true;
  36366. depthTexture.needsUpdate = true;
  36367. renderTargetData.sampleCount = sampleCount;
  36368. }
  36369. //
  36370. const options = { sampleCount };
  36371. for ( let i = 0; i < textures.length; i ++ ) {
  36372. const texture = textures[ i ];
  36373. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  36374. this.updateTexture( texture, options );
  36375. }
  36376. this.updateTexture( depthTexture, options );
  36377. // dispose handler
  36378. if ( renderTargetData.initialized !== true ) {
  36379. renderTargetData.initialized = true;
  36380. // dispose
  36381. const onDispose = () => {
  36382. renderTarget.removeEventListener( 'dispose', onDispose );
  36383. if ( textures !== undefined ) {
  36384. for ( let i = 0; i < textures.length; i ++ ) {
  36385. this._destroyTexture( textures[ i ] );
  36386. }
  36387. } else {
  36388. this._destroyTexture( texture );
  36389. }
  36390. this._destroyTexture( depthTexture );
  36391. this.delete( renderTarget );
  36392. };
  36393. renderTarget.addEventListener( 'dispose', onDispose );
  36394. }
  36395. }
  36396. updateTexture( texture, options = {} ) {
  36397. const textureData = this.get( texture );
  36398. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  36399. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  36400. const backend = this.backend;
  36401. if ( isRenderTarget && textureData.initialized === true ) {
  36402. // it's an update
  36403. backend.destroySampler( texture );
  36404. backend.destroyTexture( texture );
  36405. }
  36406. //
  36407. if ( texture.isFramebufferTexture ) {
  36408. const renderer = this.renderer;
  36409. const renderTarget = renderer.getRenderTarget();
  36410. if ( renderTarget ) {
  36411. texture.type = renderTarget.texture.type;
  36412. } else {
  36413. texture.type = UnsignedByteType;
  36414. }
  36415. }
  36416. //
  36417. const { width, height, depth } = this.getSize( texture );
  36418. options.width = width;
  36419. options.height = height;
  36420. options.depth = depth;
  36421. options.needsMipmaps = this.needsMipmaps( texture );
  36422. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  36423. //
  36424. if ( isRenderTarget || texture.isStorageTexture === true ) {
  36425. backend.createSampler( texture );
  36426. backend.createTexture( texture, options );
  36427. } else {
  36428. const needsCreate = textureData.initialized !== true;
  36429. if ( needsCreate ) backend.createSampler( texture );
  36430. if ( texture.version > 0 ) {
  36431. const image = texture.image;
  36432. if ( image === undefined ) {
  36433. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  36434. } else if ( image.complete === false ) {
  36435. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  36436. } else {
  36437. if ( texture.images ) {
  36438. const images = [];
  36439. for ( const image of texture.images ) {
  36440. images.push( image );
  36441. }
  36442. options.images = images;
  36443. } else {
  36444. options.image = image;
  36445. }
  36446. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  36447. backend.createTexture( texture, options );
  36448. textureData.isDefaultTexture = false;
  36449. }
  36450. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  36451. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  36452. }
  36453. } else {
  36454. // async update
  36455. backend.createDefaultTexture( texture );
  36456. textureData.isDefaultTexture = true;
  36457. }
  36458. }
  36459. // dispose handler
  36460. if ( textureData.initialized !== true ) {
  36461. textureData.initialized = true;
  36462. //
  36463. this.info.memory.textures ++;
  36464. // dispose
  36465. const onDispose = () => {
  36466. texture.removeEventListener( 'dispose', onDispose );
  36467. this._destroyTexture( texture );
  36468. this.info.memory.textures --;
  36469. };
  36470. texture.addEventListener( 'dispose', onDispose );
  36471. }
  36472. //
  36473. textureData.version = texture.version;
  36474. }
  36475. getSize( texture, target = _size ) {
  36476. let image = texture.images ? texture.images[ 0 ] : texture.image;
  36477. if ( image ) {
  36478. if ( image.image !== undefined ) image = image.image;
  36479. target.width = image.width;
  36480. target.height = image.height;
  36481. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  36482. } else {
  36483. target.width = target.height = target.depth = 1;
  36484. }
  36485. return target;
  36486. }
  36487. getMipLevels( texture, width, height ) {
  36488. let mipLevelCount;
  36489. if ( texture.isCompressedTexture ) {
  36490. mipLevelCount = texture.mipmaps.length;
  36491. } else {
  36492. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  36493. }
  36494. return mipLevelCount;
  36495. }
  36496. needsMipmaps( texture ) {
  36497. if ( this.isEnvironmentTexture( texture ) ) return true;
  36498. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  36499. }
  36500. isEnvironmentTexture( texture ) {
  36501. const mapping = texture.mapping;
  36502. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  36503. }
  36504. _destroyTexture( texture ) {
  36505. this.backend.destroySampler( texture );
  36506. this.backend.destroyTexture( texture );
  36507. this.delete( texture );
  36508. }
  36509. }
  36510. class Color4 extends Color {
  36511. constructor( r, g, b, a = 1 ) {
  36512. super( r, g, b );
  36513. this.a = a;
  36514. }
  36515. set( r, g, b, a = 1 ) {
  36516. this.a = a;
  36517. return super.set( r, g, b );
  36518. }
  36519. copy( color ) {
  36520. if ( color.a !== undefined ) this.a = color.a;
  36521. return super.copy( color );
  36522. }
  36523. clone() {
  36524. return new this.constructor( this.r, this.g, this.b, this.a );
  36525. }
  36526. }
  36527. const _clearColor = /*@__PURE__*/ new Color4();
  36528. class Background extends DataMap {
  36529. constructor( renderer, nodes ) {
  36530. super();
  36531. this.renderer = renderer;
  36532. this.nodes = nodes;
  36533. }
  36534. update( scene, renderList, renderContext ) {
  36535. const renderer = this.renderer;
  36536. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  36537. let forceClear = false;
  36538. if ( background === null ) {
  36539. // no background settings, use clear color configuration from the renderer
  36540. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  36541. _clearColor.a = renderer._clearColor.a;
  36542. } else if ( background.isColor === true ) {
  36543. // background is an opaque color
  36544. background.getRGB( _clearColor, LinearSRGBColorSpace );
  36545. _clearColor.a = 1;
  36546. forceClear = true;
  36547. } else if ( background.isNode === true ) {
  36548. const sceneData = this.get( scene );
  36549. const backgroundNode = background;
  36550. _clearColor.copy( renderer._clearColor );
  36551. let backgroundMesh = sceneData.backgroundMesh;
  36552. if ( backgroundMesh === undefined ) {
  36553. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  36554. // @TODO: Add Texture2D support using node context
  36555. getUV: () => normalWorld,
  36556. getTextureLevel: () => backgroundBlurriness
  36557. } );
  36558. let viewProj = modelViewProjection();
  36559. viewProj = viewProj.setZ( viewProj.w );
  36560. const nodeMaterial = new NodeMaterial();
  36561. nodeMaterial.name = 'Background.material';
  36562. nodeMaterial.side = BackSide;
  36563. nodeMaterial.depthTest = false;
  36564. nodeMaterial.depthWrite = false;
  36565. nodeMaterial.fog = false;
  36566. nodeMaterial.lights = false;
  36567. nodeMaterial.vertexNode = viewProj;
  36568. nodeMaterial.colorNode = backgroundMeshNode;
  36569. sceneData.backgroundMeshNode = backgroundMeshNode;
  36570. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  36571. backgroundMesh.frustumCulled = false;
  36572. backgroundMesh.name = 'Background.mesh';
  36573. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  36574. this.matrixWorld.copyPosition( camera.matrixWorld );
  36575. };
  36576. }
  36577. const backgroundCacheKey = backgroundNode.getCacheKey();
  36578. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  36579. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  36580. sceneData.backgroundMeshNode.needsUpdate = true;
  36581. backgroundMesh.material.needsUpdate = true;
  36582. sceneData.backgroundCacheKey = backgroundCacheKey;
  36583. }
  36584. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  36585. } else {
  36586. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  36587. }
  36588. //
  36589. if ( renderer.autoClear === true || forceClear === true ) {
  36590. _clearColor.multiplyScalar( _clearColor.a );
  36591. const clearColorValue = renderContext.clearColorValue;
  36592. clearColorValue.r = _clearColor.r;
  36593. clearColorValue.g = _clearColor.g;
  36594. clearColorValue.b = _clearColor.b;
  36595. clearColorValue.a = _clearColor.a;
  36596. renderContext.depthClearValue = renderer._clearDepth;
  36597. renderContext.stencilClearValue = renderer._clearStencil;
  36598. renderContext.clearColor = renderer.autoClearColor === true;
  36599. renderContext.clearDepth = renderer.autoClearDepth === true;
  36600. renderContext.clearStencil = renderer.autoClearStencil === true;
  36601. } else {
  36602. renderContext.clearColor = false;
  36603. renderContext.clearDepth = false;
  36604. renderContext.clearStencil = false;
  36605. }
  36606. }
  36607. }
  36608. class NodeBuilderState {
  36609. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, instanceBindGroups = true, transforms = [] ) {
  36610. this.vertexShader = vertexShader;
  36611. this.fragmentShader = fragmentShader;
  36612. this.computeShader = computeShader;
  36613. this.transforms = transforms;
  36614. this.nodeAttributes = nodeAttributes;
  36615. this.bindings = bindings;
  36616. this.updateNodes = updateNodes;
  36617. this.updateBeforeNodes = updateBeforeNodes;
  36618. this.updateAfterNodes = updateAfterNodes;
  36619. this.instanceBindGroups = instanceBindGroups;
  36620. this.usedTimes = 0;
  36621. }
  36622. createBindings() {
  36623. const bindings = [];
  36624. for ( const instanceGroup of this.bindings ) {
  36625. const shared = this.instanceBindGroups && instanceGroup.bindings[ 0 ].groupNode.shared;
  36626. if ( shared !== true ) {
  36627. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index );
  36628. bindings.push( bindingsGroup );
  36629. for ( const instanceBinding of instanceGroup.bindings ) {
  36630. bindingsGroup.bindings.push( instanceBinding.clone() );
  36631. }
  36632. } else {
  36633. bindings.push( instanceGroup );
  36634. }
  36635. }
  36636. return bindings;
  36637. }
  36638. }
  36639. const outputNodeMap = new WeakMap();
  36640. class Nodes extends DataMap {
  36641. constructor( renderer, backend ) {
  36642. super();
  36643. this.renderer = renderer;
  36644. this.backend = backend;
  36645. this.nodeFrame = new NodeFrame();
  36646. this.nodeBuilderCache = new Map();
  36647. this.callHashCache = new ChainMap();
  36648. this.groupsData = new ChainMap();
  36649. }
  36650. updateGroup( nodeUniformsGroup ) {
  36651. const groupNode = nodeUniformsGroup.groupNode;
  36652. const name = groupNode.name;
  36653. // objectGroup is every updated
  36654. if ( name === objectGroup.name ) return true;
  36655. // renderGroup is updated once per render/compute call
  36656. if ( name === renderGroup.name ) {
  36657. const uniformsGroupData = this.get( nodeUniformsGroup );
  36658. const renderId = this.nodeFrame.renderId;
  36659. if ( uniformsGroupData.renderId !== renderId ) {
  36660. uniformsGroupData.renderId = renderId;
  36661. return true;
  36662. }
  36663. return false;
  36664. }
  36665. // frameGroup is updated once per frame
  36666. if ( name === frameGroup.name ) {
  36667. const uniformsGroupData = this.get( nodeUniformsGroup );
  36668. const frameId = this.nodeFrame.frameId;
  36669. if ( uniformsGroupData.frameId !== frameId ) {
  36670. uniformsGroupData.frameId = frameId;
  36671. return true;
  36672. }
  36673. return false;
  36674. }
  36675. // other groups are updated just when groupNode.needsUpdate is true
  36676. const groupChain = [ groupNode, nodeUniformsGroup ];
  36677. let groupData = this.groupsData.get( groupChain );
  36678. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36679. if ( groupData.version !== groupNode.version ) {
  36680. groupData.version = groupNode.version;
  36681. return true;
  36682. }
  36683. return false;
  36684. }
  36685. getForRenderCacheKey( renderObject ) {
  36686. return renderObject.initialCacheKey;
  36687. }
  36688. getForRender( renderObject ) {
  36689. const renderObjectData = this.get( renderObject );
  36690. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36691. if ( nodeBuilderState === undefined ) {
  36692. const { nodeBuilderCache } = this;
  36693. const cacheKey = this.getForRenderCacheKey( renderObject );
  36694. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36695. if ( nodeBuilderState === undefined ) {
  36696. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36697. nodeBuilder.scene = renderObject.scene;
  36698. nodeBuilder.material = renderObject.material;
  36699. nodeBuilder.camera = renderObject.camera;
  36700. nodeBuilder.context.material = renderObject.material;
  36701. nodeBuilder.lightsNode = renderObject.lightsNode;
  36702. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36703. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36704. nodeBuilder.clippingContext = renderObject.clippingContext;
  36705. nodeBuilder.build();
  36706. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36707. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36708. }
  36709. nodeBuilderState.usedTimes ++;
  36710. renderObjectData.nodeBuilderState = nodeBuilderState;
  36711. }
  36712. return nodeBuilderState;
  36713. }
  36714. delete( object ) {
  36715. if ( object.isRenderObject ) {
  36716. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36717. nodeBuilderState.usedTimes --;
  36718. if ( nodeBuilderState.usedTimes === 0 ) {
  36719. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36720. }
  36721. }
  36722. return super.delete( object );
  36723. }
  36724. getForCompute( computeNode ) {
  36725. const computeData = this.get( computeNode );
  36726. let nodeBuilderState = computeData.nodeBuilderState;
  36727. if ( nodeBuilderState === undefined ) {
  36728. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36729. nodeBuilder.build();
  36730. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36731. computeData.nodeBuilderState = nodeBuilderState;
  36732. }
  36733. return nodeBuilderState;
  36734. }
  36735. _createNodeBuilderState( nodeBuilder ) {
  36736. return new NodeBuilderState(
  36737. nodeBuilder.vertexShader,
  36738. nodeBuilder.fragmentShader,
  36739. nodeBuilder.computeShader,
  36740. nodeBuilder.getAttributesArray(),
  36741. nodeBuilder.getBindings(),
  36742. nodeBuilder.updateNodes,
  36743. nodeBuilder.updateBeforeNodes,
  36744. nodeBuilder.updateAfterNodes,
  36745. nodeBuilder.instanceBindGroups,
  36746. nodeBuilder.transforms
  36747. );
  36748. }
  36749. getEnvironmentNode( scene ) {
  36750. return scene.environmentNode || this.get( scene ).environmentNode || null;
  36751. }
  36752. getBackgroundNode( scene ) {
  36753. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  36754. }
  36755. getFogNode( scene ) {
  36756. return scene.fogNode || this.get( scene ).fogNode || null;
  36757. }
  36758. getCacheKey( scene, lightsNode ) {
  36759. const chain = [ scene, lightsNode ];
  36760. const callId = this.renderer.info.calls;
  36761. let cacheKeyData = this.callHashCache.get( chain );
  36762. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  36763. const environmentNode = this.getEnvironmentNode( scene );
  36764. const fogNode = this.getFogNode( scene );
  36765. const cacheKey = [];
  36766. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey( true ) );
  36767. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  36768. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  36769. cacheKeyData = {
  36770. callId,
  36771. cacheKey: cacheKey.join( ',' )
  36772. };
  36773. this.callHashCache.set( chain, cacheKeyData );
  36774. }
  36775. return cacheKeyData.cacheKey;
  36776. }
  36777. updateScene( scene ) {
  36778. this.updateEnvironment( scene );
  36779. this.updateFog( scene );
  36780. this.updateBackground( scene );
  36781. }
  36782. get isToneMappingState() {
  36783. return this.renderer.getRenderTarget() ? false : true;
  36784. }
  36785. updateBackground( scene ) {
  36786. const sceneData = this.get( scene );
  36787. const background = scene.background;
  36788. if ( background ) {
  36789. if ( sceneData.background !== background ) {
  36790. let backgroundNode = null;
  36791. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping ) ) {
  36792. backgroundNode = pmremTexture( background, normalWorld );
  36793. } else if ( background.isTexture === true ) {
  36794. backgroundNode = texture( background, viewportBottomLeft ).setUpdateMatrix( true );
  36795. } else if ( background.isColor !== true ) {
  36796. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36797. }
  36798. sceneData.backgroundNode = backgroundNode;
  36799. sceneData.background = background;
  36800. }
  36801. } else if ( sceneData.backgroundNode ) {
  36802. delete sceneData.backgroundNode;
  36803. delete sceneData.background;
  36804. }
  36805. }
  36806. updateFog( scene ) {
  36807. const sceneData = this.get( scene );
  36808. const fog = scene.fog;
  36809. if ( fog ) {
  36810. if ( sceneData.fog !== fog ) {
  36811. let fogNode = null;
  36812. if ( fog.isFogExp2 ) {
  36813. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  36814. } else if ( fog.isFog ) {
  36815. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  36816. } else {
  36817. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  36818. }
  36819. sceneData.fogNode = fogNode;
  36820. sceneData.fog = fog;
  36821. }
  36822. } else {
  36823. delete sceneData.fogNode;
  36824. delete sceneData.fog;
  36825. }
  36826. }
  36827. updateEnvironment( scene ) {
  36828. const sceneData = this.get( scene );
  36829. const environment = scene.environment;
  36830. if ( environment ) {
  36831. if ( sceneData.environment !== environment ) {
  36832. let environmentNode = null;
  36833. if ( environment.isCubeTexture === true ) {
  36834. environmentNode = cubeTexture( environment );
  36835. } else if ( environment.isTexture === true ) {
  36836. environmentNode = texture( environment );
  36837. } else {
  36838. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36839. }
  36840. sceneData.environmentNode = environmentNode;
  36841. sceneData.environment = environment;
  36842. }
  36843. } else if ( sceneData.environmentNode ) {
  36844. delete sceneData.environmentNode;
  36845. delete sceneData.environment;
  36846. }
  36847. }
  36848. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36849. const nodeFrame = this.nodeFrame;
  36850. nodeFrame.renderer = renderer;
  36851. nodeFrame.scene = scene;
  36852. nodeFrame.object = object;
  36853. nodeFrame.camera = camera;
  36854. nodeFrame.material = material;
  36855. return nodeFrame;
  36856. }
  36857. getNodeFrameForRender( renderObject ) {
  36858. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36859. }
  36860. getOutputCacheKey() {
  36861. const renderer = this.renderer;
  36862. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  36863. }
  36864. hasOutputChange( outputTarget ) {
  36865. const cacheKey = outputNodeMap.get( outputTarget );
  36866. return cacheKey !== this.getOutputCacheKey();
  36867. }
  36868. getOutputNode( outputTexture ) {
  36869. const renderer = this.renderer;
  36870. const cacheKey = this.getOutputCacheKey();
  36871. const output = texture( outputTexture, viewportTopLeft ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36872. outputNodeMap.set( outputTexture, cacheKey );
  36873. return output;
  36874. }
  36875. updateBefore( renderObject ) {
  36876. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36877. const nodeBuilder = renderObject.getNodeBuilderState();
  36878. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36879. nodeFrame.updateBeforeNode( node );
  36880. }
  36881. }
  36882. updateAfter( renderObject ) {
  36883. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36884. const nodeBuilder = renderObject.getNodeBuilderState();
  36885. for ( const node of nodeBuilder.updateAfterNodes ) {
  36886. nodeFrame.updateAfterNode( node );
  36887. }
  36888. }
  36889. updateForCompute( computeNode ) {
  36890. const nodeFrame = this.getNodeFrame();
  36891. const nodeBuilder = this.getForCompute( computeNode );
  36892. for ( const node of nodeBuilder.updateNodes ) {
  36893. nodeFrame.updateNode( node );
  36894. }
  36895. }
  36896. updateForRender( renderObject ) {
  36897. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36898. const nodeBuilder = renderObject.getNodeBuilderState();
  36899. for ( const node of nodeBuilder.updateNodes ) {
  36900. nodeFrame.updateNode( node );
  36901. }
  36902. }
  36903. dispose() {
  36904. super.dispose();
  36905. this.nodeFrame = new NodeFrame();
  36906. this.nodeBuilderCache = new Map();
  36907. }
  36908. }
  36909. class RenderBundle {
  36910. constructor( scene, camera ) {
  36911. this.scene = scene;
  36912. this.camera = camera;
  36913. }
  36914. clone() {
  36915. return Object.assign( new this.constructor(), this );
  36916. }
  36917. }
  36918. class RenderBundles {
  36919. constructor() {
  36920. this.lists = new ChainMap();
  36921. }
  36922. get( scene, camera ) {
  36923. const lists = this.lists;
  36924. const keys = [ scene, camera ];
  36925. let list = lists.get( keys );
  36926. if ( list === undefined ) {
  36927. list = new RenderBundle( scene, camera );
  36928. lists.set( keys, list );
  36929. }
  36930. return list;
  36931. }
  36932. dispose() {
  36933. this.lists = new ChainMap();
  36934. }
  36935. }
  36936. const _scene = /*@__PURE__*/ new Scene();
  36937. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36938. const _screen = /*@__PURE__*/ new Vector4();
  36939. const _frustum = /*@__PURE__*/ new Frustum();
  36940. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36941. const _vector3 = /*@__PURE__*/ new Vector3();
  36942. class Renderer {
  36943. constructor( backend, parameters = {} ) {
  36944. this.isRenderer = true;
  36945. //
  36946. const {
  36947. logarithmicDepthBuffer = false,
  36948. alpha = true,
  36949. antialias = false,
  36950. samples = 0
  36951. } = parameters;
  36952. // public
  36953. this.domElement = backend.getDomElement();
  36954. this.backend = backend;
  36955. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36956. this.autoClear = true;
  36957. this.autoClearColor = true;
  36958. this.autoClearDepth = true;
  36959. this.autoClearStencil = true;
  36960. this.alpha = alpha;
  36961. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36962. this.outputColorSpace = SRGBColorSpace;
  36963. this.toneMapping = NoToneMapping;
  36964. this.toneMappingExposure = 1.0;
  36965. this.sortObjects = true;
  36966. this.depth = true;
  36967. this.stencil = false;
  36968. this.clippingPlanes = [];
  36969. this.info = new Info();
  36970. // internals
  36971. this._pixelRatio = 1;
  36972. this._width = this.domElement.width;
  36973. this._height = this.domElement.height;
  36974. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36975. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36976. this._scissorTest = false;
  36977. this._attributes = null;
  36978. this._geometries = null;
  36979. this._nodes = null;
  36980. this._animation = null;
  36981. this._bindings = null;
  36982. this._objects = null;
  36983. this._pipelines = null;
  36984. this._bundles = null;
  36985. this._renderLists = null;
  36986. this._renderContexts = null;
  36987. this._textures = null;
  36988. this._background = null;
  36989. this._quad = new QuadMesh( new NodeMaterial() );
  36990. this._currentRenderContext = null;
  36991. this._opaqueSort = null;
  36992. this._transparentSort = null;
  36993. this._frameBufferTarget = null;
  36994. const alphaClear = this.alpha === true ? 0 : 1;
  36995. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  36996. this._clearDepth = 1;
  36997. this._clearStencil = 0;
  36998. this._renderTarget = null;
  36999. this._activeCubeFace = 0;
  37000. this._activeMipmapLevel = 0;
  37001. this._mrt = null;
  37002. this._renderObjectFunction = null;
  37003. this._currentRenderObjectFunction = null;
  37004. this._currentRenderBundle = null;
  37005. this._handleObjectFunction = this._renderObjectDirect;
  37006. this._initialized = false;
  37007. this._initPromise = null;
  37008. this._compilationPromises = null;
  37009. this.transparent = true;
  37010. this.opaque = true;
  37011. this.shadowMap = {
  37012. enabled: false,
  37013. type: PCFShadowMap$1
  37014. };
  37015. this.xr = {
  37016. enabled: false
  37017. };
  37018. this.debug = {
  37019. checkShaderErrors: true,
  37020. onShaderError: null,
  37021. getShaderAsync: async ( scene, camera, object ) => {
  37022. await this.compileAsync( scene, camera );
  37023. const renderList = this._renderLists.get( scene, camera );
  37024. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37025. const material = scene.overrideMaterial || object.material;
  37026. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37027. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37028. return { fragmentShader, vertexShader };
  37029. }
  37030. };
  37031. }
  37032. async init() {
  37033. if ( this._initialized ) {
  37034. throw new Error( 'Renderer: Backend has already been initialized.' );
  37035. }
  37036. if ( this._initPromise !== null ) {
  37037. return this._initPromise;
  37038. }
  37039. this._initPromise = new Promise( async ( resolve, reject ) => {
  37040. const backend = this.backend;
  37041. try {
  37042. await backend.init( this );
  37043. } catch ( error ) {
  37044. reject( error );
  37045. return;
  37046. }
  37047. this._nodes = new Nodes( this, backend );
  37048. this._animation = new Animation( this._nodes, this.info );
  37049. this._attributes = new Attributes( backend );
  37050. this._background = new Background( this, this._nodes );
  37051. this._geometries = new Geometries( this._attributes, this.info );
  37052. this._textures = new Textures( this, backend, this.info );
  37053. this._pipelines = new Pipelines( backend, this._nodes );
  37054. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37055. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37056. this._renderLists = new RenderLists();
  37057. this._bundles = new RenderBundles();
  37058. this._renderContexts = new RenderContexts();
  37059. //
  37060. this._initialized = true;
  37061. resolve();
  37062. } );
  37063. return this._initPromise;
  37064. }
  37065. get coordinateSystem() {
  37066. return this.backend.coordinateSystem;
  37067. }
  37068. async compileAsync( scene, camera, targetScene = null ) {
  37069. if ( this._initialized === false ) await this.init();
  37070. // preserve render tree
  37071. const nodeFrame = this._nodes.nodeFrame;
  37072. const previousRenderId = nodeFrame.renderId;
  37073. const previousRenderContext = this._currentRenderContext;
  37074. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37075. const previousCompilationPromises = this._compilationPromises;
  37076. //
  37077. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37078. if ( targetScene === null ) targetScene = scene;
  37079. const renderTarget = this._renderTarget;
  37080. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37081. const activeMipmapLevel = this._activeMipmapLevel;
  37082. const compilationPromises = [];
  37083. this._currentRenderContext = renderContext;
  37084. this._currentRenderObjectFunction = this.renderObject;
  37085. this._handleObjectFunction = this._createObjectPipeline;
  37086. this._compilationPromises = compilationPromises;
  37087. nodeFrame.renderId ++;
  37088. //
  37089. nodeFrame.update();
  37090. //
  37091. renderContext.depth = this.depth;
  37092. renderContext.stencil = this.stencil;
  37093. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37094. renderContext.clippingContext.updateGlobal( this, camera );
  37095. //
  37096. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37097. //
  37098. const renderList = this._renderLists.get( scene, camera );
  37099. renderList.begin();
  37100. this._projectObject( scene, camera, 0, renderList );
  37101. // include lights from target scene
  37102. if ( targetScene !== scene ) {
  37103. targetScene.traverseVisible( function ( object ) {
  37104. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37105. renderList.pushLight( object );
  37106. }
  37107. } );
  37108. }
  37109. renderList.finish();
  37110. //
  37111. if ( renderTarget !== null ) {
  37112. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37113. const renderTargetData = this._textures.get( renderTarget );
  37114. renderContext.textures = renderTargetData.textures;
  37115. renderContext.depthTexture = renderTargetData.depthTexture;
  37116. } else {
  37117. renderContext.textures = null;
  37118. renderContext.depthTexture = null;
  37119. }
  37120. //
  37121. this._nodes.updateScene( sceneRef );
  37122. //
  37123. this._background.update( sceneRef, renderList, renderContext );
  37124. // process render lists
  37125. const opaqueObjects = renderList.opaque;
  37126. const transparentObjects = renderList.transparent;
  37127. const lightsNode = renderList.lightsNode;
  37128. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37129. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37130. // restore render tree
  37131. nodeFrame.renderId = previousRenderId;
  37132. this._currentRenderContext = previousRenderContext;
  37133. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37134. this._compilationPromises = previousCompilationPromises;
  37135. this._handleObjectFunction = this._renderObjectDirect;
  37136. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37137. await Promise.all( compilationPromises );
  37138. }
  37139. async renderAsync( scene, camera ) {
  37140. if ( this._initialized === false ) await this.init();
  37141. const renderContext = this._renderScene( scene, camera );
  37142. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37143. }
  37144. setMRT( mrt ) {
  37145. this._mrt = mrt;
  37146. return this;
  37147. }
  37148. getMRT() {
  37149. return this._mrt;
  37150. }
  37151. _renderBundle( bundle, sceneRef, lightsNode ) {
  37152. const { object, camera, renderList } = bundle;
  37153. const renderContext = this._currentRenderContext;
  37154. const renderContextData = this.backend.get( renderContext );
  37155. //
  37156. const renderBundle = this._bundles.get( object, camera );
  37157. const renderBundleData = this.backend.get( renderBundle );
  37158. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37159. //
  37160. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || object.needsUpdate === true;
  37161. renderBundleData.renderContexts.add( renderContext );
  37162. if ( renderBundleNeedsUpdate ) {
  37163. if ( renderContextData.renderObjects === undefined || object.needsUpdate === true ) {
  37164. const nodeFrame = this._nodes.nodeFrame;
  37165. renderContextData.renderObjects = [];
  37166. renderContextData.renderBundles = [];
  37167. renderContextData.scene = sceneRef;
  37168. renderContextData.camera = camera;
  37169. renderContextData.renderId = nodeFrame.renderId;
  37170. renderContextData.registerBundlesPhase = true;
  37171. }
  37172. this._currentRenderBundle = renderBundle;
  37173. const opaqueObjects = renderList.opaque;
  37174. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37175. this._currentRenderBundle = null;
  37176. //
  37177. object.needsUpdate = false;
  37178. } else {
  37179. const renderContext = this._currentRenderContext;
  37180. const renderContextData = this.backend.get( renderContext );
  37181. for ( let i = 0, l = renderContextData.renderObjects.length; i < l; i ++ ) {
  37182. const renderObject = renderContextData.renderObjects[ i ];
  37183. this._nodes.updateBefore( renderObject );
  37184. //
  37185. renderObject.object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, renderObject.object.matrixWorld );
  37186. renderObject.object.normalMatrix.getNormalMatrix( renderObject.object.modelViewMatrix );
  37187. this._nodes.updateForRender( renderObject );
  37188. this._bindings.updateForRender( renderObject );
  37189. this.backend.draw( renderObject, this.info );
  37190. this._nodes.updateAfter( renderObject );
  37191. }
  37192. }
  37193. }
  37194. render( scene, camera ) {
  37195. if ( this._initialized === false ) {
  37196. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37197. return this.renderAsync( scene, camera );
  37198. }
  37199. this._renderScene( scene, camera );
  37200. }
  37201. _getFrameBufferTarget() {
  37202. const { currentColorSpace } = this;
  37203. const useToneMapping = this._renderTarget === null && ( this.toneMapping !== NoToneMapping );
  37204. const useColorSpace = this._renderTarget === null && ( currentColorSpace !== LinearSRGBColorSpace && currentColorSpace !== NoColorSpace );
  37205. if ( useToneMapping === false && useColorSpace === false ) return null;
  37206. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37207. const { depth, stencil } = this;
  37208. let frameBufferTarget = this._frameBufferTarget;
  37209. if ( frameBufferTarget === null ) {
  37210. frameBufferTarget = new RenderTarget( width, height, {
  37211. depthBuffer: depth,
  37212. stencilBuffer: stencil,
  37213. type: HalfFloatType, // FloatType
  37214. format: RGBAFormat,
  37215. colorSpace: LinearSRGBColorSpace,
  37216. generateMipmaps: false,
  37217. minFilter: LinearFilter,
  37218. magFilter: LinearFilter,
  37219. samples: this.samples
  37220. } );
  37221. frameBufferTarget.isPostProcessingRenderTarget = true;
  37222. this._frameBufferTarget = frameBufferTarget;
  37223. }
  37224. frameBufferTarget.depthBuffer = depth;
  37225. frameBufferTarget.stencilBuffer = stencil;
  37226. frameBufferTarget.setSize( width, height );
  37227. frameBufferTarget.viewport.copy( this._viewport );
  37228. frameBufferTarget.scissor.copy( this._scissor );
  37229. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37230. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37231. frameBufferTarget.scissorTest = this._scissorTest;
  37232. return frameBufferTarget;
  37233. }
  37234. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37235. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37236. // preserve render tree
  37237. const nodeFrame = this._nodes.nodeFrame;
  37238. const previousRenderId = nodeFrame.renderId;
  37239. const previousRenderContext = this._currentRenderContext;
  37240. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37241. //
  37242. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37243. const outputRenderTarget = this._renderTarget;
  37244. const activeCubeFace = this._activeCubeFace;
  37245. const activeMipmapLevel = this._activeMipmapLevel;
  37246. //
  37247. let renderTarget;
  37248. if ( frameBufferTarget !== null ) {
  37249. renderTarget = frameBufferTarget;
  37250. this.setRenderTarget( renderTarget );
  37251. } else {
  37252. renderTarget = outputRenderTarget;
  37253. }
  37254. //
  37255. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37256. this._currentRenderContext = renderContext;
  37257. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37258. //
  37259. this.info.calls ++;
  37260. this.info.render.calls ++;
  37261. this.info.render.frameCalls ++;
  37262. nodeFrame.renderId = this.info.calls;
  37263. //
  37264. const coordinateSystem = this.coordinateSystem;
  37265. if ( camera.coordinateSystem !== coordinateSystem ) {
  37266. camera.coordinateSystem = coordinateSystem;
  37267. camera.updateProjectionMatrix();
  37268. }
  37269. //
  37270. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37271. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37272. //
  37273. let viewport = this._viewport;
  37274. let scissor = this._scissor;
  37275. let pixelRatio = this._pixelRatio;
  37276. if ( renderTarget !== null ) {
  37277. viewport = renderTarget.viewport;
  37278. scissor = renderTarget.scissor;
  37279. pixelRatio = 1;
  37280. }
  37281. this.getDrawingBufferSize( _drawingBufferSize );
  37282. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37283. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37284. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37285. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37286. renderContext.viewportValue.width >>= activeMipmapLevel;
  37287. renderContext.viewportValue.height >>= activeMipmapLevel;
  37288. renderContext.viewportValue.minDepth = minDepth;
  37289. renderContext.viewportValue.maxDepth = maxDepth;
  37290. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37291. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37292. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37293. renderContext.scissorValue.width >>= activeMipmapLevel;
  37294. renderContext.scissorValue.height >>= activeMipmapLevel;
  37295. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37296. renderContext.clippingContext.updateGlobal( this, camera );
  37297. //
  37298. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37299. //
  37300. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37301. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37302. const renderList = this._renderLists.get( scene, camera );
  37303. renderList.begin();
  37304. this._projectObject( scene, camera, 0, renderList );
  37305. renderList.finish();
  37306. if ( this.sortObjects === true ) {
  37307. renderList.sort( this._opaqueSort, this._transparentSort );
  37308. }
  37309. //
  37310. if ( renderTarget !== null ) {
  37311. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37312. const renderTargetData = this._textures.get( renderTarget );
  37313. renderContext.textures = renderTargetData.textures;
  37314. renderContext.depthTexture = renderTargetData.depthTexture;
  37315. renderContext.width = renderTargetData.width;
  37316. renderContext.height = renderTargetData.height;
  37317. renderContext.renderTarget = renderTarget;
  37318. renderContext.depth = renderTarget.depthBuffer;
  37319. renderContext.stencil = renderTarget.stencilBuffer;
  37320. } else {
  37321. renderContext.textures = null;
  37322. renderContext.depthTexture = null;
  37323. renderContext.width = this.domElement.width;
  37324. renderContext.height = this.domElement.height;
  37325. renderContext.depth = this.depth;
  37326. renderContext.stencil = this.stencil;
  37327. }
  37328. renderContext.width >>= activeMipmapLevel;
  37329. renderContext.height >>= activeMipmapLevel;
  37330. renderContext.activeCubeFace = activeCubeFace;
  37331. renderContext.activeMipmapLevel = activeMipmapLevel;
  37332. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37333. //
  37334. this._nodes.updateScene( sceneRef );
  37335. //
  37336. this._background.update( sceneRef, renderList, renderContext );
  37337. //
  37338. this.backend.beginRender( renderContext );
  37339. // process render lists
  37340. const opaqueObjects = renderList.opaque;
  37341. const transparentObjects = renderList.transparent;
  37342. const bundles = renderList.bundles;
  37343. const lightsNode = renderList.lightsNode;
  37344. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37345. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37346. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37347. // finish render pass
  37348. this.backend.finishRender( renderContext );
  37349. // restore render tree
  37350. nodeFrame.renderId = previousRenderId;
  37351. this._currentRenderContext = previousRenderContext;
  37352. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37353. //
  37354. if ( frameBufferTarget !== null ) {
  37355. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37356. const quad = this._quad;
  37357. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37358. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37359. quad.material.needsUpdate = true;
  37360. }
  37361. this._renderScene( quad, quad.camera, false );
  37362. }
  37363. //
  37364. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37365. //
  37366. return renderContext;
  37367. }
  37368. getMaxAnisotropy() {
  37369. return this.backend.getMaxAnisotropy();
  37370. }
  37371. getActiveCubeFace() {
  37372. return this._activeCubeFace;
  37373. }
  37374. getActiveMipmapLevel() {
  37375. return this._activeMipmapLevel;
  37376. }
  37377. async setAnimationLoop( callback ) {
  37378. if ( this._initialized === false ) await this.init();
  37379. this._animation.setAnimationLoop( callback );
  37380. }
  37381. async getArrayBufferAsync( attribute ) {
  37382. return await this.backend.getArrayBufferAsync( attribute );
  37383. }
  37384. getContext() {
  37385. return this.backend.getContext();
  37386. }
  37387. getPixelRatio() {
  37388. return this._pixelRatio;
  37389. }
  37390. getDrawingBufferSize( target ) {
  37391. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37392. }
  37393. getSize( target ) {
  37394. return target.set( this._width, this._height );
  37395. }
  37396. setPixelRatio( value = 1 ) {
  37397. this._pixelRatio = value;
  37398. this.setSize( this._width, this._height, false );
  37399. }
  37400. setDrawingBufferSize( width, height, pixelRatio ) {
  37401. this._width = width;
  37402. this._height = height;
  37403. this._pixelRatio = pixelRatio;
  37404. this.domElement.width = Math.floor( width * pixelRatio );
  37405. this.domElement.height = Math.floor( height * pixelRatio );
  37406. this.setViewport( 0, 0, width, height );
  37407. if ( this._initialized ) this.backend.updateSize();
  37408. }
  37409. setSize( width, height, updateStyle = true ) {
  37410. this._width = width;
  37411. this._height = height;
  37412. this.domElement.width = Math.floor( width * this._pixelRatio );
  37413. this.domElement.height = Math.floor( height * this._pixelRatio );
  37414. if ( updateStyle === true ) {
  37415. this.domElement.style.width = width + 'px';
  37416. this.domElement.style.height = height + 'px';
  37417. }
  37418. this.setViewport( 0, 0, width, height );
  37419. if ( this._initialized ) this.backend.updateSize();
  37420. }
  37421. setOpaqueSort( method ) {
  37422. this._opaqueSort = method;
  37423. }
  37424. setTransparentSort( method ) {
  37425. this._transparentSort = method;
  37426. }
  37427. getScissor( target ) {
  37428. const scissor = this._scissor;
  37429. target.x = scissor.x;
  37430. target.y = scissor.y;
  37431. target.width = scissor.width;
  37432. target.height = scissor.height;
  37433. return target;
  37434. }
  37435. setScissor( x, y, width, height ) {
  37436. const scissor = this._scissor;
  37437. if ( x.isVector4 ) {
  37438. scissor.copy( x );
  37439. } else {
  37440. scissor.set( x, y, width, height );
  37441. }
  37442. }
  37443. getScissorTest() {
  37444. return this._scissorTest;
  37445. }
  37446. setScissorTest( boolean ) {
  37447. this._scissorTest = boolean;
  37448. this.backend.setScissorTest( boolean );
  37449. }
  37450. getViewport( target ) {
  37451. return target.copy( this._viewport );
  37452. }
  37453. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37454. const viewport = this._viewport;
  37455. if ( x.isVector4 ) {
  37456. viewport.copy( x );
  37457. } else {
  37458. viewport.set( x, y, width, height );
  37459. }
  37460. viewport.minDepth = minDepth;
  37461. viewport.maxDepth = maxDepth;
  37462. }
  37463. getClearColor( target ) {
  37464. return target.copy( this._clearColor );
  37465. }
  37466. setClearColor( color, alpha = 1 ) {
  37467. this._clearColor.set( color );
  37468. this._clearColor.a = alpha;
  37469. }
  37470. getClearAlpha() {
  37471. return this._clearColor.a;
  37472. }
  37473. setClearAlpha( alpha ) {
  37474. this._clearColor.a = alpha;
  37475. }
  37476. getClearDepth() {
  37477. return this._clearDepth;
  37478. }
  37479. setClearDepth( depth ) {
  37480. this._clearDepth = depth;
  37481. }
  37482. getClearStencil() {
  37483. return this._clearStencil;
  37484. }
  37485. setClearStencil( stencil ) {
  37486. this._clearStencil = stencil;
  37487. }
  37488. isOccluded( object ) {
  37489. const renderContext = this._currentRenderContext;
  37490. return renderContext && this.backend.isOccluded( renderContext, object );
  37491. }
  37492. clear( color = true, depth = true, stencil = true ) {
  37493. if ( this._initialized === false ) {
  37494. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37495. return this.clearAsync( color, depth, stencil );
  37496. }
  37497. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37498. let renderTargetData = null;
  37499. if ( renderTarget !== null ) {
  37500. this._textures.updateRenderTarget( renderTarget );
  37501. renderTargetData = this._textures.get( renderTarget );
  37502. }
  37503. this.backend.clear( color, depth, stencil, renderTargetData );
  37504. if ( renderTarget !== null && this._renderTarget === null ) {
  37505. // If a color space transform or tone mapping is required,
  37506. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37507. const quad = this._quad;
  37508. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37509. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37510. quad.material.needsUpdate = true;
  37511. }
  37512. this._renderScene( quad, quad.camera, false );
  37513. }
  37514. }
  37515. clearColor() {
  37516. return this.clear( true, false, false );
  37517. }
  37518. clearDepth() {
  37519. return this.clear( false, true, false );
  37520. }
  37521. clearStencil() {
  37522. return this.clear( false, false, true );
  37523. }
  37524. async clearAsync( color = true, depth = true, stencil = true ) {
  37525. if ( this._initialized === false ) await this.init();
  37526. this.clear( color, depth, stencil );
  37527. }
  37528. clearColorAsync() {
  37529. return this.clearAsync( true, false, false );
  37530. }
  37531. clearDepthAsync() {
  37532. return this.clearAsync( false, true, false );
  37533. }
  37534. clearStencilAsync() {
  37535. return this.clearAsync( false, false, true );
  37536. }
  37537. get currentColorSpace() {
  37538. const renderTarget = this._renderTarget;
  37539. if ( renderTarget !== null ) {
  37540. const texture = renderTarget.texture;
  37541. return ( Array.isArray( texture ) ? texture[ 0 ] : texture ).colorSpace;
  37542. }
  37543. return this.outputColorSpace;
  37544. }
  37545. dispose() {
  37546. this.info.dispose();
  37547. this._animation.dispose();
  37548. this._objects.dispose();
  37549. this._pipelines.dispose();
  37550. this._nodes.dispose();
  37551. this._bindings.dispose();
  37552. this._renderLists.dispose();
  37553. this._renderContexts.dispose();
  37554. this._textures.dispose();
  37555. this.setRenderTarget( null );
  37556. this.setAnimationLoop( null );
  37557. }
  37558. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37559. this._renderTarget = renderTarget;
  37560. this._activeCubeFace = activeCubeFace;
  37561. this._activeMipmapLevel = activeMipmapLevel;
  37562. }
  37563. getRenderTarget() {
  37564. return this._renderTarget;
  37565. }
  37566. setRenderObjectFunction( renderObjectFunction ) {
  37567. this._renderObjectFunction = renderObjectFunction;
  37568. }
  37569. getRenderObjectFunction() {
  37570. return this._renderObjectFunction;
  37571. }
  37572. async computeAsync( computeNodes ) {
  37573. if ( this._initialized === false ) await this.init();
  37574. const nodeFrame = this._nodes.nodeFrame;
  37575. const previousRenderId = nodeFrame.renderId;
  37576. //
  37577. this.info.calls ++;
  37578. this.info.compute.calls ++;
  37579. this.info.compute.frameCalls ++;
  37580. nodeFrame.renderId = this.info.calls;
  37581. //
  37582. const backend = this.backend;
  37583. const pipelines = this._pipelines;
  37584. const bindings = this._bindings;
  37585. const nodes = this._nodes;
  37586. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37587. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37588. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37589. }
  37590. backend.beginCompute( computeNodes );
  37591. for ( const computeNode of computeList ) {
  37592. // onInit
  37593. if ( pipelines.has( computeNode ) === false ) {
  37594. const dispose = () => {
  37595. computeNode.removeEventListener( 'dispose', dispose );
  37596. pipelines.delete( computeNode );
  37597. bindings.delete( computeNode );
  37598. nodes.delete( computeNode );
  37599. };
  37600. computeNode.addEventListener( 'dispose', dispose );
  37601. //
  37602. computeNode.onInit( { renderer: this } );
  37603. }
  37604. nodes.updateForCompute( computeNode );
  37605. bindings.updateForCompute( computeNode );
  37606. const computeBindings = bindings.getForCompute( computeNode );
  37607. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37608. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37609. }
  37610. backend.finishCompute( computeNodes );
  37611. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  37612. //
  37613. nodeFrame.renderId = previousRenderId;
  37614. }
  37615. async hasFeatureAsync( name ) {
  37616. if ( this._initialized === false ) await this.init();
  37617. return this.backend.hasFeature( name );
  37618. }
  37619. hasFeature( name ) {
  37620. if ( this._initialized === false ) {
  37621. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37622. return false;
  37623. }
  37624. return this.backend.hasFeature( name );
  37625. }
  37626. copyFramebufferToTexture( framebufferTexture ) {
  37627. const renderContext = this._currentRenderContext;
  37628. this._textures.updateTexture( framebufferTexture );
  37629. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  37630. }
  37631. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37632. this._textures.updateTexture( srcTexture );
  37633. this._textures.updateTexture( dstTexture );
  37634. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  37635. }
  37636. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0 ) {
  37637. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height );
  37638. }
  37639. _projectObject( object, camera, groupOrder, renderList ) {
  37640. if ( object.visible === false ) return;
  37641. const visible = object.layers.test( camera.layers );
  37642. if ( visible ) {
  37643. if ( object.isGroup ) {
  37644. groupOrder = object.renderOrder;
  37645. } else if ( object.isLOD ) {
  37646. if ( object.autoUpdate === true ) object.update( camera );
  37647. } else if ( object.isLight ) {
  37648. renderList.pushLight( object );
  37649. } else if ( object.isSprite ) {
  37650. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37651. if ( this.sortObjects === true ) {
  37652. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  37653. }
  37654. const geometry = object.geometry;
  37655. const material = object.material;
  37656. if ( material.visible ) {
  37657. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37658. }
  37659. }
  37660. } else if ( object.isLineLoop ) {
  37661. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  37662. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  37663. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  37664. const geometry = object.geometry;
  37665. const material = object.material;
  37666. if ( this.sortObjects === true ) {
  37667. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  37668. _vector3
  37669. .copy( geometry.boundingSphere.center )
  37670. .applyMatrix4( object.matrixWorld )
  37671. .applyMatrix4( _projScreenMatrix );
  37672. }
  37673. if ( Array.isArray( material ) ) {
  37674. const groups = geometry.groups;
  37675. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  37676. const group = groups[ i ];
  37677. const groupMaterial = material[ group.materialIndex ];
  37678. if ( groupMaterial && groupMaterial.visible ) {
  37679. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  37680. }
  37681. }
  37682. } else if ( material.visible ) {
  37683. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  37684. }
  37685. }
  37686. }
  37687. }
  37688. if ( object.static === true ) {
  37689. const baseRenderList = renderList;
  37690. // replace render list
  37691. renderList = this._renderLists.get( object, camera );
  37692. renderList.begin();
  37693. baseRenderList.pushBundle( {
  37694. object,
  37695. camera,
  37696. renderList,
  37697. } );
  37698. renderList.finish();
  37699. }
  37700. const children = object.children;
  37701. for ( let i = 0, l = children.length; i < l; i ++ ) {
  37702. this._projectObject( children[ i ], camera, groupOrder, renderList );
  37703. }
  37704. }
  37705. _renderBundles( bundles, sceneRef, lightsNode ) {
  37706. for ( const bundle of bundles ) {
  37707. this._renderBundle( bundle, sceneRef, lightsNode );
  37708. }
  37709. }
  37710. _renderObjects( renderList, camera, scene, lightsNode ) {
  37711. // process renderable objects
  37712. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  37713. const renderItem = renderList[ i ];
  37714. // @TODO: Add support for multiple materials per object. This will require to extract
  37715. // the material from the renderItem object and pass it with its group data to renderObject().
  37716. const { object, geometry, material, group } = renderItem;
  37717. if ( camera.isArrayCamera ) {
  37718. const cameras = camera.cameras;
  37719. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  37720. const camera2 = cameras[ j ];
  37721. if ( object.layers.test( camera2.layers ) ) {
  37722. const vp = camera2.viewport;
  37723. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  37724. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  37725. const viewportValue = this._currentRenderContext.viewportValue;
  37726. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  37727. viewportValue.minDepth = minDepth;
  37728. viewportValue.maxDepth = maxDepth;
  37729. this.backend.updateViewport( this._currentRenderContext );
  37730. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  37731. }
  37732. }
  37733. } else {
  37734. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  37735. }
  37736. }
  37737. }
  37738. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  37739. let overridePositionNode;
  37740. let overrideFragmentNode;
  37741. let overrideDepthNode;
  37742. //
  37743. object.onBeforeRender( this, scene, camera, geometry, material, group );
  37744. //
  37745. if ( scene.overrideMaterial !== null ) {
  37746. const overrideMaterial = scene.overrideMaterial;
  37747. if ( material.positionNode && material.positionNode.isNode ) {
  37748. overridePositionNode = overrideMaterial.positionNode;
  37749. overrideMaterial.positionNode = material.positionNode;
  37750. }
  37751. if ( overrideMaterial.isShadowNodeMaterial ) {
  37752. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  37753. if ( material.depthNode && material.depthNode.isNode ) {
  37754. overrideDepthNode = overrideMaterial.depthNode;
  37755. overrideMaterial.depthNode = material.depthNode;
  37756. }
  37757. if ( material.shadowNode && material.shadowNode.isNode ) {
  37758. overrideFragmentNode = overrideMaterial.fragmentNode;
  37759. overrideMaterial.fragmentNode = material.shadowNode;
  37760. }
  37761. if ( this.localClippingEnabled ) {
  37762. if ( material.clipShadows ) {
  37763. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  37764. overrideMaterial.clippingPlanes = material.clippingPlanes;
  37765. overrideMaterial.needsUpdate = true;
  37766. }
  37767. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  37768. overrideMaterial.clipIntersection = material.clipIntersection;
  37769. }
  37770. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  37771. overrideMaterial.clippingPlanes = null;
  37772. overrideMaterial.needsUpdate = true;
  37773. }
  37774. }
  37775. }
  37776. material = overrideMaterial;
  37777. }
  37778. //
  37779. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  37780. material.side = BackSide;
  37781. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  37782. material.side = FrontSide;
  37783. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  37784. material.side = DoubleSide;
  37785. } else {
  37786. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  37787. }
  37788. //
  37789. if ( overridePositionNode !== undefined ) {
  37790. scene.overrideMaterial.positionNode = overridePositionNode;
  37791. }
  37792. if ( overrideDepthNode !== undefined ) {
  37793. scene.overrideMaterial.depthNode = overrideDepthNode;
  37794. }
  37795. if ( overrideFragmentNode !== undefined ) {
  37796. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  37797. }
  37798. //
  37799. object.onAfterRender( this, scene, camera, geometry, material, group );
  37800. }
  37801. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  37802. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37803. renderObject.drawRange = group || object.geometry.drawRange;
  37804. //
  37805. this._nodes.updateBefore( renderObject );
  37806. //
  37807. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  37808. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  37809. //
  37810. this._nodes.updateForRender( renderObject );
  37811. this._geometries.updateForRender( renderObject );
  37812. this._bindings.updateForRender( renderObject );
  37813. this._pipelines.updateForRender( renderObject );
  37814. //
  37815. if ( this._currentRenderBundle !== null && this._currentRenderBundle.needsUpdate === true ) {
  37816. const renderObjectData = this.backend.get( renderObject );
  37817. renderObjectData.bundleEncoder = undefined;
  37818. renderObjectData.lastPipelineGPU = undefined;
  37819. }
  37820. this.backend.draw( renderObject, this.info );
  37821. if ( this._currentRenderBundle !== null ) {
  37822. const renderContextData = this.backend.get( this._currentRenderContext );
  37823. renderContextData.renderObjects.push( renderObject );
  37824. }
  37825. this._nodes.updateAfter( renderObject );
  37826. }
  37827. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  37828. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  37829. //
  37830. this._nodes.updateBefore( renderObject );
  37831. //
  37832. this._nodes.updateForRender( renderObject );
  37833. this._geometries.updateForRender( renderObject );
  37834. this._bindings.updateForRender( renderObject );
  37835. this._pipelines.getForRender( renderObject, this._compilationPromises );
  37836. this._nodes.updateAfter( renderObject );
  37837. }
  37838. get compute() {
  37839. return this.computeAsync;
  37840. }
  37841. get compile() {
  37842. return this.compileAsync;
  37843. }
  37844. }
  37845. class Binding {
  37846. constructor( name = '' ) {
  37847. this.name = name;
  37848. this.visibility = 0;
  37849. }
  37850. setVisibility( visibility ) {
  37851. this.visibility |= visibility;
  37852. }
  37853. clone() {
  37854. return Object.assign( new this.constructor(), this );
  37855. }
  37856. }
  37857. function getFloatLength( floatLength ) {
  37858. // ensure chunk size alignment (STD140 layout)
  37859. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  37860. }
  37861. class Buffer extends Binding {
  37862. constructor( name, buffer = null ) {
  37863. super( name );
  37864. this.isBuffer = true;
  37865. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  37866. this._buffer = buffer;
  37867. }
  37868. get byteLength() {
  37869. return getFloatLength( this._buffer.byteLength );
  37870. }
  37871. get buffer() {
  37872. return this._buffer;
  37873. }
  37874. update() {
  37875. return true;
  37876. }
  37877. }
  37878. class UniformBuffer extends Buffer {
  37879. constructor( name, buffer = null ) {
  37880. super( name, buffer );
  37881. this.isUniformBuffer = true;
  37882. }
  37883. }
  37884. let _id$4 = 0;
  37885. class NodeUniformBuffer extends UniformBuffer {
  37886. constructor( nodeUniform, groupNode ) {
  37887. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37888. this.nodeUniform = nodeUniform;
  37889. this.groupNode = groupNode;
  37890. }
  37891. get buffer() {
  37892. return this.nodeUniform.value;
  37893. }
  37894. }
  37895. class UniformsGroup extends UniformBuffer {
  37896. constructor( name ) {
  37897. super( name );
  37898. this.isUniformsGroup = true;
  37899. this._values = null;
  37900. // the order of uniforms in this array must match the order of uniforms in the shader
  37901. this.uniforms = [];
  37902. }
  37903. addUniform( uniform ) {
  37904. this.uniforms.push( uniform );
  37905. return this;
  37906. }
  37907. removeUniform( uniform ) {
  37908. const index = this.uniforms.indexOf( uniform );
  37909. if ( index !== - 1 ) {
  37910. this.uniforms.splice( index, 1 );
  37911. }
  37912. return this;
  37913. }
  37914. get values() {
  37915. if ( this._values === null ) {
  37916. this._values = Array.from( this.buffer );
  37917. }
  37918. return this._values;
  37919. }
  37920. get buffer() {
  37921. let buffer = this._buffer;
  37922. if ( buffer === null ) {
  37923. const byteLength = this.byteLength;
  37924. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37925. this._buffer = buffer;
  37926. }
  37927. return buffer;
  37928. }
  37929. get byteLength() {
  37930. let offset = 0; // global buffer offset in bytes
  37931. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37932. const uniform = this.uniforms[ i ];
  37933. const { boundary, itemSize } = uniform;
  37934. // offset within a single chunk in bytes
  37935. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37936. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37937. // conformance tests
  37938. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37939. // check for chunk overflow
  37940. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37941. } else if ( chunkOffset % boundary !== 0 ) {
  37942. // check for correct alignment
  37943. offset += ( chunkOffset % boundary );
  37944. }
  37945. uniform.offset = ( offset / this.bytesPerElement );
  37946. offset += ( itemSize * this.bytesPerElement );
  37947. }
  37948. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37949. }
  37950. update() {
  37951. let updated = false;
  37952. for ( const uniform of this.uniforms ) {
  37953. if ( this.updateByType( uniform ) === true ) {
  37954. updated = true;
  37955. }
  37956. }
  37957. return updated;
  37958. }
  37959. updateByType( uniform ) {
  37960. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37961. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37962. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37963. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37964. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37965. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37966. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37967. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37968. }
  37969. updateNumber( uniform ) {
  37970. let updated = false;
  37971. const a = this.values;
  37972. const v = uniform.getValue();
  37973. const offset = uniform.offset;
  37974. if ( a[ offset ] !== v ) {
  37975. const b = this.buffer;
  37976. b[ offset ] = a[ offset ] = v;
  37977. updated = true;
  37978. }
  37979. return updated;
  37980. }
  37981. updateVector2( uniform ) {
  37982. let updated = false;
  37983. const a = this.values;
  37984. const v = uniform.getValue();
  37985. const offset = uniform.offset;
  37986. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37987. const b = this.buffer;
  37988. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37989. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37990. updated = true;
  37991. }
  37992. return updated;
  37993. }
  37994. updateVector3( uniform ) {
  37995. let updated = false;
  37996. const a = this.values;
  37997. const v = uniform.getValue();
  37998. const offset = uniform.offset;
  37999. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38000. const b = this.buffer;
  38001. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38002. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38003. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38004. updated = true;
  38005. }
  38006. return updated;
  38007. }
  38008. updateVector4( uniform ) {
  38009. let updated = false;
  38010. const a = this.values;
  38011. const v = uniform.getValue();
  38012. const offset = uniform.offset;
  38013. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38014. const b = this.buffer;
  38015. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38016. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38017. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38018. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38019. updated = true;
  38020. }
  38021. return updated;
  38022. }
  38023. updateColor( uniform ) {
  38024. let updated = false;
  38025. const a = this.values;
  38026. const c = uniform.getValue();
  38027. const offset = uniform.offset;
  38028. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38029. const b = this.buffer;
  38030. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38031. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38032. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38033. updated = true;
  38034. }
  38035. return updated;
  38036. }
  38037. updateMatrix3( uniform ) {
  38038. let updated = false;
  38039. const a = this.values;
  38040. const e = uniform.getValue().elements;
  38041. const offset = uniform.offset;
  38042. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38043. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38044. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38045. const b = this.buffer;
  38046. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38047. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38048. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38049. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38050. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38051. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38052. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38053. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38054. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38055. updated = true;
  38056. }
  38057. return updated;
  38058. }
  38059. updateMatrix4( uniform ) {
  38060. let updated = false;
  38061. const a = this.values;
  38062. const e = uniform.getValue().elements;
  38063. const offset = uniform.offset;
  38064. if ( arraysEqual( a, e, offset ) === false ) {
  38065. const b = this.buffer;
  38066. b.set( e, offset );
  38067. setArray( a, e, offset );
  38068. updated = true;
  38069. }
  38070. return updated;
  38071. }
  38072. }
  38073. function setArray( a, b, offset ) {
  38074. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38075. a[ offset + i ] = b[ i ];
  38076. }
  38077. }
  38078. function arraysEqual( a, b, offset ) {
  38079. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38080. if ( a[ offset + i ] !== b[ i ] ) return false;
  38081. }
  38082. return true;
  38083. }
  38084. let _id$3 = 0;
  38085. class NodeUniformsGroup extends UniformsGroup {
  38086. constructor( name, groupNode ) {
  38087. super( name );
  38088. this.id = _id$3 ++;
  38089. this.groupNode = groupNode;
  38090. this.isNodeUniformsGroup = true;
  38091. }
  38092. getNodes() {
  38093. const nodes = [];
  38094. for ( const uniform of this.uniforms ) {
  38095. const node = uniform.nodeUniform.node;
  38096. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38097. nodes.push( node );
  38098. }
  38099. return nodes;
  38100. }
  38101. }
  38102. let _id$2 = 0;
  38103. class SampledTexture extends Binding {
  38104. constructor( name, texture ) {
  38105. super( name );
  38106. this.id = _id$2 ++;
  38107. this.texture = texture;
  38108. this.version = texture ? texture.version : 0;
  38109. this.store = false;
  38110. this.isSampledTexture = true;
  38111. }
  38112. get needsBindingsUpdate() {
  38113. const { texture, version } = this;
  38114. return texture.isVideoTexture ? true : version !== texture.version; // @TODO: version === 0 && texture.version > 0 ( add it just to External Textures like PNG,JPG )
  38115. }
  38116. update() {
  38117. const { texture, version } = this;
  38118. if ( version !== texture.version ) {
  38119. this.version = texture.version;
  38120. return true;
  38121. }
  38122. return false;
  38123. }
  38124. }
  38125. class NodeSampledTexture extends SampledTexture {
  38126. constructor( name, textureNode, groupNode, access = null ) {
  38127. super( name, textureNode ? textureNode.value : null );
  38128. this.textureNode = textureNode;
  38129. this.groupNode = groupNode;
  38130. this.access = access;
  38131. }
  38132. get needsBindingsUpdate() {
  38133. return this.textureNode.value !== this.texture || super.needsBindingsUpdate;
  38134. }
  38135. update() {
  38136. const { textureNode } = this;
  38137. if ( this.texture !== textureNode.value ) {
  38138. this.texture = textureNode.value;
  38139. return true;
  38140. }
  38141. return super.update();
  38142. }
  38143. }
  38144. class NodeSampledCubeTexture extends NodeSampledTexture {
  38145. constructor( name, textureNode, groupNode, access ) {
  38146. super( name, textureNode, groupNode, access );
  38147. this.isSampledCubeTexture = true;
  38148. }
  38149. }
  38150. class NodeSampledTexture3D extends NodeSampledTexture {
  38151. constructor( name, textureNode, groupNode, access ) {
  38152. super( name, textureNode, groupNode, access );
  38153. this.isSampledTexture3D = true;
  38154. }
  38155. }
  38156. const glslMethods = {
  38157. [ MathNode.ATAN2 ]: 'atan',
  38158. textureDimensions: 'textureSize',
  38159. equals: 'equal'
  38160. };
  38161. const precisionLib = {
  38162. low: 'lowp',
  38163. medium: 'mediump',
  38164. high: 'highp'
  38165. };
  38166. const supports$1 = {
  38167. swizzleAssign: true,
  38168. storageBuffer: false
  38169. };
  38170. const defaultPrecisions = `
  38171. precision highp float;
  38172. precision highp int;
  38173. precision highp sampler2D;
  38174. precision highp sampler3D;
  38175. precision highp samplerCube;
  38176. precision highp sampler2DArray;
  38177. precision highp usampler2D;
  38178. precision highp usampler3D;
  38179. precision highp usamplerCube;
  38180. precision highp usampler2DArray;
  38181. precision highp isampler2D;
  38182. precision highp isampler3D;
  38183. precision highp isamplerCube;
  38184. precision highp isampler2DArray;
  38185. precision lowp sampler2DShadow;
  38186. `;
  38187. class GLSLNodeBuilder extends NodeBuilder {
  38188. constructor( object, renderer ) {
  38189. super( object, renderer, new GLSLNodeParser() );
  38190. this.uniformGroups = {};
  38191. this.transforms = [];
  38192. this.instanceBindGroups = false;
  38193. }
  38194. getMethod( method ) {
  38195. return glslMethods[ method ] || method;
  38196. }
  38197. getOutputStructName() {
  38198. return '';
  38199. }
  38200. buildFunctionCode( shaderNode ) {
  38201. const layout = shaderNode.layout;
  38202. const flowData = this.flowShaderNode( shaderNode );
  38203. const parameters = [];
  38204. for ( const input of layout.inputs ) {
  38205. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38206. }
  38207. //
  38208. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38209. ${ flowData.vars }
  38210. ${ flowData.code }
  38211. return ${ flowData.result };
  38212. }`;
  38213. //
  38214. return code;
  38215. }
  38216. setupPBO( storageBufferNode ) {
  38217. const attribute = storageBufferNode.value;
  38218. if ( attribute.pbo === undefined ) {
  38219. const originalArray = attribute.array;
  38220. const numElements = attribute.count * attribute.itemSize;
  38221. const { itemSize } = attribute;
  38222. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38223. let format = isInteger ? RedIntegerFormat : RedFormat;
  38224. if ( itemSize === 2 ) {
  38225. format = isInteger ? RGIntegerFormat : RGFormat;
  38226. } else if ( itemSize === 3 ) {
  38227. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38228. } else if ( itemSize === 4 ) {
  38229. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38230. }
  38231. const typeMap = {
  38232. Float32Array: FloatType,
  38233. Uint8Array: UnsignedByteType,
  38234. Uint16Array: UnsignedShortType,
  38235. Uint32Array: UnsignedIntType,
  38236. Int8Array: ByteType,
  38237. Int16Array: ShortType,
  38238. Int32Array: IntType,
  38239. Uint8ClampedArray: UnsignedByteType,
  38240. };
  38241. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38242. let height = Math.ceil( ( numElements / itemSize ) / width );
  38243. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38244. const newSize = width * height * itemSize;
  38245. const newArray = new originalArray.constructor( newSize );
  38246. newArray.set( originalArray, 0 );
  38247. attribute.array = newArray;
  38248. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38249. pboTexture.needsUpdate = true;
  38250. pboTexture.isPBOTexture = true;
  38251. const pbo = new TextureNode( pboTexture, null, null );
  38252. pbo.setPrecision( 'high' );
  38253. attribute.pboNode = pbo;
  38254. attribute.pbo = pbo.value;
  38255. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38256. }
  38257. }
  38258. getPropertyName( node, shaderStage = this.shaderStage ) {
  38259. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38260. return shaderStage.charAt( 0 ) + '_' + node.name;
  38261. }
  38262. return super.getPropertyName( node, shaderStage );
  38263. }
  38264. generatePBO( storageArrayElementNode ) {
  38265. const { node, indexNode } = storageArrayElementNode;
  38266. const attribute = node.value;
  38267. if ( this.renderer.backend.has( attribute ) ) {
  38268. const attributeData = this.renderer.backend.get( attribute );
  38269. attributeData.pbo = attribute.pbo;
  38270. }
  38271. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38272. const textureName = this.getPropertyName( nodeUniform );
  38273. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  38274. const indexSnippet = indexNode.build( this, 'uint' );
  38275. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38276. let propertyName = elementNodeData.propertyName;
  38277. if ( propertyName === undefined ) {
  38278. // property element
  38279. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38280. propertyName = this.getPropertyName( nodeVar );
  38281. // property size
  38282. const bufferNodeData = this.getDataFromNode( node );
  38283. let propertySizeName = bufferNodeData.propertySizeName;
  38284. if ( propertySizeName === undefined ) {
  38285. propertySizeName = propertyName + 'Size';
  38286. this.getVarFromNode( node, propertySizeName, 'uint' );
  38287. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  38288. bufferNodeData.propertySizeName = propertySizeName;
  38289. }
  38290. //
  38291. const { itemSize } = attribute;
  38292. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38293. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38294. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38295. //
  38296. let prefix = 'vec4';
  38297. if ( attribute.pbo.type === UnsignedIntType ) {
  38298. prefix = 'uvec4';
  38299. } else if ( attribute.pbo.type === IntType ) {
  38300. prefix = 'ivec4';
  38301. }
  38302. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  38303. elementNodeData.propertyName = propertyName;
  38304. }
  38305. return propertyName;
  38306. }
  38307. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38308. if ( depthSnippet ) {
  38309. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38310. } else {
  38311. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38312. }
  38313. }
  38314. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38315. if ( texture.isDepthTexture ) {
  38316. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38317. } else {
  38318. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38319. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38320. }
  38321. }
  38322. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38323. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38324. }
  38325. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38326. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38327. }
  38328. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38329. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38330. }
  38331. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38332. if ( shaderStage === 'fragment' ) {
  38333. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38334. } else {
  38335. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38336. }
  38337. }
  38338. getVars( shaderStage ) {
  38339. const snippets = [];
  38340. const vars = this.vars[ shaderStage ];
  38341. if ( vars !== undefined ) {
  38342. for ( const variable of vars ) {
  38343. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38344. }
  38345. }
  38346. return snippets.join( '\n\t' );
  38347. }
  38348. getUniforms( shaderStage ) {
  38349. const uniforms = this.uniforms[ shaderStage ];
  38350. const bindingSnippets = [];
  38351. const uniformGroups = {};
  38352. for ( const uniform of uniforms ) {
  38353. let snippet = null;
  38354. let group = false;
  38355. if ( uniform.type === 'texture' ) {
  38356. const texture = uniform.node.value;
  38357. let typePrefix = '';
  38358. if ( texture.isDataTexture === true ) {
  38359. if ( texture.type === UnsignedIntType ) {
  38360. typePrefix = 'u';
  38361. } else if ( texture.type === IntType ) {
  38362. typePrefix = 'i';
  38363. }
  38364. }
  38365. if ( texture.compareFunction ) {
  38366. snippet = `sampler2DShadow ${ uniform.name };`;
  38367. } else if ( texture.isDataArrayTexture === true ) {
  38368. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38369. } else {
  38370. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38371. }
  38372. } else if ( uniform.type === 'cubeTexture' ) {
  38373. snippet = `samplerCube ${ uniform.name };`;
  38374. } else if ( uniform.type === 'texture3D' ) {
  38375. snippet = `sampler3D ${ uniform.name };`;
  38376. } else if ( uniform.type === 'buffer' ) {
  38377. const bufferNode = uniform.node;
  38378. const bufferType = this.getType( bufferNode.bufferType );
  38379. const bufferCount = bufferNode.bufferCount;
  38380. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38381. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38382. } else {
  38383. const vectorType = this.getVectorType( uniform.type );
  38384. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38385. group = true;
  38386. }
  38387. const precision = uniform.node.precision;
  38388. if ( precision !== null ) {
  38389. snippet = precisionLib[ precision ] + ' ' + snippet;
  38390. }
  38391. if ( group ) {
  38392. snippet = '\t' + snippet;
  38393. const groupName = uniform.groupNode.name;
  38394. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38395. groupSnippets.push( snippet );
  38396. } else {
  38397. snippet = 'uniform ' + snippet;
  38398. bindingSnippets.push( snippet );
  38399. }
  38400. }
  38401. let output = '';
  38402. for ( const name in uniformGroups ) {
  38403. const groupSnippets = uniformGroups[ name ];
  38404. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38405. }
  38406. output += bindingSnippets.join( '\n' );
  38407. return output;
  38408. }
  38409. getTypeFromAttribute( attribute ) {
  38410. let nodeType = super.getTypeFromAttribute( attribute );
  38411. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38412. let dataAttribute = attribute;
  38413. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38414. const array = dataAttribute.array;
  38415. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38416. nodeType = nodeType.slice( 1 );
  38417. }
  38418. }
  38419. return nodeType;
  38420. }
  38421. getAttributes( shaderStage ) {
  38422. let snippet = '';
  38423. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38424. const attributes = this.getAttributesArray();
  38425. let location = 0;
  38426. for ( const attribute of attributes ) {
  38427. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38428. }
  38429. }
  38430. return snippet;
  38431. }
  38432. getStructMembers( struct ) {
  38433. const snippets = [];
  38434. const members = struct.getMemberTypes();
  38435. for ( let i = 0; i < members.length; i ++ ) {
  38436. const member = members[ i ];
  38437. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38438. }
  38439. return snippets.join( '\n' );
  38440. }
  38441. getStructs( shaderStage ) {
  38442. const snippets = [];
  38443. const structs = this.structs[ shaderStage ];
  38444. if ( structs.length === 0 ) {
  38445. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38446. }
  38447. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38448. const struct = structs[ index ];
  38449. let snippet = '\n';
  38450. snippet += this.getStructMembers( struct );
  38451. snippet += '\n';
  38452. snippets.push( snippet );
  38453. }
  38454. return snippets.join( '\n\n' );
  38455. }
  38456. getVaryings( shaderStage ) {
  38457. let snippet = '';
  38458. const varyings = this.varyings;
  38459. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38460. for ( const varying of varyings ) {
  38461. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38462. const type = varying.type;
  38463. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38464. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38465. }
  38466. } else if ( shaderStage === 'fragment' ) {
  38467. for ( const varying of varyings ) {
  38468. if ( varying.needsInterpolation ) {
  38469. const type = varying.type;
  38470. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38471. snippet += `${flat}in ${type} ${varying.name};\n`;
  38472. }
  38473. }
  38474. }
  38475. return snippet;
  38476. }
  38477. getVertexIndex() {
  38478. return 'uint( gl_VertexID )';
  38479. }
  38480. getInstanceIndex() {
  38481. return 'uint( gl_InstanceID )';
  38482. }
  38483. getDrawIndex() {
  38484. const extensions = this.renderer.backend.extensions;
  38485. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38486. return 'uint( gl_DrawID )';
  38487. }
  38488. return null;
  38489. }
  38490. getFrontFacing() {
  38491. return 'gl_FrontFacing';
  38492. }
  38493. getFragCoord() {
  38494. return 'gl_FragCoord';
  38495. }
  38496. getFragDepth() {
  38497. return 'gl_FragDepth';
  38498. }
  38499. getExtensions( shaderStage ) {
  38500. let extensions = '';
  38501. if ( shaderStage === 'vertex' ) {
  38502. const ext = this.renderer.backend.extensions;
  38503. const isBatchedMesh = this.object.isBatchedMesh;
  38504. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38505. extensions += '#extension GL_ANGLE_multi_draw : require\n';
  38506. }
  38507. }
  38508. return extensions;
  38509. }
  38510. isAvailable( name ) {
  38511. let result = supports$1[ name ];
  38512. if ( result === undefined ) {
  38513. if ( name === 'float32Filterable' ) {
  38514. const extensions = this.renderer.backend.extensions;
  38515. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38516. extensions.get( 'OES_texture_float_linear' );
  38517. result = true;
  38518. } else {
  38519. result = false;
  38520. }
  38521. }
  38522. supports$1[ name ] = result;
  38523. }
  38524. return result;
  38525. }
  38526. isFlipY() {
  38527. return true;
  38528. }
  38529. registerTransform( varyingName, attributeNode ) {
  38530. this.transforms.push( { varyingName, attributeNode } );
  38531. }
  38532. getTransforms( /* shaderStage */ ) {
  38533. const transforms = this.transforms;
  38534. let snippet = '';
  38535. for ( let i = 0; i < transforms.length; i ++ ) {
  38536. const transform = transforms[ i ];
  38537. const attributeName = this.getPropertyName( transform.attributeNode );
  38538. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38539. }
  38540. return snippet;
  38541. }
  38542. _getGLSLUniformStruct( name, vars ) {
  38543. return `
  38544. layout( std140 ) uniform ${name} {
  38545. ${vars}
  38546. };`;
  38547. }
  38548. _getGLSLVertexCode( shaderData ) {
  38549. return `#version 300 es
  38550. // extensions
  38551. ${shaderData.extensions}
  38552. // precision
  38553. ${ defaultPrecisions }
  38554. // uniforms
  38555. ${shaderData.uniforms}
  38556. // varyings
  38557. ${shaderData.varyings}
  38558. // attributes
  38559. ${shaderData.attributes}
  38560. // codes
  38561. ${shaderData.codes}
  38562. void main() {
  38563. // vars
  38564. ${shaderData.vars}
  38565. // transforms
  38566. ${shaderData.transforms}
  38567. // flow
  38568. ${shaderData.flow}
  38569. gl_PointSize = 1.0;
  38570. }
  38571. `;
  38572. }
  38573. _getGLSLFragmentCode( shaderData ) {
  38574. return `#version 300 es
  38575. ${ this.getSignature() }
  38576. // precision
  38577. ${ defaultPrecisions }
  38578. // uniforms
  38579. ${shaderData.uniforms}
  38580. // varyings
  38581. ${shaderData.varyings}
  38582. // codes
  38583. ${shaderData.codes}
  38584. ${shaderData.structs}
  38585. void main() {
  38586. // vars
  38587. ${shaderData.vars}
  38588. // flow
  38589. ${shaderData.flow}
  38590. }
  38591. `;
  38592. }
  38593. buildCode() {
  38594. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38595. for ( const shaderStage in shadersData ) {
  38596. let flow = '// code\n\n';
  38597. flow += this.flowCode[ shaderStage ];
  38598. const flowNodes = this.flowNodes[ shaderStage ];
  38599. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38600. for ( const node of flowNodes ) {
  38601. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38602. const slotName = node.name;
  38603. if ( slotName ) {
  38604. if ( flow.length > 0 ) flow += '\n';
  38605. flow += `\t// flow -> ${ slotName }\n\t`;
  38606. }
  38607. flow += `${ flowSlotData.code }\n\t`;
  38608. if ( node === mainNode && shaderStage !== 'compute' ) {
  38609. flow += '// result\n\t';
  38610. if ( shaderStage === 'vertex' ) {
  38611. flow += 'gl_Position = ';
  38612. flow += `${ flowSlotData.result };`;
  38613. } else if ( shaderStage === 'fragment' ) {
  38614. if ( ! node.outputNode.isOutputStructNode ) {
  38615. flow += 'fragColor = ';
  38616. flow += `${ flowSlotData.result };`;
  38617. }
  38618. }
  38619. }
  38620. }
  38621. const stageData = shadersData[ shaderStage ];
  38622. stageData.extensions = this.getExtensions( shaderStage );
  38623. stageData.uniforms = this.getUniforms( shaderStage );
  38624. stageData.attributes = this.getAttributes( shaderStage );
  38625. stageData.varyings = this.getVaryings( shaderStage );
  38626. stageData.vars = this.getVars( shaderStage );
  38627. stageData.structs = this.getStructs( shaderStage );
  38628. stageData.codes = this.getCodes( shaderStage );
  38629. stageData.transforms = this.getTransforms( shaderStage );
  38630. stageData.flow = flow;
  38631. }
  38632. if ( this.material !== null ) {
  38633. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38634. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38635. } else {
  38636. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38637. }
  38638. }
  38639. getUniformFromNode( node, type, shaderStage, name = null ) {
  38640. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38641. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38642. let uniformGPU = nodeData.uniformGPU;
  38643. if ( uniformGPU === undefined ) {
  38644. const group = node.groupNode;
  38645. const groupName = group.name;
  38646. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38647. if ( type === 'texture' ) {
  38648. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38649. bindings.push( uniformGPU );
  38650. } else if ( type === 'cubeTexture' ) {
  38651. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38652. bindings.push( uniformGPU );
  38653. } else if ( type === 'texture3D' ) {
  38654. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38655. bindings.push( uniformGPU );
  38656. } else if ( type === 'buffer' ) {
  38657. node.name = `NodeBuffer_${ node.id }`;
  38658. uniformNode.name = `buffer${ node.id }`;
  38659. const buffer = new NodeUniformBuffer( node, group );
  38660. buffer.name = node.name;
  38661. bindings.push( buffer );
  38662. uniformGPU = buffer;
  38663. } else {
  38664. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38665. let uniformsGroup = uniformsStage[ groupName ];
  38666. if ( uniformsGroup === undefined ) {
  38667. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38668. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38669. uniformsStage[ groupName ] = uniformsGroup;
  38670. bindings.push( uniformsGroup );
  38671. }
  38672. uniformGPU = this.getNodeUniform( uniformNode, type );
  38673. uniformsGroup.addUniform( uniformGPU );
  38674. }
  38675. nodeData.uniformGPU = uniformGPU;
  38676. }
  38677. return uniformNode;
  38678. }
  38679. }
  38680. let vector2 = null;
  38681. let vector4 = null;
  38682. let color4 = null;
  38683. class Backend {
  38684. constructor( parameters = {} ) {
  38685. this.parameters = Object.assign( {}, parameters );
  38686. this.data = new WeakMap();
  38687. this.renderer = null;
  38688. this.domElement = null;
  38689. }
  38690. async init( renderer ) {
  38691. this.renderer = renderer;
  38692. }
  38693. // render context
  38694. begin( /*renderContext*/ ) { }
  38695. finish( /*renderContext*/ ) { }
  38696. // render object
  38697. draw( /*renderObject, info*/ ) { }
  38698. // program
  38699. createProgram( /*program*/ ) { }
  38700. destroyProgram( /*program*/ ) { }
  38701. // bindings
  38702. createBindings( /*renderObject*/ ) { }
  38703. updateBindings( /*renderObject*/ ) { }
  38704. // pipeline
  38705. createRenderPipeline( /*renderObject*/ ) { }
  38706. createComputePipeline( /*computeNode, pipeline*/ ) { }
  38707. destroyPipeline( /*pipeline*/ ) { }
  38708. // cache key
  38709. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  38710. getRenderCacheKey( /*renderObject*/ ) { } // return String
  38711. // node builder
  38712. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  38713. // textures
  38714. createSampler( /*texture*/ ) { }
  38715. createDefaultTexture( /*texture*/ ) { }
  38716. createTexture( /*texture*/ ) { }
  38717. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  38718. // attributes
  38719. createAttribute( /*attribute*/ ) { }
  38720. createIndexAttribute( /*attribute*/ ) { }
  38721. updateAttribute( /*attribute*/ ) { }
  38722. destroyAttribute( /*attribute*/ ) { }
  38723. // canvas
  38724. getContext() { }
  38725. updateSize() { }
  38726. // utils
  38727. resolveTimestampAsync( /*renderContext, type*/ ) { }
  38728. hasFeatureAsync( /*name*/ ) { } // return Boolean
  38729. hasFeature( /*name*/ ) { } // return Boolean
  38730. getInstanceCount( renderObject ) {
  38731. const { object, geometry } = renderObject;
  38732. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  38733. }
  38734. getDrawingBufferSize() {
  38735. vector2 = vector2 || new Vector2();
  38736. return this.renderer.getDrawingBufferSize( vector2 );
  38737. }
  38738. getScissor() {
  38739. vector4 = vector4 || new Vector4();
  38740. return this.renderer.getScissor( vector4 );
  38741. }
  38742. setScissorTest( /*boolean*/ ) { }
  38743. getClearColor() {
  38744. const renderer = this.renderer;
  38745. color4 = color4 || new Color4();
  38746. renderer.getClearColor( color4 );
  38747. color4.getRGB( color4, this.renderer.currentColorSpace );
  38748. return color4;
  38749. }
  38750. getDomElement() {
  38751. let domElement = this.domElement;
  38752. if ( domElement === null ) {
  38753. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38754. // OffscreenCanvas does not have setAttribute, see #22811
  38755. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38756. this.domElement = domElement;
  38757. }
  38758. return domElement;
  38759. }
  38760. // resource properties
  38761. set( object, value ) {
  38762. this.data.set( object, value );
  38763. }
  38764. get( object ) {
  38765. let map = this.data.get( object );
  38766. if ( map === undefined ) {
  38767. map = {};
  38768. this.data.set( object, map );
  38769. }
  38770. return map;
  38771. }
  38772. has( object ) {
  38773. return this.data.has( object );
  38774. }
  38775. delete( object ) {
  38776. this.data.delete( object );
  38777. }
  38778. }
  38779. let _id$1 = 0;
  38780. class DualAttributeData {
  38781. constructor( attributeData, dualBuffer ) {
  38782. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38783. this.type = attributeData.type;
  38784. this.bufferType = attributeData.bufferType;
  38785. this.pbo = attributeData.pbo;
  38786. this.byteLength = attributeData.byteLength;
  38787. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38788. this.version = attributeData.version;
  38789. this.isInteger = attributeData.isInteger;
  38790. this.activeBufferIndex = 0;
  38791. this.baseId = attributeData.id;
  38792. }
  38793. get id() {
  38794. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38795. }
  38796. get bufferGPU() {
  38797. return this.buffers[ this.activeBufferIndex ];
  38798. }
  38799. get transformBuffer() {
  38800. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38801. }
  38802. switchBuffers() {
  38803. this.activeBufferIndex ^= 1;
  38804. }
  38805. }
  38806. class WebGLAttributeUtils {
  38807. constructor( backend ) {
  38808. this.backend = backend;
  38809. }
  38810. createAttribute( attribute, bufferType ) {
  38811. const backend = this.backend;
  38812. const { gl } = backend;
  38813. const array = attribute.array;
  38814. const usage = attribute.usage || gl.STATIC_DRAW;
  38815. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38816. const bufferData = backend.get( bufferAttribute );
  38817. let bufferGPU = bufferData.bufferGPU;
  38818. if ( bufferGPU === undefined ) {
  38819. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38820. bufferData.bufferGPU = bufferGPU;
  38821. bufferData.bufferType = bufferType;
  38822. bufferData.version = bufferAttribute.version;
  38823. }
  38824. //attribute.onUploadCallback();
  38825. let type;
  38826. if ( array instanceof Float32Array ) {
  38827. type = gl.FLOAT;
  38828. } else if ( array instanceof Uint16Array ) {
  38829. if ( attribute.isFloat16BufferAttribute ) {
  38830. type = gl.HALF_FLOAT;
  38831. } else {
  38832. type = gl.UNSIGNED_SHORT;
  38833. }
  38834. } else if ( array instanceof Int16Array ) {
  38835. type = gl.SHORT;
  38836. } else if ( array instanceof Uint32Array ) {
  38837. type = gl.UNSIGNED_INT;
  38838. } else if ( array instanceof Int32Array ) {
  38839. type = gl.INT;
  38840. } else if ( array instanceof Int8Array ) {
  38841. type = gl.BYTE;
  38842. } else if ( array instanceof Uint8Array ) {
  38843. type = gl.UNSIGNED_BYTE;
  38844. } else if ( array instanceof Uint8ClampedArray ) {
  38845. type = gl.UNSIGNED_BYTE;
  38846. } else {
  38847. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38848. }
  38849. let attributeData = {
  38850. bufferGPU,
  38851. bufferType,
  38852. type,
  38853. byteLength: array.byteLength,
  38854. bytesPerElement: array.BYTES_PER_ELEMENT,
  38855. version: attribute.version,
  38856. pbo: attribute.pbo,
  38857. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38858. id: _id$1 ++
  38859. };
  38860. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38861. // create buffer for tranform feedback use
  38862. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38863. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38864. }
  38865. backend.set( attribute, attributeData );
  38866. }
  38867. updateAttribute( attribute ) {
  38868. const backend = this.backend;
  38869. const { gl } = backend;
  38870. const array = attribute.array;
  38871. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38872. const bufferData = backend.get( bufferAttribute );
  38873. const bufferType = bufferData.bufferType;
  38874. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38875. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38876. if ( updateRanges.length === 0 ) {
  38877. // Not using update ranges
  38878. gl.bufferSubData( bufferType, 0, array );
  38879. } else {
  38880. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38881. const range = updateRanges[ i ];
  38882. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38883. array, range.start, range.count );
  38884. }
  38885. bufferAttribute.clearUpdateRanges();
  38886. }
  38887. gl.bindBuffer( bufferType, null );
  38888. bufferData.version = bufferAttribute.version;
  38889. }
  38890. destroyAttribute( attribute ) {
  38891. const backend = this.backend;
  38892. const { gl } = backend;
  38893. if ( attribute.isInterleavedBufferAttribute ) {
  38894. backend.delete( attribute.data );
  38895. }
  38896. const attributeData = backend.get( attribute );
  38897. gl.deleteBuffer( attributeData.bufferGPU );
  38898. backend.delete( attribute );
  38899. }
  38900. async getArrayBufferAsync( attribute ) {
  38901. const backend = this.backend;
  38902. const { gl } = backend;
  38903. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38904. const { bufferGPU } = backend.get( bufferAttribute );
  38905. const array = attribute.array;
  38906. const byteLength = array.byteLength;
  38907. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38908. const writeBuffer = gl.createBuffer();
  38909. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38910. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38911. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38912. await backend.utils._clientWaitAsync();
  38913. const dstBuffer = new attribute.array.constructor( array.length );
  38914. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38915. gl.deleteBuffer( writeBuffer );
  38916. return dstBuffer.buffer;
  38917. }
  38918. _createBuffer( gl, bufferType, array, usage ) {
  38919. const bufferGPU = gl.createBuffer();
  38920. gl.bindBuffer( bufferType, bufferGPU );
  38921. gl.bufferData( bufferType, array, usage );
  38922. gl.bindBuffer( bufferType, null );
  38923. return bufferGPU;
  38924. }
  38925. }
  38926. let initialized$1 = false, equationToGL, factorToGL;
  38927. class WebGLState {
  38928. constructor( backend ) {
  38929. this.backend = backend;
  38930. this.gl = this.backend.gl;
  38931. this.enabled = {};
  38932. this.currentFlipSided = null;
  38933. this.currentCullFace = null;
  38934. this.currentProgram = null;
  38935. this.currentBlendingEnabled = false;
  38936. this.currentBlending = null;
  38937. this.currentBlendSrc = null;
  38938. this.currentBlendDst = null;
  38939. this.currentBlendSrcAlpha = null;
  38940. this.currentBlendDstAlpha = null;
  38941. this.currentPremultipledAlpha = null;
  38942. this.currentPolygonOffsetFactor = null;
  38943. this.currentPolygonOffsetUnits = null;
  38944. this.currentColorMask = null;
  38945. this.currentDepthFunc = null;
  38946. this.currentDepthMask = null;
  38947. this.currentStencilFunc = null;
  38948. this.currentStencilRef = null;
  38949. this.currentStencilFuncMask = null;
  38950. this.currentStencilFail = null;
  38951. this.currentStencilZFail = null;
  38952. this.currentStencilZPass = null;
  38953. this.currentStencilMask = null;
  38954. this.currentLineWidth = null;
  38955. this.currentBoundFramebuffers = {};
  38956. this.currentDrawbuffers = new WeakMap();
  38957. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38958. this.currentTextureSlot = null;
  38959. this.currentBoundTextures = {};
  38960. if ( initialized$1 === false ) {
  38961. this._init( this.gl );
  38962. initialized$1 = true;
  38963. }
  38964. }
  38965. _init( gl ) {
  38966. // Store only WebGL constants here.
  38967. equationToGL = {
  38968. [ AddEquation ]: gl.FUNC_ADD,
  38969. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38970. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38971. };
  38972. factorToGL = {
  38973. [ ZeroFactor ]: gl.ZERO,
  38974. [ OneFactor ]: gl.ONE,
  38975. [ SrcColorFactor ]: gl.SRC_COLOR,
  38976. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38977. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38978. [ DstColorFactor ]: gl.DST_COLOR,
  38979. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38980. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38981. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38982. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38983. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38984. };
  38985. }
  38986. enable( id ) {
  38987. const { enabled } = this;
  38988. if ( enabled[ id ] !== true ) {
  38989. this.gl.enable( id );
  38990. enabled[ id ] = true;
  38991. }
  38992. }
  38993. disable( id ) {
  38994. const { enabled } = this;
  38995. if ( enabled[ id ] !== false ) {
  38996. this.gl.disable( id );
  38997. enabled[ id ] = false;
  38998. }
  38999. }
  39000. setFlipSided( flipSided ) {
  39001. if ( this.currentFlipSided !== flipSided ) {
  39002. const { gl } = this;
  39003. if ( flipSided ) {
  39004. gl.frontFace( gl.CW );
  39005. } else {
  39006. gl.frontFace( gl.CCW );
  39007. }
  39008. this.currentFlipSided = flipSided;
  39009. }
  39010. }
  39011. setCullFace( cullFace ) {
  39012. const { gl } = this;
  39013. if ( cullFace !== CullFaceNone ) {
  39014. this.enable( gl.CULL_FACE );
  39015. if ( cullFace !== this.currentCullFace ) {
  39016. if ( cullFace === CullFaceBack ) {
  39017. gl.cullFace( gl.BACK );
  39018. } else if ( cullFace === CullFaceFront ) {
  39019. gl.cullFace( gl.FRONT );
  39020. } else {
  39021. gl.cullFace( gl.FRONT_AND_BACK );
  39022. }
  39023. }
  39024. } else {
  39025. this.disable( gl.CULL_FACE );
  39026. }
  39027. this.currentCullFace = cullFace;
  39028. }
  39029. setLineWidth( width ) {
  39030. const { currentLineWidth, gl } = this;
  39031. if ( width !== currentLineWidth ) {
  39032. gl.lineWidth( width );
  39033. this.currentLineWidth = width;
  39034. }
  39035. }
  39036. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39037. const { gl } = this;
  39038. if ( blending === NoBlending ) {
  39039. if ( this.currentBlendingEnabled === true ) {
  39040. this.disable( gl.BLEND );
  39041. this.currentBlendingEnabled = false;
  39042. }
  39043. return;
  39044. }
  39045. if ( this.currentBlendingEnabled === false ) {
  39046. this.enable( gl.BLEND );
  39047. this.currentBlendingEnabled = true;
  39048. }
  39049. if ( blending !== CustomBlending ) {
  39050. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39051. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39052. gl.blendEquation( gl.FUNC_ADD );
  39053. this.currentBlendEquation = AddEquation;
  39054. this.currentBlendEquationAlpha = AddEquation;
  39055. }
  39056. if ( premultipliedAlpha ) {
  39057. switch ( blending ) {
  39058. case NormalBlending:
  39059. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39060. break;
  39061. case AdditiveBlending:
  39062. gl.blendFunc( gl.ONE, gl.ONE );
  39063. break;
  39064. case SubtractiveBlending:
  39065. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39066. break;
  39067. case MultiplyBlending:
  39068. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39069. break;
  39070. default:
  39071. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39072. break;
  39073. }
  39074. } else {
  39075. switch ( blending ) {
  39076. case NormalBlending:
  39077. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39078. break;
  39079. case AdditiveBlending:
  39080. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39081. break;
  39082. case SubtractiveBlending:
  39083. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39084. break;
  39085. case MultiplyBlending:
  39086. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39087. break;
  39088. default:
  39089. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39090. break;
  39091. }
  39092. }
  39093. this.currentBlendSrc = null;
  39094. this.currentBlendDst = null;
  39095. this.currentBlendSrcAlpha = null;
  39096. this.currentBlendDstAlpha = null;
  39097. this.currentBlending = blending;
  39098. this.currentPremultipledAlpha = premultipliedAlpha;
  39099. }
  39100. return;
  39101. }
  39102. // custom blending
  39103. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39104. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39105. blendDstAlpha = blendDstAlpha || blendDst;
  39106. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39107. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39108. this.currentBlendEquation = blendEquation;
  39109. this.currentBlendEquationAlpha = blendEquationAlpha;
  39110. }
  39111. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39112. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39113. this.currentBlendSrc = blendSrc;
  39114. this.currentBlendDst = blendDst;
  39115. this.currentBlendSrcAlpha = blendSrcAlpha;
  39116. this.currentBlendDstAlpha = blendDstAlpha;
  39117. }
  39118. this.currentBlending = blending;
  39119. this.currentPremultipledAlpha = false;
  39120. }
  39121. setColorMask( colorMask ) {
  39122. if ( this.currentColorMask !== colorMask ) {
  39123. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39124. this.currentColorMask = colorMask;
  39125. }
  39126. }
  39127. setDepthTest( depthTest ) {
  39128. const { gl } = this;
  39129. if ( depthTest ) {
  39130. this.enable( gl.DEPTH_TEST );
  39131. } else {
  39132. this.disable( gl.DEPTH_TEST );
  39133. }
  39134. }
  39135. setDepthMask( depthMask ) {
  39136. if ( this.currentDepthMask !== depthMask ) {
  39137. this.gl.depthMask( depthMask );
  39138. this.currentDepthMask = depthMask;
  39139. }
  39140. }
  39141. setDepthFunc( depthFunc ) {
  39142. if ( this.currentDepthFunc !== depthFunc ) {
  39143. const { gl } = this;
  39144. switch ( depthFunc ) {
  39145. case NeverDepth:
  39146. gl.depthFunc( gl.NEVER );
  39147. break;
  39148. case AlwaysDepth:
  39149. gl.depthFunc( gl.ALWAYS );
  39150. break;
  39151. case LessDepth:
  39152. gl.depthFunc( gl.LESS );
  39153. break;
  39154. case LessEqualDepth:
  39155. gl.depthFunc( gl.LEQUAL );
  39156. break;
  39157. case EqualDepth:
  39158. gl.depthFunc( gl.EQUAL );
  39159. break;
  39160. case GreaterEqualDepth:
  39161. gl.depthFunc( gl.GEQUAL );
  39162. break;
  39163. case GreaterDepth:
  39164. gl.depthFunc( gl.GREATER );
  39165. break;
  39166. case NotEqualDepth:
  39167. gl.depthFunc( gl.NOTEQUAL );
  39168. break;
  39169. default:
  39170. gl.depthFunc( gl.LEQUAL );
  39171. }
  39172. this.currentDepthFunc = depthFunc;
  39173. }
  39174. }
  39175. setStencilTest( stencilTest ) {
  39176. const { gl } = this;
  39177. if ( stencilTest ) {
  39178. this.enable( gl.STENCIL_TEST );
  39179. } else {
  39180. this.disable( gl.STENCIL_TEST );
  39181. }
  39182. }
  39183. setStencilMask( stencilMask ) {
  39184. if ( this.currentStencilMask !== stencilMask ) {
  39185. this.gl.stencilMask( stencilMask );
  39186. this.currentStencilMask = stencilMask;
  39187. }
  39188. }
  39189. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39190. if ( this.currentStencilFunc !== stencilFunc ||
  39191. this.currentStencilRef !== stencilRef ||
  39192. this.currentStencilFuncMask !== stencilMask ) {
  39193. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39194. this.currentStencilFunc = stencilFunc;
  39195. this.currentStencilRef = stencilRef;
  39196. this.currentStencilFuncMask = stencilMask;
  39197. }
  39198. }
  39199. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39200. if ( this.currentStencilFail !== stencilFail ||
  39201. this.currentStencilZFail !== stencilZFail ||
  39202. this.currentStencilZPass !== stencilZPass ) {
  39203. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39204. this.currentStencilFail = stencilFail;
  39205. this.currentStencilZFail = stencilZFail;
  39206. this.currentStencilZPass = stencilZPass;
  39207. }
  39208. }
  39209. setMaterial( material, frontFaceCW ) {
  39210. const { gl } = this;
  39211. material.side === DoubleSide
  39212. ? this.disable( gl.CULL_FACE )
  39213. : this.enable( gl.CULL_FACE );
  39214. let flipSided = ( material.side === BackSide );
  39215. if ( frontFaceCW ) flipSided = ! flipSided;
  39216. this.setFlipSided( flipSided );
  39217. ( material.blending === NormalBlending && material.transparent === false )
  39218. ? this.setBlending( NoBlending )
  39219. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39220. this.setDepthFunc( material.depthFunc );
  39221. this.setDepthTest( material.depthTest );
  39222. this.setDepthMask( material.depthWrite );
  39223. this.setColorMask( material.colorWrite );
  39224. const stencilWrite = material.stencilWrite;
  39225. this.setStencilTest( stencilWrite );
  39226. if ( stencilWrite ) {
  39227. this.setStencilMask( material.stencilWriteMask );
  39228. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39229. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39230. }
  39231. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39232. material.alphaToCoverage === true
  39233. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39234. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39235. }
  39236. setPolygonOffset( polygonOffset, factor, units ) {
  39237. const { gl } = this;
  39238. if ( polygonOffset ) {
  39239. this.enable( gl.POLYGON_OFFSET_FILL );
  39240. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39241. gl.polygonOffset( factor, units );
  39242. this.currentPolygonOffsetFactor = factor;
  39243. this.currentPolygonOffsetUnits = units;
  39244. }
  39245. } else {
  39246. this.disable( gl.POLYGON_OFFSET_FILL );
  39247. }
  39248. }
  39249. useProgram( program ) {
  39250. if ( this.currentProgram !== program ) {
  39251. this.gl.useProgram( program );
  39252. this.currentProgram = program;
  39253. return true;
  39254. }
  39255. return false;
  39256. }
  39257. // framebuffer
  39258. bindFramebuffer( target, framebuffer ) {
  39259. const { gl, currentBoundFramebuffers } = this;
  39260. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39261. gl.bindFramebuffer( target, framebuffer );
  39262. currentBoundFramebuffers[ target ] = framebuffer;
  39263. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39264. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39265. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39266. }
  39267. if ( target === gl.FRAMEBUFFER ) {
  39268. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39269. }
  39270. return true;
  39271. }
  39272. return false;
  39273. }
  39274. drawBuffers( renderContext, framebuffer ) {
  39275. const { gl } = this;
  39276. let drawBuffers = [];
  39277. let needsUpdate = false;
  39278. if ( renderContext.textures !== null ) {
  39279. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39280. if ( drawBuffers === undefined ) {
  39281. drawBuffers = [];
  39282. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39283. }
  39284. const textures = renderContext.textures;
  39285. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39286. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39287. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39288. }
  39289. drawBuffers.length = textures.length;
  39290. needsUpdate = true;
  39291. }
  39292. } else {
  39293. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39294. drawBuffers[ 0 ] = gl.BACK;
  39295. needsUpdate = true;
  39296. }
  39297. }
  39298. if ( needsUpdate ) {
  39299. gl.drawBuffers( drawBuffers );
  39300. }
  39301. }
  39302. // texture
  39303. activeTexture( webglSlot ) {
  39304. const { gl, currentTextureSlot, maxTextures } = this;
  39305. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39306. if ( currentTextureSlot !== webglSlot ) {
  39307. gl.activeTexture( webglSlot );
  39308. this.currentTextureSlot = webglSlot;
  39309. }
  39310. }
  39311. bindTexture( webglType, webglTexture, webglSlot ) {
  39312. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39313. if ( webglSlot === undefined ) {
  39314. if ( currentTextureSlot === null ) {
  39315. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39316. } else {
  39317. webglSlot = currentTextureSlot;
  39318. }
  39319. }
  39320. let boundTexture = currentBoundTextures[ webglSlot ];
  39321. if ( boundTexture === undefined ) {
  39322. boundTexture = { type: undefined, texture: undefined };
  39323. currentBoundTextures[ webglSlot ] = boundTexture;
  39324. }
  39325. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39326. if ( currentTextureSlot !== webglSlot ) {
  39327. gl.activeTexture( webglSlot );
  39328. this.currentTextureSlot = webglSlot;
  39329. }
  39330. gl.bindTexture( webglType, webglTexture );
  39331. boundTexture.type = webglType;
  39332. boundTexture.texture = webglTexture;
  39333. }
  39334. }
  39335. unbindTexture() {
  39336. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39337. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39338. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39339. gl.bindTexture( boundTexture.type, null );
  39340. boundTexture.type = undefined;
  39341. boundTexture.texture = undefined;
  39342. }
  39343. }
  39344. }
  39345. class WebGLUtils {
  39346. constructor( backend ) {
  39347. this.backend = backend;
  39348. this.gl = this.backend.gl;
  39349. this.extensions = backend.extensions;
  39350. }
  39351. convert( p, colorSpace = NoColorSpace ) {
  39352. const { gl, extensions } = this;
  39353. let extension;
  39354. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39355. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39356. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39357. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39358. if ( p === ByteType ) return gl.BYTE;
  39359. if ( p === ShortType ) return gl.SHORT;
  39360. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39361. if ( p === IntType ) return gl.INT;
  39362. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39363. if ( p === FloatType ) return gl.FLOAT;
  39364. if ( p === HalfFloatType ) {
  39365. return gl.HALF_FLOAT;
  39366. }
  39367. if ( p === AlphaFormat ) return gl.ALPHA;
  39368. if ( p === RGBFormat ) return gl.RGB;
  39369. if ( p === RGBAFormat ) return gl.RGBA;
  39370. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39371. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39372. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39373. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39374. // WebGL2 formats.
  39375. if ( p === RedFormat ) return gl.RED;
  39376. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39377. if ( p === RGFormat ) return gl.RG;
  39378. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39379. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39380. // S3TC
  39381. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39382. if ( colorSpace === SRGBColorSpace ) {
  39383. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39384. if ( extension !== null ) {
  39385. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39386. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39387. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39388. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39389. } else {
  39390. return null;
  39391. }
  39392. } else {
  39393. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39394. if ( extension !== null ) {
  39395. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39396. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39397. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39398. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39399. } else {
  39400. return null;
  39401. }
  39402. }
  39403. }
  39404. // PVRTC
  39405. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39406. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39407. if ( extension !== null ) {
  39408. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39409. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39410. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39411. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39412. } else {
  39413. return null;
  39414. }
  39415. }
  39416. // ETC
  39417. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39418. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39419. if ( extension !== null ) {
  39420. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39421. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39422. } else {
  39423. return null;
  39424. }
  39425. }
  39426. // ASTC
  39427. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39428. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39429. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39430. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39431. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39432. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39433. if ( extension !== null ) {
  39434. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39435. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39436. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39437. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39438. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39439. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39440. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39441. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39442. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39443. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39444. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39445. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39446. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39447. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39448. } else {
  39449. return null;
  39450. }
  39451. }
  39452. // BPTC
  39453. if ( p === RGBA_BPTC_Format ) {
  39454. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39455. if ( extension !== null ) {
  39456. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39457. } else {
  39458. return null;
  39459. }
  39460. }
  39461. // RGTC
  39462. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39463. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39464. if ( extension !== null ) {
  39465. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39466. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39467. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39468. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39469. } else {
  39470. return null;
  39471. }
  39472. }
  39473. //
  39474. if ( p === UnsignedInt248Type ) {
  39475. return gl.UNSIGNED_INT_24_8;
  39476. }
  39477. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39478. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39479. }
  39480. _clientWaitAsync() {
  39481. const { gl } = this;
  39482. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39483. gl.flush();
  39484. return new Promise( ( resolve, reject ) => {
  39485. function test() {
  39486. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39487. if ( res === gl.WAIT_FAILED ) {
  39488. gl.deleteSync( sync );
  39489. reject();
  39490. return;
  39491. }
  39492. if ( res === gl.TIMEOUT_EXPIRED ) {
  39493. requestAnimationFrame( test );
  39494. return;
  39495. }
  39496. gl.deleteSync( sync );
  39497. resolve();
  39498. }
  39499. test();
  39500. } );
  39501. }
  39502. }
  39503. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39504. class WebGLTextureUtils {
  39505. constructor( backend ) {
  39506. this.backend = backend;
  39507. this.gl = backend.gl;
  39508. this.extensions = backend.extensions;
  39509. this.defaultTextures = {};
  39510. if ( initialized === false ) {
  39511. this._init( this.gl );
  39512. initialized = true;
  39513. }
  39514. }
  39515. _init( gl ) {
  39516. // Store only WebGL constants here.
  39517. wrappingToGL = {
  39518. [ RepeatWrapping ]: gl.REPEAT,
  39519. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39520. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39521. };
  39522. filterToGL = {
  39523. [ NearestFilter ]: gl.NEAREST,
  39524. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39525. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39526. [ LinearFilter ]: gl.LINEAR,
  39527. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39528. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39529. };
  39530. compareToGL = {
  39531. [ NeverCompare ]: gl.NEVER,
  39532. [ AlwaysCompare ]: gl.ALWAYS,
  39533. [ LessCompare ]: gl.LESS,
  39534. [ LessEqualCompare ]: gl.LEQUAL,
  39535. [ EqualCompare ]: gl.EQUAL,
  39536. [ GreaterEqualCompare ]: gl.GEQUAL,
  39537. [ GreaterCompare ]: gl.GREATER,
  39538. [ NotEqualCompare ]: gl.NOTEQUAL
  39539. };
  39540. }
  39541. filterFallback( f ) {
  39542. const { gl } = this;
  39543. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  39544. return gl.NEAREST;
  39545. }
  39546. return gl.LINEAR;
  39547. }
  39548. getGLTextureType( texture ) {
  39549. const { gl } = this;
  39550. let glTextureType;
  39551. if ( texture.isCubeTexture === true ) {
  39552. glTextureType = gl.TEXTURE_CUBE_MAP;
  39553. } else if ( texture.isDataArrayTexture === true ) {
  39554. glTextureType = gl.TEXTURE_2D_ARRAY;
  39555. } else if ( texture.isData3DTexture === true ) {
  39556. glTextureType = gl.TEXTURE_3D;
  39557. } else {
  39558. glTextureType = gl.TEXTURE_2D;
  39559. }
  39560. return glTextureType;
  39561. }
  39562. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39563. const { gl, extensions } = this;
  39564. if ( internalFormatName !== null ) {
  39565. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39566. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39567. }
  39568. let internalFormat = glFormat;
  39569. if ( glFormat === gl.RED ) {
  39570. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39571. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39572. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39573. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39574. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39575. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39576. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39577. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39578. }
  39579. if ( glFormat === gl.RED_INTEGER ) {
  39580. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39581. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39582. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39583. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39584. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39585. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39586. }
  39587. if ( glFormat === gl.RG ) {
  39588. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39589. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39590. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39591. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39592. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39593. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39594. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39595. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39596. }
  39597. if ( glFormat === gl.RG_INTEGER ) {
  39598. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39599. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39600. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39601. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39602. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39603. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39604. }
  39605. if ( glFormat === gl.RGB ) {
  39606. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39607. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39608. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39609. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39610. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39611. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39612. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39613. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39614. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39615. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39616. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39617. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39618. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39619. }
  39620. if ( glFormat === gl.RGB_INTEGER ) {
  39621. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39622. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39623. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39624. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39625. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39626. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39627. }
  39628. if ( glFormat === gl.RGBA ) {
  39629. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39630. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39631. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39632. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39633. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39634. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39635. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39636. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39637. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39638. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39639. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39640. }
  39641. if ( glFormat === gl.RGBA_INTEGER ) {
  39642. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39643. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39644. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39645. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39646. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39647. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39648. }
  39649. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39650. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39651. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39652. }
  39653. if ( glFormat === gl.DEPTH_STENCIL ) {
  39654. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39655. }
  39656. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39657. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39658. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39659. extensions.get( 'EXT_color_buffer_float' );
  39660. }
  39661. return internalFormat;
  39662. }
  39663. setTextureParameters( textureType, texture ) {
  39664. const { gl, extensions, backend } = this;
  39665. const { currentAnisotropy } = backend.get( texture );
  39666. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39667. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39668. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39669. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39670. }
  39671. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39672. // follow WebGPU backend mapping for texture filtering
  39673. const minFilter = ! texture.isVideoTexture && texture.minFilter === LinearFilter ? LinearMipmapLinearFilter : texture.minFilter;
  39674. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39675. if ( texture.compareFunction ) {
  39676. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39677. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39678. }
  39679. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39680. if ( texture.magFilter === NearestFilter ) return;
  39681. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39682. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39683. if ( texture.anisotropy > 1 || currentAnisotropy !== texture.anisotropy ) {
  39684. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39685. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39686. backend.get( texture ).currentAnisotropy = texture.anisotropy;
  39687. }
  39688. }
  39689. }
  39690. createDefaultTexture( texture ) {
  39691. const { gl, backend, defaultTextures } = this;
  39692. const glTextureType = this.getGLTextureType( texture );
  39693. let textureGPU = defaultTextures[ glTextureType ];
  39694. if ( textureGPU === undefined ) {
  39695. textureGPU = gl.createTexture();
  39696. backend.state.bindTexture( glTextureType, textureGPU );
  39697. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39698. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39699. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39700. defaultTextures[ glTextureType ] = textureGPU;
  39701. }
  39702. backend.set( texture, {
  39703. textureGPU,
  39704. glTextureType,
  39705. isDefault: true
  39706. } );
  39707. }
  39708. createTexture( texture, options ) {
  39709. const { gl, backend } = this;
  39710. const { levels, width, height, depth } = options;
  39711. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39712. const glType = backend.utils.convert( texture.type );
  39713. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39714. const textureGPU = gl.createTexture();
  39715. const glTextureType = this.getGLTextureType( texture );
  39716. backend.state.bindTexture( glTextureType, textureGPU );
  39717. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39718. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39719. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39720. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39721. this.setTextureParameters( glTextureType, texture );
  39722. if ( texture.isDataArrayTexture ) {
  39723. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39724. } else if ( texture.isData3DTexture ) {
  39725. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39726. } else if ( ! texture.isVideoTexture ) {
  39727. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39728. }
  39729. backend.set( texture, {
  39730. textureGPU,
  39731. glTextureType,
  39732. glFormat,
  39733. glType,
  39734. glInternalFormat
  39735. } );
  39736. }
  39737. copyBufferToTexture( buffer, texture ) {
  39738. const { gl, backend } = this;
  39739. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39740. const { width, height } = texture.source.data;
  39741. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39742. backend.state.bindTexture( glTextureType, textureGPU );
  39743. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39744. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39745. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39746. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39747. backend.state.unbindTexture();
  39748. // debug
  39749. // const framebuffer = gl.createFramebuffer();
  39750. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39751. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39752. // const readout = new Float32Array( width * height * 4 );
  39753. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39754. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39755. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39756. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39757. // console.log( readout );
  39758. }
  39759. updateTexture( texture, options ) {
  39760. const { gl } = this;
  39761. const { width, height } = options;
  39762. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39763. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39764. return;
  39765. const getImage = ( source ) => {
  39766. if ( source.isDataTexture ) {
  39767. return source.image.data;
  39768. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  39769. return source;
  39770. }
  39771. return source.data;
  39772. };
  39773. this.backend.state.bindTexture( glTextureType, textureGPU );
  39774. if ( texture.isCompressedTexture ) {
  39775. const mipmaps = texture.mipmaps;
  39776. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39777. const mipmap = mipmaps[ i ];
  39778. if ( texture.isCompressedArrayTexture ) {
  39779. const image = options.image;
  39780. if ( texture.format !== gl.RGBA ) {
  39781. if ( glFormat !== null ) {
  39782. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  39783. } else {
  39784. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39785. }
  39786. } else {
  39787. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39788. }
  39789. } else {
  39790. if ( glFormat !== null ) {
  39791. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39792. } else {
  39793. console.warn( 'Unsupported compressed texture format' );
  39794. }
  39795. }
  39796. }
  39797. } else if ( texture.isCubeTexture ) {
  39798. const images = options.images;
  39799. for ( let i = 0; i < 6; i ++ ) {
  39800. const image = getImage( images[ i ] );
  39801. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39802. }
  39803. } else if ( texture.isDataArrayTexture ) {
  39804. const image = options.image;
  39805. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39806. } else if ( texture.isData3DTexture ) {
  39807. const image = options.image;
  39808. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39809. } else if ( texture.isVideoTexture ) {
  39810. texture.update();
  39811. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39812. } else {
  39813. const image = getImage( options.image );
  39814. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39815. }
  39816. }
  39817. generateMipmaps( texture ) {
  39818. const { gl, backend } = this;
  39819. const { textureGPU, glTextureType } = backend.get( texture );
  39820. backend.state.bindTexture( glTextureType, textureGPU );
  39821. gl.generateMipmap( glTextureType );
  39822. }
  39823. deallocateRenderBuffers( renderTarget ) {
  39824. const { gl, backend } = this;
  39825. // remove framebuffer reference
  39826. if ( renderTarget ) {
  39827. const renderContextData = backend.get( renderTarget );
  39828. renderContextData.renderBufferStorageSetup = undefined;
  39829. if ( renderContextData.framebuffer ) {
  39830. gl.deleteFramebuffer( renderContextData.framebuffer );
  39831. renderContextData.framebuffer = undefined;
  39832. }
  39833. if ( renderContextData.depthRenderbuffer ) {
  39834. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39835. renderContextData.depthRenderbuffer = undefined;
  39836. }
  39837. if ( renderContextData.stencilRenderbuffer ) {
  39838. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39839. renderContextData.stencilRenderbuffer = undefined;
  39840. }
  39841. if ( renderContextData.msaaFrameBuffer ) {
  39842. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39843. renderContextData.msaaFrameBuffer = undefined;
  39844. }
  39845. if ( renderContextData.msaaRenderbuffers ) {
  39846. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39847. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39848. }
  39849. renderContextData.msaaRenderbuffers = undefined;
  39850. }
  39851. }
  39852. }
  39853. destroyTexture( texture ) {
  39854. const { gl, backend } = this;
  39855. const { textureGPU, renderTarget } = backend.get( texture );
  39856. this.deallocateRenderBuffers( renderTarget );
  39857. gl.deleteTexture( textureGPU );
  39858. backend.delete( texture );
  39859. }
  39860. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39861. const { gl, backend } = this;
  39862. const { state } = this.backend;
  39863. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39864. let width, height, minX, minY;
  39865. let dstX, dstY;
  39866. if ( srcRegion !== null ) {
  39867. width = srcRegion.max.x - srcRegion.min.x;
  39868. height = srcRegion.max.y - srcRegion.min.y;
  39869. minX = srcRegion.min.x;
  39870. minY = srcRegion.min.y;
  39871. } else {
  39872. width = srcTexture.image.width;
  39873. height = srcTexture.image.height;
  39874. minX = 0;
  39875. minY = 0;
  39876. }
  39877. if ( dstPosition !== null ) {
  39878. dstX = dstPosition.x;
  39879. dstY = dstPosition.y;
  39880. } else {
  39881. dstX = 0;
  39882. dstY = 0;
  39883. }
  39884. state.bindTexture( glTextureType, dstTextureGPU );
  39885. // As another texture upload may have changed pixelStorei
  39886. // parameters, make sure they are correct for the dstTexture
  39887. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39888. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39889. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39890. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39891. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39892. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39893. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39894. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39895. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39896. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39897. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39898. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39899. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39900. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39901. if ( srcTexture.isDataTexture ) {
  39902. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39903. } else {
  39904. if ( srcTexture.isCompressedTexture ) {
  39905. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39906. } else {
  39907. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39908. }
  39909. }
  39910. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39911. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39912. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39913. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39914. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39915. // Generate mipmaps only when copying level 0
  39916. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39917. state.unbindTexture();
  39918. }
  39919. copyFramebufferToTexture( texture, renderContext ) {
  39920. const { gl } = this;
  39921. const { state } = this.backend;
  39922. const { textureGPU } = this.backend.get( texture );
  39923. const width = texture.image.width;
  39924. const height = texture.image.height;
  39925. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39926. if ( requireDrawFrameBuffer ) {
  39927. let mask;
  39928. let attachment;
  39929. if ( texture.isDepthTexture === true ) {
  39930. mask = gl.DEPTH_BUFFER_BIT;
  39931. attachment = gl.DEPTH_ATTACHMENT;
  39932. if ( renderContext.stencil ) {
  39933. mask |= gl.STENCIL_BUFFER_BIT;
  39934. }
  39935. } else {
  39936. mask = gl.COLOR_BUFFER_BIT;
  39937. attachment = gl.COLOR_ATTACHMENT0;
  39938. }
  39939. const fb = gl.createFramebuffer();
  39940. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39941. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39942. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39943. gl.deleteFramebuffer( fb );
  39944. } else {
  39945. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39946. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  39947. state.unbindTexture();
  39948. }
  39949. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39950. this.backend._setFramebuffer( renderContext );
  39951. }
  39952. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  39953. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39954. const { gl } = this;
  39955. const renderTarget = renderContext.renderTarget;
  39956. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39957. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39958. if ( depthBuffer && ! stencilBuffer ) {
  39959. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39960. if ( samples > 0 ) {
  39961. if ( depthTexture && depthTexture.isDepthTexture ) {
  39962. if ( depthTexture.type === gl.FLOAT ) {
  39963. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39964. }
  39965. }
  39966. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39967. } else {
  39968. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39969. }
  39970. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39971. } else if ( depthBuffer && stencilBuffer ) {
  39972. if ( samples > 0 ) {
  39973. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39974. } else {
  39975. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39976. }
  39977. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39978. }
  39979. }
  39980. async copyTextureToBuffer( texture, x, y, width, height ) {
  39981. const { backend, gl } = this;
  39982. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  39983. const fb = gl.createFramebuffer();
  39984. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39985. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  39986. const typedArrayType = this._getTypedArrayType( glType );
  39987. const bytesPerTexel = this._getBytesPerTexel( glFormat );
  39988. const elementCount = width * height;
  39989. const byteLength = elementCount * bytesPerTexel;
  39990. const buffer = gl.createBuffer();
  39991. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39992. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  39993. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  39994. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39995. await backend.utils._clientWaitAsync();
  39996. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  39997. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39998. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  39999. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40000. gl.deleteFramebuffer( fb );
  40001. return dstBuffer;
  40002. }
  40003. _getTypedArrayType( glType ) {
  40004. const { gl } = this;
  40005. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40006. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40007. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40008. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40009. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40010. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40011. if ( glType === gl.FLOAT ) return Float32Array;
  40012. throw new Error( `Unsupported WebGL type: ${glType}` );
  40013. }
  40014. _getBytesPerTexel( glFormat ) {
  40015. const { gl } = this;
  40016. if ( glFormat === gl.RGBA ) return 4;
  40017. if ( glFormat === gl.RGB ) return 3;
  40018. if ( glFormat === gl.ALPHA ) return 1;
  40019. }
  40020. }
  40021. class WebGLExtensions {
  40022. constructor( backend ) {
  40023. this.backend = backend;
  40024. this.gl = this.backend.gl;
  40025. this.availableExtensions = this.gl.getSupportedExtensions();
  40026. this.extensions = {};
  40027. }
  40028. get( name ) {
  40029. let extension = this.extensions[ name ];
  40030. if ( extension === undefined ) {
  40031. extension = this.gl.getExtension( name );
  40032. this.extensions[ name ] = extension;
  40033. }
  40034. return extension;
  40035. }
  40036. has( name ) {
  40037. return this.availableExtensions.includes( name );
  40038. }
  40039. }
  40040. class WebGLCapabilities {
  40041. constructor( backend ) {
  40042. this.backend = backend;
  40043. this.maxAnisotropy = null;
  40044. }
  40045. getMaxAnisotropy() {
  40046. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40047. const gl = this.backend.gl;
  40048. const extensions = this.backend.extensions;
  40049. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40050. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40051. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40052. } else {
  40053. this.maxAnisotropy = 0;
  40054. }
  40055. return this.maxAnisotropy;
  40056. }
  40057. }
  40058. const GLFeatureName = {
  40059. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40060. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40061. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40062. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40063. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40064. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40065. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40066. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40067. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40068. };
  40069. class WebGLBufferRenderer {
  40070. constructor( backend ) {
  40071. this.gl = backend.gl;
  40072. this.extensions = backend.extensions;
  40073. this.info = backend.renderer.info;
  40074. this.mode = null;
  40075. this.index = 0;
  40076. this.type = null;
  40077. this.object = null;
  40078. }
  40079. render( start, count ) {
  40080. const { gl, mode, object, type, info, index } = this;
  40081. if ( index !== 0 ) {
  40082. gl.drawElements( mode, count, type, start );
  40083. } else {
  40084. gl.drawArrays( mode, start, count );
  40085. }
  40086. info.update( object, count, mode, 1 );
  40087. }
  40088. renderInstances( start, count, primcount ) {
  40089. const { gl, mode, type, index, object, info } = this;
  40090. if ( primcount === 0 ) return;
  40091. if ( index !== 0 ) {
  40092. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40093. } else {
  40094. gl.drawArraysInstanced( mode, start, count, primcount );
  40095. }
  40096. info.update( object, count, mode, primcount );
  40097. }
  40098. renderMultiDraw( starts, counts, drawCount ) {
  40099. const { extensions, mode, object, info } = this;
  40100. if ( drawCount === 0 ) return;
  40101. const extension = extensions.get( 'WEBGL_multi_draw' );
  40102. if ( extension === null ) {
  40103. for ( let i = 0; i < drawCount; i ++ ) {
  40104. this.render( starts[ i ], counts[ i ] );
  40105. }
  40106. } else {
  40107. if ( this.index !== 0 ) {
  40108. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40109. } else {
  40110. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40111. }
  40112. let elementCount = 0;
  40113. for ( let i = 0; i < drawCount; i ++ ) {
  40114. elementCount += counts[ i ];
  40115. }
  40116. info.update( object, elementCount, mode, 1 );
  40117. }
  40118. }
  40119. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40120. const { extensions, mode, object, info } = this;
  40121. if ( drawCount === 0 ) return;
  40122. const extension = extensions.get( 'WEBGL_multi_draw' );
  40123. if ( extension === null ) {
  40124. for ( let i = 0; i < drawCount; i ++ ) {
  40125. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40126. }
  40127. } else {
  40128. if ( this.index !== 0 ) {
  40129. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40130. } else {
  40131. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40132. }
  40133. let elementCount = 0;
  40134. for ( let i = 0; i < drawCount; i ++ ) {
  40135. elementCount += counts[ i ];
  40136. }
  40137. for ( let i = 0; i < primcount.length; i ++ ) {
  40138. info.update( object, elementCount, mode, primcount[ i ] );
  40139. }
  40140. }
  40141. }
  40142. //
  40143. }
  40144. //
  40145. class WebGLBackend extends Backend {
  40146. constructor( parameters = {} ) {
  40147. super( parameters );
  40148. this.isWebGLBackend = true;
  40149. }
  40150. init( renderer ) {
  40151. super.init( renderer );
  40152. //
  40153. const parameters = this.parameters;
  40154. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40155. this.gl = glContext;
  40156. this.extensions = new WebGLExtensions( this );
  40157. this.capabilities = new WebGLCapabilities( this );
  40158. this.attributeUtils = new WebGLAttributeUtils( this );
  40159. this.textureUtils = new WebGLTextureUtils( this );
  40160. this.bufferRenderer = new WebGLBufferRenderer( this );
  40161. this.state = new WebGLState( this );
  40162. this.utils = new WebGLUtils( this );
  40163. this.vaoCache = {};
  40164. this.transformFeedbackCache = {};
  40165. this.discard = false;
  40166. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40167. this.extensions.get( 'EXT_color_buffer_float' );
  40168. this.extensions.get( 'WEBGL_multi_draw' );
  40169. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40170. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40171. this._currentContext = null;
  40172. }
  40173. get coordinateSystem() {
  40174. return WebGLCoordinateSystem;
  40175. }
  40176. async getArrayBufferAsync( attribute ) {
  40177. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40178. }
  40179. initTimestampQuery( renderContext ) {
  40180. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40181. const renderContextData = this.get( renderContext );
  40182. if ( this.queryRunning ) {
  40183. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40184. renderContextData.queryQueue.push( renderContext );
  40185. return;
  40186. }
  40187. if ( renderContextData.activeQuery ) {
  40188. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40189. renderContextData.activeQuery = null;
  40190. }
  40191. renderContextData.activeQuery = this.gl.createQuery();
  40192. if ( renderContextData.activeQuery !== null ) {
  40193. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40194. this.queryRunning = true;
  40195. }
  40196. }
  40197. // timestamp utils
  40198. prepareTimestampBuffer( renderContext ) {
  40199. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40200. const renderContextData = this.get( renderContext );
  40201. if ( renderContextData.activeQuery ) {
  40202. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40203. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40204. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40205. renderContextData.activeQuery = null;
  40206. this.queryRunning = false;
  40207. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40208. const nextRenderContext = renderContextData.queryQueue.shift();
  40209. this.initTimestampQuery( nextRenderContext );
  40210. }
  40211. }
  40212. }
  40213. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40214. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40215. const renderContextData = this.get( renderContext );
  40216. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40217. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40218. const queryInfo = renderContextData.gpuQueries[ i ];
  40219. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40220. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40221. if ( available && ! disjoint ) {
  40222. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40223. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40224. this.gl.deleteQuery( queryInfo.query );
  40225. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40226. i --;
  40227. this.renderer.info.updateTimestamp( type, duration );
  40228. }
  40229. }
  40230. }
  40231. getContext() {
  40232. return this.gl;
  40233. }
  40234. beginRender( renderContext ) {
  40235. const { gl } = this;
  40236. const renderContextData = this.get( renderContext );
  40237. //
  40238. //
  40239. this.initTimestampQuery( renderContext );
  40240. renderContextData.previousContext = this._currentContext;
  40241. this._currentContext = renderContext;
  40242. this._setFramebuffer( renderContext );
  40243. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40244. //
  40245. if ( renderContext.viewport ) {
  40246. this.updateViewport( renderContext );
  40247. } else {
  40248. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40249. }
  40250. if ( renderContext.scissor ) {
  40251. const { x, y, width, height } = renderContext.scissorValue;
  40252. gl.scissor( x, y, width, height );
  40253. }
  40254. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40255. if ( occlusionQueryCount > 0 ) {
  40256. // Get a reference to the array of objects with queries. The renderContextData property
  40257. // can be changed by another render pass before the async reading of all previous queries complete
  40258. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40259. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40260. renderContextData.lastOcclusionObject = null;
  40261. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40262. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40263. renderContextData.occlusionQueryIndex = 0;
  40264. }
  40265. }
  40266. finishRender( renderContext ) {
  40267. const { gl, state } = this;
  40268. const renderContextData = this.get( renderContext );
  40269. const previousContext = renderContextData.previousContext;
  40270. const textures = renderContext.textures;
  40271. if ( textures !== null ) {
  40272. for ( let i = 0; i < textures.length; i ++ ) {
  40273. const texture = textures[ i ];
  40274. if ( texture.generateMipmaps ) {
  40275. this.generateMipmaps( texture );
  40276. }
  40277. }
  40278. }
  40279. this._currentContext = previousContext;
  40280. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40281. const renderTargetContextData = this.get( renderContext.renderTarget );
  40282. const { samples } = renderContext.renderTarget;
  40283. const fb = renderTargetContextData.framebuffer;
  40284. const mask = gl.COLOR_BUFFER_BIT;
  40285. if ( samples > 0 ) {
  40286. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40287. const textures = renderContext.textures;
  40288. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40289. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40290. for ( let i = 0; i < textures.length; i ++ ) {
  40291. // TODO Add support for MRT
  40292. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40293. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40294. }
  40295. }
  40296. }
  40297. if ( previousContext !== null ) {
  40298. this._setFramebuffer( previousContext );
  40299. if ( previousContext.viewport ) {
  40300. this.updateViewport( previousContext );
  40301. } else {
  40302. const gl = this.gl;
  40303. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40304. }
  40305. }
  40306. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40307. if ( occlusionQueryCount > 0 ) {
  40308. const renderContextData = this.get( renderContext );
  40309. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40310. const { gl } = this;
  40311. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40312. }
  40313. this.resolveOccludedAsync( renderContext );
  40314. }
  40315. this.prepareTimestampBuffer( renderContext );
  40316. }
  40317. resolveOccludedAsync( renderContext ) {
  40318. const renderContextData = this.get( renderContext );
  40319. // handle occlusion query results
  40320. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40321. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40322. const occluded = new WeakSet();
  40323. const { gl } = this;
  40324. renderContextData.currentOcclusionQueryObjects = null;
  40325. renderContextData.currentOcclusionQueries = null;
  40326. const check = () => {
  40327. let completed = 0;
  40328. // check all queries and requeue as appropriate
  40329. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40330. const query = currentOcclusionQueries[ i ];
  40331. if ( query === null ) continue;
  40332. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40333. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40334. currentOcclusionQueries[ i ] = null;
  40335. gl.deleteQuery( query );
  40336. completed ++;
  40337. }
  40338. }
  40339. if ( completed < currentOcclusionQueries.length ) {
  40340. requestAnimationFrame( check );
  40341. } else {
  40342. renderContextData.occluded = occluded;
  40343. }
  40344. };
  40345. check();
  40346. }
  40347. }
  40348. isOccluded( renderContext, object ) {
  40349. const renderContextData = this.get( renderContext );
  40350. return renderContextData.occluded && renderContextData.occluded.has( object );
  40351. }
  40352. updateViewport( renderContext ) {
  40353. const gl = this.gl;
  40354. const { x, y, width, height } = renderContext.viewportValue;
  40355. gl.viewport( x, y, width, height );
  40356. }
  40357. setScissorTest( boolean ) {
  40358. const gl = this.gl;
  40359. if ( boolean ) {
  40360. gl.enable( gl.SCISSOR_TEST );
  40361. } else {
  40362. gl.disable( gl.SCISSOR_TEST );
  40363. }
  40364. }
  40365. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40366. const { gl } = this;
  40367. if ( descriptor === null ) {
  40368. descriptor = {
  40369. textures: null,
  40370. clearColorValue: this.getClearColor()
  40371. };
  40372. }
  40373. //
  40374. let clear = 0;
  40375. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40376. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40377. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40378. if ( clear !== 0 ) {
  40379. const clearColor = descriptor.clearColorValue || this.getClearColor();
  40380. if ( depth ) this.state.setDepthMask( true );
  40381. if ( descriptor.textures === null ) {
  40382. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40383. gl.clear( clear );
  40384. } else {
  40385. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40386. if ( color ) {
  40387. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40388. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40389. }
  40390. }
  40391. if ( depth && stencil ) {
  40392. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40393. } else if ( depth ) {
  40394. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40395. } else if ( stencil ) {
  40396. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40397. }
  40398. }
  40399. }
  40400. }
  40401. beginCompute( computeGroup ) {
  40402. const gl = this.gl;
  40403. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40404. this.initTimestampQuery( computeGroup );
  40405. }
  40406. compute( computeGroup, computeNode, bindings, pipeline ) {
  40407. const gl = this.gl;
  40408. if ( ! this.discard ) {
  40409. // required here to handle async behaviour of render.compute()
  40410. gl.enable( gl.RASTERIZER_DISCARD );
  40411. this.discard = true;
  40412. }
  40413. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40414. const vaoKey = this._getVaoKey( null, attributes );
  40415. const vaoGPU = this.vaoCache[ vaoKey ];
  40416. if ( vaoGPU === undefined ) {
  40417. this._createVao( null, attributes );
  40418. } else {
  40419. gl.bindVertexArray( vaoGPU );
  40420. }
  40421. gl.useProgram( programGPU );
  40422. this._bindUniforms( bindings );
  40423. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40424. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40425. gl.beginTransformFeedback( gl.POINTS );
  40426. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40427. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40428. } else {
  40429. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40430. }
  40431. gl.endTransformFeedback();
  40432. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40433. // switch active buffers
  40434. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40435. const dualAttributeData = transformBuffers[ i ];
  40436. if ( dualAttributeData.pbo ) {
  40437. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40438. }
  40439. dualAttributeData.switchBuffers();
  40440. }
  40441. }
  40442. finishCompute( computeGroup ) {
  40443. const gl = this.gl;
  40444. this.discard = false;
  40445. gl.disable( gl.RASTERIZER_DISCARD );
  40446. this.prepareTimestampBuffer( computeGroup );
  40447. }
  40448. draw( renderObject/*, info*/ ) {
  40449. const { object, pipeline, material, context } = renderObject;
  40450. const { programGPU } = this.get( pipeline );
  40451. const { gl, state } = this;
  40452. const contextData = this.get( context );
  40453. //
  40454. this._bindUniforms( renderObject.getBindings() );
  40455. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40456. state.setMaterial( material, frontFaceCW );
  40457. gl.useProgram( programGPU );
  40458. //
  40459. let vaoGPU = renderObject.staticVao;
  40460. if ( vaoGPU === undefined ) {
  40461. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40462. vaoGPU = this.vaoCache[ vaoKey ];
  40463. if ( vaoGPU === undefined ) {
  40464. let staticVao;
  40465. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40466. if ( staticVao ) renderObject.staticVao = vaoGPU;
  40467. }
  40468. }
  40469. gl.bindVertexArray( vaoGPU );
  40470. //
  40471. const index = renderObject.getIndex();
  40472. const geometry = renderObject.geometry;
  40473. const drawRange = renderObject.drawRange;
  40474. const firstVertex = drawRange.start;
  40475. //
  40476. const lastObject = contextData.lastOcclusionObject;
  40477. if ( lastObject !== object && lastObject !== undefined ) {
  40478. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40479. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40480. contextData.occlusionQueryIndex ++;
  40481. }
  40482. if ( object.occlusionTest === true ) {
  40483. const query = gl.createQuery();
  40484. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40485. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40486. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40487. }
  40488. contextData.lastOcclusionObject = object;
  40489. }
  40490. //
  40491. const renderer = this.bufferRenderer;
  40492. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40493. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40494. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40495. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40496. else {
  40497. if ( material.wireframe === true ) {
  40498. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40499. renderer.mode = gl.LINES;
  40500. } else {
  40501. renderer.mode = gl.TRIANGLES;
  40502. }
  40503. }
  40504. //
  40505. let count;
  40506. renderer.object = object;
  40507. if ( index !== null ) {
  40508. const indexData = this.get( index );
  40509. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  40510. renderer.index = index.count;
  40511. renderer.type = indexData.type;
  40512. count = indexCount;
  40513. } else {
  40514. renderer.index = 0;
  40515. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  40516. count = vertexCount;
  40517. }
  40518. const instanceCount = this.getInstanceCount( renderObject );
  40519. if ( object.isBatchedMesh ) {
  40520. if ( object._multiDrawInstances !== null ) {
  40521. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40522. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40523. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40524. } else {
  40525. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40526. }
  40527. } else if ( instanceCount > 1 ) {
  40528. renderer.renderInstances( firstVertex, count, instanceCount );
  40529. } else {
  40530. renderer.render( firstVertex, count );
  40531. }
  40532. //
  40533. gl.bindVertexArray( null );
  40534. }
  40535. needsRenderUpdate( /*renderObject*/ ) {
  40536. return false;
  40537. }
  40538. getRenderCacheKey( renderObject ) {
  40539. return renderObject.id;
  40540. }
  40541. // textures
  40542. createDefaultTexture( texture ) {
  40543. this.textureUtils.createDefaultTexture( texture );
  40544. }
  40545. createTexture( texture, options ) {
  40546. this.textureUtils.createTexture( texture, options );
  40547. }
  40548. updateTexture( texture, options ) {
  40549. this.textureUtils.updateTexture( texture, options );
  40550. }
  40551. generateMipmaps( texture ) {
  40552. this.textureUtils.generateMipmaps( texture );
  40553. }
  40554. destroyTexture( texture ) {
  40555. this.textureUtils.destroyTexture( texture );
  40556. }
  40557. copyTextureToBuffer( texture, x, y, width, height ) {
  40558. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  40559. }
  40560. createSampler( /*texture*/ ) {
  40561. //console.warn( 'Abstract class.' );
  40562. }
  40563. destroySampler() {}
  40564. // node builder
  40565. createNodeBuilder( object, renderer ) {
  40566. return new GLSLNodeBuilder( object, renderer );
  40567. }
  40568. // program
  40569. createProgram( program ) {
  40570. const gl = this.gl;
  40571. const { stage, code } = program;
  40572. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40573. gl.shaderSource( shader, code );
  40574. gl.compileShader( shader );
  40575. this.set( program, {
  40576. shaderGPU: shader
  40577. } );
  40578. }
  40579. destroyProgram( /*program*/ ) {
  40580. console.warn( 'Abstract class.' );
  40581. }
  40582. createRenderPipeline( renderObject, promises ) {
  40583. const gl = this.gl;
  40584. const pipeline = renderObject.pipeline;
  40585. // Program
  40586. const { fragmentProgram, vertexProgram } = pipeline;
  40587. const programGPU = gl.createProgram();
  40588. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40589. const vertexShader = this.get( vertexProgram ).shaderGPU;
  40590. gl.attachShader( programGPU, fragmentShader );
  40591. gl.attachShader( programGPU, vertexShader );
  40592. gl.linkProgram( programGPU );
  40593. this.set( pipeline, {
  40594. programGPU,
  40595. fragmentShader,
  40596. vertexShader
  40597. } );
  40598. if ( promises !== null && this.parallel ) {
  40599. const p = new Promise( ( resolve /*, reject*/ ) => {
  40600. const parallel = this.parallel;
  40601. const checkStatus = () => {
  40602. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  40603. this._completeCompile( renderObject, pipeline );
  40604. resolve();
  40605. } else {
  40606. requestAnimationFrame( checkStatus );
  40607. }
  40608. };
  40609. checkStatus();
  40610. } );
  40611. promises.push( p );
  40612. return;
  40613. }
  40614. this._completeCompile( renderObject, pipeline );
  40615. }
  40616. _handleSource( string, errorLine ) {
  40617. const lines = string.split( '\n' );
  40618. const lines2 = [];
  40619. const from = Math.max( errorLine - 6, 0 );
  40620. const to = Math.min( errorLine + 6, lines.length );
  40621. for ( let i = from; i < to; i ++ ) {
  40622. const line = i + 1;
  40623. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  40624. }
  40625. return lines2.join( '\n' );
  40626. }
  40627. _getShaderErrors( gl, shader, type ) {
  40628. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  40629. const errors = gl.getShaderInfoLog( shader ).trim();
  40630. if ( status && errors === '' ) return '';
  40631. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  40632. if ( errorMatches ) {
  40633. const errorLine = parseInt( errorMatches[ 1 ] );
  40634. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  40635. } else {
  40636. return errors;
  40637. }
  40638. }
  40639. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  40640. if ( this.renderer.debug.checkShaderErrors ) {
  40641. const gl = this.gl;
  40642. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  40643. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40644. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  40645. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  40646. } else {
  40647. // default error reporting
  40648. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  40649. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  40650. console.error(
  40651. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  40652. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  40653. 'Program Info Log: ' + programLog + '\n' +
  40654. vertexErrors + '\n' +
  40655. fragmentErrors
  40656. );
  40657. }
  40658. } else if ( programLog !== '' ) {
  40659. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  40660. }
  40661. }
  40662. }
  40663. _completeCompile( renderObject, pipeline ) {
  40664. const gl = this.gl;
  40665. const pipelineData = this.get( pipeline );
  40666. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  40667. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40668. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40669. }
  40670. gl.useProgram( programGPU );
  40671. // Bindings
  40672. const bindings = renderObject.getBindings();
  40673. this._setupBindings( bindings, programGPU );
  40674. //
  40675. this.set( pipeline, {
  40676. programGPU
  40677. } );
  40678. }
  40679. createComputePipeline( computePipeline, bindings ) {
  40680. const gl = this.gl;
  40681. // Program
  40682. const fragmentProgram = {
  40683. stage: 'fragment',
  40684. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  40685. };
  40686. this.createProgram( fragmentProgram );
  40687. const { computeProgram } = computePipeline;
  40688. const programGPU = gl.createProgram();
  40689. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40690. const vertexShader = this.get( computeProgram ).shaderGPU;
  40691. const transforms = computeProgram.transforms;
  40692. const transformVaryingNames = [];
  40693. const transformAttributeNodes = [];
  40694. for ( let i = 0; i < transforms.length; i ++ ) {
  40695. const transform = transforms[ i ];
  40696. transformVaryingNames.push( transform.varyingName );
  40697. transformAttributeNodes.push( transform.attributeNode );
  40698. }
  40699. gl.attachShader( programGPU, fragmentShader );
  40700. gl.attachShader( programGPU, vertexShader );
  40701. gl.transformFeedbackVaryings(
  40702. programGPU,
  40703. transformVaryingNames,
  40704. gl.SEPARATE_ATTRIBS
  40705. );
  40706. gl.linkProgram( programGPU );
  40707. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40708. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40709. }
  40710. gl.useProgram( programGPU );
  40711. // Bindings
  40712. this.createBindings( null, bindings );
  40713. this._setupBindings( bindings, programGPU );
  40714. const attributeNodes = computeProgram.attributes;
  40715. const attributes = [];
  40716. const transformBuffers = [];
  40717. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  40718. const attribute = attributeNodes[ i ].node.attribute;
  40719. attributes.push( attribute );
  40720. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40721. }
  40722. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  40723. const attribute = transformAttributeNodes[ i ].attribute;
  40724. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40725. const attributeData = this.get( attribute );
  40726. transformBuffers.push( attributeData );
  40727. }
  40728. //
  40729. this.set( computePipeline, {
  40730. programGPU,
  40731. transformBuffers,
  40732. attributes
  40733. } );
  40734. }
  40735. createBindings( bindGroup, bindings ) {
  40736. this.updateBindings( bindGroup, bindings );
  40737. }
  40738. updateBindings( bindGroup, bindings ) {
  40739. const { gl } = this;
  40740. let groupIndex = 0;
  40741. let textureIndex = 0;
  40742. for ( const bindGroup of bindings ) {
  40743. for ( const binding of bindGroup.bindings ) {
  40744. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40745. const bufferGPU = gl.createBuffer();
  40746. const data = binding.buffer;
  40747. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40748. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40749. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  40750. this.set( binding, {
  40751. index: groupIndex ++,
  40752. bufferGPU
  40753. } );
  40754. } else if ( binding.isSampledTexture ) {
  40755. const { textureGPU, glTextureType } = this.get( binding.texture );
  40756. this.set( binding, {
  40757. index: textureIndex ++,
  40758. textureGPU,
  40759. glTextureType
  40760. } );
  40761. }
  40762. }
  40763. }
  40764. }
  40765. updateBinding( binding ) {
  40766. const gl = this.gl;
  40767. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40768. const bindingData = this.get( binding );
  40769. const bufferGPU = bindingData.bufferGPU;
  40770. const data = binding.buffer;
  40771. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40772. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40773. }
  40774. }
  40775. // attributes
  40776. createIndexAttribute( attribute ) {
  40777. const gl = this.gl;
  40778. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  40779. }
  40780. createAttribute( attribute ) {
  40781. if ( this.has( attribute ) ) return;
  40782. const gl = this.gl;
  40783. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40784. }
  40785. createStorageAttribute( attribute ) {
  40786. if ( this.has( attribute ) ) return;
  40787. const gl = this.gl;
  40788. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40789. }
  40790. updateAttribute( attribute ) {
  40791. this.attributeUtils.updateAttribute( attribute );
  40792. }
  40793. destroyAttribute( attribute ) {
  40794. this.attributeUtils.destroyAttribute( attribute );
  40795. }
  40796. updateSize() {
  40797. //console.warn( 'Abstract class.' );
  40798. }
  40799. hasFeature( name ) {
  40800. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  40801. const extensions = this.extensions;
  40802. for ( let i = 0; i < keysMatching.length; i ++ ) {
  40803. if ( extensions.has( keysMatching[ i ] ) ) return true;
  40804. }
  40805. return false;
  40806. }
  40807. getMaxAnisotropy() {
  40808. return this.capabilities.getMaxAnisotropy();
  40809. }
  40810. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  40811. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  40812. }
  40813. copyFramebufferToTexture( texture, renderContext ) {
  40814. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  40815. }
  40816. _setFramebuffer( renderContext ) {
  40817. const { gl, state } = this;
  40818. let currentFrameBuffer = null;
  40819. if ( renderContext.textures !== null ) {
  40820. const renderTarget = renderContext.renderTarget;
  40821. const renderTargetContextData = this.get( renderTarget );
  40822. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  40823. const cubeFace = this.renderer._activeCubeFace;
  40824. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  40825. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  40826. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  40827. let fb;
  40828. if ( isCube ) {
  40829. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  40830. renderTargetContextData.cubeFramebuffers = [];
  40831. }
  40832. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  40833. } else {
  40834. fb = renderTargetContextData.framebuffer;
  40835. }
  40836. if ( fb === undefined ) {
  40837. fb = gl.createFramebuffer();
  40838. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  40839. const textures = renderContext.textures;
  40840. if ( isCube ) {
  40841. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  40842. const { textureGPU } = this.get( textures[ 0 ] );
  40843. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  40844. } else {
  40845. for ( let i = 0; i < textures.length; i ++ ) {
  40846. const texture = textures[ i ];
  40847. const textureData = this.get( texture );
  40848. textureData.renderTarget = renderContext.renderTarget;
  40849. const attachment = gl.COLOR_ATTACHMENT0 + i;
  40850. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40851. }
  40852. renderTargetContextData.framebuffer = fb;
  40853. state.drawBuffers( renderContext, fb );
  40854. }
  40855. if ( renderContext.depthTexture !== null ) {
  40856. const textureData = this.get( renderContext.depthTexture );
  40857. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40858. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40859. }
  40860. }
  40861. if ( samples > 0 ) {
  40862. if ( msaaFb === undefined ) {
  40863. const invalidationArray = [];
  40864. msaaFb = gl.createFramebuffer();
  40865. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  40866. const msaaRenderbuffers = [];
  40867. const textures = renderContext.textures;
  40868. for ( let i = 0; i < textures.length; i ++ ) {
  40869. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  40870. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40871. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  40872. if ( depthBuffer ) {
  40873. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40874. invalidationArray.push( depthStyle );
  40875. }
  40876. const texture = renderContext.textures[ i ];
  40877. const textureData = this.get( texture );
  40878. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  40879. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40880. }
  40881. renderTargetContextData.msaaFrameBuffer = msaaFb;
  40882. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  40883. if ( depthRenderbuffer === undefined ) {
  40884. depthRenderbuffer = gl.createRenderbuffer();
  40885. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  40886. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  40887. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40888. invalidationArray.push( depthStyle );
  40889. }
  40890. renderTargetContextData.invalidationArray = invalidationArray;
  40891. }
  40892. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40893. } else {
  40894. currentFrameBuffer = fb;
  40895. }
  40896. }
  40897. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  40898. }
  40899. _getVaoKey( index, attributes ) {
  40900. let key = [];
  40901. if ( index !== null ) {
  40902. const indexData = this.get( index );
  40903. key += ':' + indexData.id;
  40904. }
  40905. for ( let i = 0; i < attributes.length; i ++ ) {
  40906. const attributeData = this.get( attributes[ i ] );
  40907. key += ':' + attributeData.id;
  40908. }
  40909. return key;
  40910. }
  40911. _createVao( index, attributes ) {
  40912. const { gl } = this;
  40913. const vaoGPU = gl.createVertexArray();
  40914. let key = '';
  40915. let staticVao = true;
  40916. gl.bindVertexArray( vaoGPU );
  40917. if ( index !== null ) {
  40918. const indexData = this.get( index );
  40919. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  40920. key += ':' + indexData.id;
  40921. }
  40922. for ( let i = 0; i < attributes.length; i ++ ) {
  40923. const attribute = attributes[ i ];
  40924. const attributeData = this.get( attribute );
  40925. key += ':' + attributeData.id;
  40926. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  40927. gl.enableVertexAttribArray( i );
  40928. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  40929. let stride, offset;
  40930. if ( attribute.isInterleavedBufferAttribute === true ) {
  40931. stride = attribute.data.stride * attributeData.bytesPerElement;
  40932. offset = attribute.offset * attributeData.bytesPerElement;
  40933. } else {
  40934. stride = 0;
  40935. offset = 0;
  40936. }
  40937. if ( attributeData.isInteger ) {
  40938. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  40939. } else {
  40940. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  40941. }
  40942. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  40943. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  40944. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  40945. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  40946. }
  40947. }
  40948. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  40949. this.vaoCache[ key ] = vaoGPU;
  40950. return { vaoGPU, staticVao };
  40951. }
  40952. _getTransformFeedback( transformBuffers ) {
  40953. let key = '';
  40954. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40955. key += ':' + transformBuffers[ i ].id;
  40956. }
  40957. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  40958. if ( transformFeedbackGPU !== undefined ) {
  40959. return transformFeedbackGPU;
  40960. }
  40961. const gl = this.gl;
  40962. transformFeedbackGPU = gl.createTransformFeedback();
  40963. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40964. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40965. const attributeData = transformBuffers[ i ];
  40966. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  40967. }
  40968. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40969. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  40970. return transformFeedbackGPU;
  40971. }
  40972. _setupBindings( bindings, programGPU ) {
  40973. const gl = this.gl;
  40974. for ( const bindGroup of bindings ) {
  40975. for ( const binding of bindGroup.bindings ) {
  40976. const bindingData = this.get( binding );
  40977. const index = bindingData.index;
  40978. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40979. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  40980. gl.uniformBlockBinding( programGPU, location, index );
  40981. } else if ( binding.isSampledTexture ) {
  40982. const location = gl.getUniformLocation( programGPU, binding.name );
  40983. gl.uniform1i( location, index );
  40984. }
  40985. }
  40986. }
  40987. }
  40988. _bindUniforms( bindings ) {
  40989. const { gl, state } = this;
  40990. for ( const bindGroup of bindings ) {
  40991. for ( const binding of bindGroup.bindings ) {
  40992. const bindingData = this.get( binding );
  40993. const index = bindingData.index;
  40994. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40995. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  40996. } else if ( binding.isSampledTexture ) {
  40997. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  40998. }
  40999. }
  41000. }
  41001. }
  41002. }
  41003. class Sampler extends Binding {
  41004. constructor( name, texture ) {
  41005. super( name );
  41006. this.texture = texture;
  41007. this.version = texture ? texture.version : 0;
  41008. this.isSampler = true;
  41009. }
  41010. }
  41011. class NodeSampler extends Sampler {
  41012. constructor( name, textureNode, groupNode ) {
  41013. super( name, textureNode ? textureNode.value : null );
  41014. this.textureNode = textureNode;
  41015. this.groupNode = groupNode;
  41016. }
  41017. update() {
  41018. this.texture = this.textureNode.value;
  41019. }
  41020. }
  41021. class StorageBuffer extends Buffer {
  41022. constructor( name, attribute ) {
  41023. super( name, attribute ? attribute.array : null );
  41024. this.attribute = attribute;
  41025. this.isStorageBuffer = true;
  41026. }
  41027. }
  41028. let _id = 0;
  41029. class NodeStorageBuffer extends StorageBuffer {
  41030. constructor( nodeUniform, groupNode ) {
  41031. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41032. this.nodeUniform = nodeUniform;
  41033. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41034. this.groupNode = groupNode;
  41035. }
  41036. get buffer() {
  41037. return this.nodeUniform.value;
  41038. }
  41039. }
  41040. class WebGPUTexturePassUtils {
  41041. constructor( device ) {
  41042. this.device = device;
  41043. const mipmapVertexSource = `
  41044. struct VarysStruct {
  41045. @builtin( position ) Position: vec4<f32>,
  41046. @location( 0 ) vTex : vec2<f32>
  41047. };
  41048. @vertex
  41049. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41050. var Varys : VarysStruct;
  41051. var pos = array< vec2<f32>, 4 >(
  41052. vec2<f32>( -1.0, 1.0 ),
  41053. vec2<f32>( 1.0, 1.0 ),
  41054. vec2<f32>( -1.0, -1.0 ),
  41055. vec2<f32>( 1.0, -1.0 )
  41056. );
  41057. var tex = array< vec2<f32>, 4 >(
  41058. vec2<f32>( 0.0, 0.0 ),
  41059. vec2<f32>( 1.0, 0.0 ),
  41060. vec2<f32>( 0.0, 1.0 ),
  41061. vec2<f32>( 1.0, 1.0 )
  41062. );
  41063. Varys.vTex = tex[ vertexIndex ];
  41064. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41065. return Varys;
  41066. }
  41067. `;
  41068. const mipmapFragmentSource = `
  41069. @group( 0 ) @binding( 0 )
  41070. var imgSampler : sampler;
  41071. @group( 0 ) @binding( 1 )
  41072. var img : texture_2d<f32>;
  41073. @fragment
  41074. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41075. return textureSample( img, imgSampler, vTex );
  41076. }
  41077. `;
  41078. const flipYFragmentSource = `
  41079. @group( 0 ) @binding( 0 )
  41080. var imgSampler : sampler;
  41081. @group( 0 ) @binding( 1 )
  41082. var img : texture_2d<f32>;
  41083. @fragment
  41084. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41085. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41086. }
  41087. `;
  41088. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41089. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41090. // We'll need a new pipeline for every texture format used.
  41091. this.transferPipelines = {};
  41092. this.flipYPipelines = {};
  41093. this.mipmapVertexShaderModule = device.createShaderModule( {
  41094. label: 'mipmapVertex',
  41095. code: mipmapVertexSource
  41096. } );
  41097. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41098. label: 'mipmapFragment',
  41099. code: mipmapFragmentSource
  41100. } );
  41101. this.flipYFragmentShaderModule = device.createShaderModule( {
  41102. label: 'flipYFragment',
  41103. code: flipYFragmentSource
  41104. } );
  41105. }
  41106. getTransferPipeline( format ) {
  41107. let pipeline = this.transferPipelines[ format ];
  41108. if ( pipeline === undefined ) {
  41109. pipeline = this.device.createRenderPipeline( {
  41110. vertex: {
  41111. module: this.mipmapVertexShaderModule,
  41112. entryPoint: 'main'
  41113. },
  41114. fragment: {
  41115. module: this.mipmapFragmentShaderModule,
  41116. entryPoint: 'main',
  41117. targets: [ { format } ]
  41118. },
  41119. primitive: {
  41120. topology: GPUPrimitiveTopology.TriangleStrip,
  41121. stripIndexFormat: GPUIndexFormat.Uint32
  41122. },
  41123. layout: 'auto'
  41124. } );
  41125. this.transferPipelines[ format ] = pipeline;
  41126. }
  41127. return pipeline;
  41128. }
  41129. getFlipYPipeline( format ) {
  41130. let pipeline = this.flipYPipelines[ 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.flipYFragmentShaderModule,
  41139. entryPoint: 'main',
  41140. targets: [ { format } ]
  41141. },
  41142. primitive: {
  41143. topology: GPUPrimitiveTopology.TriangleStrip,
  41144. stripIndexFormat: GPUIndexFormat.Uint32
  41145. },
  41146. layout: 'auto'
  41147. } );
  41148. this.flipYPipelines[ format ] = pipeline;
  41149. }
  41150. return pipeline;
  41151. }
  41152. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41153. const format = textureGPUDescriptor.format;
  41154. const { width, height } = textureGPUDescriptor.size;
  41155. const transferPipeline = this.getTransferPipeline( format );
  41156. const flipYPipeline = this.getFlipYPipeline( format );
  41157. const tempTexture = this.device.createTexture( {
  41158. size: { width, height, depthOrArrayLayers: 1 },
  41159. format,
  41160. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41161. } );
  41162. const srcView = textureGPU.createView( {
  41163. baseMipLevel: 0,
  41164. mipLevelCount: 1,
  41165. dimension: GPUTextureViewDimension.TwoD,
  41166. baseArrayLayer
  41167. } );
  41168. const dstView = tempTexture.createView( {
  41169. baseMipLevel: 0,
  41170. mipLevelCount: 1,
  41171. dimension: GPUTextureViewDimension.TwoD,
  41172. baseArrayLayer: 0
  41173. } );
  41174. const commandEncoder = this.device.createCommandEncoder( {} );
  41175. const pass = ( pipeline, sourceView, destinationView ) => {
  41176. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41177. const bindGroup = this.device.createBindGroup( {
  41178. layout: bindGroupLayout,
  41179. entries: [ {
  41180. binding: 0,
  41181. resource: this.flipYSampler
  41182. }, {
  41183. binding: 1,
  41184. resource: sourceView
  41185. } ]
  41186. } );
  41187. const passEncoder = commandEncoder.beginRenderPass( {
  41188. colorAttachments: [ {
  41189. view: destinationView,
  41190. loadOp: GPULoadOp.Clear,
  41191. storeOp: GPUStoreOp.Store,
  41192. clearValue: [ 0, 0, 0, 0 ]
  41193. } ]
  41194. } );
  41195. passEncoder.setPipeline( pipeline );
  41196. passEncoder.setBindGroup( 0, bindGroup );
  41197. passEncoder.draw( 4, 1, 0, 0 );
  41198. passEncoder.end();
  41199. };
  41200. pass( transferPipeline, srcView, dstView );
  41201. pass( flipYPipeline, dstView, srcView );
  41202. this.device.queue.submit( [ commandEncoder.finish() ] );
  41203. tempTexture.destroy();
  41204. }
  41205. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41206. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41207. const commandEncoder = this.device.createCommandEncoder( {} );
  41208. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41209. let srcView = textureGPU.createView( {
  41210. baseMipLevel: 0,
  41211. mipLevelCount: 1,
  41212. dimension: GPUTextureViewDimension.TwoD,
  41213. baseArrayLayer
  41214. } );
  41215. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41216. const bindGroup = this.device.createBindGroup( {
  41217. layout: bindGroupLayout,
  41218. entries: [ {
  41219. binding: 0,
  41220. resource: this.mipmapSampler
  41221. }, {
  41222. binding: 1,
  41223. resource: srcView
  41224. } ]
  41225. } );
  41226. const dstView = textureGPU.createView( {
  41227. baseMipLevel: i,
  41228. mipLevelCount: 1,
  41229. dimension: GPUTextureViewDimension.TwoD,
  41230. baseArrayLayer
  41231. } );
  41232. const passEncoder = commandEncoder.beginRenderPass( {
  41233. colorAttachments: [ {
  41234. view: dstView,
  41235. loadOp: GPULoadOp.Clear,
  41236. storeOp: GPUStoreOp.Store,
  41237. clearValue: [ 0, 0, 0, 0 ]
  41238. } ]
  41239. } );
  41240. passEncoder.setPipeline( pipeline );
  41241. passEncoder.setBindGroup( 0, bindGroup );
  41242. passEncoder.draw( 4, 1, 0, 0 );
  41243. passEncoder.end();
  41244. srcView = dstView;
  41245. }
  41246. this.device.queue.submit( [ commandEncoder.finish() ] );
  41247. }
  41248. }
  41249. const _compareToWebGPU = {
  41250. [ NeverCompare ]: 'never',
  41251. [ LessCompare ]: 'less',
  41252. [ EqualCompare ]: 'equal',
  41253. [ LessEqualCompare ]: 'less-equal',
  41254. [ GreaterCompare ]: 'greater',
  41255. [ GreaterEqualCompare ]: 'greater-equal',
  41256. [ AlwaysCompare ]: 'always',
  41257. [ NotEqualCompare ]: 'not-equal'
  41258. };
  41259. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41260. class WebGPUTextureUtils {
  41261. constructor( backend ) {
  41262. this.backend = backend;
  41263. this._passUtils = null;
  41264. this.defaultTexture = {};
  41265. this.defaultCubeTexture = {};
  41266. this.defaultVideoFrame = null;
  41267. this.colorBuffer = null;
  41268. this.depthTexture = new DepthTexture();
  41269. this.depthTexture.name = 'depthBuffer';
  41270. }
  41271. createSampler( texture ) {
  41272. const backend = this.backend;
  41273. const device = backend.device;
  41274. const textureGPU = backend.get( texture );
  41275. const samplerDescriptorGPU = {
  41276. addressModeU: this._convertAddressMode( texture.wrapS ),
  41277. addressModeV: this._convertAddressMode( texture.wrapT ),
  41278. addressModeW: this._convertAddressMode( texture.wrapR ),
  41279. magFilter: this._convertFilterMode( texture.magFilter ),
  41280. minFilter: this._convertFilterMode( texture.minFilter ),
  41281. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41282. maxAnisotropy: texture.anisotropy
  41283. };
  41284. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41285. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41286. }
  41287. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41288. }
  41289. createDefaultTexture( texture ) {
  41290. let textureGPU;
  41291. const format = getFormat( texture );
  41292. if ( texture.isCubeTexture ) {
  41293. textureGPU = this._getDefaultCubeTextureGPU( format );
  41294. } else if ( texture.isVideoTexture ) {
  41295. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41296. } else {
  41297. textureGPU = this._getDefaultTextureGPU( format );
  41298. }
  41299. this.backend.get( texture ).texture = textureGPU;
  41300. }
  41301. createTexture( texture, options = {} ) {
  41302. const backend = this.backend;
  41303. const textureData = backend.get( texture );
  41304. if ( textureData.initialized ) {
  41305. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41306. }
  41307. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41308. if ( options.levels === undefined ) options.levels = 1;
  41309. if ( options.depth === undefined ) options.depth = 1;
  41310. const { width, height, depth, levels } = options;
  41311. const dimension = this._getDimension( texture );
  41312. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41313. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41314. sampleCount = backend.utils.getSampleCount( sampleCount );
  41315. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41316. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41317. if ( texture.isStorageTexture === true ) {
  41318. usage |= GPUTextureUsage.STORAGE_BINDING;
  41319. }
  41320. if ( texture.isCompressedTexture !== true ) {
  41321. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41322. }
  41323. const textureDescriptorGPU = {
  41324. label: texture.name,
  41325. size: {
  41326. width: width,
  41327. height: height,
  41328. depthOrArrayLayers: depth,
  41329. },
  41330. mipLevelCount: levels,
  41331. sampleCount: primarySampleCount,
  41332. dimension: dimension,
  41333. format: format,
  41334. usage: usage
  41335. };
  41336. // texture creation
  41337. if ( texture.isVideoTexture ) {
  41338. const video = texture.source.data;
  41339. const videoFrame = new VideoFrame( video );
  41340. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41341. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41342. videoFrame.close();
  41343. textureData.externalTexture = video;
  41344. } else {
  41345. if ( format === undefined ) {
  41346. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41347. return this.createDefaultTexture( texture );
  41348. }
  41349. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41350. }
  41351. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41352. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41353. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41354. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41355. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41356. }
  41357. textureData.initialized = true;
  41358. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41359. }
  41360. destroyTexture( texture ) {
  41361. const backend = this.backend;
  41362. const textureData = backend.get( texture );
  41363. textureData.texture.destroy();
  41364. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41365. backend.delete( texture );
  41366. }
  41367. destroySampler( texture ) {
  41368. const backend = this.backend;
  41369. const textureData = backend.get( texture );
  41370. delete textureData.sampler;
  41371. }
  41372. generateMipmaps( texture ) {
  41373. const textureData = this.backend.get( texture );
  41374. if ( texture.isCubeTexture ) {
  41375. for ( let i = 0; i < 6; i ++ ) {
  41376. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41377. }
  41378. } else {
  41379. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU );
  41380. }
  41381. }
  41382. getColorBuffer() {
  41383. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41384. const backend = this.backend;
  41385. const { width, height } = backend.getDrawingBufferSize();
  41386. this.colorBuffer = backend.device.createTexture( {
  41387. label: 'colorBuffer',
  41388. size: {
  41389. width: width,
  41390. height: height,
  41391. depthOrArrayLayers: 1
  41392. },
  41393. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41394. format: GPUTextureFormat.BGRA8Unorm,
  41395. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41396. } );
  41397. return this.colorBuffer;
  41398. }
  41399. getDepthBuffer( depth = true, stencil = false ) {
  41400. const backend = this.backend;
  41401. const { width, height } = backend.getDrawingBufferSize();
  41402. const depthTexture = this.depthTexture;
  41403. const depthTextureGPU = backend.get( depthTexture ).texture;
  41404. let format, type;
  41405. if ( stencil ) {
  41406. format = DepthStencilFormat;
  41407. type = UnsignedInt248Type;
  41408. } else if ( depth ) {
  41409. format = DepthFormat;
  41410. type = UnsignedIntType;
  41411. }
  41412. if ( depthTextureGPU !== undefined ) {
  41413. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41414. return depthTextureGPU;
  41415. }
  41416. this.destroyTexture( depthTexture );
  41417. }
  41418. depthTexture.name = 'depthBuffer';
  41419. depthTexture.format = format;
  41420. depthTexture.type = type;
  41421. depthTexture.image.width = width;
  41422. depthTexture.image.height = height;
  41423. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  41424. return backend.get( depthTexture ).texture;
  41425. }
  41426. updateTexture( texture, options ) {
  41427. const textureData = this.backend.get( texture );
  41428. const { textureDescriptorGPU } = textureData;
  41429. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41430. return;
  41431. // transfer texture data
  41432. if ( texture.isDataTexture ) {
  41433. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41434. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41435. for ( let i = 0; i < options.image.depth; i ++ ) {
  41436. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41437. }
  41438. } else if ( texture.isCompressedTexture ) {
  41439. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41440. } else if ( texture.isCubeTexture ) {
  41441. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41442. } else if ( texture.isVideoTexture ) {
  41443. const video = texture.source.data;
  41444. textureData.externalTexture = video;
  41445. } else {
  41446. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41447. }
  41448. //
  41449. textureData.version = texture.version;
  41450. if ( texture.onUpdate ) texture.onUpdate( texture );
  41451. }
  41452. async copyTextureToBuffer( texture, x, y, width, height ) {
  41453. const device = this.backend.device;
  41454. const textureData = this.backend.get( texture );
  41455. const textureGPU = textureData.texture;
  41456. const format = textureData.textureDescriptorGPU.format;
  41457. const bytesPerTexel = this._getBytesPerTexel( format );
  41458. let bytesPerRow = width * bytesPerTexel;
  41459. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41460. const readBuffer = device.createBuffer(
  41461. {
  41462. size: width * height * bytesPerTexel,
  41463. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41464. }
  41465. );
  41466. const encoder = device.createCommandEncoder();
  41467. encoder.copyTextureToBuffer(
  41468. {
  41469. texture: textureGPU,
  41470. origin: { x, y },
  41471. },
  41472. {
  41473. buffer: readBuffer,
  41474. bytesPerRow: bytesPerRow
  41475. },
  41476. {
  41477. width: width,
  41478. height: height
  41479. }
  41480. );
  41481. const typedArrayType = this._getTypedArrayType( format );
  41482. device.queue.submit( [ encoder.finish() ] );
  41483. await readBuffer.mapAsync( GPUMapMode.READ );
  41484. const buffer = readBuffer.getMappedRange();
  41485. return new typedArrayType( buffer );
  41486. }
  41487. _isEnvironmentTexture( texture ) {
  41488. const mapping = texture.mapping;
  41489. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41490. }
  41491. _getDefaultTextureGPU( format ) {
  41492. let defaultTexture = this.defaultTexture[ format ];
  41493. if ( defaultTexture === undefined ) {
  41494. const texture = new Texture();
  41495. texture.minFilter = NearestFilter;
  41496. texture.magFilter = NearestFilter;
  41497. this.createTexture( texture, { width: 1, height: 1, format } );
  41498. this.defaultTexture[ format ] = defaultTexture = texture;
  41499. }
  41500. return this.backend.get( defaultTexture ).texture;
  41501. }
  41502. _getDefaultCubeTextureGPU( format ) {
  41503. let defaultCubeTexture = this.defaultTexture[ format ];
  41504. if ( defaultCubeTexture === undefined ) {
  41505. const texture = new CubeTexture();
  41506. texture.minFilter = NearestFilter;
  41507. texture.magFilter = NearestFilter;
  41508. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41509. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41510. }
  41511. return this.backend.get( defaultCubeTexture ).texture;
  41512. }
  41513. _getDefaultVideoFrame() {
  41514. let defaultVideoFrame = this.defaultVideoFrame;
  41515. if ( defaultVideoFrame === null ) {
  41516. const init = {
  41517. timestamp: 0,
  41518. codedWidth: 1,
  41519. codedHeight: 1,
  41520. format: 'RGBA',
  41521. };
  41522. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41523. }
  41524. return defaultVideoFrame;
  41525. }
  41526. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  41527. for ( let i = 0; i < 6; i ++ ) {
  41528. const image = images[ i ];
  41529. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  41530. if ( image.isDataTexture ) {
  41531. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41532. } else {
  41533. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41534. }
  41535. }
  41536. }
  41537. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  41538. const device = this.backend.device;
  41539. device.queue.copyExternalImageToTexture(
  41540. {
  41541. source: image
  41542. }, {
  41543. texture: textureGPU,
  41544. mipLevel: 0,
  41545. origin: { x: 0, y: 0, z: originDepth }
  41546. }, {
  41547. width: image.width,
  41548. height: image.height,
  41549. depthOrArrayLayers: 1
  41550. }
  41551. );
  41552. if ( flipY === true ) {
  41553. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41554. }
  41555. }
  41556. _getPassUtils() {
  41557. let passUtils = this._passUtils;
  41558. if ( passUtils === null ) {
  41559. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  41560. }
  41561. return passUtils;
  41562. }
  41563. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  41564. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  41565. }
  41566. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  41567. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  41568. }
  41569. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  41570. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41571. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  41572. const device = this.backend.device;
  41573. const data = image.data;
  41574. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  41575. const bytesPerRow = image.width * bytesPerTexel;
  41576. device.queue.writeTexture(
  41577. {
  41578. texture: textureGPU,
  41579. mipLevel: 0,
  41580. origin: { x: 0, y: 0, z: originDepth }
  41581. },
  41582. data,
  41583. {
  41584. offset: image.width * image.height * bytesPerTexel * depth,
  41585. bytesPerRow
  41586. },
  41587. {
  41588. width: image.width,
  41589. height: image.height,
  41590. depthOrArrayLayers: 1
  41591. } );
  41592. if ( flipY === true ) {
  41593. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41594. }
  41595. }
  41596. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  41597. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41598. const device = this.backend.device;
  41599. const blockData = this._getBlockData( textureDescriptorGPU.format );
  41600. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41601. const mipmap = mipmaps[ i ];
  41602. const width = mipmap.width;
  41603. const height = mipmap.height;
  41604. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  41605. device.queue.writeTexture(
  41606. {
  41607. texture: textureGPU,
  41608. mipLevel: i
  41609. },
  41610. mipmap.data,
  41611. {
  41612. offset: 0,
  41613. bytesPerRow
  41614. },
  41615. {
  41616. width: Math.ceil( width / blockData.width ) * blockData.width,
  41617. height: Math.ceil( height / blockData.width ) * blockData.width,
  41618. depthOrArrayLayers: 1
  41619. }
  41620. );
  41621. }
  41622. }
  41623. _getBlockData( format ) {
  41624. // this method is only relevant for compressed texture formats
  41625. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  41626. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  41627. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  41628. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  41629. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  41630. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  41631. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  41632. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41633. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41634. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41635. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  41636. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  41637. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  41638. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  41639. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41640. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  41641. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  41642. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  41643. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  41644. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  41645. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  41646. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  41647. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  41648. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  41649. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  41650. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  41651. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  41652. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  41653. }
  41654. _convertAddressMode( value ) {
  41655. let addressMode = GPUAddressMode.ClampToEdge;
  41656. if ( value === RepeatWrapping ) {
  41657. addressMode = GPUAddressMode.Repeat;
  41658. } else if ( value === MirroredRepeatWrapping ) {
  41659. addressMode = GPUAddressMode.MirrorRepeat;
  41660. }
  41661. return addressMode;
  41662. }
  41663. _convertFilterMode( value ) {
  41664. let filterMode = GPUFilterMode.Linear;
  41665. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  41666. filterMode = GPUFilterMode.Nearest;
  41667. }
  41668. return filterMode;
  41669. }
  41670. _getBytesPerTexel( format ) {
  41671. // 8-bit formats
  41672. if ( format === GPUTextureFormat.R8Unorm ||
  41673. format === GPUTextureFormat.R8Snorm ||
  41674. format === GPUTextureFormat.R8Uint ||
  41675. format === GPUTextureFormat.R8Sint ) return 1;
  41676. // 16-bit formats
  41677. if ( format === GPUTextureFormat.R16Uint ||
  41678. format === GPUTextureFormat.R16Sint ||
  41679. format === GPUTextureFormat.R16Float ||
  41680. format === GPUTextureFormat.RG8Unorm ||
  41681. format === GPUTextureFormat.RG8Snorm ||
  41682. format === GPUTextureFormat.RG8Uint ||
  41683. format === GPUTextureFormat.RG8Sint ) return 2;
  41684. // 32-bit formats
  41685. if ( format === GPUTextureFormat.R32Uint ||
  41686. format === GPUTextureFormat.R32Sint ||
  41687. format === GPUTextureFormat.R32Float ||
  41688. format === GPUTextureFormat.RG16Uint ||
  41689. format === GPUTextureFormat.RG16Sint ||
  41690. format === GPUTextureFormat.RG16Float ||
  41691. format === GPUTextureFormat.RGBA8Unorm ||
  41692. format === GPUTextureFormat.RGBA8UnormSRGB ||
  41693. format === GPUTextureFormat.RGBA8Snorm ||
  41694. format === GPUTextureFormat.RGBA8Uint ||
  41695. format === GPUTextureFormat.RGBA8Sint ||
  41696. format === GPUTextureFormat.BGRA8Unorm ||
  41697. format === GPUTextureFormat.BGRA8UnormSRGB ||
  41698. // Packed 32-bit formats
  41699. format === GPUTextureFormat.RGB9E5UFloat ||
  41700. format === GPUTextureFormat.RGB10A2Unorm ||
  41701. format === GPUTextureFormat.RG11B10UFloat ||
  41702. format === GPUTextureFormat.Depth32Float ||
  41703. format === GPUTextureFormat.Depth24Plus ||
  41704. format === GPUTextureFormat.Depth24PlusStencil8 ||
  41705. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  41706. // 64-bit formats
  41707. if ( format === GPUTextureFormat.RG32Uint ||
  41708. format === GPUTextureFormat.RG32Sint ||
  41709. format === GPUTextureFormat.RG32Float ||
  41710. format === GPUTextureFormat.RGBA16Uint ||
  41711. format === GPUTextureFormat.RGBA16Sint ||
  41712. format === GPUTextureFormat.RGBA16Float ) return 8;
  41713. // 128-bit formats
  41714. if ( format === GPUTextureFormat.RGBA32Uint ||
  41715. format === GPUTextureFormat.RGBA32Sint ||
  41716. format === GPUTextureFormat.RGBA32Float ) return 16;
  41717. }
  41718. _getTypedArrayType( format ) {
  41719. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  41720. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  41721. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  41722. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  41723. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  41724. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  41725. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  41726. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  41727. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  41728. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  41729. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  41730. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  41731. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  41732. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  41733. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  41734. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  41735. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  41736. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  41737. if ( format === GPUTextureFormat.R16Float ) return Float32Array;
  41738. if ( format === GPUTextureFormat.RG16Float ) return Float32Array;
  41739. if ( format === GPUTextureFormat.RGBA16Float ) return Float32Array;
  41740. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  41741. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  41742. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  41743. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  41744. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  41745. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  41746. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  41747. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  41748. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  41749. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  41750. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  41751. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  41752. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  41753. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  41754. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  41755. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  41756. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  41757. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  41758. }
  41759. _getDimension( texture ) {
  41760. let dimension;
  41761. if ( texture.isData3DTexture ) {
  41762. dimension = GPUTextureDimension.ThreeD;
  41763. } else {
  41764. dimension = GPUTextureDimension.TwoD;
  41765. }
  41766. return dimension;
  41767. }
  41768. }
  41769. function getFormat( texture, device = null ) {
  41770. const format = texture.format;
  41771. const type = texture.type;
  41772. const colorSpace = texture.colorSpace;
  41773. let formatGPU;
  41774. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  41775. formatGPU = GPUTextureFormat.BGRA8Unorm;
  41776. } else if ( texture.isCompressedTexture === true ) {
  41777. switch ( format ) {
  41778. case RGBA_S3TC_DXT1_Format:
  41779. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  41780. break;
  41781. case RGBA_S3TC_DXT3_Format:
  41782. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  41783. break;
  41784. case RGBA_S3TC_DXT5_Format:
  41785. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  41786. break;
  41787. case RGB_ETC2_Format:
  41788. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  41789. break;
  41790. case RGBA_ETC2_EAC_Format:
  41791. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  41792. break;
  41793. case RGBA_ASTC_4x4_Format:
  41794. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  41795. break;
  41796. case RGBA_ASTC_5x4_Format:
  41797. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  41798. break;
  41799. case RGBA_ASTC_5x5_Format:
  41800. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  41801. break;
  41802. case RGBA_ASTC_6x5_Format:
  41803. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  41804. break;
  41805. case RGBA_ASTC_6x6_Format:
  41806. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  41807. break;
  41808. case RGBA_ASTC_8x5_Format:
  41809. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  41810. break;
  41811. case RGBA_ASTC_8x6_Format:
  41812. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  41813. break;
  41814. case RGBA_ASTC_8x8_Format:
  41815. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  41816. break;
  41817. case RGBA_ASTC_10x5_Format:
  41818. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  41819. break;
  41820. case RGBA_ASTC_10x6_Format:
  41821. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  41822. break;
  41823. case RGBA_ASTC_10x8_Format:
  41824. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  41825. break;
  41826. case RGBA_ASTC_10x10_Format:
  41827. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  41828. break;
  41829. case RGBA_ASTC_12x10_Format:
  41830. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  41831. break;
  41832. case RGBA_ASTC_12x12_Format:
  41833. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  41834. break;
  41835. default:
  41836. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  41837. }
  41838. } else {
  41839. switch ( format ) {
  41840. case RGBAFormat:
  41841. switch ( type ) {
  41842. case ByteType:
  41843. formatGPU = GPUTextureFormat.RGBA8Snorm;
  41844. break;
  41845. case ShortType:
  41846. formatGPU = GPUTextureFormat.RGBA16Sint;
  41847. break;
  41848. case UnsignedShortType:
  41849. formatGPU = GPUTextureFormat.RGBA16Uint;
  41850. break;
  41851. case UnsignedIntType:
  41852. formatGPU = GPUTextureFormat.RGBA32Uint;
  41853. break;
  41854. case IntType:
  41855. formatGPU = GPUTextureFormat.RGBA32Sint;
  41856. break;
  41857. case UnsignedByteType:
  41858. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  41859. break;
  41860. case HalfFloatType:
  41861. formatGPU = GPUTextureFormat.RGBA16Float;
  41862. break;
  41863. case FloatType:
  41864. formatGPU = GPUTextureFormat.RGBA32Float;
  41865. break;
  41866. default:
  41867. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  41868. }
  41869. break;
  41870. case RGBFormat:
  41871. switch ( type ) {
  41872. case UnsignedInt5999Type:
  41873. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  41874. break;
  41875. default:
  41876. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  41877. }
  41878. break;
  41879. case RedFormat:
  41880. switch ( type ) {
  41881. case ByteType:
  41882. formatGPU = GPUTextureFormat.R8Snorm;
  41883. break;
  41884. case ShortType:
  41885. formatGPU = GPUTextureFormat.R16Sint;
  41886. break;
  41887. case UnsignedShortType:
  41888. formatGPU = GPUTextureFormat.R16Uint;
  41889. break;
  41890. case UnsignedIntType:
  41891. formatGPU = GPUTextureFormat.R32Uint;
  41892. break;
  41893. case IntType:
  41894. formatGPU = GPUTextureFormat.R32Sint;
  41895. break;
  41896. case UnsignedByteType:
  41897. formatGPU = GPUTextureFormat.R8Unorm;
  41898. break;
  41899. case HalfFloatType:
  41900. formatGPU = GPUTextureFormat.R16Float;
  41901. break;
  41902. case FloatType:
  41903. formatGPU = GPUTextureFormat.R32Float;
  41904. break;
  41905. default:
  41906. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  41907. }
  41908. break;
  41909. case RGFormat:
  41910. switch ( type ) {
  41911. case ByteType:
  41912. formatGPU = GPUTextureFormat.RG8Snorm;
  41913. break;
  41914. case ShortType:
  41915. formatGPU = GPUTextureFormat.RG16Sint;
  41916. break;
  41917. case UnsignedShortType:
  41918. formatGPU = GPUTextureFormat.RG16Uint;
  41919. break;
  41920. case UnsignedIntType:
  41921. formatGPU = GPUTextureFormat.RG32Uint;
  41922. break;
  41923. case IntType:
  41924. formatGPU = GPUTextureFormat.RG32Sint;
  41925. break;
  41926. case UnsignedByteType:
  41927. formatGPU = GPUTextureFormat.RG8Unorm;
  41928. break;
  41929. case HalfFloatType:
  41930. formatGPU = GPUTextureFormat.RG16Float;
  41931. break;
  41932. case FloatType:
  41933. formatGPU = GPUTextureFormat.RG32Float;
  41934. break;
  41935. default:
  41936. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  41937. }
  41938. break;
  41939. case DepthFormat:
  41940. switch ( type ) {
  41941. case UnsignedShortType:
  41942. formatGPU = GPUTextureFormat.Depth16Unorm;
  41943. break;
  41944. case UnsignedIntType:
  41945. formatGPU = GPUTextureFormat.Depth24Plus;
  41946. break;
  41947. case FloatType:
  41948. formatGPU = GPUTextureFormat.Depth32Float;
  41949. break;
  41950. default:
  41951. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  41952. }
  41953. break;
  41954. case DepthStencilFormat:
  41955. switch ( type ) {
  41956. case UnsignedInt248Type:
  41957. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  41958. break;
  41959. case FloatType:
  41960. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  41961. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  41962. }
  41963. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  41964. break;
  41965. default:
  41966. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  41967. }
  41968. break;
  41969. case RedIntegerFormat:
  41970. switch ( type ) {
  41971. case IntType:
  41972. formatGPU = GPUTextureFormat.R32Sint;
  41973. break;
  41974. case UnsignedIntType:
  41975. formatGPU = GPUTextureFormat.R32Uint;
  41976. break;
  41977. default:
  41978. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  41979. }
  41980. break;
  41981. case RGIntegerFormat:
  41982. switch ( type ) {
  41983. case IntType:
  41984. formatGPU = GPUTextureFormat.RG32Sint;
  41985. break;
  41986. case UnsignedIntType:
  41987. formatGPU = GPUTextureFormat.RG32Uint;
  41988. break;
  41989. default:
  41990. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  41991. }
  41992. break;
  41993. case RGBAIntegerFormat:
  41994. switch ( type ) {
  41995. case IntType:
  41996. formatGPU = GPUTextureFormat.RGBA32Sint;
  41997. break;
  41998. case UnsignedIntType:
  41999. formatGPU = GPUTextureFormat.RGBA32Uint;
  42000. break;
  42001. default:
  42002. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42003. }
  42004. break;
  42005. default:
  42006. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42007. }
  42008. }
  42009. return formatGPU;
  42010. }
  42011. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42012. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42013. const wgslTypeLib$1 = {
  42014. 'f32': 'float',
  42015. 'i32': 'int',
  42016. 'u32': 'uint',
  42017. 'bool': 'bool',
  42018. 'vec2<f32>': 'vec2',
  42019. 'vec2<i32>': 'ivec2',
  42020. 'vec2<u32>': 'uvec2',
  42021. 'vec2<bool>': 'bvec2',
  42022. 'vec2f': 'vec2',
  42023. 'vec2i': 'ivec2',
  42024. 'vec2u': 'uvec2',
  42025. 'vec2b': 'bvec2',
  42026. 'vec3<f32>': 'vec3',
  42027. 'vec3<i32>': 'ivec3',
  42028. 'vec3<u32>': 'uvec3',
  42029. 'vec3<bool>': 'bvec3',
  42030. 'vec3f': 'vec3',
  42031. 'vec3i': 'ivec3',
  42032. 'vec3u': 'uvec3',
  42033. 'vec3b': 'bvec3',
  42034. 'vec4<f32>': 'vec4',
  42035. 'vec4<i32>': 'ivec4',
  42036. 'vec4<u32>': 'uvec4',
  42037. 'vec4<bool>': 'bvec4',
  42038. 'vec4f': 'vec4',
  42039. 'vec4i': 'ivec4',
  42040. 'vec4u': 'uvec4',
  42041. 'vec4b': 'bvec4',
  42042. 'mat2x2<f32>': 'mat2',
  42043. 'mat2x2f': 'mat2',
  42044. 'mat3x3<f32>': 'mat3',
  42045. 'mat3x3f': 'mat3',
  42046. 'mat4x4<f32>': 'mat4',
  42047. 'mat4x4f': 'mat4',
  42048. 'sampler': 'sampler',
  42049. 'texture_1d': 'texture',
  42050. 'texture_2d': 'texture',
  42051. 'texture_2d_array': 'texture',
  42052. 'texture_multisampled_2d': 'cubeTexture',
  42053. 'texture_depth_2d': 'depthTexture',
  42054. 'texture_3d': 'texture3D',
  42055. 'texture_cube': 'cubeTexture',
  42056. 'texture_cube_array': 'cubeTexture',
  42057. 'texture_storage_1d': 'storageTexture',
  42058. 'texture_storage_2d': 'storageTexture',
  42059. 'texture_storage_2d_array': 'storageTexture',
  42060. 'texture_storage_3d': 'storageTexture'
  42061. };
  42062. const parse = ( source ) => {
  42063. source = source.trim();
  42064. const declaration = source.match( declarationRegexp );
  42065. if ( declaration !== null && declaration.length === 4 ) {
  42066. const inputsCode = declaration[ 2 ];
  42067. const propsMatches = [];
  42068. let match = null;
  42069. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42070. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42071. }
  42072. // Process matches to correctly pair names and types
  42073. const inputs = [];
  42074. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42075. const { name, type } = propsMatches[ i ];
  42076. let resolvedType = type;
  42077. if ( resolvedType.startsWith( 'texture' ) ) {
  42078. resolvedType = type.split( '<' )[ 0 ];
  42079. }
  42080. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  42081. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42082. }
  42083. const blockCode = source.substring( declaration[ 0 ].length );
  42084. const outputType = declaration[ 3 ] || 'void';
  42085. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42086. const type = wgslTypeLib$1[ outputType ] || outputType;
  42087. return {
  42088. type,
  42089. inputs,
  42090. name,
  42091. inputsCode,
  42092. blockCode,
  42093. outputType
  42094. };
  42095. } else {
  42096. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42097. }
  42098. };
  42099. class WGSLNodeFunction extends NodeFunction {
  42100. constructor( source ) {
  42101. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42102. super( type, inputs, name );
  42103. this.inputsCode = inputsCode;
  42104. this.blockCode = blockCode;
  42105. this.outputType = outputType;
  42106. }
  42107. getCode( name = this.name ) {
  42108. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42109. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42110. }
  42111. }
  42112. class WGSLNodeParser extends NodeParser {
  42113. parseFunction( source ) {
  42114. return new WGSLNodeFunction( source );
  42115. }
  42116. }
  42117. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42118. const GPUShaderStage = self.GPUShaderStage;
  42119. const gpuShaderStageLib = {
  42120. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42121. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42122. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42123. };
  42124. const supports = {
  42125. instance: true,
  42126. swizzleAssign: false,
  42127. storageBuffer: true
  42128. };
  42129. const wgslFnOpLib = {
  42130. '^^': 'threejs_xor'
  42131. };
  42132. const wgslTypeLib = {
  42133. float: 'f32',
  42134. int: 'i32',
  42135. uint: 'u32',
  42136. bool: 'bool',
  42137. color: 'vec3<f32>',
  42138. vec2: 'vec2<f32>',
  42139. ivec2: 'vec2<i32>',
  42140. uvec2: 'vec2<u32>',
  42141. bvec2: 'vec2<bool>',
  42142. vec3: 'vec3<f32>',
  42143. ivec3: 'vec3<i32>',
  42144. uvec3: 'vec3<u32>',
  42145. bvec3: 'vec3<bool>',
  42146. vec4: 'vec4<f32>',
  42147. ivec4: 'vec4<i32>',
  42148. uvec4: 'vec4<u32>',
  42149. bvec4: 'vec4<bool>',
  42150. mat2: 'mat2x2<f32>',
  42151. imat2: 'mat2x2<i32>',
  42152. umat2: 'mat2x2<u32>',
  42153. bmat2: 'mat2x2<bool>',
  42154. mat3: 'mat3x3<f32>',
  42155. imat3: 'mat3x3<i32>',
  42156. umat3: 'mat3x3<u32>',
  42157. bmat3: 'mat3x3<bool>',
  42158. mat4: 'mat4x4<f32>',
  42159. imat4: 'mat4x4<i32>',
  42160. umat4: 'mat4x4<u32>',
  42161. bmat4: 'mat4x4<bool>'
  42162. };
  42163. const wgslPolyfill = {
  42164. threejs_xor: new CodeNode( `
  42165. fn threejs_xor( a : bool, b : bool ) -> bool {
  42166. return ( a || b ) && !( a && b );
  42167. }
  42168. ` ),
  42169. lessThanEqual: new CodeNode( `
  42170. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42171. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  42172. }
  42173. ` ),
  42174. greaterThan: new CodeNode( `
  42175. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  42176. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  42177. }
  42178. ` ),
  42179. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42180. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42181. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42182. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42183. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42184. 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 ); }' ),
  42185. 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 ); }' ),
  42186. 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 ); }' ),
  42187. repeatWrapping: new CodeNode( `
  42188. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42189. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42190. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42191. }
  42192. ` ),
  42193. biquadraticTexture: new CodeNode( `
  42194. fn threejs_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42195. let res = vec2f( textureDimensions( map, level ) );
  42196. let uvScaled = coord * res;
  42197. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42198. // https://www.shadertoy.com/view/WtyXRy
  42199. let uv = uvWrapping - 0.5;
  42200. let iuv = floor( uv );
  42201. let f = fract( uv );
  42202. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  42203. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  42204. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  42205. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  42206. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42207. }
  42208. ` )
  42209. };
  42210. const wgslMethods = {
  42211. dFdx: 'dpdx',
  42212. dFdy: '- dpdy',
  42213. mod_float: 'threejs_mod_float',
  42214. mod_vec2: 'threejs_mod_vec2',
  42215. mod_vec3: 'threejs_mod_vec3',
  42216. mod_vec4: 'threejs_mod_vec4',
  42217. equals_bool: 'threejs_equals_bool',
  42218. equals_bvec2: 'threejs_equals_bvec2',
  42219. equals_bvec3: 'threejs_equals_bvec3',
  42220. equals_bvec4: 'threejs_equals_bvec4',
  42221. lessThanEqual: 'threejs_lessThanEqual',
  42222. greaterThan: 'threejs_greaterThan',
  42223. inversesqrt: 'inverseSqrt',
  42224. bitcast: 'bitcast<f32>'
  42225. };
  42226. // WebGPU issue: does not support pow() with negative base on Windows
  42227. if ( /Windows/g.test( navigator.userAgent ) ) {
  42228. 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 ); }' );
  42229. 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 ] );
  42230. 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 ] );
  42231. 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 ] );
  42232. wgslMethods.pow_float = 'threejs_pow_float';
  42233. wgslMethods.pow_vec2 = 'threejs_pow_vec2';
  42234. wgslMethods.pow_vec3 = 'threejs_pow_vec3';
  42235. wgslMethods.pow_vec4 = 'threejs_pow_vec4';
  42236. }
  42237. //
  42238. class WGSLNodeBuilder extends NodeBuilder {
  42239. constructor( object, renderer ) {
  42240. super( object, renderer, new WGSLNodeParser() );
  42241. this.uniformGroups = {};
  42242. this.builtins = {};
  42243. this.directives = {};
  42244. }
  42245. needsColorSpaceToLinear( texture ) {
  42246. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42247. }
  42248. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42249. if ( shaderStage === 'fragment' ) {
  42250. if ( depthSnippet ) {
  42251. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42252. } else {
  42253. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42254. }
  42255. } else if ( this.isFilteredTexture( texture ) ) {
  42256. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42257. } else {
  42258. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42259. }
  42260. }
  42261. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42262. if ( shaderStage === 'fragment' ) {
  42263. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42264. } else {
  42265. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42266. }
  42267. }
  42268. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42269. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42270. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42271. } else if ( this.isFilteredTexture( texture ) ) {
  42272. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42273. } else {
  42274. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42275. }
  42276. }
  42277. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42278. this._include( 'biquadraticTexture' );
  42279. return `threejs_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42280. }
  42281. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42282. this._include( 'repeatWrapping' );
  42283. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42284. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42285. }
  42286. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42287. if ( depthSnippet ) {
  42288. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42289. } else {
  42290. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42291. }
  42292. }
  42293. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42294. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42295. }
  42296. isUnfilterable( texture ) {
  42297. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42298. }
  42299. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42300. let snippet = null;
  42301. if ( texture.isVideoTexture === true ) {
  42302. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42303. } else if ( this.isUnfilterable( texture ) ) {
  42304. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42305. } else {
  42306. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42307. }
  42308. return snippet;
  42309. }
  42310. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42311. if ( shaderStage === 'fragment' ) {
  42312. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42313. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42314. } else {
  42315. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42316. }
  42317. }
  42318. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42319. if ( shaderStage === 'fragment' ) {
  42320. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42321. } else {
  42322. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42323. }
  42324. }
  42325. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42326. let snippet = null;
  42327. if ( texture.isVideoTexture === true ) {
  42328. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42329. } else {
  42330. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42331. }
  42332. return snippet;
  42333. }
  42334. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42335. if ( shaderStage === 'fragment' ) {
  42336. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42337. } else {
  42338. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42339. }
  42340. }
  42341. getPropertyName( node, shaderStage = this.shaderStage ) {
  42342. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42343. if ( shaderStage === 'vertex' ) {
  42344. return `varyings.${ node.name }`;
  42345. }
  42346. } else if ( node.isNodeUniform === true ) {
  42347. const name = node.name;
  42348. const type = node.type;
  42349. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42350. return name;
  42351. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42352. return `NodeBuffer_${ node.id }.${name}`;
  42353. } else {
  42354. return node.groupNode.name + '.' + name;
  42355. }
  42356. }
  42357. return super.getPropertyName( node );
  42358. }
  42359. getOutputStructName() {
  42360. return 'output';
  42361. }
  42362. _getUniformGroupCount( shaderStage ) {
  42363. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42364. }
  42365. getFunctionOperator( op ) {
  42366. const fnOp = wgslFnOpLib[ op ];
  42367. if ( fnOp !== undefined ) {
  42368. this._include( fnOp );
  42369. return fnOp;
  42370. }
  42371. return null;
  42372. }
  42373. getStorageAccess( node ) {
  42374. if ( node.isStorageTextureNode ) {
  42375. switch ( node.access ) {
  42376. case GPUStorageTextureAccess.ReadOnly:
  42377. return 'read';
  42378. case GPUStorageTextureAccess.WriteOnly:
  42379. return 'write';
  42380. default:
  42381. return 'read_write';
  42382. }
  42383. } else {
  42384. switch ( node.access ) {
  42385. case GPUBufferBindingType.Storage:
  42386. return 'read_write';
  42387. case GPUBufferBindingType.ReadOnlyStorage:
  42388. return 'read';
  42389. default:
  42390. return 'write';
  42391. }
  42392. }
  42393. }
  42394. getUniformFromNode( node, type, shaderStage, name = null ) {
  42395. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42396. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42397. if ( nodeData.uniformGPU === undefined ) {
  42398. let uniformGPU;
  42399. const group = node.groupNode;
  42400. const groupName = group.name;
  42401. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42402. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42403. let texture = null;
  42404. if ( type === 'texture' || type === 'storageTexture' ) {
  42405. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42406. } else if ( type === 'cubeTexture' ) {
  42407. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42408. } else if ( type === 'texture3D' ) {
  42409. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42410. }
  42411. texture.store = node.isStorageTextureNode === true;
  42412. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42413. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42414. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42415. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42416. bindings.push( sampler, texture );
  42417. uniformGPU = [ sampler, texture ];
  42418. } else {
  42419. bindings.push( texture );
  42420. uniformGPU = [ texture ];
  42421. }
  42422. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  42423. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  42424. const buffer = new bufferClass( node, group );
  42425. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42426. bindings.push( buffer );
  42427. uniformGPU = buffer;
  42428. } else {
  42429. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42430. let uniformsGroup = uniformsStage[ groupName ];
  42431. if ( uniformsGroup === undefined ) {
  42432. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42433. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42434. uniformsStage[ groupName ] = uniformsGroup;
  42435. bindings.push( uniformsGroup );
  42436. }
  42437. uniformGPU = this.getNodeUniform( uniformNode, type );
  42438. uniformsGroup.addUniform( uniformGPU );
  42439. }
  42440. nodeData.uniformGPU = uniformGPU;
  42441. }
  42442. return uniformNode;
  42443. }
  42444. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42445. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42446. if ( map.has( name ) === false ) {
  42447. map.set( name, {
  42448. name,
  42449. property,
  42450. type
  42451. } );
  42452. }
  42453. return property;
  42454. }
  42455. getVertexIndex() {
  42456. if ( this.shaderStage === 'vertex' ) {
  42457. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  42458. }
  42459. return 'vertexIndex';
  42460. }
  42461. buildFunctionCode( shaderNode ) {
  42462. const layout = shaderNode.layout;
  42463. const flowData = this.flowShaderNode( shaderNode );
  42464. const parameters = [];
  42465. for ( const input of layout.inputs ) {
  42466. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  42467. }
  42468. //
  42469. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  42470. ${ flowData.vars }
  42471. ${ flowData.code }
  42472. return ${ flowData.result };
  42473. }`;
  42474. //
  42475. return code;
  42476. }
  42477. getInstanceIndex() {
  42478. if ( this.shaderStage === 'vertex' ) {
  42479. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  42480. }
  42481. return 'instanceIndex';
  42482. }
  42483. getDrawIndex() {
  42484. return null;
  42485. }
  42486. getFrontFacing() {
  42487. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  42488. }
  42489. getFragCoord() {
  42490. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  42491. }
  42492. getFragDepth() {
  42493. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  42494. }
  42495. isFlipY() {
  42496. return false;
  42497. }
  42498. enableDirective( name, shaderStage = this.shaderStage ) {
  42499. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = [] );
  42500. stage.push( name );
  42501. }
  42502. getDirectives( shaderStage ) {
  42503. const snippets = [];
  42504. const directives = this.directives[ shaderStage ];
  42505. if ( directives !== undefined ) {
  42506. for ( const directive of directives ) {
  42507. snippets.push( `enable ${directive}` );
  42508. }
  42509. }
  42510. return snippets.join( '\n' );
  42511. }
  42512. enableClipDistances() {
  42513. this.enableDirective( 'clip_distances' );
  42514. }
  42515. enableShaderF16() {
  42516. this.enableDirective( 'f16' );
  42517. }
  42518. enableDualSourceBlending() {
  42519. this.enableDirective( 'dual_source_blending' );
  42520. }
  42521. getBuiltins( shaderStage ) {
  42522. const snippets = [];
  42523. const builtins = this.builtins[ shaderStage ];
  42524. if ( builtins !== undefined ) {
  42525. for ( const { name, property, type } of builtins.values() ) {
  42526. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  42527. }
  42528. }
  42529. return snippets.join( ',\n\t' );
  42530. }
  42531. getAttributes( shaderStage ) {
  42532. const snippets = [];
  42533. if ( shaderStage === 'compute' ) {
  42534. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  42535. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  42536. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  42537. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  42538. }
  42539. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42540. const builtins = this.getBuiltins( 'attribute' );
  42541. if ( builtins ) snippets.push( builtins );
  42542. const attributes = this.getAttributesArray();
  42543. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  42544. const attribute = attributes[ index ];
  42545. const name = attribute.name;
  42546. const type = this.getType( attribute.type );
  42547. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  42548. }
  42549. }
  42550. return snippets.join( ',\n\t' );
  42551. }
  42552. getStructMembers( struct ) {
  42553. const snippets = [];
  42554. const members = struct.getMemberTypes();
  42555. for ( let i = 0; i < members.length; i ++ ) {
  42556. const member = members[ i ];
  42557. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  42558. }
  42559. const builtins = this.getBuiltins( 'output' );
  42560. if ( builtins ) snippets.push( builtins );
  42561. return snippets.join( ',\n' );
  42562. }
  42563. getStructs( shaderStage ) {
  42564. const snippets = [];
  42565. const structs = this.structs[ shaderStage ];
  42566. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  42567. const struct = structs[ index ];
  42568. const name = struct.name;
  42569. let snippet = `\struct ${ name } {\n`;
  42570. snippet += this.getStructMembers( struct );
  42571. snippet += '\n}';
  42572. snippets.push( snippet );
  42573. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  42574. }
  42575. return snippets.join( '\n\n' );
  42576. }
  42577. getVar( type, name ) {
  42578. return `var ${ name } : ${ this.getType( type ) }`;
  42579. }
  42580. getVars( shaderStage ) {
  42581. const snippets = [];
  42582. const vars = this.vars[ shaderStage ];
  42583. if ( vars !== undefined ) {
  42584. for ( const variable of vars ) {
  42585. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  42586. }
  42587. }
  42588. return `\n${ snippets.join( '\n' ) }\n`;
  42589. }
  42590. getVaryings( shaderStage ) {
  42591. const snippets = [];
  42592. if ( shaderStage === 'vertex' ) {
  42593. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  42594. }
  42595. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  42596. const varyings = this.varyings;
  42597. const vars = this.vars[ shaderStage ];
  42598. for ( let index = 0; index < varyings.length; index ++ ) {
  42599. const varying = varyings[ index ];
  42600. if ( varying.needsInterpolation ) {
  42601. let attributesSnippet = `@location( ${index} )`;
  42602. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  42603. attributesSnippet += ' @interpolate( flat )';
  42604. }
  42605. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  42606. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  42607. vars.push( varying );
  42608. }
  42609. }
  42610. }
  42611. const builtins = this.getBuiltins( shaderStage );
  42612. if ( builtins ) snippets.push( builtins );
  42613. const code = snippets.join( ',\n\t' );
  42614. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  42615. }
  42616. getUniforms( shaderStage ) {
  42617. const uniforms = this.uniforms[ shaderStage ];
  42618. const bindingSnippets = [];
  42619. const bufferSnippets = [];
  42620. const structSnippets = [];
  42621. const uniformGroups = {};
  42622. for ( const uniform of uniforms ) {
  42623. const groundName = uniform.groupNode.name;
  42624. const uniformIndexes = this.bindingsIndexes[ groundName ];
  42625. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  42626. const texture = uniform.node.value;
  42627. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  42628. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  42629. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  42630. } else {
  42631. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  42632. }
  42633. }
  42634. let textureType;
  42635. let multisampled = '';
  42636. if ( texture.isMultisampleRenderTargetTexture === true ) {
  42637. multisampled = '_multisampled';
  42638. }
  42639. if ( texture.isCubeTexture === true ) {
  42640. textureType = 'texture_cube<f32>';
  42641. } else if ( texture.isDataArrayTexture === true ) {
  42642. textureType = 'texture_2d_array<f32>';
  42643. } else if ( texture.isDepthTexture === true ) {
  42644. textureType = `texture_depth${multisampled}_2d`;
  42645. } else if ( texture.isVideoTexture === true ) {
  42646. textureType = 'texture_external';
  42647. } else if ( texture.isData3DTexture === true ) {
  42648. textureType = 'texture_3d<f32>';
  42649. } else if ( uniform.node.isStorageTextureNode === true ) {
  42650. const format = getFormat( texture );
  42651. const access = this.getStorageAccess( uniform.node );
  42652. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  42653. } else {
  42654. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  42655. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  42656. }
  42657. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  42658. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  42659. const bufferNode = uniform.node;
  42660. const bufferType = this.getType( bufferNode.bufferType );
  42661. const bufferCount = bufferNode.bufferCount;
  42662. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  42663. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferType }${ bufferCountSnippet } >\n`;
  42664. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  42665. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  42666. } else {
  42667. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  42668. const groupName = uniform.groupNode.name;
  42669. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  42670. index: uniformIndexes.binding ++,
  42671. id: uniformIndexes.group,
  42672. snippets: []
  42673. } );
  42674. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  42675. }
  42676. }
  42677. for ( const name in uniformGroups ) {
  42678. const group = uniformGroups[ name ];
  42679. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  42680. }
  42681. let code = bindingSnippets.join( '\n' );
  42682. code += bufferSnippets.join( '\n' );
  42683. code += structSnippets.join( '\n' );
  42684. return code;
  42685. }
  42686. buildCode() {
  42687. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42688. for ( const shaderStage in shadersData ) {
  42689. const stageData = shadersData[ shaderStage ];
  42690. stageData.uniforms = this.getUniforms( shaderStage );
  42691. stageData.attributes = this.getAttributes( shaderStage );
  42692. stageData.varyings = this.getVaryings( shaderStage );
  42693. stageData.structs = this.getStructs( shaderStage );
  42694. stageData.vars = this.getVars( shaderStage );
  42695. stageData.codes = this.getCodes( shaderStage );
  42696. stageData.directives = this.getDirectives( shaderStage );
  42697. //
  42698. let flow = '// code\n\n';
  42699. flow += this.flowCode[ shaderStage ];
  42700. const flowNodes = this.flowNodes[ shaderStage ];
  42701. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42702. const outputNode = mainNode.outputNode;
  42703. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  42704. for ( const node of flowNodes ) {
  42705. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42706. const slotName = node.name;
  42707. if ( slotName ) {
  42708. if ( flow.length > 0 ) flow += '\n';
  42709. flow += `\t// flow -> ${ slotName }\n\t`;
  42710. }
  42711. flow += `${ flowSlotData.code }\n\t`;
  42712. if ( node === mainNode && shaderStage !== 'compute' ) {
  42713. flow += '// result\n\n\t';
  42714. if ( shaderStage === 'vertex' ) {
  42715. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  42716. } else if ( shaderStage === 'fragment' ) {
  42717. if ( isOutputStruct ) {
  42718. stageData.returnType = outputNode.nodeType;
  42719. flow += `return ${ flowSlotData.result };`;
  42720. } else {
  42721. let structSnippet = '\t@location(0) color: vec4<f32>';
  42722. const builtins = this.getBuiltins( 'output' );
  42723. if ( builtins ) structSnippet += ',\n\t' + builtins;
  42724. stageData.returnType = 'OutputStruct';
  42725. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  42726. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  42727. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  42728. }
  42729. }
  42730. }
  42731. }
  42732. stageData.flow = flow;
  42733. }
  42734. if ( this.material !== null ) {
  42735. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  42736. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  42737. } else {
  42738. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  42739. }
  42740. }
  42741. getMethod( method, output = null ) {
  42742. let wgslMethod;
  42743. if ( output !== null ) {
  42744. wgslMethod = this._getWGSLMethod( method + '_' + output );
  42745. }
  42746. if ( wgslMethod === undefined ) {
  42747. wgslMethod = this._getWGSLMethod( method );
  42748. }
  42749. return wgslMethod || method;
  42750. }
  42751. getType( type ) {
  42752. return wgslTypeLib[ type ] || type;
  42753. }
  42754. isAvailable( name ) {
  42755. let result = supports[ name ];
  42756. if ( result === undefined ) {
  42757. if ( name === 'float32Filterable' ) {
  42758. result = this.renderer.hasFeature( 'float32-filterable' );
  42759. }
  42760. supports[ name ] = result;
  42761. }
  42762. return result;
  42763. }
  42764. _getWGSLMethod( method ) {
  42765. if ( wgslPolyfill[ method ] !== undefined ) {
  42766. this._include( method );
  42767. }
  42768. return wgslMethods[ method ];
  42769. }
  42770. _include( name ) {
  42771. const codeNode = wgslPolyfill[ name ];
  42772. codeNode.build( this );
  42773. if ( this.currentFunctionNode !== null ) {
  42774. this.currentFunctionNode.includes.push( codeNode );
  42775. }
  42776. return codeNode;
  42777. }
  42778. _getWGSLVertexCode( shaderData ) {
  42779. return `${ this.getSignature() }
  42780. // directives
  42781. ${shaderData.directives};
  42782. // uniforms
  42783. ${shaderData.uniforms}
  42784. // varyings
  42785. ${shaderData.varyings}
  42786. var<private> varyings : VaryingsStruct;
  42787. // codes
  42788. ${shaderData.codes}
  42789. @vertex
  42790. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  42791. // vars
  42792. ${shaderData.vars}
  42793. // flow
  42794. ${shaderData.flow}
  42795. return varyings;
  42796. }
  42797. `;
  42798. }
  42799. _getWGSLFragmentCode( shaderData ) {
  42800. return `${ this.getSignature() }
  42801. diagnostic( off, derivative_uniformity );
  42802. // uniforms
  42803. ${shaderData.uniforms}
  42804. // structs
  42805. ${shaderData.structs}
  42806. // codes
  42807. ${shaderData.codes}
  42808. @fragment
  42809. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  42810. // vars
  42811. ${shaderData.vars}
  42812. // flow
  42813. ${shaderData.flow}
  42814. }
  42815. `;
  42816. }
  42817. _getWGSLComputeCode( shaderData, workgroupSize ) {
  42818. return `${ this.getSignature() }
  42819. // directives
  42820. ${shaderData.directives}
  42821. // system
  42822. var<private> instanceIndex : u32;
  42823. // uniforms
  42824. ${shaderData.uniforms}
  42825. // codes
  42826. ${shaderData.codes}
  42827. @compute @workgroup_size( ${workgroupSize} )
  42828. fn main( ${shaderData.attributes} ) {
  42829. // system
  42830. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  42831. // vars
  42832. ${shaderData.vars}
  42833. // flow
  42834. ${shaderData.flow}
  42835. }
  42836. `;
  42837. }
  42838. _getWGSLStruct( name, vars ) {
  42839. return `
  42840. struct ${name} {
  42841. ${vars}
  42842. };`;
  42843. }
  42844. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  42845. const structName = name + 'Struct';
  42846. const structSnippet = this._getWGSLStruct( structName, vars );
  42847. return `${structSnippet}
  42848. @binding( ${binding} ) @group( ${group} )
  42849. var<${access}> ${name} : ${structName};`;
  42850. }
  42851. }
  42852. class WebGPUUtils {
  42853. constructor( backend ) {
  42854. this.backend = backend;
  42855. }
  42856. getCurrentDepthStencilFormat( renderContext ) {
  42857. let format;
  42858. if ( renderContext.depthTexture !== null ) {
  42859. format = this.getTextureFormatGPU( renderContext.depthTexture );
  42860. } else if ( renderContext.depth && renderContext.stencil ) {
  42861. format = GPUTextureFormat.Depth24PlusStencil8;
  42862. } else if ( renderContext.depth ) {
  42863. format = GPUTextureFormat.Depth24Plus;
  42864. }
  42865. return format;
  42866. }
  42867. getTextureFormatGPU( texture ) {
  42868. return this.backend.get( texture ).texture.format;
  42869. }
  42870. getCurrentColorFormat( renderContext ) {
  42871. let format;
  42872. if ( renderContext.textures !== null ) {
  42873. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  42874. } else {
  42875. format = GPUTextureFormat.BGRA8Unorm; // default context format
  42876. }
  42877. return format;
  42878. }
  42879. getCurrentColorSpace( renderContext ) {
  42880. if ( renderContext.textures !== null ) {
  42881. return renderContext.textures[ 0 ].colorSpace;
  42882. }
  42883. return this.backend.renderer.outputColorSpace;
  42884. }
  42885. getPrimitiveTopology( object, material ) {
  42886. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  42887. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  42888. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  42889. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  42890. }
  42891. getSampleCount( sampleCount ) {
  42892. let count = 1;
  42893. if ( sampleCount > 1 ) {
  42894. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  42895. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  42896. if ( count === 2 ) {
  42897. count = 4;
  42898. }
  42899. }
  42900. return count;
  42901. }
  42902. getSampleCountRenderContext( renderContext ) {
  42903. if ( renderContext.textures !== null ) {
  42904. return this.getSampleCount( renderContext.sampleCount );
  42905. }
  42906. return this.getSampleCount( this.backend.renderer.samples );
  42907. }
  42908. }
  42909. const typedArraysToVertexFormatPrefix = new Map( [
  42910. [ Int8Array, [ 'sint8', 'snorm8' ]],
  42911. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  42912. [ Int16Array, [ 'sint16', 'snorm16' ]],
  42913. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  42914. [ Int32Array, [ 'sint32', 'snorm32' ]],
  42915. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  42916. [ Float32Array, [ 'float32', ]],
  42917. ] );
  42918. const typedAttributeToVertexFormatPrefix = new Map( [
  42919. [ Float16BufferAttribute, [ 'float16', ]],
  42920. ] );
  42921. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  42922. [ Int32Array, 'sint32' ],
  42923. [ Int16Array, 'sint32' ], // patch for INT16
  42924. [ Uint32Array, 'uint32' ],
  42925. [ Uint16Array, 'uint32' ], // patch for UINT16
  42926. [ Float32Array, 'float32' ]
  42927. ] );
  42928. class WebGPUAttributeUtils {
  42929. constructor( backend ) {
  42930. this.backend = backend;
  42931. }
  42932. createAttribute( attribute, usage ) {
  42933. const bufferAttribute = this._getBufferAttribute( attribute );
  42934. const backend = this.backend;
  42935. const bufferData = backend.get( bufferAttribute );
  42936. let buffer = bufferData.buffer;
  42937. if ( buffer === undefined ) {
  42938. const device = backend.device;
  42939. let array = bufferAttribute.array;
  42940. // patch for INT16 and UINT16
  42941. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  42942. const tempArray = new Uint32Array( array.length );
  42943. for ( let i = 0; i < array.length; i ++ ) {
  42944. tempArray[ i ] = array[ i ];
  42945. }
  42946. array = tempArray;
  42947. }
  42948. bufferAttribute.array = array;
  42949. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  42950. array = new array.constructor( bufferAttribute.count * 4 );
  42951. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  42952. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  42953. }
  42954. // Update BufferAttribute
  42955. bufferAttribute.itemSize = 4;
  42956. bufferAttribute.array = array;
  42957. }
  42958. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  42959. buffer = device.createBuffer( {
  42960. label: bufferAttribute.name,
  42961. size: size,
  42962. usage: usage,
  42963. mappedAtCreation: true
  42964. } );
  42965. new array.constructor( buffer.getMappedRange() ).set( array );
  42966. buffer.unmap();
  42967. bufferData.buffer = buffer;
  42968. }
  42969. }
  42970. updateAttribute( attribute ) {
  42971. const bufferAttribute = this._getBufferAttribute( attribute );
  42972. const backend = this.backend;
  42973. const device = backend.device;
  42974. const buffer = backend.get( bufferAttribute ).buffer;
  42975. const array = bufferAttribute.array;
  42976. const updateRanges = bufferAttribute.updateRanges;
  42977. if ( updateRanges.length === 0 ) {
  42978. // Not using update ranges
  42979. device.queue.writeBuffer(
  42980. buffer,
  42981. 0,
  42982. array,
  42983. 0
  42984. );
  42985. } else {
  42986. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42987. const range = updateRanges[ i ];
  42988. device.queue.writeBuffer(
  42989. buffer,
  42990. 0,
  42991. array,
  42992. range.start * array.BYTES_PER_ELEMENT,
  42993. range.count * array.BYTES_PER_ELEMENT
  42994. );
  42995. }
  42996. bufferAttribute.clearUpdateRanges();
  42997. }
  42998. }
  42999. createShaderVertexBuffers( renderObject ) {
  43000. const attributes = renderObject.getAttributes();
  43001. const vertexBuffers = new Map();
  43002. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43003. const geometryAttribute = attributes[ slot ];
  43004. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43005. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43006. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43007. if ( vertexBufferLayout === undefined ) {
  43008. let arrayStride, stepMode;
  43009. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43010. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43011. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43012. } else {
  43013. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43014. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43015. }
  43016. // patch for INT16 and UINT16
  43017. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43018. arrayStride = 4;
  43019. }
  43020. vertexBufferLayout = {
  43021. arrayStride,
  43022. attributes: [],
  43023. stepMode
  43024. };
  43025. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43026. }
  43027. const format = this._getVertexFormat( geometryAttribute );
  43028. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43029. vertexBufferLayout.attributes.push( {
  43030. shaderLocation: slot,
  43031. offset,
  43032. format
  43033. } );
  43034. }
  43035. return Array.from( vertexBuffers.values() );
  43036. }
  43037. destroyAttribute( attribute ) {
  43038. const backend = this.backend;
  43039. const data = backend.get( this._getBufferAttribute( attribute ) );
  43040. data.buffer.destroy();
  43041. backend.delete( attribute );
  43042. }
  43043. async getArrayBufferAsync( attribute ) {
  43044. const backend = this.backend;
  43045. const device = backend.device;
  43046. const data = backend.get( this._getBufferAttribute( attribute ) );
  43047. const bufferGPU = data.buffer;
  43048. const size = bufferGPU.size;
  43049. let readBufferGPU = data.readBuffer;
  43050. let needsUnmap = true;
  43051. if ( readBufferGPU === undefined ) {
  43052. readBufferGPU = device.createBuffer( {
  43053. label: attribute.name,
  43054. size,
  43055. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43056. } );
  43057. needsUnmap = false;
  43058. data.readBuffer = readBufferGPU;
  43059. }
  43060. const cmdEncoder = device.createCommandEncoder( {} );
  43061. cmdEncoder.copyBufferToBuffer(
  43062. bufferGPU,
  43063. 0,
  43064. readBufferGPU,
  43065. 0,
  43066. size
  43067. );
  43068. if ( needsUnmap ) readBufferGPU.unmap();
  43069. const gpuCommands = cmdEncoder.finish();
  43070. device.queue.submit( [ gpuCommands ] );
  43071. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43072. const arrayBuffer = readBufferGPU.getMappedRange();
  43073. return arrayBuffer;
  43074. }
  43075. _getVertexFormat( geometryAttribute ) {
  43076. const { itemSize, normalized } = geometryAttribute;
  43077. const ArrayType = geometryAttribute.array.constructor;
  43078. const AttributeType = geometryAttribute.constructor;
  43079. let format;
  43080. if ( itemSize == 1 ) {
  43081. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43082. } else {
  43083. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43084. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43085. if ( prefix ) {
  43086. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43087. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43088. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43089. if ( paddedItemSize % 1 ) {
  43090. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43091. }
  43092. format = `${prefix}x${paddedItemSize}`;
  43093. }
  43094. }
  43095. if ( ! format ) {
  43096. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43097. }
  43098. return format;
  43099. }
  43100. _getBufferAttribute( attribute ) {
  43101. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43102. return attribute;
  43103. }
  43104. }
  43105. class WebGPUBindingUtils {
  43106. constructor( backend ) {
  43107. this.backend = backend;
  43108. }
  43109. createBindingsLayout( bindGroup ) {
  43110. const backend = this.backend;
  43111. const device = backend.device;
  43112. const entries = [];
  43113. let index = 0;
  43114. for ( const binding of bindGroup.bindings ) {
  43115. const bindingGPU = {
  43116. binding: index ++,
  43117. visibility: binding.visibility
  43118. };
  43119. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43120. const buffer = {}; // GPUBufferBindingLayout
  43121. if ( binding.isStorageBuffer ) {
  43122. buffer.type = binding.access;
  43123. }
  43124. bindingGPU.buffer = buffer;
  43125. } else if ( binding.isSampler ) {
  43126. const sampler = {}; // GPUSamplerBindingLayout
  43127. if ( binding.texture.isDepthTexture ) {
  43128. if ( binding.texture.compareFunction !== null ) {
  43129. sampler.type = 'comparison';
  43130. }
  43131. }
  43132. bindingGPU.sampler = sampler;
  43133. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43134. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43135. } else if ( binding.isSampledTexture && binding.store ) {
  43136. const format = this.backend.get( binding.texture ).texture.format;
  43137. const access = binding.access;
  43138. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43139. } else if ( binding.isSampledTexture ) {
  43140. const texture = {}; // GPUTextureBindingLayout
  43141. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43142. texture.multisampled = true;
  43143. }
  43144. if ( binding.texture.isDepthTexture ) {
  43145. texture.sampleType = GPUTextureSampleType.Depth;
  43146. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43147. const type = binding.texture.type;
  43148. if ( type === IntType ) {
  43149. texture.sampleType = GPUTextureSampleType.SInt;
  43150. } else if ( type === UnsignedIntType ) {
  43151. texture.sampleType = GPUTextureSampleType.UInt;
  43152. } else if ( type === FloatType ) {
  43153. // @TODO: Add support for this soon: backend.hasFeature( 'float32-filterable' )
  43154. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43155. }
  43156. }
  43157. if ( binding.isSampledCubeTexture ) {
  43158. texture.viewDimension = GPUTextureViewDimension.Cube;
  43159. } else if ( binding.texture.isDataArrayTexture ) {
  43160. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43161. } else if ( binding.isSampledTexture3D ) {
  43162. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43163. }
  43164. bindingGPU.texture = texture;
  43165. } else {
  43166. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43167. }
  43168. entries.push( bindingGPU );
  43169. }
  43170. return device.createBindGroupLayout( { entries } );
  43171. }
  43172. createBindings( bindGroup ) {
  43173. const backend = this.backend;
  43174. const bindingsData = backend.get( bindGroup );
  43175. // setup (static) binding layout and (dynamic) binding group
  43176. const bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43177. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43178. bindingsData.layout = bindLayoutGPU;
  43179. bindingsData.group = bindGroupGPU;
  43180. }
  43181. updateBinding( binding ) {
  43182. const backend = this.backend;
  43183. const device = backend.device;
  43184. const buffer = binding.buffer;
  43185. const bufferGPU = backend.get( binding ).buffer;
  43186. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43187. }
  43188. createBindGroup( bindGroup, layoutGPU ) {
  43189. const backend = this.backend;
  43190. const device = backend.device;
  43191. let bindingPoint = 0;
  43192. const entriesGPU = [];
  43193. for ( const binding of bindGroup.bindings ) {
  43194. if ( binding.isUniformBuffer ) {
  43195. const bindingData = backend.get( binding );
  43196. if ( bindingData.buffer === undefined ) {
  43197. const byteLength = binding.byteLength;
  43198. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43199. const bufferGPU = device.createBuffer( {
  43200. label: 'bindingBuffer_' + binding.name,
  43201. size: byteLength,
  43202. usage: usage
  43203. } );
  43204. bindingData.buffer = bufferGPU;
  43205. }
  43206. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43207. } else if ( binding.isStorageBuffer ) {
  43208. const bindingData = backend.get( binding );
  43209. if ( bindingData.buffer === undefined ) {
  43210. const attribute = binding.attribute;
  43211. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43212. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43213. bindingData.buffer = backend.get( attribute ).buffer;
  43214. }
  43215. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43216. } else if ( binding.isSampler ) {
  43217. const textureGPU = backend.get( binding.texture );
  43218. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43219. } else if ( binding.isSampledTexture ) {
  43220. const textureData = backend.get( binding.texture );
  43221. let dimensionViewGPU;
  43222. if ( binding.isSampledCubeTexture ) {
  43223. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43224. } else if ( binding.isSampledTexture3D ) {
  43225. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43226. } else if ( binding.texture.isDataArrayTexture ) {
  43227. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43228. } else {
  43229. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43230. }
  43231. let resourceGPU;
  43232. if ( textureData.externalTexture !== undefined ) {
  43233. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43234. } else {
  43235. const aspectGPU = GPUTextureAspect.All;
  43236. resourceGPU = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount: binding.store ? 1 : textureData.mipLevelCount } );
  43237. }
  43238. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43239. }
  43240. bindingPoint ++;
  43241. }
  43242. return device.createBindGroup( {
  43243. label: 'bindGroup_' + bindGroup.name,
  43244. layout: layoutGPU,
  43245. entries: entriesGPU
  43246. } );
  43247. }
  43248. }
  43249. class WebGPUPipelineUtils {
  43250. constructor( backend ) {
  43251. this.backend = backend;
  43252. }
  43253. _getSampleCount( renderObjectContext ) {
  43254. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43255. }
  43256. createRenderPipeline( renderObject, promises ) {
  43257. const { object, material, geometry, pipeline } = renderObject;
  43258. const { vertexProgram, fragmentProgram } = pipeline;
  43259. const backend = this.backend;
  43260. const device = backend.device;
  43261. const utils = backend.utils;
  43262. const pipelineData = backend.get( pipeline );
  43263. // bind group layouts
  43264. const bindGroupLayouts = [];
  43265. for ( const bindGroup of renderObject.getBindings() ) {
  43266. const bindingsData = backend.get( bindGroup );
  43267. bindGroupLayouts.push( bindingsData.layout );
  43268. }
  43269. // vertex buffers
  43270. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43271. // blending
  43272. let blending;
  43273. if ( material.transparent === true && material.blending !== NoBlending ) {
  43274. blending = this._getBlending( material );
  43275. }
  43276. // stencil
  43277. let stencilFront = {};
  43278. if ( material.stencilWrite === true ) {
  43279. stencilFront = {
  43280. compare: this._getStencilCompare( material ),
  43281. failOp: this._getStencilOperation( material.stencilFail ),
  43282. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43283. passOp: this._getStencilOperation( material.stencilZPass )
  43284. };
  43285. }
  43286. const colorWriteMask = this._getColorWriteMask( material );
  43287. const targets = [];
  43288. if ( renderObject.context.textures !== null ) {
  43289. const textures = renderObject.context.textures;
  43290. for ( let i = 0; i < textures.length; i ++ ) {
  43291. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43292. targets.push( {
  43293. format: colorFormat,
  43294. blend: blending,
  43295. writeMask: colorWriteMask
  43296. } );
  43297. }
  43298. } else {
  43299. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43300. targets.push( {
  43301. format: colorFormat,
  43302. blend: blending,
  43303. writeMask: colorWriteMask
  43304. } );
  43305. }
  43306. const vertexModule = backend.get( vertexProgram ).module;
  43307. const fragmentModule = backend.get( fragmentProgram ).module;
  43308. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43309. const depthCompare = this._getDepthCompare( material );
  43310. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43311. const sampleCount = this._getSampleCount( renderObject.context );
  43312. const pipelineDescriptor = {
  43313. label: 'renderPipeline',
  43314. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43315. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43316. primitive: primitiveState,
  43317. depthStencil: {
  43318. format: depthStencilFormat,
  43319. depthWriteEnabled: material.depthWrite,
  43320. depthCompare: depthCompare,
  43321. stencilFront: stencilFront,
  43322. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43323. stencilReadMask: material.stencilFuncMask,
  43324. stencilWriteMask: material.stencilWriteMask
  43325. },
  43326. multisample: {
  43327. count: sampleCount,
  43328. alphaToCoverageEnabled: material.alphaToCoverage
  43329. },
  43330. layout: device.createPipelineLayout( {
  43331. bindGroupLayouts
  43332. } )
  43333. };
  43334. if ( promises === null ) {
  43335. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43336. } else {
  43337. const p = new Promise( ( resolve /*, reject*/ ) => {
  43338. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43339. pipelineData.pipeline = pipeline;
  43340. resolve();
  43341. } );
  43342. } );
  43343. promises.push( p );
  43344. }
  43345. }
  43346. createBundleEncoder( renderContext, renderObject ) {
  43347. const backend = this.backend;
  43348. const { utils, device } = backend;
  43349. const renderContextData = backend.get( renderContext );
  43350. const renderObjectData = backend.get( renderObject );
  43351. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  43352. const colorFormat = utils.getCurrentColorFormat( renderContext );
  43353. const sampleCount = this._getSampleCount( renderObject.context );
  43354. const descriptor = {
  43355. label: 'renderBundleEncoder',
  43356. colorFormats: [ colorFormat ],
  43357. depthStencilFormat,
  43358. sampleCount
  43359. };
  43360. const bundleEncoder = device.createRenderBundleEncoder( descriptor );
  43361. renderObjectData.bundleEncoder = bundleEncoder;
  43362. renderContextData.currentSets = { attributes: {} };
  43363. renderContextData._renderBundleViewport = renderContext.width + '_' + renderContext.height;
  43364. return bundleEncoder;
  43365. }
  43366. createComputePipeline( pipeline, bindings ) {
  43367. const backend = this.backend;
  43368. const device = backend.device;
  43369. const computeProgram = backend.get( pipeline.computeProgram ).module;
  43370. const pipelineGPU = backend.get( pipeline );
  43371. // bind group layouts
  43372. const bindGroupLayouts = [];
  43373. for ( const bindingsGroup of bindings ) {
  43374. const bindingsData = backend.get( bindingsGroup );
  43375. bindGroupLayouts.push( bindingsData.layout );
  43376. }
  43377. pipelineGPU.pipeline = device.createComputePipeline( {
  43378. compute: computeProgram,
  43379. layout: device.createPipelineLayout( {
  43380. bindGroupLayouts
  43381. } )
  43382. } );
  43383. }
  43384. _getBlending( material ) {
  43385. let color, alpha;
  43386. const blending = material.blending;
  43387. const blendSrc = material.blendSrc;
  43388. const blendDst = material.blendDst;
  43389. const blendEquation = material.blendEquation;
  43390. if ( blending === CustomBlending ) {
  43391. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  43392. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  43393. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  43394. color = {
  43395. srcFactor: this._getBlendFactor( blendSrc ),
  43396. dstFactor: this._getBlendFactor( blendDst ),
  43397. operation: this._getBlendOperation( blendEquation )
  43398. };
  43399. alpha = {
  43400. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  43401. dstFactor: this._getBlendFactor( blendDstAlpha ),
  43402. operation: this._getBlendOperation( blendEquationAlpha )
  43403. };
  43404. } else {
  43405. const premultipliedAlpha = material.premultipliedAlpha;
  43406. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  43407. color = {
  43408. srcFactor: srcRGB,
  43409. dstFactor: dstRGB,
  43410. operation: GPUBlendOperation.Add
  43411. };
  43412. alpha = {
  43413. srcFactor: srcAlpha,
  43414. dstFactor: dstAlpha,
  43415. operation: GPUBlendOperation.Add
  43416. };
  43417. };
  43418. if ( premultipliedAlpha ) {
  43419. switch ( blending ) {
  43420. case NormalBlending:
  43421. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43422. break;
  43423. case AdditiveBlending:
  43424. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  43425. break;
  43426. case SubtractiveBlending:
  43427. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43428. break;
  43429. case MultiplyBlending:
  43430. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  43431. break;
  43432. }
  43433. } else {
  43434. switch ( blending ) {
  43435. case NormalBlending:
  43436. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43437. break;
  43438. case AdditiveBlending:
  43439. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  43440. break;
  43441. case SubtractiveBlending:
  43442. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43443. break;
  43444. case MultiplyBlending:
  43445. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  43446. break;
  43447. }
  43448. }
  43449. }
  43450. if ( color !== undefined && alpha !== undefined ) {
  43451. return { color, alpha };
  43452. } else {
  43453. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  43454. }
  43455. }
  43456. _getBlendFactor( blend ) {
  43457. let blendFactor;
  43458. switch ( blend ) {
  43459. case ZeroFactor:
  43460. blendFactor = GPUBlendFactor.Zero;
  43461. break;
  43462. case OneFactor:
  43463. blendFactor = GPUBlendFactor.One;
  43464. break;
  43465. case SrcColorFactor:
  43466. blendFactor = GPUBlendFactor.Src;
  43467. break;
  43468. case OneMinusSrcColorFactor:
  43469. blendFactor = GPUBlendFactor.OneMinusSrc;
  43470. break;
  43471. case SrcAlphaFactor:
  43472. blendFactor = GPUBlendFactor.SrcAlpha;
  43473. break;
  43474. case OneMinusSrcAlphaFactor:
  43475. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  43476. break;
  43477. case DstColorFactor:
  43478. blendFactor = GPUBlendFactor.Dst;
  43479. break;
  43480. case OneMinusDstColorFactor:
  43481. blendFactor = GPUBlendFactor.OneMinusDstColor;
  43482. break;
  43483. case DstAlphaFactor:
  43484. blendFactor = GPUBlendFactor.DstAlpha;
  43485. break;
  43486. case OneMinusDstAlphaFactor:
  43487. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  43488. break;
  43489. case SrcAlphaSaturateFactor:
  43490. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  43491. break;
  43492. case BlendColorFactor:
  43493. blendFactor = GPUBlendFactor.Constant;
  43494. break;
  43495. case OneMinusBlendColorFactor:
  43496. blendFactor = GPUBlendFactor.OneMinusConstant;
  43497. break;
  43498. default:
  43499. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  43500. }
  43501. return blendFactor;
  43502. }
  43503. _getStencilCompare( material ) {
  43504. let stencilCompare;
  43505. const stencilFunc = material.stencilFunc;
  43506. switch ( stencilFunc ) {
  43507. case NeverStencilFunc:
  43508. stencilCompare = GPUCompareFunction.Never;
  43509. break;
  43510. case AlwaysStencilFunc:
  43511. stencilCompare = GPUCompareFunction.Always;
  43512. break;
  43513. case LessStencilFunc:
  43514. stencilCompare = GPUCompareFunction.Less;
  43515. break;
  43516. case LessEqualStencilFunc:
  43517. stencilCompare = GPUCompareFunction.LessEqual;
  43518. break;
  43519. case EqualStencilFunc:
  43520. stencilCompare = GPUCompareFunction.Equal;
  43521. break;
  43522. case GreaterEqualStencilFunc:
  43523. stencilCompare = GPUCompareFunction.GreaterEqual;
  43524. break;
  43525. case GreaterStencilFunc:
  43526. stencilCompare = GPUCompareFunction.Greater;
  43527. break;
  43528. case NotEqualStencilFunc:
  43529. stencilCompare = GPUCompareFunction.NotEqual;
  43530. break;
  43531. default:
  43532. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  43533. }
  43534. return stencilCompare;
  43535. }
  43536. _getStencilOperation( op ) {
  43537. let stencilOperation;
  43538. switch ( op ) {
  43539. case KeepStencilOp:
  43540. stencilOperation = GPUStencilOperation.Keep;
  43541. break;
  43542. case ZeroStencilOp:
  43543. stencilOperation = GPUStencilOperation.Zero;
  43544. break;
  43545. case ReplaceStencilOp:
  43546. stencilOperation = GPUStencilOperation.Replace;
  43547. break;
  43548. case InvertStencilOp:
  43549. stencilOperation = GPUStencilOperation.Invert;
  43550. break;
  43551. case IncrementStencilOp:
  43552. stencilOperation = GPUStencilOperation.IncrementClamp;
  43553. break;
  43554. case DecrementStencilOp:
  43555. stencilOperation = GPUStencilOperation.DecrementClamp;
  43556. break;
  43557. case IncrementWrapStencilOp:
  43558. stencilOperation = GPUStencilOperation.IncrementWrap;
  43559. break;
  43560. case DecrementWrapStencilOp:
  43561. stencilOperation = GPUStencilOperation.DecrementWrap;
  43562. break;
  43563. default:
  43564. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  43565. }
  43566. return stencilOperation;
  43567. }
  43568. _getBlendOperation( blendEquation ) {
  43569. let blendOperation;
  43570. switch ( blendEquation ) {
  43571. case AddEquation:
  43572. blendOperation = GPUBlendOperation.Add;
  43573. break;
  43574. case SubtractEquation:
  43575. blendOperation = GPUBlendOperation.Subtract;
  43576. break;
  43577. case ReverseSubtractEquation:
  43578. blendOperation = GPUBlendOperation.ReverseSubtract;
  43579. break;
  43580. case MinEquation:
  43581. blendOperation = GPUBlendOperation.Min;
  43582. break;
  43583. case MaxEquation:
  43584. blendOperation = GPUBlendOperation.Max;
  43585. break;
  43586. default:
  43587. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  43588. }
  43589. return blendOperation;
  43590. }
  43591. _getPrimitiveState( object, geometry, material ) {
  43592. const descriptor = {};
  43593. const utils = this.backend.utils;
  43594. descriptor.topology = utils.getPrimitiveTopology( object, material );
  43595. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  43596. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43597. }
  43598. switch ( material.side ) {
  43599. case FrontSide:
  43600. descriptor.frontFace = GPUFrontFace.CCW;
  43601. descriptor.cullMode = GPUCullMode.Back;
  43602. break;
  43603. case BackSide:
  43604. descriptor.frontFace = GPUFrontFace.CCW;
  43605. descriptor.cullMode = GPUCullMode.Front;
  43606. break;
  43607. case DoubleSide:
  43608. descriptor.frontFace = GPUFrontFace.CCW;
  43609. descriptor.cullMode = GPUCullMode.None;
  43610. break;
  43611. default:
  43612. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  43613. break;
  43614. }
  43615. return descriptor;
  43616. }
  43617. _getColorWriteMask( material ) {
  43618. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  43619. }
  43620. _getDepthCompare( material ) {
  43621. let depthCompare;
  43622. if ( material.depthTest === false ) {
  43623. depthCompare = GPUCompareFunction.Always;
  43624. } else {
  43625. const depthFunc = material.depthFunc;
  43626. switch ( depthFunc ) {
  43627. case NeverDepth:
  43628. depthCompare = GPUCompareFunction.Never;
  43629. break;
  43630. case AlwaysDepth:
  43631. depthCompare = GPUCompareFunction.Always;
  43632. break;
  43633. case LessDepth:
  43634. depthCompare = GPUCompareFunction.Less;
  43635. break;
  43636. case LessEqualDepth:
  43637. depthCompare = GPUCompareFunction.LessEqual;
  43638. break;
  43639. case EqualDepth:
  43640. depthCompare = GPUCompareFunction.Equal;
  43641. break;
  43642. case GreaterEqualDepth:
  43643. depthCompare = GPUCompareFunction.GreaterEqual;
  43644. break;
  43645. case GreaterDepth:
  43646. depthCompare = GPUCompareFunction.Greater;
  43647. break;
  43648. case NotEqualDepth:
  43649. depthCompare = GPUCompareFunction.NotEqual;
  43650. break;
  43651. default:
  43652. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  43653. }
  43654. }
  43655. return depthCompare;
  43656. }
  43657. }
  43658. /*// debugger tools
  43659. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  43660. //*/
  43661. //
  43662. class WebGPUBackend extends Backend {
  43663. constructor( parameters = {} ) {
  43664. super( parameters );
  43665. this.isWebGPUBackend = true;
  43666. // some parameters require default values other than "undefined"
  43667. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  43668. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  43669. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43670. this.device = null;
  43671. this.context = null;
  43672. this.colorBuffer = null;
  43673. this.defaultRenderPassdescriptor = null;
  43674. this.utils = new WebGPUUtils( this );
  43675. this.attributeUtils = new WebGPUAttributeUtils( this );
  43676. this.bindingUtils = new WebGPUBindingUtils( this );
  43677. this.pipelineUtils = new WebGPUPipelineUtils( this );
  43678. this.textureUtils = new WebGPUTextureUtils( this );
  43679. this.occludedResolveCache = new Map();
  43680. }
  43681. async init( renderer ) {
  43682. await super.init( renderer );
  43683. //
  43684. const parameters = this.parameters;
  43685. // create the device if it is not passed with parameters
  43686. let device;
  43687. if ( parameters.device === undefined ) {
  43688. const adapterOptions = {
  43689. powerPreference: parameters.powerPreference
  43690. };
  43691. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  43692. if ( adapter === null ) {
  43693. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  43694. }
  43695. // feature support
  43696. const features = Object.values( GPUFeatureName );
  43697. const supportedFeatures = [];
  43698. for ( const name of features ) {
  43699. if ( adapter.features.has( name ) ) {
  43700. supportedFeatures.push( name );
  43701. }
  43702. }
  43703. const deviceDescriptor = {
  43704. requiredFeatures: supportedFeatures,
  43705. requiredLimits: parameters.requiredLimits
  43706. };
  43707. device = await adapter.requestDevice( deviceDescriptor );
  43708. } else {
  43709. device = parameters.device;
  43710. }
  43711. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  43712. this.device = device;
  43713. this.context = context;
  43714. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  43715. this.context.configure( {
  43716. device: this.device,
  43717. format: GPUTextureFormat.BGRA8Unorm,
  43718. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  43719. alphaMode: alphaMode
  43720. } );
  43721. this.updateSize();
  43722. }
  43723. get coordinateSystem() {
  43724. return WebGPUCoordinateSystem;
  43725. }
  43726. async getArrayBufferAsync( attribute ) {
  43727. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43728. }
  43729. getContext() {
  43730. return this.context;
  43731. }
  43732. _getDefaultRenderPassDescriptor() {
  43733. let descriptor = this.defaultRenderPassdescriptor;
  43734. if ( descriptor === null ) {
  43735. const renderer = this.renderer;
  43736. descriptor = {
  43737. colorAttachments: [ {
  43738. view: null
  43739. } ],
  43740. depthStencilAttachment: {
  43741. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  43742. }
  43743. };
  43744. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43745. if ( this.renderer.samples > 0 ) {
  43746. colorAttachment.view = this.colorBuffer.createView();
  43747. } else {
  43748. colorAttachment.resolveTarget = undefined;
  43749. }
  43750. this.defaultRenderPassdescriptor = descriptor;
  43751. }
  43752. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43753. if ( this.renderer.samples > 0 ) {
  43754. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  43755. } else {
  43756. colorAttachment.view = this.context.getCurrentTexture().createView();
  43757. }
  43758. return descriptor;
  43759. }
  43760. _getRenderPassDescriptor( renderContext ) {
  43761. const renderTarget = renderContext.renderTarget;
  43762. const renderTargetData = this.get( renderTarget );
  43763. let descriptors = renderTargetData.descriptors;
  43764. if ( descriptors === undefined ) {
  43765. descriptors = [];
  43766. renderTargetData.descriptors = descriptors;
  43767. }
  43768. if ( renderTargetData.width !== renderTarget.width ||
  43769. renderTargetData.height !== renderTarget.height ||
  43770. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  43771. renderTargetData.samples !== renderTarget.samples ||
  43772. descriptors.length !== renderTarget.textures.length
  43773. ) {
  43774. descriptors.length = 0;
  43775. // dispose
  43776. const onDispose = () => {
  43777. renderTarget.removeEventListener( 'dispose', onDispose );
  43778. this.delete( renderTarget );
  43779. };
  43780. renderTarget.addEventListener( 'dispose', onDispose );
  43781. }
  43782. let descriptor = descriptors[ renderContext.activeCubeFace ];
  43783. if ( descriptor === undefined ) {
  43784. const textures = renderContext.textures;
  43785. const colorAttachments = [];
  43786. for ( let i = 0; i < textures.length; i ++ ) {
  43787. const textureData = this.get( textures[ i ] );
  43788. const textureView = textureData.texture.createView( {
  43789. baseMipLevel: renderContext.activeMipmapLevel,
  43790. mipLevelCount: 1,
  43791. baseArrayLayer: renderContext.activeCubeFace,
  43792. dimension: GPUTextureViewDimension.TwoD
  43793. } );
  43794. let view, resolveTarget;
  43795. if ( textureData.msaaTexture !== undefined ) {
  43796. view = textureData.msaaTexture.createView();
  43797. resolveTarget = textureView;
  43798. } else {
  43799. view = textureView;
  43800. resolveTarget = undefined;
  43801. }
  43802. colorAttachments.push( {
  43803. view,
  43804. resolveTarget,
  43805. loadOp: GPULoadOp.Load,
  43806. storeOp: GPUStoreOp.Store
  43807. } );
  43808. }
  43809. const depthTextureData = this.get( renderContext.depthTexture );
  43810. const depthStencilAttachment = {
  43811. view: depthTextureData.texture.createView()
  43812. };
  43813. descriptor = {
  43814. colorAttachments,
  43815. depthStencilAttachment
  43816. };
  43817. descriptors[ renderContext.activeCubeFace ] = descriptor;
  43818. renderTargetData.width = renderTarget.width;
  43819. renderTargetData.height = renderTarget.height;
  43820. renderTargetData.samples = renderTarget.samples;
  43821. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  43822. }
  43823. return descriptor;
  43824. }
  43825. beginRender( renderContext ) {
  43826. const renderContextData = this.get( renderContext );
  43827. const device = this.device;
  43828. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43829. let occlusionQuerySet;
  43830. if ( occlusionQueryCount > 0 ) {
  43831. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  43832. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  43833. // Get a reference to the array of objects with queries. The renderContextData property
  43834. // can be changed by another render pass before the buffer.mapAsyc() completes.
  43835. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  43836. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  43837. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43838. //
  43839. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  43840. renderContextData.occlusionQuerySet = occlusionQuerySet;
  43841. renderContextData.occlusionQueryIndex = 0;
  43842. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43843. renderContextData.lastOcclusionObject = null;
  43844. }
  43845. let descriptor;
  43846. if ( renderContext.textures === null ) {
  43847. descriptor = this._getDefaultRenderPassDescriptor();
  43848. } else {
  43849. descriptor = this._getRenderPassDescriptor( renderContext );
  43850. }
  43851. this.initTimestampQuery( renderContext, descriptor );
  43852. descriptor.occlusionQuerySet = occlusionQuerySet;
  43853. const depthStencilAttachment = descriptor.depthStencilAttachment;
  43854. if ( renderContext.textures !== null ) {
  43855. const colorAttachments = descriptor.colorAttachments;
  43856. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  43857. const colorAttachment = colorAttachments[ i ];
  43858. if ( renderContext.clearColor ) {
  43859. colorAttachment.clearValue = renderContext.clearColorValue;
  43860. colorAttachment.loadOp = GPULoadOp.Clear;
  43861. colorAttachment.storeOp = GPUStoreOp.Store;
  43862. } else {
  43863. colorAttachment.loadOp = GPULoadOp.Load;
  43864. colorAttachment.storeOp = GPUStoreOp.Store;
  43865. }
  43866. }
  43867. } else {
  43868. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43869. if ( renderContext.clearColor ) {
  43870. colorAttachment.clearValue = renderContext.clearColorValue;
  43871. colorAttachment.loadOp = GPULoadOp.Clear;
  43872. colorAttachment.storeOp = GPUStoreOp.Store;
  43873. } else {
  43874. colorAttachment.loadOp = GPULoadOp.Load;
  43875. colorAttachment.storeOp = GPUStoreOp.Store;
  43876. }
  43877. }
  43878. //
  43879. if ( renderContext.depth ) {
  43880. if ( renderContext.clearDepth ) {
  43881. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  43882. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43883. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43884. } else {
  43885. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43886. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43887. }
  43888. }
  43889. if ( renderContext.stencil ) {
  43890. if ( renderContext.clearStencil ) {
  43891. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  43892. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43893. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43894. } else {
  43895. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43896. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43897. }
  43898. }
  43899. //
  43900. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  43901. const currentPass = encoder.beginRenderPass( descriptor );
  43902. //
  43903. renderContextData.descriptor = descriptor;
  43904. renderContextData.encoder = encoder;
  43905. renderContextData.currentPass = currentPass;
  43906. renderContextData.currentSets = { attributes: {} };
  43907. //
  43908. if ( renderContext.viewport ) {
  43909. this.updateViewport( renderContext );
  43910. }
  43911. if ( renderContext.scissor ) {
  43912. const { x, y, width, height } = renderContext.scissorValue;
  43913. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  43914. }
  43915. }
  43916. finishRender( renderContext ) {
  43917. const renderContextData = this.get( renderContext );
  43918. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43919. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  43920. renderContextData.registerBundlesPhase = false;
  43921. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  43922. }
  43923. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43924. renderContextData.currentPass.endOcclusionQuery();
  43925. }
  43926. renderContextData.currentPass.end();
  43927. if ( occlusionQueryCount > 0 ) {
  43928. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  43929. //
  43930. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  43931. if ( queryResolveBuffer === undefined ) {
  43932. queryResolveBuffer = this.device.createBuffer(
  43933. {
  43934. size: bufferSize,
  43935. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  43936. }
  43937. );
  43938. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  43939. }
  43940. //
  43941. const readBuffer = this.device.createBuffer(
  43942. {
  43943. size: bufferSize,
  43944. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43945. }
  43946. );
  43947. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  43948. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  43949. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  43950. renderContextData.occlusionQueryBuffer = readBuffer;
  43951. //
  43952. this.resolveOccludedAsync( renderContext );
  43953. }
  43954. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  43955. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  43956. //
  43957. if ( renderContext.textures !== null ) {
  43958. const textures = renderContext.textures;
  43959. for ( let i = 0; i < textures.length; i ++ ) {
  43960. const texture = textures[ i ];
  43961. if ( texture.generateMipmaps === true ) {
  43962. this.textureUtils.generateMipmaps( texture );
  43963. }
  43964. }
  43965. }
  43966. }
  43967. isOccluded( renderContext, object ) {
  43968. const renderContextData = this.get( renderContext );
  43969. return renderContextData.occluded && renderContextData.occluded.has( object );
  43970. }
  43971. async resolveOccludedAsync( renderContext ) {
  43972. const renderContextData = this.get( renderContext );
  43973. // handle occlusion query results
  43974. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  43975. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  43976. const occluded = new WeakSet();
  43977. renderContextData.currentOcclusionQueryObjects = null;
  43978. renderContextData.currentOcclusionQueryBuffer = null;
  43979. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  43980. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  43981. const results = new BigUint64Array( buffer );
  43982. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  43983. if ( results[ i ] !== BigInt( 0 ) ) {
  43984. occluded.add( currentOcclusionQueryObjects[ i ] );
  43985. }
  43986. }
  43987. currentOcclusionQueryBuffer.destroy();
  43988. renderContextData.occluded = occluded;
  43989. }
  43990. }
  43991. updateViewport( renderContext ) {
  43992. const { currentPass } = this.get( renderContext );
  43993. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  43994. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  43995. }
  43996. clear( color, depth, stencil, renderTargetData = null ) {
  43997. const device = this.device;
  43998. const renderer = this.renderer;
  43999. let colorAttachments = [];
  44000. let depthStencilAttachment;
  44001. let clearValue;
  44002. let supportsDepth;
  44003. let supportsStencil;
  44004. if ( color ) {
  44005. const clearColor = this.getClearColor();
  44006. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44007. }
  44008. if ( renderTargetData === null ) {
  44009. supportsDepth = renderer.depth;
  44010. supportsStencil = renderer.stencil;
  44011. const descriptor = this._getDefaultRenderPassDescriptor();
  44012. if ( color ) {
  44013. colorAttachments = descriptor.colorAttachments;
  44014. const colorAttachment = colorAttachments[ 0 ];
  44015. colorAttachment.clearValue = clearValue;
  44016. colorAttachment.loadOp = GPULoadOp.Clear;
  44017. colorAttachment.storeOp = GPUStoreOp.Store;
  44018. }
  44019. if ( supportsDepth || supportsStencil ) {
  44020. depthStencilAttachment = descriptor.depthStencilAttachment;
  44021. }
  44022. } else {
  44023. supportsDepth = renderTargetData.depth;
  44024. supportsStencil = renderTargetData.stencil;
  44025. if ( color ) {
  44026. for ( const texture of renderTargetData.textures ) {
  44027. const textureData = this.get( texture );
  44028. const textureView = textureData.texture.createView();
  44029. let view, resolveTarget;
  44030. if ( textureData.msaaTexture !== undefined ) {
  44031. view = textureData.msaaTexture.createView();
  44032. resolveTarget = textureView;
  44033. } else {
  44034. view = textureView;
  44035. resolveTarget = undefined;
  44036. }
  44037. colorAttachments.push( {
  44038. view,
  44039. resolveTarget,
  44040. clearValue,
  44041. loadOp: GPULoadOp.Clear,
  44042. storeOp: GPUStoreOp.Store
  44043. } );
  44044. }
  44045. }
  44046. if ( supportsDepth || supportsStencil ) {
  44047. const depthTextureData = this.get( renderTargetData.depthTexture );
  44048. depthStencilAttachment = {
  44049. view: depthTextureData.texture.createView()
  44050. };
  44051. }
  44052. }
  44053. //
  44054. if ( supportsDepth ) {
  44055. if ( depth ) {
  44056. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44057. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44058. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44059. } else {
  44060. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44061. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44062. }
  44063. }
  44064. //
  44065. if ( supportsStencil ) {
  44066. if ( stencil ) {
  44067. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44068. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44069. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44070. } else {
  44071. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44072. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44073. }
  44074. }
  44075. //
  44076. const encoder = device.createCommandEncoder( {} );
  44077. const currentPass = encoder.beginRenderPass( {
  44078. colorAttachments,
  44079. depthStencilAttachment
  44080. } );
  44081. currentPass.end();
  44082. device.queue.submit( [ encoder.finish() ] );
  44083. }
  44084. // compute
  44085. beginCompute( computeGroup ) {
  44086. const groupGPU = this.get( computeGroup );
  44087. const descriptor = {};
  44088. this.initTimestampQuery( computeGroup, descriptor );
  44089. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44090. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44091. }
  44092. compute( computeGroup, computeNode, bindings, pipeline ) {
  44093. const { passEncoderGPU } = this.get( computeGroup );
  44094. // pipeline
  44095. const pipelineGPU = this.get( pipeline ).pipeline;
  44096. passEncoderGPU.setPipeline( pipelineGPU );
  44097. // bind groups
  44098. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44099. const bindGroup = bindings[ i ];
  44100. const bindingsData = this.get( bindGroup );
  44101. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44102. }
  44103. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44104. const computeNodeData = this.get( computeNode );
  44105. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44106. const { dispatchSize } = computeNodeData;
  44107. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44108. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44109. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44110. } else {
  44111. dispatchSize.x = computeNode.dispatchCount;
  44112. }
  44113. passEncoderGPU.dispatchWorkgroups(
  44114. dispatchSize.x,
  44115. dispatchSize.y,
  44116. dispatchSize.z
  44117. );
  44118. }
  44119. finishCompute( computeGroup ) {
  44120. const groupData = this.get( computeGroup );
  44121. groupData.passEncoderGPU.end();
  44122. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44123. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44124. }
  44125. // render object
  44126. draw( renderObject, info ) {
  44127. const { object, geometry, context, pipeline } = renderObject;
  44128. const bindings = renderObject.getBindings();
  44129. const contextData = this.get( context );
  44130. const pipelineGPU = this.get( pipeline ).pipeline;
  44131. const currentSets = contextData.currentSets;
  44132. const renderObjectData = this.get( renderObject );
  44133. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  44134. const renderContextData = this.get( context );
  44135. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  44136. renderContextData.renderBundles.push( renderBundle );
  44137. return;
  44138. }
  44139. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  44140. // pipeline
  44141. if ( currentSets.pipeline !== pipelineGPU ) {
  44142. passEncoderGPU.setPipeline( pipelineGPU );
  44143. currentSets.pipeline = pipelineGPU;
  44144. }
  44145. // bind groups
  44146. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44147. const bindGroup = bindings[ i ];
  44148. const bindingsData = this.get( bindGroup );
  44149. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  44150. }
  44151. // attributes
  44152. const index = renderObject.getIndex();
  44153. const hasIndex = ( index !== null );
  44154. // index
  44155. if ( hasIndex === true ) {
  44156. if ( currentSets.index !== index ) {
  44157. const buffer = this.get( index ).buffer;
  44158. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44159. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44160. currentSets.index = index;
  44161. }
  44162. }
  44163. // vertex buffers
  44164. const vertexBuffers = renderObject.getVertexBuffers();
  44165. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44166. const vertexBuffer = vertexBuffers[ i ];
  44167. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44168. const buffer = this.get( vertexBuffer ).buffer;
  44169. passEncoderGPU.setVertexBuffer( i, buffer );
  44170. currentSets.attributes[ i ] = vertexBuffer;
  44171. }
  44172. }
  44173. // occlusion queries - handle multiple consecutive draw calls for an object
  44174. if ( contextData.occlusionQuerySet !== undefined ) {
  44175. const lastObject = contextData.lastOcclusionObject;
  44176. if ( lastObject !== object ) {
  44177. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44178. passEncoderGPU.endOcclusionQuery();
  44179. contextData.occlusionQueryIndex ++;
  44180. }
  44181. if ( object.occlusionTest === true ) {
  44182. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  44183. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44184. }
  44185. contextData.lastOcclusionObject = object;
  44186. }
  44187. }
  44188. // draw
  44189. const drawRange = renderObject.drawRange;
  44190. const firstVertex = drawRange.start;
  44191. const instanceCount = this.getInstanceCount( renderObject );
  44192. if ( instanceCount === 0 ) return;
  44193. if ( object.isBatchedMesh === true ) {
  44194. const starts = object._multiDrawStarts;
  44195. const counts = object._multiDrawCounts;
  44196. const drawCount = object._multiDrawCount;
  44197. const drawInstances = object._multiDrawInstances;
  44198. const bytesPerElement = index.bytesPerElement || 1;
  44199. for ( let i = 0; i < drawCount; i ++ ) {
  44200. const count = drawInstances ? drawInstances[ i ] : 1;
  44201. const firstInstance = count > 1 ? 0 : i;
  44202. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  44203. }
  44204. } else if ( hasIndex === true ) {
  44205. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  44206. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  44207. info.update( object, indexCount, instanceCount );
  44208. } else {
  44209. const positionAttribute = geometry.attributes.position;
  44210. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  44211. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44212. info.update( object, vertexCount, instanceCount );
  44213. }
  44214. if ( this.renderer._currentRenderBundle ) {
  44215. const renderBundle = passEncoderGPU.finish();
  44216. renderObjectData.lastPipelineGPU = pipelineGPU;
  44217. renderObjectData.renderBundle = renderBundle;
  44218. renderObjectData.bundleEncoder = passEncoderGPU;
  44219. }
  44220. }
  44221. // cache key
  44222. needsRenderUpdate( renderObject ) {
  44223. const data = this.get( renderObject );
  44224. const { object, material } = renderObject;
  44225. const utils = this.utils;
  44226. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44227. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44228. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44229. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44230. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44231. let needsUpdate = false;
  44232. if ( data.material !== material || data.materialVersion !== material.version ||
  44233. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44234. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44235. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44236. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44237. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44238. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44239. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44240. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44241. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44242. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44243. data.primitiveTopology !== primitiveTopology ||
  44244. data.clippingContextVersion !== renderObject.clippingContextVersion
  44245. ) {
  44246. data.material = material; data.materialVersion = material.version;
  44247. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44248. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44249. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44250. data.colorWrite = material.colorWrite;
  44251. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44252. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44253. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44254. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44255. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44256. data.sampleCount = sampleCount;
  44257. data.colorSpace = colorSpace;
  44258. data.colorFormat = colorFormat;
  44259. data.depthStencilFormat = depthStencilFormat;
  44260. data.primitiveTopology = primitiveTopology;
  44261. data.clippingContextVersion = renderObject.clippingContextVersion;
  44262. needsUpdate = true;
  44263. }
  44264. return needsUpdate;
  44265. }
  44266. getRenderCacheKey( renderObject ) {
  44267. const { object, material } = renderObject;
  44268. const utils = this.utils;
  44269. const renderContext = renderObject.context;
  44270. return [
  44271. material.transparent, material.blending, material.premultipliedAlpha,
  44272. material.blendSrc, material.blendDst, material.blendEquation,
  44273. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44274. material.colorWrite,
  44275. material.depthWrite, material.depthTest, material.depthFunc,
  44276. material.stencilWrite, material.stencilFunc,
  44277. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44278. material.stencilFuncMask, material.stencilWriteMask,
  44279. material.side,
  44280. utils.getSampleCountRenderContext( renderContext ),
  44281. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44282. utils.getPrimitiveTopology( object, material ),
  44283. renderObject.clippingContextVersion
  44284. ].join();
  44285. }
  44286. // textures
  44287. createSampler( texture ) {
  44288. this.textureUtils.createSampler( texture );
  44289. }
  44290. destroySampler( texture ) {
  44291. this.textureUtils.destroySampler( texture );
  44292. }
  44293. createDefaultTexture( texture ) {
  44294. this.textureUtils.createDefaultTexture( texture );
  44295. }
  44296. createTexture( texture, options ) {
  44297. this.textureUtils.createTexture( texture, options );
  44298. }
  44299. updateTexture( texture, options ) {
  44300. this.textureUtils.updateTexture( texture, options );
  44301. }
  44302. generateMipmaps( texture ) {
  44303. this.textureUtils.generateMipmaps( texture );
  44304. }
  44305. destroyTexture( texture ) {
  44306. this.textureUtils.destroyTexture( texture );
  44307. }
  44308. copyTextureToBuffer( texture, x, y, width, height ) {
  44309. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  44310. }
  44311. initTimestampQuery( renderContext, descriptor ) {
  44312. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44313. const renderContextData = this.get( renderContext );
  44314. if ( ! renderContextData.timeStampQuerySet ) {
  44315. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44316. // beginning and one for the end of compute pass execution.
  44317. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44318. const timestampWrites = {
  44319. querySet: timeStampQuerySet,
  44320. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44321. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44322. };
  44323. Object.assign( descriptor, {
  44324. timestampWrites,
  44325. } );
  44326. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44327. }
  44328. }
  44329. // timestamp utils
  44330. prepareTimestampBuffer( renderContext, encoder ) {
  44331. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44332. const renderContextData = this.get( renderContext );
  44333. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44334. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44335. renderContextData.currentTimestampQueryBuffers = {
  44336. resolveBuffer: this.device.createBuffer( {
  44337. label: 'timestamp resolve buffer',
  44338. size: size,
  44339. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44340. } ),
  44341. resultBuffer: this.device.createBuffer( {
  44342. label: 'timestamp result buffer',
  44343. size: size,
  44344. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  44345. } ),
  44346. isMappingPending: false,
  44347. };
  44348. }
  44349. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44350. if ( isMappingPending === true ) return;
  44351. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  44352. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  44353. }
  44354. async resolveTimestampAsync( renderContext, type = 'render' ) {
  44355. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  44356. const renderContextData = this.get( renderContext );
  44357. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  44358. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44359. if ( isMappingPending === true ) return;
  44360. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  44361. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  44362. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  44363. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  44364. this.renderer.info.updateTimestamp( type, duration );
  44365. resultBuffer.unmap();
  44366. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  44367. } );
  44368. }
  44369. // node builder
  44370. createNodeBuilder( object, renderer ) {
  44371. return new WGSLNodeBuilder( object, renderer );
  44372. }
  44373. // program
  44374. createProgram( program ) {
  44375. const programGPU = this.get( program );
  44376. programGPU.module = {
  44377. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  44378. entryPoint: 'main'
  44379. };
  44380. }
  44381. destroyProgram( program ) {
  44382. this.delete( program );
  44383. }
  44384. // pipelines
  44385. createRenderPipeline( renderObject, promises ) {
  44386. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  44387. }
  44388. createComputePipeline( computePipeline, bindings ) {
  44389. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  44390. }
  44391. createBundleEncoder( renderContext, renderObject ) {
  44392. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  44393. }
  44394. // bindings
  44395. createBindings( bindGroup ) {
  44396. this.bindingUtils.createBindings( bindGroup );
  44397. }
  44398. updateBindings( bindGroup ) {
  44399. this.bindingUtils.createBindings( bindGroup );
  44400. }
  44401. updateBinding( binding ) {
  44402. this.bindingUtils.updateBinding( binding );
  44403. }
  44404. // attributes
  44405. createIndexAttribute( attribute ) {
  44406. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44407. }
  44408. createAttribute( attribute ) {
  44409. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44410. }
  44411. createStorageAttribute( attribute ) {
  44412. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44413. }
  44414. updateAttribute( attribute ) {
  44415. this.attributeUtils.updateAttribute( attribute );
  44416. }
  44417. destroyAttribute( attribute ) {
  44418. this.attributeUtils.destroyAttribute( attribute );
  44419. }
  44420. // canvas
  44421. updateSize() {
  44422. this.colorBuffer = this.textureUtils.getColorBuffer();
  44423. this.defaultRenderPassdescriptor = null;
  44424. }
  44425. // utils public
  44426. getMaxAnisotropy() {
  44427. return 16;
  44428. }
  44429. hasFeature( name ) {
  44430. return this.device.features.has( name );
  44431. }
  44432. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  44433. let dstX = 0;
  44434. let dstY = 0;
  44435. let srcX = 0;
  44436. let srcY = 0;
  44437. let srcWidth = srcTexture.image.width;
  44438. let srcHeight = srcTexture.image.height;
  44439. if ( srcRegion !== null ) {
  44440. srcX = srcRegion.x;
  44441. srcY = srcRegion.y;
  44442. srcWidth = srcRegion.width;
  44443. srcHeight = srcRegion.height;
  44444. }
  44445. if ( dstPosition !== null ) {
  44446. dstX = dstPosition.x;
  44447. dstY = dstPosition.y;
  44448. }
  44449. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  44450. const sourceGPU = this.get( srcTexture ).texture;
  44451. const destinationGPU = this.get( dstTexture ).texture;
  44452. encoder.copyTextureToTexture(
  44453. {
  44454. texture: sourceGPU,
  44455. mipLevel: level,
  44456. origin: { x: srcX, y: srcY, z: 0 }
  44457. },
  44458. {
  44459. texture: destinationGPU,
  44460. mipLevel: level,
  44461. origin: { x: dstX, y: dstY, z: 0 }
  44462. },
  44463. [
  44464. srcWidth,
  44465. srcHeight
  44466. ]
  44467. );
  44468. this.device.queue.submit( [ encoder.finish() ] );
  44469. }
  44470. copyFramebufferToTexture( texture, renderContext ) {
  44471. const renderContextData = this.get( renderContext );
  44472. const { encoder, descriptor } = renderContextData;
  44473. let sourceGPU = null;
  44474. if ( renderContext.renderTarget ) {
  44475. if ( texture.isDepthTexture ) {
  44476. sourceGPU = this.get( renderContext.depthTexture ).texture;
  44477. } else {
  44478. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  44479. }
  44480. } else {
  44481. if ( texture.isDepthTexture ) {
  44482. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  44483. } else {
  44484. sourceGPU = this.context.getCurrentTexture();
  44485. }
  44486. }
  44487. const destinationGPU = this.get( texture ).texture;
  44488. if ( sourceGPU.format !== destinationGPU.format ) {
  44489. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  44490. return;
  44491. }
  44492. renderContextData.currentPass.end();
  44493. encoder.copyTextureToTexture(
  44494. {
  44495. texture: sourceGPU,
  44496. origin: { x: 0, y: 0, z: 0 }
  44497. },
  44498. {
  44499. texture: destinationGPU
  44500. },
  44501. [
  44502. texture.image.width,
  44503. texture.image.height
  44504. ]
  44505. );
  44506. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  44507. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  44508. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  44509. }
  44510. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44511. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44512. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  44513. renderContextData.currentSets = { attributes: {} };
  44514. }
  44515. }
  44516. /*
  44517. const debugHandler = {
  44518. get: function ( target, name ) {
  44519. // Add |update
  44520. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  44521. return target[ name ];
  44522. }
  44523. };
  44524. */
  44525. class WebGPURenderer extends Renderer {
  44526. constructor( parameters = {} ) {
  44527. let BackendClass;
  44528. if ( parameters.forceWebGL ) {
  44529. BackendClass = WebGLBackend;
  44530. } else if ( WebGPU.isAvailable() ) {
  44531. BackendClass = WebGPUBackend;
  44532. } else {
  44533. BackendClass = WebGLBackend;
  44534. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  44535. }
  44536. const backend = new BackendClass( parameters );
  44537. //super( new Proxy( backend, debugHandler ) );
  44538. super( backend, parameters );
  44539. this.isWebGPURenderer = true;
  44540. }
  44541. }
  44542. const _material = /*@__PURE__*/ new NodeMaterial();
  44543. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  44544. class PostProcessing {
  44545. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  44546. this.renderer = renderer;
  44547. this.outputNode = outputNode;
  44548. this.outputColorTransform = true;
  44549. this.needsUpdate = true;
  44550. }
  44551. render() {
  44552. this.update();
  44553. const renderer = this.renderer;
  44554. const toneMapping = renderer.toneMapping;
  44555. const outputColorSpace = renderer.outputColorSpace;
  44556. renderer.toneMapping = NoToneMapping;
  44557. renderer.outputColorSpace = LinearSRGBColorSpace;
  44558. //
  44559. _quadMesh.render( renderer );
  44560. //
  44561. renderer.toneMapping = toneMapping;
  44562. renderer.outputColorSpace = outputColorSpace;
  44563. }
  44564. update() {
  44565. if ( this.needsUpdate === true ) {
  44566. const renderer = this.renderer;
  44567. const toneMapping = renderer.toneMapping;
  44568. const outputColorSpace = renderer.outputColorSpace;
  44569. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  44570. _quadMesh.material.needsUpdate = true;
  44571. this.needsUpdate = false;
  44572. }
  44573. }
  44574. async renderAsync() {
  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. await _quadMesh.renderAsync( renderer );
  44583. //
  44584. renderer.toneMapping = toneMapping;
  44585. renderer.outputColorSpace = outputColorSpace;
  44586. }
  44587. }
  44588. class StorageTexture extends Texture {
  44589. constructor( width = 1, height = 1 ) {
  44590. super();
  44591. this.image = { width, height };
  44592. this.magFilter = LinearFilter;
  44593. this.minFilter = LinearFilter;
  44594. this.isStorageTexture = true;
  44595. }
  44596. }
  44597. class StorageBufferAttribute extends BufferAttribute {
  44598. constructor( array, itemSize, typeClass = Float32Array ) {
  44599. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44600. super( array, itemSize );
  44601. this.isStorageBufferAttribute = true;
  44602. }
  44603. }
  44604. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  44605. constructor( array, itemSize, typeClass = Float32Array ) {
  44606. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  44607. super( array, itemSize );
  44608. this.isStorageInstancedBufferAttribute = true;
  44609. }
  44610. }
  44611. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  44612. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  44613. revision: REVISION,
  44614. } } ) );
  44615. }
  44616. if ( typeof window !== 'undefined' ) {
  44617. if ( window.__THREE__ ) {
  44618. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  44619. } else {
  44620. window.__THREE__ = REVISION;
  44621. }
  44622. }
  44623. 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, viewportSharedTexture, viewportTexture, viewportTopLeft, viewportTopRight, wgsl, wgslFn, xor };
粤ICP备19079148号