es6.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = Object.setPrototypeOf ||
  3. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5. return function (d, b) {
  6. extendStatics(d, b);
  7. function __() { this.constructor = d; }
  8. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9. };
  10. })();
  11. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  15. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16. };
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. BABYLON.Effect.ShadersStore['defaultVertexShader'] = "#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}";
  839. BABYLON.Effect.ShadersStore['defaultPixelShader'] = "#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}";
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. var Color3 = /** @class */ (function () {
  997. /**
  998. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  999. */
  1000. function Color3(r, g, b) {
  1001. if (r === void 0) { r = 0; }
  1002. if (g === void 0) { g = 0; }
  1003. if (b === void 0) { b = 0; }
  1004. this.r = r;
  1005. this.g = g;
  1006. this.b = b;
  1007. }
  1008. /**
  1009. * Returns a string with the Color3 current values.
  1010. */
  1011. Color3.prototype.toString = function () {
  1012. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1013. };
  1014. /**
  1015. * Returns the string "Color3".
  1016. */
  1017. Color3.prototype.getClassName = function () {
  1018. return "Color3";
  1019. };
  1020. /**
  1021. * Returns the Color3 hash code.
  1022. */
  1023. Color3.prototype.getHashCode = function () {
  1024. var hash = this.r || 0;
  1025. hash = (hash * 397) ^ (this.g || 0);
  1026. hash = (hash * 397) ^ (this.b || 0);
  1027. return hash;
  1028. };
  1029. // Operators
  1030. /**
  1031. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1032. * Returns the Color3.
  1033. */
  1034. Color3.prototype.toArray = function (array, index) {
  1035. if (index === undefined) {
  1036. index = 0;
  1037. }
  1038. array[index] = this.r;
  1039. array[index + 1] = this.g;
  1040. array[index + 2] = this.b;
  1041. return this;
  1042. };
  1043. /**
  1044. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1045. */
  1046. Color3.prototype.toColor4 = function (alpha) {
  1047. if (alpha === void 0) { alpha = 1; }
  1048. return new Color4(this.r, this.g, this.b, alpha);
  1049. };
  1050. /**
  1051. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1052. */
  1053. Color3.prototype.asArray = function () {
  1054. var result = new Array();
  1055. this.toArray(result, 0);
  1056. return result;
  1057. };
  1058. /**
  1059. * Returns the luminance value (float).
  1060. */
  1061. Color3.prototype.toLuminance = function () {
  1062. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1063. };
  1064. /**
  1065. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1066. * Returns this new object.
  1067. */
  1068. Color3.prototype.multiply = function (otherColor) {
  1069. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1070. };
  1071. /**
  1072. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1073. * Returns the current Color3.
  1074. */
  1075. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1076. result.r = this.r * otherColor.r;
  1077. result.g = this.g * otherColor.g;
  1078. result.b = this.b * otherColor.b;
  1079. return this;
  1080. };
  1081. /**
  1082. * Boolean : True if the rgb values are equal to the passed ones.
  1083. */
  1084. Color3.prototype.equals = function (otherColor) {
  1085. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1086. };
  1087. /**
  1088. * Boolean : True if the rgb values are equal to the passed ones.
  1089. */
  1090. Color3.prototype.equalsFloats = function (r, g, b) {
  1091. return this.r === r && this.g === g && this.b === b;
  1092. };
  1093. /**
  1094. * Multiplies in place each rgb value by scale.
  1095. * Returns the updated Color3.
  1096. */
  1097. Color3.prototype.scale = function (scale) {
  1098. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1099. };
  1100. /**
  1101. * Multiplies the rgb values by scale and stores the result into "result".
  1102. * Returns the unmodified current Color3.
  1103. */
  1104. Color3.prototype.scaleToRef = function (scale, result) {
  1105. result.r = this.r * scale;
  1106. result.g = this.g * scale;
  1107. result.b = this.b * scale;
  1108. return this;
  1109. };
  1110. /**
  1111. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1112. */
  1113. Color3.prototype.add = function (otherColor) {
  1114. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1115. };
  1116. /**
  1117. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1118. * Returns the unmodified current Color3.
  1119. */
  1120. Color3.prototype.addToRef = function (otherColor, result) {
  1121. result.r = this.r + otherColor.r;
  1122. result.g = this.g + otherColor.g;
  1123. result.b = this.b + otherColor.b;
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1128. */
  1129. Color3.prototype.subtract = function (otherColor) {
  1130. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1131. };
  1132. /**
  1133. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1134. * Returns the unmodified current Color3.
  1135. */
  1136. Color3.prototype.subtractToRef = function (otherColor, result) {
  1137. result.r = this.r - otherColor.r;
  1138. result.g = this.g - otherColor.g;
  1139. result.b = this.b - otherColor.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Returns a new Color3 copied the current one.
  1144. */
  1145. Color3.prototype.clone = function () {
  1146. return new Color3(this.r, this.g, this.b);
  1147. };
  1148. /**
  1149. * Copies the rgb values from the source in the current Color3.
  1150. * Returns the updated Color3.
  1151. */
  1152. Color3.prototype.copyFrom = function (source) {
  1153. this.r = source.r;
  1154. this.g = source.g;
  1155. this.b = source.b;
  1156. return this;
  1157. };
  1158. /**
  1159. * Updates the Color3 rgb values from the passed floats.
  1160. * Returns the Color3.
  1161. */
  1162. Color3.prototype.copyFromFloats = function (r, g, b) {
  1163. this.r = r;
  1164. this.g = g;
  1165. this.b = b;
  1166. return this;
  1167. };
  1168. /**
  1169. * Updates the Color3 rgb values from the passed floats.
  1170. * Returns the Color3.
  1171. */
  1172. Color3.prototype.set = function (r, g, b) {
  1173. return this.copyFromFloats(r, g, b);
  1174. };
  1175. /**
  1176. * Returns the Color3 hexadecimal code as a string.
  1177. */
  1178. Color3.prototype.toHexString = function () {
  1179. var intR = (this.r * 255) | 0;
  1180. var intG = (this.g * 255) | 0;
  1181. var intB = (this.b * 255) | 0;
  1182. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1183. };
  1184. /**
  1185. * Returns a new Color3 converted to linear space.
  1186. */
  1187. Color3.prototype.toLinearSpace = function () {
  1188. var convertedColor = new Color3();
  1189. this.toLinearSpaceToRef(convertedColor);
  1190. return convertedColor;
  1191. };
  1192. /**
  1193. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1194. * Returns the unmodified Color3.
  1195. */
  1196. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1197. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1198. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1199. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1200. return this;
  1201. };
  1202. /**
  1203. * Returns a new Color3 converted to gamma space.
  1204. */
  1205. Color3.prototype.toGammaSpace = function () {
  1206. var convertedColor = new Color3();
  1207. this.toGammaSpaceToRef(convertedColor);
  1208. return convertedColor;
  1209. };
  1210. /**
  1211. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1212. * Returns the unmodified Color3.
  1213. */
  1214. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1215. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1216. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1217. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1218. return this;
  1219. };
  1220. // Statics
  1221. /**
  1222. * Creates a new Color3 from the string containing valid hexadecimal values.
  1223. */
  1224. Color3.FromHexString = function (hex) {
  1225. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1226. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1227. return new Color3(0, 0, 0);
  1228. }
  1229. var r = parseInt(hex.substring(1, 3), 16);
  1230. var g = parseInt(hex.substring(3, 5), 16);
  1231. var b = parseInt(hex.substring(5, 7), 16);
  1232. return Color3.FromInts(r, g, b);
  1233. };
  1234. /**
  1235. * Creates a new Vector3 from the startind index of the passed array.
  1236. */
  1237. Color3.FromArray = function (array, offset) {
  1238. if (offset === void 0) { offset = 0; }
  1239. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1240. };
  1241. /**
  1242. * Creates a new Color3 from integer values ( < 256).
  1243. */
  1244. Color3.FromInts = function (r, g, b) {
  1245. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1246. };
  1247. /**
  1248. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1249. */
  1250. Color3.Lerp = function (start, end, amount) {
  1251. var r = start.r + ((end.r - start.r) * amount);
  1252. var g = start.g + ((end.g - start.g) * amount);
  1253. var b = start.b + ((end.b - start.b) * amount);
  1254. return new Color3(r, g, b);
  1255. };
  1256. Color3.Red = function () { return new Color3(1, 0, 0); };
  1257. Color3.Green = function () { return new Color3(0, 1, 0); };
  1258. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1259. Color3.Black = function () { return new Color3(0, 0, 0); };
  1260. Color3.White = function () { return new Color3(1, 1, 1); };
  1261. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1262. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1263. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1264. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1265. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1266. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1267. return Color3;
  1268. }());
  1269. BABYLON.Color3 = Color3;
  1270. var Color4 = /** @class */ (function () {
  1271. /**
  1272. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1273. */
  1274. function Color4(r, g, b, a) {
  1275. if (r === void 0) { r = 0; }
  1276. if (g === void 0) { g = 0; }
  1277. if (b === void 0) { b = 0; }
  1278. if (a === void 0) { a = 1; }
  1279. this.r = r;
  1280. this.g = g;
  1281. this.b = b;
  1282. this.a = a;
  1283. }
  1284. // Operators
  1285. /**
  1286. * Adds in place the passed Color4 values to the current Color4.
  1287. * Returns the updated Color4.
  1288. */
  1289. Color4.prototype.addInPlace = function (right) {
  1290. this.r += right.r;
  1291. this.g += right.g;
  1292. this.b += right.b;
  1293. this.a += right.a;
  1294. return this;
  1295. };
  1296. /**
  1297. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1298. */
  1299. Color4.prototype.asArray = function () {
  1300. var result = new Array();
  1301. this.toArray(result, 0);
  1302. return result;
  1303. };
  1304. /**
  1305. * Stores from the starting index in the passed array the Color4 successive values.
  1306. * Returns the Color4.
  1307. */
  1308. Color4.prototype.toArray = function (array, index) {
  1309. if (index === undefined) {
  1310. index = 0;
  1311. }
  1312. array[index] = this.r;
  1313. array[index + 1] = this.g;
  1314. array[index + 2] = this.b;
  1315. array[index + 3] = this.a;
  1316. return this;
  1317. };
  1318. /**
  1319. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1320. */
  1321. Color4.prototype.add = function (right) {
  1322. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1323. };
  1324. /**
  1325. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1326. */
  1327. Color4.prototype.subtract = function (right) {
  1328. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1329. };
  1330. /**
  1331. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1332. * Returns the Color4.
  1333. */
  1334. Color4.prototype.subtractToRef = function (right, result) {
  1335. result.r = this.r - right.r;
  1336. result.g = this.g - right.g;
  1337. result.b = this.b - right.b;
  1338. result.a = this.a - right.a;
  1339. return this;
  1340. };
  1341. /**
  1342. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1343. */
  1344. Color4.prototype.scale = function (scale) {
  1345. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1346. };
  1347. /**
  1348. * Multiplies the current Color4 values by scale and stores the result in "result".
  1349. * Returns the Color4.
  1350. */
  1351. Color4.prototype.scaleToRef = function (scale, result) {
  1352. result.r = this.r * scale;
  1353. result.g = this.g * scale;
  1354. result.b = this.b * scale;
  1355. result.a = this.a * scale;
  1356. return this;
  1357. };
  1358. /**
  1359. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1360. * @param color The Color4 (RGBA) value to multiply by
  1361. * @returns A new Color4.
  1362. */
  1363. Color4.prototype.multiply = function (color) {
  1364. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1365. };
  1366. /**
  1367. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1368. * @param color The Color4 (RGBA) value to multiply by
  1369. * @param result The Color4 (RGBA) to fill the result in
  1370. * @returns the result Color4.
  1371. */
  1372. Color4.prototype.multiplyToRef = function (color, result) {
  1373. result.r = this.r * color.r;
  1374. result.g = this.g * color.g;
  1375. result.b = this.b * color.b;
  1376. result.a = this.a * color.a;
  1377. return result;
  1378. };
  1379. /**
  1380. * Returns a string with the Color4 values.
  1381. */
  1382. Color4.prototype.toString = function () {
  1383. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1384. };
  1385. /**
  1386. * Returns the string "Color4"
  1387. */
  1388. Color4.prototype.getClassName = function () {
  1389. return "Color4";
  1390. };
  1391. /**
  1392. * Return the Color4 hash code as a number.
  1393. */
  1394. Color4.prototype.getHashCode = function () {
  1395. var hash = this.r || 0;
  1396. hash = (hash * 397) ^ (this.g || 0);
  1397. hash = (hash * 397) ^ (this.b || 0);
  1398. hash = (hash * 397) ^ (this.a || 0);
  1399. return hash;
  1400. };
  1401. /**
  1402. * Creates a new Color4 copied from the current one.
  1403. */
  1404. Color4.prototype.clone = function () {
  1405. return new Color4(this.r, this.g, this.b, this.a);
  1406. };
  1407. /**
  1408. * Copies the passed Color4 values into the current one.
  1409. * Returns the updated Color4.
  1410. */
  1411. Color4.prototype.copyFrom = function (source) {
  1412. this.r = source.r;
  1413. this.g = source.g;
  1414. this.b = source.b;
  1415. this.a = source.a;
  1416. return this;
  1417. };
  1418. /**
  1419. * Copies the passed float values into the current one.
  1420. * Returns the updated Color4.
  1421. */
  1422. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1423. this.r = r;
  1424. this.g = g;
  1425. this.b = b;
  1426. this.a = a;
  1427. return this;
  1428. };
  1429. /**
  1430. * Copies the passed float values into the current one.
  1431. * Returns the updated Color4.
  1432. */
  1433. Color4.prototype.set = function (r, g, b, a) {
  1434. return this.copyFromFloats(r, g, b, a);
  1435. };
  1436. /**
  1437. * Returns a string containing the hexadecimal Color4 code.
  1438. */
  1439. Color4.prototype.toHexString = function () {
  1440. var intR = (this.r * 255) | 0;
  1441. var intG = (this.g * 255) | 0;
  1442. var intB = (this.b * 255) | 0;
  1443. var intA = (this.a * 255) | 0;
  1444. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1445. };
  1446. /**
  1447. * Returns a new Color4 converted to linear space.
  1448. */
  1449. Color4.prototype.toLinearSpace = function () {
  1450. var convertedColor = new Color4();
  1451. this.toLinearSpaceToRef(convertedColor);
  1452. return convertedColor;
  1453. };
  1454. /**
  1455. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1456. * Returns the unmodified Color4.
  1457. */
  1458. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1459. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1460. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1461. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1462. convertedColor.a = this.a;
  1463. return this;
  1464. };
  1465. /**
  1466. * Returns a new Color4 converted to gamma space.
  1467. */
  1468. Color4.prototype.toGammaSpace = function () {
  1469. var convertedColor = new Color4();
  1470. this.toGammaSpaceToRef(convertedColor);
  1471. return convertedColor;
  1472. };
  1473. /**
  1474. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1475. * Returns the unmodified Color4.
  1476. */
  1477. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1478. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1479. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1480. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1481. convertedColor.a = this.a;
  1482. return this;
  1483. };
  1484. // Statics
  1485. /**
  1486. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1487. */
  1488. Color4.FromHexString = function (hex) {
  1489. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1490. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1491. return new Color4(0.0, 0.0, 0.0, 0.0);
  1492. }
  1493. var r = parseInt(hex.substring(1, 3), 16);
  1494. var g = parseInt(hex.substring(3, 5), 16);
  1495. var b = parseInt(hex.substring(5, 7), 16);
  1496. var a = parseInt(hex.substring(7, 9), 16);
  1497. return Color4.FromInts(r, g, b, a);
  1498. };
  1499. /**
  1500. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1501. */
  1502. Color4.Lerp = function (left, right, amount) {
  1503. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1504. Color4.LerpToRef(left, right, amount, result);
  1505. return result;
  1506. };
  1507. /**
  1508. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1509. */
  1510. Color4.LerpToRef = function (left, right, amount, result) {
  1511. result.r = left.r + (right.r - left.r) * amount;
  1512. result.g = left.g + (right.g - left.g) * amount;
  1513. result.b = left.b + (right.b - left.b) * amount;
  1514. result.a = left.a + (right.a - left.a) * amount;
  1515. };
  1516. /**
  1517. * Creates a new Color4 from the starting index element of the passed array.
  1518. */
  1519. Color4.FromArray = function (array, offset) {
  1520. if (offset === void 0) { offset = 0; }
  1521. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1522. };
  1523. /**
  1524. * Creates a new Color4 from the passed integers ( < 256 ).
  1525. */
  1526. Color4.FromInts = function (r, g, b, a) {
  1527. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1528. };
  1529. Color4.CheckColors4 = function (colors, count) {
  1530. // Check if color3 was used
  1531. if (colors.length === count * 3) {
  1532. var colors4 = [];
  1533. for (var index = 0; index < colors.length; index += 3) {
  1534. var newIndex = (index / 3) * 4;
  1535. colors4[newIndex] = colors[index];
  1536. colors4[newIndex + 1] = colors[index + 1];
  1537. colors4[newIndex + 2] = colors[index + 2];
  1538. colors4[newIndex + 3] = 1.0;
  1539. }
  1540. return colors4;
  1541. }
  1542. return colors;
  1543. };
  1544. return Color4;
  1545. }());
  1546. BABYLON.Color4 = Color4;
  1547. var Vector2 = /** @class */ (function () {
  1548. /**
  1549. * Creates a new Vector2 from the passed x and y coordinates.
  1550. */
  1551. function Vector2(x, y) {
  1552. this.x = x;
  1553. this.y = y;
  1554. }
  1555. /**
  1556. * Returns a string with the Vector2 coordinates.
  1557. */
  1558. Vector2.prototype.toString = function () {
  1559. return "{X: " + this.x + " Y:" + this.y + "}";
  1560. };
  1561. /**
  1562. * Returns the string "Vector2"
  1563. */
  1564. Vector2.prototype.getClassName = function () {
  1565. return "Vector2";
  1566. };
  1567. /**
  1568. * Returns the Vector2 hash code as a number.
  1569. */
  1570. Vector2.prototype.getHashCode = function () {
  1571. var hash = this.x || 0;
  1572. hash = (hash * 397) ^ (this.y || 0);
  1573. return hash;
  1574. };
  1575. // Operators
  1576. /**
  1577. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1578. * Returns the Vector2.
  1579. */
  1580. Vector2.prototype.toArray = function (array, index) {
  1581. if (index === void 0) { index = 0; }
  1582. array[index] = this.x;
  1583. array[index + 1] = this.y;
  1584. return this;
  1585. };
  1586. /**
  1587. * Returns a new array with 2 elements : the Vector2 coordinates.
  1588. */
  1589. Vector2.prototype.asArray = function () {
  1590. var result = new Array();
  1591. this.toArray(result, 0);
  1592. return result;
  1593. };
  1594. /**
  1595. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1596. * Returns the updated Vector2.
  1597. */
  1598. Vector2.prototype.copyFrom = function (source) {
  1599. this.x = source.x;
  1600. this.y = source.y;
  1601. return this;
  1602. };
  1603. /**
  1604. * Sets the Vector2 coordinates with the passed floats.
  1605. * Returns the updated Vector2.
  1606. */
  1607. Vector2.prototype.copyFromFloats = function (x, y) {
  1608. this.x = x;
  1609. this.y = y;
  1610. return this;
  1611. };
  1612. /**
  1613. * Sets the Vector2 coordinates with the passed floats.
  1614. * Returns the updated Vector2.
  1615. */
  1616. Vector2.prototype.set = function (x, y) {
  1617. return this.copyFromFloats(x, y);
  1618. };
  1619. /**
  1620. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1621. */
  1622. Vector2.prototype.add = function (otherVector) {
  1623. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1624. };
  1625. /**
  1626. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1627. * Returns the Vector2.
  1628. */
  1629. Vector2.prototype.addToRef = function (otherVector, result) {
  1630. result.x = this.x + otherVector.x;
  1631. result.y = this.y + otherVector.y;
  1632. return this;
  1633. };
  1634. /**
  1635. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1636. * Returns the updated Vector2.
  1637. */
  1638. Vector2.prototype.addInPlace = function (otherVector) {
  1639. this.x += otherVector.x;
  1640. this.y += otherVector.y;
  1641. return this;
  1642. };
  1643. /**
  1644. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1645. */
  1646. Vector2.prototype.addVector3 = function (otherVector) {
  1647. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1648. };
  1649. /**
  1650. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1651. */
  1652. Vector2.prototype.subtract = function (otherVector) {
  1653. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1654. };
  1655. /**
  1656. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1657. * Returns the Vector2.
  1658. */
  1659. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1660. result.x = this.x - otherVector.x;
  1661. result.y = this.y - otherVector.y;
  1662. return this;
  1663. };
  1664. /**
  1665. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1666. * Returns the updated Vector2.
  1667. */
  1668. Vector2.prototype.subtractInPlace = function (otherVector) {
  1669. this.x -= otherVector.x;
  1670. this.y -= otherVector.y;
  1671. return this;
  1672. };
  1673. /**
  1674. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1675. * Returns the updated Vector2.
  1676. */
  1677. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1678. this.x *= otherVector.x;
  1679. this.y *= otherVector.y;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1684. */
  1685. Vector2.prototype.multiply = function (otherVector) {
  1686. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1687. };
  1688. /**
  1689. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1690. * Returns the Vector2.
  1691. */
  1692. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1693. result.x = this.x * otherVector.x;
  1694. result.y = this.y * otherVector.y;
  1695. return this;
  1696. };
  1697. /**
  1698. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1699. */
  1700. Vector2.prototype.multiplyByFloats = function (x, y) {
  1701. return new Vector2(this.x * x, this.y * y);
  1702. };
  1703. /**
  1704. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1705. */
  1706. Vector2.prototype.divide = function (otherVector) {
  1707. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1708. };
  1709. /**
  1710. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1711. * Returns the Vector2.
  1712. */
  1713. Vector2.prototype.divideToRef = function (otherVector, result) {
  1714. result.x = this.x / otherVector.x;
  1715. result.y = this.y / otherVector.y;
  1716. return this;
  1717. };
  1718. /**
  1719. * Divides the current Vector3 coordinates by the passed ones.
  1720. * Returns the updated Vector3.
  1721. */
  1722. Vector2.prototype.divideInPlace = function (otherVector) {
  1723. return this.divideToRef(otherVector, this);
  1724. };
  1725. /**
  1726. * Returns a new Vector2 with current Vector2 negated coordinates.
  1727. */
  1728. Vector2.prototype.negate = function () {
  1729. return new Vector2(-this.x, -this.y);
  1730. };
  1731. /**
  1732. * Multiply the Vector2 coordinates by scale.
  1733. * Returns the updated Vector2.
  1734. */
  1735. Vector2.prototype.scaleInPlace = function (scale) {
  1736. this.x *= scale;
  1737. this.y *= scale;
  1738. return this;
  1739. };
  1740. /**
  1741. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1742. */
  1743. Vector2.prototype.scale = function (scale) {
  1744. return new Vector2(this.x * scale, this.y * scale);
  1745. };
  1746. /**
  1747. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1748. */
  1749. Vector2.prototype.equals = function (otherVector) {
  1750. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1751. };
  1752. /**
  1753. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1754. */
  1755. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1756. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1757. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1758. };
  1759. // Properties
  1760. /**
  1761. * Returns the vector length (float).
  1762. */
  1763. Vector2.prototype.length = function () {
  1764. return Math.sqrt(this.x * this.x + this.y * this.y);
  1765. };
  1766. /**
  1767. * Returns the vector squared length (float);
  1768. */
  1769. Vector2.prototype.lengthSquared = function () {
  1770. return (this.x * this.x + this.y * this.y);
  1771. };
  1772. // Methods
  1773. /**
  1774. * Normalize the vector.
  1775. * Returns the updated Vector2.
  1776. */
  1777. Vector2.prototype.normalize = function () {
  1778. var len = this.length();
  1779. if (len === 0)
  1780. return this;
  1781. var num = 1.0 / len;
  1782. this.x *= num;
  1783. this.y *= num;
  1784. return this;
  1785. };
  1786. /**
  1787. * Returns a new Vector2 copied from the Vector2.
  1788. */
  1789. Vector2.prototype.clone = function () {
  1790. return new Vector2(this.x, this.y);
  1791. };
  1792. // Statics
  1793. /**
  1794. * Returns a new Vector2(0, 0)
  1795. */
  1796. Vector2.Zero = function () {
  1797. return new Vector2(0, 0);
  1798. };
  1799. /**
  1800. * Returns a new Vector2(1, 1)
  1801. */
  1802. Vector2.One = function () {
  1803. return new Vector2(1, 1);
  1804. };
  1805. /**
  1806. * Returns a new Vector2 set from the passed index element of the passed array.
  1807. */
  1808. Vector2.FromArray = function (array, offset) {
  1809. if (offset === void 0) { offset = 0; }
  1810. return new Vector2(array[offset], array[offset + 1]);
  1811. };
  1812. /**
  1813. * Sets "result" from the passed index element of the passed array.
  1814. */
  1815. Vector2.FromArrayToRef = function (array, offset, result) {
  1816. result.x = array[offset];
  1817. result.y = array[offset + 1];
  1818. };
  1819. /**
  1820. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1821. */
  1822. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1823. var squared = amount * amount;
  1824. var cubed = amount * squared;
  1825. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1826. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1827. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1828. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1829. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1830. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1831. return new Vector2(x, y);
  1832. };
  1833. /**
  1834. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1835. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1836. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1837. */
  1838. Vector2.Clamp = function (value, min, max) {
  1839. var x = value.x;
  1840. x = (x > max.x) ? max.x : x;
  1841. x = (x < min.x) ? min.x : x;
  1842. var y = value.y;
  1843. y = (y > max.y) ? max.y : y;
  1844. y = (y < min.y) ? min.y : y;
  1845. return new Vector2(x, y);
  1846. };
  1847. /**
  1848. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1849. */
  1850. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1851. var squared = amount * amount;
  1852. var cubed = amount * squared;
  1853. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1854. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1855. var part3 = (cubed - (2.0 * squared)) + amount;
  1856. var part4 = cubed - squared;
  1857. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1858. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1859. return new Vector2(x, y);
  1860. };
  1861. /**
  1862. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1863. */
  1864. Vector2.Lerp = function (start, end, amount) {
  1865. var x = start.x + ((end.x - start.x) * amount);
  1866. var y = start.y + ((end.y - start.y) * amount);
  1867. return new Vector2(x, y);
  1868. };
  1869. /**
  1870. * Returns the dot product (float) of the vector "left" and the vector "right".
  1871. */
  1872. Vector2.Dot = function (left, right) {
  1873. return left.x * right.x + left.y * right.y;
  1874. };
  1875. /**
  1876. * Returns a new Vector2 equal to the normalized passed vector.
  1877. */
  1878. Vector2.Normalize = function (vector) {
  1879. var newVector = vector.clone();
  1880. newVector.normalize();
  1881. return newVector;
  1882. };
  1883. /**
  1884. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1885. */
  1886. Vector2.Minimize = function (left, right) {
  1887. var x = (left.x < right.x) ? left.x : right.x;
  1888. var y = (left.y < right.y) ? left.y : right.y;
  1889. return new Vector2(x, y);
  1890. };
  1891. /**
  1892. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1893. */
  1894. Vector2.Maximize = function (left, right) {
  1895. var x = (left.x > right.x) ? left.x : right.x;
  1896. var y = (left.y > right.y) ? left.y : right.y;
  1897. return new Vector2(x, y);
  1898. };
  1899. /**
  1900. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1901. */
  1902. Vector2.Transform = function (vector, transformation) {
  1903. var r = Vector2.Zero();
  1904. Vector2.TransformToRef(vector, transformation, r);
  1905. return r;
  1906. };
  1907. /**
  1908. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1909. */
  1910. Vector2.TransformToRef = function (vector, transformation, result) {
  1911. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1912. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1913. result.x = x;
  1914. result.y = y;
  1915. };
  1916. /**
  1917. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1918. */
  1919. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1920. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1921. var sign = a < 0 ? -1 : 1;
  1922. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1923. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1924. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1925. };
  1926. /**
  1927. * Returns the distance (float) between the vectors "value1" and "value2".
  1928. */
  1929. Vector2.Distance = function (value1, value2) {
  1930. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1931. };
  1932. /**
  1933. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1934. */
  1935. Vector2.DistanceSquared = function (value1, value2) {
  1936. var x = value1.x - value2.x;
  1937. var y = value1.y - value2.y;
  1938. return (x * x) + (y * y);
  1939. };
  1940. /**
  1941. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1942. */
  1943. Vector2.Center = function (value1, value2) {
  1944. var center = value1.add(value2);
  1945. center.scaleInPlace(0.5);
  1946. return center;
  1947. };
  1948. /**
  1949. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1950. */
  1951. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1952. var l2 = Vector2.DistanceSquared(segA, segB);
  1953. if (l2 === 0.0) {
  1954. return Vector2.Distance(p, segA);
  1955. }
  1956. var v = segB.subtract(segA);
  1957. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1958. var proj = segA.add(v.multiplyByFloats(t, t));
  1959. return Vector2.Distance(p, proj);
  1960. };
  1961. return Vector2;
  1962. }());
  1963. BABYLON.Vector2 = Vector2;
  1964. var Vector3 = /** @class */ (function () {
  1965. /**
  1966. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1967. * A Vector3 is the main object used in 3D geometry.
  1968. * It can represent etiher the coordinates of a point the space, either a direction.
  1969. */
  1970. function Vector3(x, y, z) {
  1971. this.x = x;
  1972. this.y = y;
  1973. this.z = z;
  1974. }
  1975. /**
  1976. * Returns a string with the Vector3 coordinates.
  1977. */
  1978. Vector3.prototype.toString = function () {
  1979. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1980. };
  1981. /**
  1982. * Returns the string "Vector3"
  1983. */
  1984. Vector3.prototype.getClassName = function () {
  1985. return "Vector3";
  1986. };
  1987. /**
  1988. * Returns the Vector hash code.
  1989. */
  1990. Vector3.prototype.getHashCode = function () {
  1991. var hash = this.x || 0;
  1992. hash = (hash * 397) ^ (this.y || 0);
  1993. hash = (hash * 397) ^ (this.z || 0);
  1994. return hash;
  1995. };
  1996. // Operators
  1997. /**
  1998. * Returns a new array with three elements : the coordinates the Vector3.
  1999. */
  2000. Vector3.prototype.asArray = function () {
  2001. var result = [];
  2002. this.toArray(result, 0);
  2003. return result;
  2004. };
  2005. /**
  2006. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2007. * Returns the Vector3.
  2008. */
  2009. Vector3.prototype.toArray = function (array, index) {
  2010. if (index === void 0) { index = 0; }
  2011. array[index] = this.x;
  2012. array[index + 1] = this.y;
  2013. array[index + 2] = this.z;
  2014. return this;
  2015. };
  2016. /**
  2017. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2018. */
  2019. Vector3.prototype.toQuaternion = function () {
  2020. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2021. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2022. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2023. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2024. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2025. var cosy = Math.cos(this.y * 0.5);
  2026. var siny = Math.sin(this.y * 0.5);
  2027. result.x = coszMinusx * siny;
  2028. result.y = -sinzMinusx * siny;
  2029. result.z = sinxPlusz * cosy;
  2030. result.w = cosxPlusz * cosy;
  2031. return result;
  2032. };
  2033. /**
  2034. * Adds the passed vector to the current Vector3.
  2035. * Returns the updated Vector3.
  2036. */
  2037. Vector3.prototype.addInPlace = function (otherVector) {
  2038. this.x += otherVector.x;
  2039. this.y += otherVector.y;
  2040. this.z += otherVector.z;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2045. */
  2046. Vector3.prototype.add = function (otherVector) {
  2047. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2048. };
  2049. /**
  2050. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2051. * Returns the current Vector3.
  2052. */
  2053. Vector3.prototype.addToRef = function (otherVector, result) {
  2054. result.x = this.x + otherVector.x;
  2055. result.y = this.y + otherVector.y;
  2056. result.z = this.z + otherVector.z;
  2057. return this;
  2058. };
  2059. /**
  2060. * Subtract the passed vector from the current Vector3.
  2061. * Returns the updated Vector3.
  2062. */
  2063. Vector3.prototype.subtractInPlace = function (otherVector) {
  2064. this.x -= otherVector.x;
  2065. this.y -= otherVector.y;
  2066. this.z -= otherVector.z;
  2067. return this;
  2068. };
  2069. /**
  2070. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2071. */
  2072. Vector3.prototype.subtract = function (otherVector) {
  2073. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2074. };
  2075. /**
  2076. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2077. * Returns the current Vector3.
  2078. */
  2079. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2080. result.x = this.x - otherVector.x;
  2081. result.y = this.y - otherVector.y;
  2082. result.z = this.z - otherVector.z;
  2083. return this;
  2084. };
  2085. /**
  2086. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2087. */
  2088. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2089. return new Vector3(this.x - x, this.y - y, this.z - z);
  2090. };
  2091. /**
  2092. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2093. * Returns the current Vector3.
  2094. */
  2095. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2096. result.x = this.x - x;
  2097. result.y = this.y - y;
  2098. result.z = this.z - z;
  2099. return this;
  2100. };
  2101. /**
  2102. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2103. */
  2104. Vector3.prototype.negate = function () {
  2105. return new Vector3(-this.x, -this.y, -this.z);
  2106. };
  2107. /**
  2108. * Multiplies the Vector3 coordinates by the float "scale".
  2109. * Returns the updated Vector3.
  2110. */
  2111. Vector3.prototype.scaleInPlace = function (scale) {
  2112. this.x *= scale;
  2113. this.y *= scale;
  2114. this.z *= scale;
  2115. return this;
  2116. };
  2117. /**
  2118. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2119. */
  2120. Vector3.prototype.scale = function (scale) {
  2121. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2122. };
  2123. /**
  2124. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2125. * Returns the current Vector3.
  2126. */
  2127. Vector3.prototype.scaleToRef = function (scale, result) {
  2128. result.x = this.x * scale;
  2129. result.y = this.y * scale;
  2130. result.z = this.z * scale;
  2131. return this;
  2132. };
  2133. /**
  2134. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2135. */
  2136. Vector3.prototype.equals = function (otherVector) {
  2137. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2138. };
  2139. /**
  2140. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2141. */
  2142. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2143. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2144. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2145. };
  2146. /**
  2147. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2148. */
  2149. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2150. return this.x === x && this.y === y && this.z === z;
  2151. };
  2152. /**
  2153. * Muliplies the current Vector3 coordinates by the passed ones.
  2154. * Returns the updated Vector3.
  2155. */
  2156. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2157. this.x *= otherVector.x;
  2158. this.y *= otherVector.y;
  2159. this.z *= otherVector.z;
  2160. return this;
  2161. };
  2162. /**
  2163. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2164. */
  2165. Vector3.prototype.multiply = function (otherVector) {
  2166. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2167. };
  2168. /**
  2169. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2170. * Returns the current Vector3.
  2171. */
  2172. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2173. result.x = this.x * otherVector.x;
  2174. result.y = this.y * otherVector.y;
  2175. result.z = this.z * otherVector.z;
  2176. return this;
  2177. };
  2178. /**
  2179. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2180. */
  2181. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2182. return new Vector3(this.x * x, this.y * y, this.z * z);
  2183. };
  2184. /**
  2185. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2186. */
  2187. Vector3.prototype.divide = function (otherVector) {
  2188. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2189. };
  2190. /**
  2191. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2192. * Returns the current Vector3.
  2193. */
  2194. Vector3.prototype.divideToRef = function (otherVector, result) {
  2195. result.x = this.x / otherVector.x;
  2196. result.y = this.y / otherVector.y;
  2197. result.z = this.z / otherVector.z;
  2198. return this;
  2199. };
  2200. /**
  2201. * Divides the current Vector3 coordinates by the passed ones.
  2202. * Returns the updated Vector3.
  2203. */
  2204. Vector3.prototype.divideInPlace = function (otherVector) {
  2205. return this.divideToRef(otherVector, this);
  2206. };
  2207. /**
  2208. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2209. * Returns the updated Vector3.
  2210. */
  2211. Vector3.prototype.MinimizeInPlace = function (other) {
  2212. if (other.x < this.x)
  2213. this.x = other.x;
  2214. if (other.y < this.y)
  2215. this.y = other.y;
  2216. if (other.z < this.z)
  2217. this.z = other.z;
  2218. return this;
  2219. };
  2220. /**
  2221. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2222. * Returns the updated Vector3.
  2223. */
  2224. Vector3.prototype.MaximizeInPlace = function (other) {
  2225. if (other.x > this.x)
  2226. this.x = other.x;
  2227. if (other.y > this.y)
  2228. this.y = other.y;
  2229. if (other.z > this.z)
  2230. this.z = other.z;
  2231. return this;
  2232. };
  2233. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2234. /**
  2235. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2236. */
  2237. get: function () {
  2238. var absX = Math.abs(this.x);
  2239. var absY = Math.abs(this.y);
  2240. if (absX !== absY) {
  2241. return true;
  2242. }
  2243. var absZ = Math.abs(this.z);
  2244. if (absX !== absZ) {
  2245. return true;
  2246. }
  2247. if (absY !== absZ) {
  2248. return true;
  2249. }
  2250. return false;
  2251. },
  2252. enumerable: true,
  2253. configurable: true
  2254. });
  2255. // Properties
  2256. /**
  2257. * Returns the length of the Vector3 (float).
  2258. */
  2259. Vector3.prototype.length = function () {
  2260. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2261. };
  2262. /**
  2263. * Returns the squared length of the Vector3 (float).
  2264. */
  2265. Vector3.prototype.lengthSquared = function () {
  2266. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2267. };
  2268. /**
  2269. * Normalize the current Vector3.
  2270. * Returns the updated Vector3.
  2271. * /!\ In place operation.
  2272. */
  2273. Vector3.prototype.normalize = function () {
  2274. var len = this.length();
  2275. if (len === 0 || len === 1.0)
  2276. return this;
  2277. var num = 1.0 / len;
  2278. this.x *= num;
  2279. this.y *= num;
  2280. this.z *= num;
  2281. return this;
  2282. };
  2283. /**
  2284. * Normalize the current Vector3 to a new vector.
  2285. * @returns the new Vector3.
  2286. */
  2287. Vector3.prototype.normalizeToNew = function () {
  2288. var normalized = new Vector3(0, 0, 0);
  2289. this.normalizeToRef(normalized);
  2290. return normalized;
  2291. };
  2292. /**
  2293. * Normalize the current Vector3 to the reference.
  2294. * @param the reference to update.
  2295. * @returns the updated Vector3.
  2296. */
  2297. Vector3.prototype.normalizeToRef = function (reference) {
  2298. var len = this.length();
  2299. if (len === 0 || len === 1.0) {
  2300. reference.set(this.x, this.y, this.z);
  2301. return reference;
  2302. }
  2303. var scale = 1.0 / len;
  2304. this.scaleToRef(scale, reference);
  2305. return reference;
  2306. };
  2307. /**
  2308. * Returns a new Vector3 copied from the current Vector3.
  2309. */
  2310. Vector3.prototype.clone = function () {
  2311. return new Vector3(this.x, this.y, this.z);
  2312. };
  2313. /**
  2314. * Copies the passed vector coordinates to the current Vector3 ones.
  2315. * Returns the updated Vector3.
  2316. */
  2317. Vector3.prototype.copyFrom = function (source) {
  2318. this.x = source.x;
  2319. this.y = source.y;
  2320. this.z = source.z;
  2321. return this;
  2322. };
  2323. /**
  2324. * Copies the passed floats to the current Vector3 coordinates.
  2325. * Returns the updated Vector3.
  2326. */
  2327. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2328. this.x = x;
  2329. this.y = y;
  2330. this.z = z;
  2331. return this;
  2332. };
  2333. /**
  2334. * Copies the passed floats to the current Vector3 coordinates.
  2335. * Returns the updated Vector3.
  2336. */
  2337. Vector3.prototype.set = function (x, y, z) {
  2338. return this.copyFromFloats(x, y, z);
  2339. };
  2340. // Statics
  2341. /**
  2342. *
  2343. */
  2344. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2345. var d0 = Vector3.Dot(vector0, axis) - size;
  2346. var d1 = Vector3.Dot(vector1, axis) - size;
  2347. var s = d0 / (d0 - d1);
  2348. return s;
  2349. };
  2350. /**
  2351. * Returns a new Vector3 set from the index "offset" of the passed array.
  2352. */
  2353. Vector3.FromArray = function (array, offset) {
  2354. if (!offset) {
  2355. offset = 0;
  2356. }
  2357. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2358. };
  2359. /**
  2360. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2361. * This function is deprecated. Use FromArray instead.
  2362. */
  2363. Vector3.FromFloatArray = function (array, offset) {
  2364. return Vector3.FromArray(array, offset);
  2365. };
  2366. /**
  2367. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2368. */
  2369. Vector3.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. result.z = array[offset + 2];
  2373. };
  2374. /**
  2375. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2376. * This function is deprecated. Use FromArrayToRef instead.
  2377. */
  2378. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2379. return Vector3.FromArrayToRef(array, offset, result);
  2380. };
  2381. /**
  2382. * Sets the passed vector "result" with the passed floats.
  2383. */
  2384. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2385. result.x = x;
  2386. result.y = y;
  2387. result.z = z;
  2388. };
  2389. /**
  2390. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2391. */
  2392. Vector3.Zero = function () {
  2393. return new Vector3(0.0, 0.0, 0.0);
  2394. };
  2395. /**
  2396. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2397. */
  2398. Vector3.One = function () {
  2399. return new Vector3(1.0, 1.0, 1.0);
  2400. };
  2401. /**
  2402. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2403. */
  2404. Vector3.Up = function () {
  2405. return new Vector3(0.0, 1.0, 0.0);
  2406. };
  2407. /**
  2408. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2409. */
  2410. Vector3.Forward = function () {
  2411. return new Vector3(0.0, 0.0, 1.0);
  2412. };
  2413. /**
  2414. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2415. */
  2416. Vector3.Right = function () {
  2417. return new Vector3(1.0, 0.0, 0.0);
  2418. };
  2419. /**
  2420. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2421. */
  2422. Vector3.Left = function () {
  2423. return new Vector3(-1.0, 0.0, 0.0);
  2424. };
  2425. /**
  2426. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2427. * This method computes tranformed coordinates only, not transformed direction vectors.
  2428. */
  2429. Vector3.TransformCoordinates = function (vector, transformation) {
  2430. var result = Vector3.Zero();
  2431. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2432. return result;
  2433. };
  2434. /**
  2435. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2436. * This method computes tranformed coordinates only, not transformed direction vectors.
  2437. */
  2438. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2439. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2440. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2441. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2442. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2443. result.x = x / w;
  2444. result.y = y / w;
  2445. result.z = z / w;
  2446. };
  2447. /**
  2448. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2449. * This method computes tranformed coordinates only, not transformed direction vectors.
  2450. */
  2451. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2452. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2453. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2454. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2455. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2456. result.x = rx / rw;
  2457. result.y = ry / rw;
  2458. result.z = rz / rw;
  2459. };
  2460. /**
  2461. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2462. * This methods computes transformed normalized direction vectors only.
  2463. */
  2464. Vector3.TransformNormal = function (vector, transformation) {
  2465. var result = Vector3.Zero();
  2466. Vector3.TransformNormalToRef(vector, transformation, result);
  2467. return result;
  2468. };
  2469. /**
  2470. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2471. * This methods computes transformed normalized direction vectors only.
  2472. */
  2473. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2474. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2475. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2476. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2477. result.x = x;
  2478. result.y = y;
  2479. result.z = z;
  2480. };
  2481. /**
  2482. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2483. * This methods computes transformed normalized direction vectors only.
  2484. */
  2485. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2486. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2487. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2488. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2489. };
  2490. /**
  2491. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2492. */
  2493. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2494. var squared = amount * amount;
  2495. var cubed = amount * squared;
  2496. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2497. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2498. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2499. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2500. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2501. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2502. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2503. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2504. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2505. return new Vector3(x, y, z);
  2506. };
  2507. /**
  2508. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  2509. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2510. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2511. */
  2512. Vector3.Clamp = function (value, min, max) {
  2513. var x = value.x;
  2514. x = (x > max.x) ? max.x : x;
  2515. x = (x < min.x) ? min.x : x;
  2516. var y = value.y;
  2517. y = (y > max.y) ? max.y : y;
  2518. y = (y < min.y) ? min.y : y;
  2519. var z = value.z;
  2520. z = (z > max.z) ? max.z : z;
  2521. z = (z < min.z) ? min.z : z;
  2522. return new Vector3(x, y, z);
  2523. };
  2524. /**
  2525. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2526. */
  2527. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2528. var squared = amount * amount;
  2529. var cubed = amount * squared;
  2530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2532. var part3 = (cubed - (2.0 * squared)) + amount;
  2533. var part4 = cubed - squared;
  2534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2536. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2537. return new Vector3(x, y, z);
  2538. };
  2539. /**
  2540. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2541. */
  2542. Vector3.Lerp = function (start, end, amount) {
  2543. var result = new Vector3(0, 0, 0);
  2544. Vector3.LerpToRef(start, end, amount, result);
  2545. return result;
  2546. };
  2547. /**
  2548. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2549. */
  2550. Vector3.LerpToRef = function (start, end, amount, result) {
  2551. result.x = start.x + ((end.x - start.x) * amount);
  2552. result.y = start.y + ((end.y - start.y) * amount);
  2553. result.z = start.z + ((end.z - start.z) * amount);
  2554. };
  2555. /**
  2556. * Returns the dot product (float) between the vectors "left" and "right".
  2557. */
  2558. Vector3.Dot = function (left, right) {
  2559. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2560. };
  2561. /**
  2562. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2563. * The cross product is then orthogonal to both "left" and "right".
  2564. */
  2565. Vector3.Cross = function (left, right) {
  2566. var result = Vector3.Zero();
  2567. Vector3.CrossToRef(left, right, result);
  2568. return result;
  2569. };
  2570. /**
  2571. * Sets the passed vector "result" with the cross product of "left" and "right".
  2572. * The cross product is then orthogonal to both "left" and "right".
  2573. */
  2574. Vector3.CrossToRef = function (left, right, result) {
  2575. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2576. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2577. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2578. result.copyFrom(MathTmp.Vector3[0]);
  2579. };
  2580. /**
  2581. * Returns a new Vector3 as the normalization of the passed vector.
  2582. */
  2583. Vector3.Normalize = function (vector) {
  2584. var result = Vector3.Zero();
  2585. Vector3.NormalizeToRef(vector, result);
  2586. return result;
  2587. };
  2588. /**
  2589. * Sets the passed vector "result" with the normalization of the passed first vector.
  2590. */
  2591. Vector3.NormalizeToRef = function (vector, result) {
  2592. result.copyFrom(vector);
  2593. result.normalize();
  2594. };
  2595. Vector3.Project = function (vector, world, transform, viewport) {
  2596. var cw = viewport.width;
  2597. var ch = viewport.height;
  2598. var cx = viewport.x;
  2599. var cy = viewport.y;
  2600. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2601. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  2602. var matrix = MathTmp.Matrix[0];
  2603. world.multiplyToRef(transform, matrix);
  2604. matrix.multiplyToRef(viewportMatrix, matrix);
  2605. return Vector3.TransformCoordinates(vector, matrix);
  2606. };
  2607. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2608. var matrix = MathTmp.Matrix[0];
  2609. world.multiplyToRef(transform, matrix);
  2610. matrix.invert();
  2611. source.x = source.x / viewportWidth * 2 - 1;
  2612. source.y = -(source.y / viewportHeight * 2 - 1);
  2613. var vector = Vector3.TransformCoordinates(source, matrix);
  2614. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2615. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2616. vector = vector.scale(1.0 / num);
  2617. }
  2618. return vector;
  2619. };
  2620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2621. var result = Vector3.Zero();
  2622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2623. return result;
  2624. };
  2625. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2626. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2627. };
  2628. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2629. var matrix = MathTmp.Matrix[0];
  2630. world.multiplyToRef(view, matrix);
  2631. matrix.multiplyToRef(projection, matrix);
  2632. matrix.invert();
  2633. var screenSource = MathTmp.Vector3[0];
  2634. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2635. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2636. screenSource.z = 2 * sourceZ - 1.0;
  2637. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2638. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2639. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2640. result.scaleInPlace(1.0 / num);
  2641. }
  2642. };
  2643. Vector3.Minimize = function (left, right) {
  2644. var min = left.clone();
  2645. min.MinimizeInPlace(right);
  2646. return min;
  2647. };
  2648. Vector3.Maximize = function (left, right) {
  2649. var max = left.clone();
  2650. max.MaximizeInPlace(right);
  2651. return max;
  2652. };
  2653. /**
  2654. * Returns the distance (float) between the vectors "value1" and "value2".
  2655. */
  2656. Vector3.Distance = function (value1, value2) {
  2657. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2658. };
  2659. /**
  2660. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2661. */
  2662. Vector3.DistanceSquared = function (value1, value2) {
  2663. var x = value1.x - value2.x;
  2664. var y = value1.y - value2.y;
  2665. var z = value1.z - value2.z;
  2666. return (x * x) + (y * y) + (z * z);
  2667. };
  2668. /**
  2669. * Returns a new Vector3 located at the center between "value1" and "value2".
  2670. */
  2671. Vector3.Center = function (value1, value2) {
  2672. var center = value1.add(value2);
  2673. center.scaleInPlace(0.5);
  2674. return center;
  2675. };
  2676. /**
  2677. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2678. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2679. * to something in order to rotate it from its local system to the given target system.
  2680. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2681. * Returns a new Vector3.
  2682. */
  2683. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2684. var rotation = Vector3.Zero();
  2685. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2686. return rotation;
  2687. };
  2688. /**
  2689. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2690. */
  2691. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2692. var quat = MathTmp.Quaternion[0];
  2693. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2694. quat.toEulerAnglesToRef(ref);
  2695. };
  2696. return Vector3;
  2697. }());
  2698. BABYLON.Vector3 = Vector3;
  2699. //Vector4 class created for EulerAngle class conversion to Quaternion
  2700. var Vector4 = /** @class */ (function () {
  2701. /**
  2702. * Creates a Vector4 object from the passed floats.
  2703. */
  2704. function Vector4(x, y, z, w) {
  2705. this.x = x;
  2706. this.y = y;
  2707. this.z = z;
  2708. this.w = w;
  2709. }
  2710. /**
  2711. * Returns the string with the Vector4 coordinates.
  2712. */
  2713. Vector4.prototype.toString = function () {
  2714. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2715. };
  2716. /**
  2717. * Returns the string "Vector4".
  2718. */
  2719. Vector4.prototype.getClassName = function () {
  2720. return "Vector4";
  2721. };
  2722. /**
  2723. * Returns the Vector4 hash code.
  2724. */
  2725. Vector4.prototype.getHashCode = function () {
  2726. var hash = this.x || 0;
  2727. hash = (hash * 397) ^ (this.y || 0);
  2728. hash = (hash * 397) ^ (this.z || 0);
  2729. hash = (hash * 397) ^ (this.w || 0);
  2730. return hash;
  2731. };
  2732. // Operators
  2733. /**
  2734. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2735. */
  2736. Vector4.prototype.asArray = function () {
  2737. var result = new Array();
  2738. this.toArray(result, 0);
  2739. return result;
  2740. };
  2741. /**
  2742. * Populates the passed array from the passed index with the Vector4 coordinates.
  2743. * Returns the Vector4.
  2744. */
  2745. Vector4.prototype.toArray = function (array, index) {
  2746. if (index === undefined) {
  2747. index = 0;
  2748. }
  2749. array[index] = this.x;
  2750. array[index + 1] = this.y;
  2751. array[index + 2] = this.z;
  2752. array[index + 3] = this.w;
  2753. return this;
  2754. };
  2755. /**
  2756. * Adds the passed vector to the current Vector4.
  2757. * Returns the updated Vector4.
  2758. */
  2759. Vector4.prototype.addInPlace = function (otherVector) {
  2760. this.x += otherVector.x;
  2761. this.y += otherVector.y;
  2762. this.z += otherVector.z;
  2763. this.w += otherVector.w;
  2764. return this;
  2765. };
  2766. /**
  2767. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2768. */
  2769. Vector4.prototype.add = function (otherVector) {
  2770. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2771. };
  2772. /**
  2773. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2774. * Returns the current Vector4.
  2775. */
  2776. Vector4.prototype.addToRef = function (otherVector, result) {
  2777. result.x = this.x + otherVector.x;
  2778. result.y = this.y + otherVector.y;
  2779. result.z = this.z + otherVector.z;
  2780. result.w = this.w + otherVector.w;
  2781. return this;
  2782. };
  2783. /**
  2784. * Subtract in place the passed vector from the current Vector4.
  2785. * Returns the updated Vector4.
  2786. */
  2787. Vector4.prototype.subtractInPlace = function (otherVector) {
  2788. this.x -= otherVector.x;
  2789. this.y -= otherVector.y;
  2790. this.z -= otherVector.z;
  2791. this.w -= otherVector.w;
  2792. return this;
  2793. };
  2794. /**
  2795. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2796. */
  2797. Vector4.prototype.subtract = function (otherVector) {
  2798. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2799. };
  2800. /**
  2801. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2802. * Returns the current Vector4.
  2803. */
  2804. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2805. result.x = this.x - otherVector.x;
  2806. result.y = this.y - otherVector.y;
  2807. result.z = this.z - otherVector.z;
  2808. result.w = this.w - otherVector.w;
  2809. return this;
  2810. };
  2811. /**
  2812. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2813. */
  2814. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2815. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2816. };
  2817. /**
  2818. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2819. * Returns the current Vector4.
  2820. */
  2821. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2822. result.x = this.x - x;
  2823. result.y = this.y - y;
  2824. result.z = this.z - z;
  2825. result.w = this.w - w;
  2826. return this;
  2827. };
  2828. /**
  2829. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2830. */
  2831. Vector4.prototype.negate = function () {
  2832. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2833. };
  2834. /**
  2835. * Multiplies the current Vector4 coordinates by scale (float).
  2836. * Returns the updated Vector4.
  2837. */
  2838. Vector4.prototype.scaleInPlace = function (scale) {
  2839. this.x *= scale;
  2840. this.y *= scale;
  2841. this.z *= scale;
  2842. this.w *= scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2847. */
  2848. Vector4.prototype.scale = function (scale) {
  2849. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2850. };
  2851. /**
  2852. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2853. * Returns the current Vector4.
  2854. */
  2855. Vector4.prototype.scaleToRef = function (scale, result) {
  2856. result.x = this.x * scale;
  2857. result.y = this.y * scale;
  2858. result.z = this.z * scale;
  2859. result.w = this.w * scale;
  2860. return this;
  2861. };
  2862. /**
  2863. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2864. */
  2865. Vector4.prototype.equals = function (otherVector) {
  2866. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2867. };
  2868. /**
  2869. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2870. */
  2871. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2872. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2873. return otherVector
  2874. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2875. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2876. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2877. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2878. };
  2879. /**
  2880. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2881. */
  2882. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2883. return this.x === x && this.y === y && this.z === z && this.w === w;
  2884. };
  2885. /**
  2886. * Multiplies in place the current Vector4 by the passed one.
  2887. * Returns the updated Vector4.
  2888. */
  2889. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2890. this.x *= otherVector.x;
  2891. this.y *= otherVector.y;
  2892. this.z *= otherVector.z;
  2893. this.w *= otherVector.w;
  2894. return this;
  2895. };
  2896. /**
  2897. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2898. */
  2899. Vector4.prototype.multiply = function (otherVector) {
  2900. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2901. };
  2902. /**
  2903. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2904. * Returns the current Vector4.
  2905. */
  2906. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2907. result.x = this.x * otherVector.x;
  2908. result.y = this.y * otherVector.y;
  2909. result.z = this.z * otherVector.z;
  2910. result.w = this.w * otherVector.w;
  2911. return this;
  2912. };
  2913. /**
  2914. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2915. */
  2916. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2917. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2918. };
  2919. /**
  2920. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2921. */
  2922. Vector4.prototype.divide = function (otherVector) {
  2923. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2924. };
  2925. /**
  2926. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2927. * Returns the current Vector4.
  2928. */
  2929. Vector4.prototype.divideToRef = function (otherVector, result) {
  2930. result.x = this.x / otherVector.x;
  2931. result.y = this.y / otherVector.y;
  2932. result.z = this.z / otherVector.z;
  2933. result.w = this.w / otherVector.w;
  2934. return this;
  2935. };
  2936. /**
  2937. * Divides the current Vector3 coordinates by the passed ones.
  2938. * Returns the updated Vector3.
  2939. */
  2940. Vector4.prototype.divideInPlace = function (otherVector) {
  2941. return this.divideToRef(otherVector, this);
  2942. };
  2943. /**
  2944. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2945. */
  2946. Vector4.prototype.MinimizeInPlace = function (other) {
  2947. if (other.x < this.x)
  2948. this.x = other.x;
  2949. if (other.y < this.y)
  2950. this.y = other.y;
  2951. if (other.z < this.z)
  2952. this.z = other.z;
  2953. if (other.w < this.w)
  2954. this.w = other.w;
  2955. return this;
  2956. };
  2957. /**
  2958. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2959. */
  2960. Vector4.prototype.MaximizeInPlace = function (other) {
  2961. if (other.x > this.x)
  2962. this.x = other.x;
  2963. if (other.y > this.y)
  2964. this.y = other.y;
  2965. if (other.z > this.z)
  2966. this.z = other.z;
  2967. if (other.w > this.w)
  2968. this.w = other.w;
  2969. return this;
  2970. };
  2971. // Properties
  2972. /**
  2973. * Returns the Vector4 length (float).
  2974. */
  2975. Vector4.prototype.length = function () {
  2976. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2977. };
  2978. /**
  2979. * Returns the Vector4 squared length (float).
  2980. */
  2981. Vector4.prototype.lengthSquared = function () {
  2982. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2983. };
  2984. // Methods
  2985. /**
  2986. * Normalizes in place the Vector4.
  2987. * Returns the updated Vector4.
  2988. */
  2989. Vector4.prototype.normalize = function () {
  2990. var len = this.length();
  2991. if (len === 0)
  2992. return this;
  2993. var num = 1.0 / len;
  2994. this.x *= num;
  2995. this.y *= num;
  2996. this.z *= num;
  2997. this.w *= num;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3002. */
  3003. Vector4.prototype.toVector3 = function () {
  3004. return new Vector3(this.x, this.y, this.z);
  3005. };
  3006. /**
  3007. * Returns a new Vector4 copied from the current one.
  3008. */
  3009. Vector4.prototype.clone = function () {
  3010. return new Vector4(this.x, this.y, this.z, this.w);
  3011. };
  3012. /**
  3013. * Updates the current Vector4 with the passed one coordinates.
  3014. * Returns the updated Vector4.
  3015. */
  3016. Vector4.prototype.copyFrom = function (source) {
  3017. this.x = source.x;
  3018. this.y = source.y;
  3019. this.z = source.z;
  3020. this.w = source.w;
  3021. return this;
  3022. };
  3023. /**
  3024. * Updates the current Vector4 coordinates with the passed floats.
  3025. * Returns the updated Vector4.
  3026. */
  3027. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3028. this.x = x;
  3029. this.y = y;
  3030. this.z = z;
  3031. this.w = w;
  3032. return this;
  3033. };
  3034. /**
  3035. * Updates the current Vector4 coordinates with the passed floats.
  3036. * Returns the updated Vector4.
  3037. */
  3038. Vector4.prototype.set = function (x, y, z, w) {
  3039. return this.copyFromFloats(x, y, z, w);
  3040. };
  3041. // Statics
  3042. /**
  3043. * Returns a new Vector4 set from the starting index of the passed array.
  3044. */
  3045. Vector4.FromArray = function (array, offset) {
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3050. };
  3051. /**
  3052. * Updates the passed vector "result" from the starting index of the passed array.
  3053. */
  3054. Vector4.FromArrayToRef = function (array, offset, result) {
  3055. result.x = array[offset];
  3056. result.y = array[offset + 1];
  3057. result.z = array[offset + 2];
  3058. result.w = array[offset + 3];
  3059. };
  3060. /**
  3061. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3062. */
  3063. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3064. Vector4.FromArrayToRef(array, offset, result);
  3065. };
  3066. /**
  3067. * Updates the passed vector "result" coordinates from the passed floats.
  3068. */
  3069. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3070. result.x = x;
  3071. result.y = y;
  3072. result.z = z;
  3073. result.w = w;
  3074. };
  3075. /**
  3076. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3077. */
  3078. Vector4.Zero = function () {
  3079. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3080. };
  3081. /**
  3082. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3083. */
  3084. Vector4.One = function () {
  3085. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3086. };
  3087. /**
  3088. * Returns a new normalized Vector4 from the passed one.
  3089. */
  3090. Vector4.Normalize = function (vector) {
  3091. var result = Vector4.Zero();
  3092. Vector4.NormalizeToRef(vector, result);
  3093. return result;
  3094. };
  3095. /**
  3096. * Updates the passed vector "result" from the normalization of the passed one.
  3097. */
  3098. Vector4.NormalizeToRef = function (vector, result) {
  3099. result.copyFrom(vector);
  3100. result.normalize();
  3101. };
  3102. Vector4.Minimize = function (left, right) {
  3103. var min = left.clone();
  3104. min.MinimizeInPlace(right);
  3105. return min;
  3106. };
  3107. Vector4.Maximize = function (left, right) {
  3108. var max = left.clone();
  3109. max.MaximizeInPlace(right);
  3110. return max;
  3111. };
  3112. /**
  3113. * Returns the distance (float) between the vectors "value1" and "value2".
  3114. */
  3115. Vector4.Distance = function (value1, value2) {
  3116. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3117. };
  3118. /**
  3119. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3120. */
  3121. Vector4.DistanceSquared = function (value1, value2) {
  3122. var x = value1.x - value2.x;
  3123. var y = value1.y - value2.y;
  3124. var z = value1.z - value2.z;
  3125. var w = value1.w - value2.w;
  3126. return (x * x) + (y * y) + (z * z) + (w * w);
  3127. };
  3128. /**
  3129. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3130. */
  3131. Vector4.Center = function (value1, value2) {
  3132. var center = value1.add(value2);
  3133. center.scaleInPlace(0.5);
  3134. return center;
  3135. };
  3136. /**
  3137. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3138. * This methods computes transformed normalized direction vectors only.
  3139. */
  3140. Vector4.TransformNormal = function (vector, transformation) {
  3141. var result = Vector4.Zero();
  3142. Vector4.TransformNormalToRef(vector, transformation, result);
  3143. return result;
  3144. };
  3145. /**
  3146. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3147. * This methods computes transformed normalized direction vectors only.
  3148. */
  3149. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3150. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3151. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3152. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3153. result.x = x;
  3154. result.y = y;
  3155. result.z = z;
  3156. result.w = vector.w;
  3157. };
  3158. /**
  3159. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3160. * This methods computes transformed normalized direction vectors only.
  3161. */
  3162. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3163. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3164. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3165. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3166. result.w = w;
  3167. };
  3168. return Vector4;
  3169. }());
  3170. BABYLON.Vector4 = Vector4;
  3171. var Size = /** @class */ (function () {
  3172. /**
  3173. * Creates a Size object from the passed width and height (floats).
  3174. */
  3175. function Size(width, height) {
  3176. this.width = width;
  3177. this.height = height;
  3178. }
  3179. // Returns a string with the Size width and height.
  3180. Size.prototype.toString = function () {
  3181. return "{W: " + this.width + ", H: " + this.height + "}";
  3182. };
  3183. /**
  3184. * Returns the string "Size"
  3185. */
  3186. Size.prototype.getClassName = function () {
  3187. return "Size";
  3188. };
  3189. /**
  3190. * Returns the Size hash code.
  3191. */
  3192. Size.prototype.getHashCode = function () {
  3193. var hash = this.width || 0;
  3194. hash = (hash * 397) ^ (this.height || 0);
  3195. return hash;
  3196. };
  3197. /**
  3198. * Updates the current size from the passed one.
  3199. * Returns the updated Size.
  3200. */
  3201. Size.prototype.copyFrom = function (src) {
  3202. this.width = src.width;
  3203. this.height = src.height;
  3204. };
  3205. /**
  3206. * Updates in place the current Size from the passed floats.
  3207. * Returns the updated Size.
  3208. */
  3209. Size.prototype.copyFromFloats = function (width, height) {
  3210. this.width = width;
  3211. this.height = height;
  3212. return this;
  3213. };
  3214. /**
  3215. * Updates in place the current Size from the passed floats.
  3216. * Returns the updated Size.
  3217. */
  3218. Size.prototype.set = function (width, height) {
  3219. return this.copyFromFloats(width, height);
  3220. };
  3221. /**
  3222. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3223. */
  3224. Size.prototype.multiplyByFloats = function (w, h) {
  3225. return new Size(this.width * w, this.height * h);
  3226. };
  3227. /**
  3228. * Returns a new Size copied from the passed one.
  3229. */
  3230. Size.prototype.clone = function () {
  3231. return new Size(this.width, this.height);
  3232. };
  3233. /**
  3234. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3235. */
  3236. Size.prototype.equals = function (other) {
  3237. if (!other) {
  3238. return false;
  3239. }
  3240. return (this.width === other.width) && (this.height === other.height);
  3241. };
  3242. Object.defineProperty(Size.prototype, "surface", {
  3243. /**
  3244. * Returns the surface of the Size : width * height (float).
  3245. */
  3246. get: function () {
  3247. return this.width * this.height;
  3248. },
  3249. enumerable: true,
  3250. configurable: true
  3251. });
  3252. /**
  3253. * Returns a new Size set to (0.0, 0.0)
  3254. */
  3255. Size.Zero = function () {
  3256. return new Size(0.0, 0.0);
  3257. };
  3258. /**
  3259. * Returns a new Size set as the addition result of the current Size and the passed one.
  3260. */
  3261. Size.prototype.add = function (otherSize) {
  3262. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3263. return r;
  3264. };
  3265. /**
  3266. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3267. */
  3268. Size.prototype.subtract = function (otherSize) {
  3269. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3270. return r;
  3271. };
  3272. /**
  3273. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3274. */
  3275. Size.Lerp = function (start, end, amount) {
  3276. var w = start.width + ((end.width - start.width) * amount);
  3277. var h = start.height + ((end.height - start.height) * amount);
  3278. return new Size(w, h);
  3279. };
  3280. return Size;
  3281. }());
  3282. BABYLON.Size = Size;
  3283. var Quaternion = /** @class */ (function () {
  3284. /**
  3285. * Creates a new Quaternion from the passed floats.
  3286. */
  3287. function Quaternion(x, y, z, w) {
  3288. if (x === void 0) { x = 0.0; }
  3289. if (y === void 0) { y = 0.0; }
  3290. if (z === void 0) { z = 0.0; }
  3291. if (w === void 0) { w = 1.0; }
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. this.w = w;
  3296. }
  3297. /**
  3298. * Returns a string with the Quaternion coordinates.
  3299. */
  3300. Quaternion.prototype.toString = function () {
  3301. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3302. };
  3303. /**
  3304. * Returns the string "Quaternion".
  3305. */
  3306. Quaternion.prototype.getClassName = function () {
  3307. return "Quaternion";
  3308. };
  3309. /**
  3310. * Returns the Quaternion hash code.
  3311. */
  3312. Quaternion.prototype.getHashCode = function () {
  3313. var hash = this.x || 0;
  3314. hash = (hash * 397) ^ (this.y || 0);
  3315. hash = (hash * 397) ^ (this.z || 0);
  3316. hash = (hash * 397) ^ (this.w || 0);
  3317. return hash;
  3318. };
  3319. /**
  3320. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3321. */
  3322. Quaternion.prototype.asArray = function () {
  3323. return [this.x, this.y, this.z, this.w];
  3324. };
  3325. /**
  3326. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3327. */
  3328. Quaternion.prototype.equals = function (otherQuaternion) {
  3329. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3330. };
  3331. /**
  3332. * Returns a new Quaternion copied from the current one.
  3333. */
  3334. Quaternion.prototype.clone = function () {
  3335. return new Quaternion(this.x, this.y, this.z, this.w);
  3336. };
  3337. /**
  3338. * Updates the current Quaternion from the passed one coordinates.
  3339. * Returns the updated Quaterion.
  3340. */
  3341. Quaternion.prototype.copyFrom = function (other) {
  3342. this.x = other.x;
  3343. this.y = other.y;
  3344. this.z = other.z;
  3345. this.w = other.w;
  3346. return this;
  3347. };
  3348. /**
  3349. * Updates the current Quaternion from the passed float coordinates.
  3350. * Returns the updated Quaterion.
  3351. */
  3352. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3353. this.x = x;
  3354. this.y = y;
  3355. this.z = z;
  3356. this.w = w;
  3357. return this;
  3358. };
  3359. /**
  3360. * Updates the current Quaternion from the passed float coordinates.
  3361. * Returns the updated Quaterion.
  3362. */
  3363. Quaternion.prototype.set = function (x, y, z, w) {
  3364. return this.copyFromFloats(x, y, z, w);
  3365. };
  3366. /**
  3367. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3368. */
  3369. Quaternion.prototype.add = function (other) {
  3370. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3371. };
  3372. /**
  3373. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3374. */
  3375. Quaternion.prototype.subtract = function (other) {
  3376. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3377. };
  3378. /**
  3379. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3380. */
  3381. Quaternion.prototype.scale = function (value) {
  3382. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3383. };
  3384. /**
  3385. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3386. */
  3387. Quaternion.prototype.multiply = function (q1) {
  3388. var result = new Quaternion(0, 0, 0, 1.0);
  3389. this.multiplyToRef(q1, result);
  3390. return result;
  3391. };
  3392. /**
  3393. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3394. * Returns the current Quaternion.
  3395. */
  3396. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3397. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3398. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3399. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3400. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3401. result.copyFromFloats(x, y, z, w);
  3402. return this;
  3403. };
  3404. /**
  3405. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3406. * Returns the updated Quaternion.
  3407. */
  3408. Quaternion.prototype.multiplyInPlace = function (q1) {
  3409. this.multiplyToRef(q1, this);
  3410. return this;
  3411. };
  3412. /**
  3413. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3414. * Returns the current Quaternion.
  3415. */
  3416. Quaternion.prototype.conjugateToRef = function (ref) {
  3417. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3418. return this;
  3419. };
  3420. /**
  3421. * Conjugates in place the current Quaternion.
  3422. * Returns the updated Quaternion.
  3423. */
  3424. Quaternion.prototype.conjugateInPlace = function () {
  3425. this.x *= -1;
  3426. this.y *= -1;
  3427. this.z *= -1;
  3428. return this;
  3429. };
  3430. /**
  3431. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3432. */
  3433. Quaternion.prototype.conjugate = function () {
  3434. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3435. return result;
  3436. };
  3437. /**
  3438. * Returns the Quaternion length (float).
  3439. */
  3440. Quaternion.prototype.length = function () {
  3441. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3442. };
  3443. /**
  3444. * Normalize in place the current Quaternion.
  3445. * Returns the updated Quaternion.
  3446. */
  3447. Quaternion.prototype.normalize = function () {
  3448. var length = 1.0 / this.length();
  3449. this.x *= length;
  3450. this.y *= length;
  3451. this.z *= length;
  3452. this.w *= length;
  3453. return this;
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3457. */
  3458. Quaternion.prototype.toEulerAngles = function (order) {
  3459. if (order === void 0) { order = "YZX"; }
  3460. var result = Vector3.Zero();
  3461. this.toEulerAnglesToRef(result, order);
  3462. return result;
  3463. };
  3464. /**
  3465. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3466. * Returns the current Quaternion.
  3467. */
  3468. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3469. if (order === void 0) { order = "YZX"; }
  3470. var qz = this.z;
  3471. var qx = this.x;
  3472. var qy = this.y;
  3473. var qw = this.w;
  3474. var sqw = qw * qw;
  3475. var sqz = qz * qz;
  3476. var sqx = qx * qx;
  3477. var sqy = qy * qy;
  3478. var zAxisY = qy * qz - qx * qw;
  3479. var limit = .4999999;
  3480. if (zAxisY < -limit) {
  3481. result.y = 2 * Math.atan2(qy, qw);
  3482. result.x = Math.PI / 2;
  3483. result.z = 0;
  3484. }
  3485. else if (zAxisY > limit) {
  3486. result.y = 2 * Math.atan2(qy, qw);
  3487. result.x = -Math.PI / 2;
  3488. result.z = 0;
  3489. }
  3490. else {
  3491. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3492. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3493. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3494. }
  3495. return this;
  3496. };
  3497. /**
  3498. * Updates the passed rotation matrix with the current Quaternion values.
  3499. * Returns the current Quaternion.
  3500. */
  3501. Quaternion.prototype.toRotationMatrix = function (result) {
  3502. var xx = this.x * this.x;
  3503. var yy = this.y * this.y;
  3504. var zz = this.z * this.z;
  3505. var xy = this.x * this.y;
  3506. var zw = this.z * this.w;
  3507. var zx = this.z * this.x;
  3508. var yw = this.y * this.w;
  3509. var yz = this.y * this.z;
  3510. var xw = this.x * this.w;
  3511. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3512. result.m[1] = 2.0 * (xy + zw);
  3513. result.m[2] = 2.0 * (zx - yw);
  3514. result.m[3] = 0;
  3515. result.m[4] = 2.0 * (xy - zw);
  3516. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3517. result.m[6] = 2.0 * (yz + xw);
  3518. result.m[7] = 0;
  3519. result.m[8] = 2.0 * (zx + yw);
  3520. result.m[9] = 2.0 * (yz - xw);
  3521. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3522. result.m[11] = 0;
  3523. result.m[12] = 0;
  3524. result.m[13] = 0;
  3525. result.m[14] = 0;
  3526. result.m[15] = 1.0;
  3527. result._markAsUpdated();
  3528. return this;
  3529. };
  3530. /**
  3531. * Updates the current Quaternion from the passed rotation matrix values.
  3532. * Returns the updated Quaternion.
  3533. */
  3534. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3535. Quaternion.FromRotationMatrixToRef(matrix, this);
  3536. return this;
  3537. };
  3538. // Statics
  3539. /**
  3540. * Returns a new Quaternion set from the passed rotation matrix values.
  3541. */
  3542. Quaternion.FromRotationMatrix = function (matrix) {
  3543. var result = new Quaternion();
  3544. Quaternion.FromRotationMatrixToRef(matrix, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3549. */
  3550. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3551. var data = matrix.m;
  3552. var m11 = data[0], m12 = data[4], m13 = data[8];
  3553. var m21 = data[1], m22 = data[5], m23 = data[9];
  3554. var m31 = data[2], m32 = data[6], m33 = data[10];
  3555. var trace = m11 + m22 + m33;
  3556. var s;
  3557. if (trace > 0) {
  3558. s = 0.5 / Math.sqrt(trace + 1.0);
  3559. result.w = 0.25 / s;
  3560. result.x = (m32 - m23) * s;
  3561. result.y = (m13 - m31) * s;
  3562. result.z = (m21 - m12) * s;
  3563. }
  3564. else if (m11 > m22 && m11 > m33) {
  3565. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3566. result.w = (m32 - m23) / s;
  3567. result.x = 0.25 * s;
  3568. result.y = (m12 + m21) / s;
  3569. result.z = (m13 + m31) / s;
  3570. }
  3571. else if (m22 > m33) {
  3572. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3573. result.w = (m13 - m31) / s;
  3574. result.x = (m12 + m21) / s;
  3575. result.y = 0.25 * s;
  3576. result.z = (m23 + m32) / s;
  3577. }
  3578. else {
  3579. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3580. result.w = (m21 - m12) / s;
  3581. result.x = (m13 + m31) / s;
  3582. result.y = (m23 + m32) / s;
  3583. result.z = 0.25 * s;
  3584. }
  3585. };
  3586. /**
  3587. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3588. */
  3589. Quaternion.Zero = function () {
  3590. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3591. };
  3592. /**
  3593. * Returns a new Quaternion as the inverted current Quaternion.
  3594. */
  3595. Quaternion.Inverse = function (q) {
  3596. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3597. };
  3598. /**
  3599. * Returns the identity Quaternion.
  3600. */
  3601. Quaternion.Identity = function () {
  3602. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3603. };
  3604. Quaternion.IsIdentity = function (quaternion) {
  3605. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3606. };
  3607. /**
  3608. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3609. */
  3610. Quaternion.RotationAxis = function (axis, angle) {
  3611. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3612. };
  3613. /**
  3614. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3615. */
  3616. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3617. var sin = Math.sin(angle / 2);
  3618. axis.normalize();
  3619. result.w = Math.cos(angle / 2);
  3620. result.x = axis.x * sin;
  3621. result.y = axis.y * sin;
  3622. result.z = axis.z * sin;
  3623. return result;
  3624. };
  3625. /**
  3626. * Retuns a new Quaternion set from the starting index of the passed array.
  3627. */
  3628. Quaternion.FromArray = function (array, offset) {
  3629. if (!offset) {
  3630. offset = 0;
  3631. }
  3632. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3633. };
  3634. /**
  3635. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3636. */
  3637. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3638. var q = new Quaternion();
  3639. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3640. return q;
  3641. };
  3642. /**
  3643. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3644. */
  3645. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3646. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3647. var halfRoll = roll * 0.5;
  3648. var halfPitch = pitch * 0.5;
  3649. var halfYaw = yaw * 0.5;
  3650. var sinRoll = Math.sin(halfRoll);
  3651. var cosRoll = Math.cos(halfRoll);
  3652. var sinPitch = Math.sin(halfPitch);
  3653. var cosPitch = Math.cos(halfPitch);
  3654. var sinYaw = Math.sin(halfYaw);
  3655. var cosYaw = Math.cos(halfYaw);
  3656. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3657. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3658. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3659. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3660. };
  3661. /**
  3662. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3663. */
  3664. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3665. var result = new Quaternion();
  3666. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3671. */
  3672. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3673. // Produces a quaternion from Euler angles in the z-x-z orientation
  3674. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3675. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3676. var halfBeta = beta * 0.5;
  3677. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3678. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3679. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3680. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3681. };
  3682. /**
  3683. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3684. * cf to Vector3.RotationFromAxis() documentation.
  3685. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3686. */
  3687. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3688. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3689. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3690. return quat;
  3691. };
  3692. /**
  3693. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3694. * cf to Vector3.RotationFromAxis() documentation.
  3695. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3696. */
  3697. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3698. var rotMat = MathTmp.Matrix[0];
  3699. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3700. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3701. };
  3702. Quaternion.Slerp = function (left, right, amount) {
  3703. var result = Quaternion.Identity();
  3704. Quaternion.SlerpToRef(left, right, amount, result);
  3705. return result;
  3706. };
  3707. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3708. var num2;
  3709. var num3;
  3710. var num = amount;
  3711. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3712. var flag = false;
  3713. if (num4 < 0) {
  3714. flag = true;
  3715. num4 = -num4;
  3716. }
  3717. if (num4 > 0.999999) {
  3718. num3 = 1 - num;
  3719. num2 = flag ? -num : num;
  3720. }
  3721. else {
  3722. var num5 = Math.acos(num4);
  3723. var num6 = (1.0 / Math.sin(num5));
  3724. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3725. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3726. }
  3727. result.x = (num3 * left.x) + (num2 * right.x);
  3728. result.y = (num3 * left.y) + (num2 * right.y);
  3729. result.z = (num3 * left.z) + (num2 * right.z);
  3730. result.w = (num3 * left.w) + (num2 * right.w);
  3731. };
  3732. /**
  3733. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3734. */
  3735. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3736. var squared = amount * amount;
  3737. var cubed = amount * squared;
  3738. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3739. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3740. var part3 = (cubed - (2.0 * squared)) + amount;
  3741. var part4 = cubed - squared;
  3742. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3743. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3744. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3745. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3746. return new Quaternion(x, y, z, w);
  3747. };
  3748. return Quaternion;
  3749. }());
  3750. BABYLON.Quaternion = Quaternion;
  3751. var Matrix = /** @class */ (function () {
  3752. function Matrix() {
  3753. this._isIdentity = false;
  3754. this._isIdentityDirty = true;
  3755. this.m = new Float32Array(16);
  3756. this._markAsUpdated();
  3757. }
  3758. Matrix.prototype._markAsUpdated = function () {
  3759. this.updateFlag = Matrix._updateFlagSeed++;
  3760. this._isIdentityDirty = true;
  3761. };
  3762. // Properties
  3763. /**
  3764. * Boolean : True is the matrix is the identity matrix
  3765. */
  3766. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3767. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3768. if (this._isIdentityDirty) {
  3769. this._isIdentityDirty = false;
  3770. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3771. this._isIdentity = false;
  3772. }
  3773. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3774. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3775. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3776. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3777. this._isIdentity = false;
  3778. }
  3779. else {
  3780. this._isIdentity = true;
  3781. }
  3782. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3783. this._isIdentity = false;
  3784. }
  3785. }
  3786. return this._isIdentity;
  3787. };
  3788. /**
  3789. * Returns the matrix determinant (float).
  3790. */
  3791. Matrix.prototype.determinant = function () {
  3792. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3793. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3794. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3795. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3796. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3797. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3798. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3799. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3800. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3801. };
  3802. // Methods
  3803. /**
  3804. * Returns the matrix underlying array.
  3805. */
  3806. Matrix.prototype.toArray = function () {
  3807. return this.m;
  3808. };
  3809. /**
  3810. * Returns the matrix underlying array.
  3811. */
  3812. Matrix.prototype.asArray = function () {
  3813. return this.toArray();
  3814. };
  3815. /**
  3816. * Inverts in place the Matrix.
  3817. * Returns the Matrix inverted.
  3818. */
  3819. Matrix.prototype.invert = function () {
  3820. this.invertToRef(this);
  3821. return this;
  3822. };
  3823. /**
  3824. * Sets all the matrix elements to zero.
  3825. * Returns the Matrix.
  3826. */
  3827. Matrix.prototype.reset = function () {
  3828. for (var index = 0; index < 16; index++) {
  3829. this.m[index] = 0.0;
  3830. }
  3831. this._markAsUpdated();
  3832. return this;
  3833. };
  3834. /**
  3835. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3836. */
  3837. Matrix.prototype.add = function (other) {
  3838. var result = new Matrix();
  3839. this.addToRef(other, result);
  3840. return result;
  3841. };
  3842. /**
  3843. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3844. * Returns the Matrix.
  3845. */
  3846. Matrix.prototype.addToRef = function (other, result) {
  3847. for (var index = 0; index < 16; index++) {
  3848. result.m[index] = this.m[index] + other.m[index];
  3849. }
  3850. result._markAsUpdated();
  3851. return this;
  3852. };
  3853. /**
  3854. * Adds in place the passed matrix to the current Matrix.
  3855. * Returns the updated Matrix.
  3856. */
  3857. Matrix.prototype.addToSelf = function (other) {
  3858. for (var index = 0; index < 16; index++) {
  3859. this.m[index] += other.m[index];
  3860. }
  3861. this._markAsUpdated();
  3862. return this;
  3863. };
  3864. /**
  3865. * Sets the passed matrix with the current inverted Matrix.
  3866. * Returns the unmodified current Matrix.
  3867. */
  3868. Matrix.prototype.invertToRef = function (other) {
  3869. var l1 = this.m[0];
  3870. var l2 = this.m[1];
  3871. var l3 = this.m[2];
  3872. var l4 = this.m[3];
  3873. var l5 = this.m[4];
  3874. var l6 = this.m[5];
  3875. var l7 = this.m[6];
  3876. var l8 = this.m[7];
  3877. var l9 = this.m[8];
  3878. var l10 = this.m[9];
  3879. var l11 = this.m[10];
  3880. var l12 = this.m[11];
  3881. var l13 = this.m[12];
  3882. var l14 = this.m[13];
  3883. var l15 = this.m[14];
  3884. var l16 = this.m[15];
  3885. var l17 = (l11 * l16) - (l12 * l15);
  3886. var l18 = (l10 * l16) - (l12 * l14);
  3887. var l19 = (l10 * l15) - (l11 * l14);
  3888. var l20 = (l9 * l16) - (l12 * l13);
  3889. var l21 = (l9 * l15) - (l11 * l13);
  3890. var l22 = (l9 * l14) - (l10 * l13);
  3891. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3892. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3893. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3894. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3895. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3896. var l28 = (l7 * l16) - (l8 * l15);
  3897. var l29 = (l6 * l16) - (l8 * l14);
  3898. var l30 = (l6 * l15) - (l7 * l14);
  3899. var l31 = (l5 * l16) - (l8 * l13);
  3900. var l32 = (l5 * l15) - (l7 * l13);
  3901. var l33 = (l5 * l14) - (l6 * l13);
  3902. var l34 = (l7 * l12) - (l8 * l11);
  3903. var l35 = (l6 * l12) - (l8 * l10);
  3904. var l36 = (l6 * l11) - (l7 * l10);
  3905. var l37 = (l5 * l12) - (l8 * l9);
  3906. var l38 = (l5 * l11) - (l7 * l9);
  3907. var l39 = (l5 * l10) - (l6 * l9);
  3908. other.m[0] = l23 * l27;
  3909. other.m[4] = l24 * l27;
  3910. other.m[8] = l25 * l27;
  3911. other.m[12] = l26 * l27;
  3912. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3913. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3914. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3915. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3916. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3917. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3918. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3919. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3920. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3921. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3922. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3923. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3924. other._markAsUpdated();
  3925. return this;
  3926. };
  3927. /**
  3928. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3929. * Returns the updated Matrix.
  3930. */
  3931. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3932. this.m[12] = x;
  3933. this.m[13] = y;
  3934. this.m[14] = z;
  3935. this._markAsUpdated();
  3936. return this;
  3937. };
  3938. /**
  3939. * Inserts the translation vector in the current Matrix.
  3940. * Returns the updated Matrix.
  3941. */
  3942. Matrix.prototype.setTranslation = function (vector3) {
  3943. this.m[12] = vector3.x;
  3944. this.m[13] = vector3.y;
  3945. this.m[14] = vector3.z;
  3946. this._markAsUpdated();
  3947. return this;
  3948. };
  3949. /**
  3950. * Returns a new Vector3 as the extracted translation from the Matrix.
  3951. */
  3952. Matrix.prototype.getTranslation = function () {
  3953. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3954. };
  3955. /**
  3956. * Fill a Vector3 with the extracted translation from the Matrix.
  3957. */
  3958. Matrix.prototype.getTranslationToRef = function (result) {
  3959. result.x = this.m[12];
  3960. result.y = this.m[13];
  3961. result.z = this.m[14];
  3962. return this;
  3963. };
  3964. /**
  3965. * Remove rotation and scaling part from the Matrix.
  3966. * Returns the updated Matrix.
  3967. */
  3968. Matrix.prototype.removeRotationAndScaling = function () {
  3969. this.setRowFromFloats(0, 1, 0, 0, 0);
  3970. this.setRowFromFloats(1, 0, 1, 0, 0);
  3971. this.setRowFromFloats(2, 0, 0, 1, 0);
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3976. */
  3977. Matrix.prototype.multiply = function (other) {
  3978. var result = new Matrix();
  3979. this.multiplyToRef(other, result);
  3980. return result;
  3981. };
  3982. /**
  3983. * Updates the current Matrix from the passed one values.
  3984. * Returns the updated Matrix.
  3985. */
  3986. Matrix.prototype.copyFrom = function (other) {
  3987. for (var index = 0; index < 16; index++) {
  3988. this.m[index] = other.m[index];
  3989. }
  3990. this._markAsUpdated();
  3991. return this;
  3992. };
  3993. /**
  3994. * Populates the passed array from the starting index with the Matrix values.
  3995. * Returns the Matrix.
  3996. */
  3997. Matrix.prototype.copyToArray = function (array, offset) {
  3998. if (offset === void 0) { offset = 0; }
  3999. for (var index = 0; index < 16; index++) {
  4000. array[offset + index] = this.m[index];
  4001. }
  4002. return this;
  4003. };
  4004. /**
  4005. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4006. */
  4007. Matrix.prototype.multiplyToRef = function (other, result) {
  4008. this.multiplyToArray(other, result.m, 0);
  4009. result._markAsUpdated();
  4010. return this;
  4011. };
  4012. /**
  4013. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4014. */
  4015. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4016. var tm0 = this.m[0];
  4017. var tm1 = this.m[1];
  4018. var tm2 = this.m[2];
  4019. var tm3 = this.m[3];
  4020. var tm4 = this.m[4];
  4021. var tm5 = this.m[5];
  4022. var tm6 = this.m[6];
  4023. var tm7 = this.m[7];
  4024. var tm8 = this.m[8];
  4025. var tm9 = this.m[9];
  4026. var tm10 = this.m[10];
  4027. var tm11 = this.m[11];
  4028. var tm12 = this.m[12];
  4029. var tm13 = this.m[13];
  4030. var tm14 = this.m[14];
  4031. var tm15 = this.m[15];
  4032. var om0 = other.m[0];
  4033. var om1 = other.m[1];
  4034. var om2 = other.m[2];
  4035. var om3 = other.m[3];
  4036. var om4 = other.m[4];
  4037. var om5 = other.m[5];
  4038. var om6 = other.m[6];
  4039. var om7 = other.m[7];
  4040. var om8 = other.m[8];
  4041. var om9 = other.m[9];
  4042. var om10 = other.m[10];
  4043. var om11 = other.m[11];
  4044. var om12 = other.m[12];
  4045. var om13 = other.m[13];
  4046. var om14 = other.m[14];
  4047. var om15 = other.m[15];
  4048. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4049. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4050. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4051. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4052. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4053. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4054. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4055. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4056. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4057. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4058. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4059. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4060. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4061. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4062. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4063. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4064. return this;
  4065. };
  4066. /**
  4067. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4068. */
  4069. Matrix.prototype.equals = function (value) {
  4070. return value &&
  4071. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4072. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4073. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4074. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4075. };
  4076. /**
  4077. * Returns a new Matrix from the current Matrix.
  4078. */
  4079. Matrix.prototype.clone = function () {
  4080. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  4081. };
  4082. /**
  4083. * Returns the string "Matrix"
  4084. */
  4085. Matrix.prototype.getClassName = function () {
  4086. return "Matrix";
  4087. };
  4088. /**
  4089. * Returns the Matrix hash code.
  4090. */
  4091. Matrix.prototype.getHashCode = function () {
  4092. var hash = this.m[0] || 0;
  4093. for (var i = 1; i < 16; i++) {
  4094. hash = (hash * 397) ^ (this.m[i] || 0);
  4095. }
  4096. return hash;
  4097. };
  4098. /**
  4099. * Decomposes the current Matrix into :
  4100. * - a scale vector3 passed as a reference to update,
  4101. * - a rotation quaternion passed as a reference to update,
  4102. * - a translation vector3 passed as a reference to update.
  4103. * Returns the boolean `true`.
  4104. */
  4105. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4106. translation.x = this.m[12];
  4107. translation.y = this.m[13];
  4108. translation.z = this.m[14];
  4109. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4110. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4111. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4112. if (this.determinant() <= 0) {
  4113. scale.y *= -1;
  4114. }
  4115. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4116. rotation.x = 0;
  4117. rotation.y = 0;
  4118. rotation.z = 0;
  4119. rotation.w = 1;
  4120. return false;
  4121. }
  4122. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  4123. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4124. return true;
  4125. };
  4126. /**
  4127. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4128. */
  4129. Matrix.prototype.getRotationMatrix = function () {
  4130. var result = Matrix.Identity();
  4131. this.getRotationMatrixToRef(result);
  4132. return result;
  4133. };
  4134. /**
  4135. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4136. * Returns the current Matrix.
  4137. */
  4138. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4139. var m = this.m;
  4140. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4141. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4142. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4143. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4144. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4145. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4146. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  4147. return this;
  4148. };
  4149. // Statics
  4150. /**
  4151. * Returns a new Matrix set from the starting index of the passed array.
  4152. */
  4153. Matrix.FromArray = function (array, offset) {
  4154. var result = new Matrix();
  4155. if (!offset) {
  4156. offset = 0;
  4157. }
  4158. Matrix.FromArrayToRef(array, offset, result);
  4159. return result;
  4160. };
  4161. /**
  4162. * Sets the passed "result" matrix from the starting index of the passed array.
  4163. */
  4164. Matrix.FromArrayToRef = function (array, offset, result) {
  4165. for (var index = 0; index < 16; index++) {
  4166. result.m[index] = array[index + offset];
  4167. }
  4168. result._markAsUpdated();
  4169. };
  4170. /**
  4171. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4172. */
  4173. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4174. for (var index = 0; index < 16; index++) {
  4175. result.m[index] = array[index + offset] * scale;
  4176. }
  4177. result._markAsUpdated();
  4178. };
  4179. /**
  4180. * Sets the passed matrix "result" with the 16 passed floats.
  4181. */
  4182. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4183. result.m[0] = initialM11;
  4184. result.m[1] = initialM12;
  4185. result.m[2] = initialM13;
  4186. result.m[3] = initialM14;
  4187. result.m[4] = initialM21;
  4188. result.m[5] = initialM22;
  4189. result.m[6] = initialM23;
  4190. result.m[7] = initialM24;
  4191. result.m[8] = initialM31;
  4192. result.m[9] = initialM32;
  4193. result.m[10] = initialM33;
  4194. result.m[11] = initialM34;
  4195. result.m[12] = initialM41;
  4196. result.m[13] = initialM42;
  4197. result.m[14] = initialM43;
  4198. result.m[15] = initialM44;
  4199. result._markAsUpdated();
  4200. };
  4201. /**
  4202. * Returns the index-th row of the current matrix as a new Vector4.
  4203. */
  4204. Matrix.prototype.getRow = function (index) {
  4205. if (index < 0 || index > 3) {
  4206. return null;
  4207. }
  4208. var i = index * 4;
  4209. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4210. };
  4211. /**
  4212. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4213. * Returns the updated Matrix.
  4214. */
  4215. Matrix.prototype.setRow = function (index, row) {
  4216. if (index < 0 || index > 3) {
  4217. return this;
  4218. }
  4219. var i = index * 4;
  4220. this.m[i + 0] = row.x;
  4221. this.m[i + 1] = row.y;
  4222. this.m[i + 2] = row.z;
  4223. this.m[i + 3] = row.w;
  4224. this._markAsUpdated();
  4225. return this;
  4226. };
  4227. /**
  4228. * Compute the transpose of the matrix.
  4229. * Returns a new Matrix.
  4230. */
  4231. Matrix.prototype.transpose = function () {
  4232. return Matrix.Transpose(this);
  4233. };
  4234. /**
  4235. * Compute the transpose of the matrix.
  4236. * Returns the current matrix.
  4237. */
  4238. Matrix.prototype.transposeToRef = function (result) {
  4239. Matrix.TransposeToRef(this, result);
  4240. return this;
  4241. };
  4242. /**
  4243. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4244. * Returns the updated Matrix.
  4245. */
  4246. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4247. if (index < 0 || index > 3) {
  4248. return this;
  4249. }
  4250. var i = index * 4;
  4251. this.m[i + 0] = x;
  4252. this.m[i + 1] = y;
  4253. this.m[i + 2] = z;
  4254. this.m[i + 3] = w;
  4255. this._markAsUpdated();
  4256. return this;
  4257. };
  4258. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4259. /**
  4260. * Static identity matrix to be used as readonly matrix
  4261. * Must not be updated.
  4262. */
  4263. get: function () {
  4264. return Matrix._identityReadOnly;
  4265. },
  4266. enumerable: true,
  4267. configurable: true
  4268. });
  4269. /**
  4270. * Returns a new Matrix set from the 16 passed floats.
  4271. */
  4272. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4273. var result = new Matrix();
  4274. result.m[0] = initialM11;
  4275. result.m[1] = initialM12;
  4276. result.m[2] = initialM13;
  4277. result.m[3] = initialM14;
  4278. result.m[4] = initialM21;
  4279. result.m[5] = initialM22;
  4280. result.m[6] = initialM23;
  4281. result.m[7] = initialM24;
  4282. result.m[8] = initialM31;
  4283. result.m[9] = initialM32;
  4284. result.m[10] = initialM33;
  4285. result.m[11] = initialM34;
  4286. result.m[12] = initialM41;
  4287. result.m[13] = initialM42;
  4288. result.m[14] = initialM43;
  4289. result.m[15] = initialM44;
  4290. return result;
  4291. };
  4292. /**
  4293. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4294. */
  4295. Matrix.Compose = function (scale, rotation, translation) {
  4296. var result = Matrix.Identity();
  4297. Matrix.ComposeToRef(scale, rotation, translation, result);
  4298. return result;
  4299. };
  4300. /**
  4301. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4302. */
  4303. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4304. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4305. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4306. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4307. result.setTranslation(translation);
  4308. };
  4309. /**
  4310. * Returns a new indentity Matrix.
  4311. */
  4312. Matrix.Identity = function () {
  4313. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  4314. };
  4315. /**
  4316. * Sets the passed "result" as an identity matrix.
  4317. */
  4318. Matrix.IdentityToRef = function (result) {
  4319. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  4320. };
  4321. /**
  4322. * Returns a new zero Matrix.
  4323. */
  4324. Matrix.Zero = function () {
  4325. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  4326. };
  4327. /**
  4328. * Returns a new rotation matrix for "angle" radians around the X axis.
  4329. */
  4330. Matrix.RotationX = function (angle) {
  4331. var result = new Matrix();
  4332. Matrix.RotationXToRef(angle, result);
  4333. return result;
  4334. };
  4335. /**
  4336. * Returns a new Matrix as the passed inverted one.
  4337. */
  4338. Matrix.Invert = function (source) {
  4339. var result = new Matrix();
  4340. source.invertToRef(result);
  4341. return result;
  4342. };
  4343. /**
  4344. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4345. */
  4346. Matrix.RotationXToRef = function (angle, result) {
  4347. var s = Math.sin(angle);
  4348. var c = Math.cos(angle);
  4349. result.m[0] = 1.0;
  4350. result.m[15] = 1.0;
  4351. result.m[5] = c;
  4352. result.m[10] = c;
  4353. result.m[9] = -s;
  4354. result.m[6] = s;
  4355. result.m[1] = 0.0;
  4356. result.m[2] = 0.0;
  4357. result.m[3] = 0.0;
  4358. result.m[4] = 0.0;
  4359. result.m[7] = 0.0;
  4360. result.m[8] = 0.0;
  4361. result.m[11] = 0.0;
  4362. result.m[12] = 0.0;
  4363. result.m[13] = 0.0;
  4364. result.m[14] = 0.0;
  4365. result._markAsUpdated();
  4366. };
  4367. /**
  4368. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4369. */
  4370. Matrix.RotationY = function (angle) {
  4371. var result = new Matrix();
  4372. Matrix.RotationYToRef(angle, result);
  4373. return result;
  4374. };
  4375. /**
  4376. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4377. */
  4378. Matrix.RotationYToRef = function (angle, result) {
  4379. var s = Math.sin(angle);
  4380. var c = Math.cos(angle);
  4381. result.m[5] = 1.0;
  4382. result.m[15] = 1.0;
  4383. result.m[0] = c;
  4384. result.m[2] = -s;
  4385. result.m[8] = s;
  4386. result.m[10] = c;
  4387. result.m[1] = 0.0;
  4388. result.m[3] = 0.0;
  4389. result.m[4] = 0.0;
  4390. result.m[6] = 0.0;
  4391. result.m[7] = 0.0;
  4392. result.m[9] = 0.0;
  4393. result.m[11] = 0.0;
  4394. result.m[12] = 0.0;
  4395. result.m[13] = 0.0;
  4396. result.m[14] = 0.0;
  4397. result._markAsUpdated();
  4398. };
  4399. /**
  4400. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4401. */
  4402. Matrix.RotationZ = function (angle) {
  4403. var result = new Matrix();
  4404. Matrix.RotationZToRef(angle, result);
  4405. return result;
  4406. };
  4407. /**
  4408. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4409. */
  4410. Matrix.RotationZToRef = function (angle, result) {
  4411. var s = Math.sin(angle);
  4412. var c = Math.cos(angle);
  4413. result.m[10] = 1.0;
  4414. result.m[15] = 1.0;
  4415. result.m[0] = c;
  4416. result.m[1] = s;
  4417. result.m[4] = -s;
  4418. result.m[5] = c;
  4419. result.m[2] = 0.0;
  4420. result.m[3] = 0.0;
  4421. result.m[6] = 0.0;
  4422. result.m[7] = 0.0;
  4423. result.m[8] = 0.0;
  4424. result.m[9] = 0.0;
  4425. result.m[11] = 0.0;
  4426. result.m[12] = 0.0;
  4427. result.m[13] = 0.0;
  4428. result.m[14] = 0.0;
  4429. result._markAsUpdated();
  4430. };
  4431. /**
  4432. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4433. */
  4434. Matrix.RotationAxis = function (axis, angle) {
  4435. var result = Matrix.Zero();
  4436. Matrix.RotationAxisToRef(axis, angle, result);
  4437. return result;
  4438. };
  4439. /**
  4440. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4441. */
  4442. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4443. var s = Math.sin(-angle);
  4444. var c = Math.cos(-angle);
  4445. var c1 = 1 - c;
  4446. axis.normalize();
  4447. result.m[0] = (axis.x * axis.x) * c1 + c;
  4448. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4449. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4450. result.m[3] = 0.0;
  4451. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4452. result.m[5] = (axis.y * axis.y) * c1 + c;
  4453. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4454. result.m[7] = 0.0;
  4455. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4456. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4457. result.m[10] = (axis.z * axis.z) * c1 + c;
  4458. result.m[11] = 0.0;
  4459. result.m[15] = 1.0;
  4460. result._markAsUpdated();
  4461. };
  4462. /**
  4463. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4464. */
  4465. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4466. var result = new Matrix();
  4467. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4468. return result;
  4469. };
  4470. /**
  4471. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4472. */
  4473. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4474. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4475. this._tempQuaternion.toRotationMatrix(result);
  4476. };
  4477. /**
  4478. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4479. */
  4480. Matrix.Scaling = function (x, y, z) {
  4481. var result = Matrix.Zero();
  4482. Matrix.ScalingToRef(x, y, z, result);
  4483. return result;
  4484. };
  4485. /**
  4486. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4487. */
  4488. Matrix.ScalingToRef = function (x, y, z, result) {
  4489. result.m[0] = x;
  4490. result.m[1] = 0.0;
  4491. result.m[2] = 0.0;
  4492. result.m[3] = 0.0;
  4493. result.m[4] = 0.0;
  4494. result.m[5] = y;
  4495. result.m[6] = 0.0;
  4496. result.m[7] = 0.0;
  4497. result.m[8] = 0.0;
  4498. result.m[9] = 0.0;
  4499. result.m[10] = z;
  4500. result.m[11] = 0.0;
  4501. result.m[12] = 0.0;
  4502. result.m[13] = 0.0;
  4503. result.m[14] = 0.0;
  4504. result.m[15] = 1.0;
  4505. result._markAsUpdated();
  4506. };
  4507. /**
  4508. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4509. */
  4510. Matrix.Translation = function (x, y, z) {
  4511. var result = Matrix.Identity();
  4512. Matrix.TranslationToRef(x, y, z, result);
  4513. return result;
  4514. };
  4515. /**
  4516. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4517. */
  4518. Matrix.TranslationToRef = function (x, y, z, result) {
  4519. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  4520. };
  4521. /**
  4522. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4523. */
  4524. Matrix.Lerp = function (startValue, endValue, gradient) {
  4525. var result = Matrix.Zero();
  4526. for (var index = 0; index < 16; index++) {
  4527. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4528. }
  4529. result._markAsUpdated();
  4530. return result;
  4531. };
  4532. /**
  4533. * Returns a new Matrix whose values are computed by :
  4534. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4535. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4536. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4537. */
  4538. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4539. var startScale = new Vector3(0, 0, 0);
  4540. var startRotation = new Quaternion();
  4541. var startTranslation = new Vector3(0, 0, 0);
  4542. startValue.decompose(startScale, startRotation, startTranslation);
  4543. var endScale = new Vector3(0, 0, 0);
  4544. var endRotation = new Quaternion();
  4545. var endTranslation = new Vector3(0, 0, 0);
  4546. endValue.decompose(endScale, endRotation, endTranslation);
  4547. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4548. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4549. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4550. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4551. };
  4552. /**
  4553. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4554. * This methods works for a Left-Handed system.
  4555. */
  4556. Matrix.LookAtLH = function (eye, target, up) {
  4557. var result = Matrix.Zero();
  4558. Matrix.LookAtLHToRef(eye, target, up, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4563. * This methods works for a Left-Handed system.
  4564. */
  4565. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4566. // Z axis
  4567. target.subtractToRef(eye, this._zAxis);
  4568. this._zAxis.normalize();
  4569. // X axis
  4570. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4571. if (this._xAxis.lengthSquared() === 0) {
  4572. this._xAxis.x = 1.0;
  4573. }
  4574. else {
  4575. this._xAxis.normalize();
  4576. }
  4577. // Y axis
  4578. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4579. this._yAxis.normalize();
  4580. // Eye angles
  4581. var ex = -Vector3.Dot(this._xAxis, eye);
  4582. var ey = -Vector3.Dot(this._yAxis, eye);
  4583. var ez = -Vector3.Dot(this._zAxis, eye);
  4584. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  4585. };
  4586. /**
  4587. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4588. * This methods works for a Right-Handed system.
  4589. */
  4590. Matrix.LookAtRH = function (eye, target, up) {
  4591. var result = Matrix.Zero();
  4592. Matrix.LookAtRHToRef(eye, target, up, result);
  4593. return result;
  4594. };
  4595. /**
  4596. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4597. * This methods works for a Left-Handed system.
  4598. */
  4599. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4600. // Z axis
  4601. eye.subtractToRef(target, this._zAxis);
  4602. this._zAxis.normalize();
  4603. // X axis
  4604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4605. if (this._xAxis.lengthSquared() === 0) {
  4606. this._xAxis.x = 1.0;
  4607. }
  4608. else {
  4609. this._xAxis.normalize();
  4610. }
  4611. // Y axis
  4612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4613. this._yAxis.normalize();
  4614. // Eye angles
  4615. var ex = -Vector3.Dot(this._xAxis, eye);
  4616. var ey = -Vector3.Dot(this._yAxis, eye);
  4617. var ez = -Vector3.Dot(this._zAxis, eye);
  4618. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  4619. };
  4620. /**
  4621. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4622. */
  4623. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4624. var matrix = Matrix.Zero();
  4625. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4626. return matrix;
  4627. };
  4628. /**
  4629. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4630. */
  4631. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4632. var n = znear;
  4633. var f = zfar;
  4634. var a = 2.0 / width;
  4635. var b = 2.0 / height;
  4636. var c = 2.0 / (f - n);
  4637. var d = -(f + n) / (f - n);
  4638. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  4639. };
  4640. /**
  4641. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4642. */
  4643. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4644. var matrix = Matrix.Zero();
  4645. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4646. return matrix;
  4647. };
  4648. /**
  4649. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4650. */
  4651. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4652. var n = znear;
  4653. var f = zfar;
  4654. var a = 2.0 / (right - left);
  4655. var b = 2.0 / (top - bottom);
  4656. var c = 2.0 / (f - n);
  4657. var d = -(f + n) / (f - n);
  4658. var i0 = (left + right) / (left - right);
  4659. var i1 = (top + bottom) / (bottom - top);
  4660. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  4661. };
  4662. /**
  4663. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4664. */
  4665. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4666. var matrix = Matrix.Zero();
  4667. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4668. return matrix;
  4669. };
  4670. /**
  4671. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4672. */
  4673. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4674. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4675. result.m[10] *= -1.0;
  4676. };
  4677. /**
  4678. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4679. */
  4680. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4681. var matrix = Matrix.Zero();
  4682. var n = znear;
  4683. var f = zfar;
  4684. var a = 2.0 * n / width;
  4685. var b = 2.0 * n / height;
  4686. var c = (f + n) / (f - n);
  4687. var d = -2.0 * f * n / (f - n);
  4688. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  4689. return matrix;
  4690. };
  4691. /**
  4692. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4693. */
  4694. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4695. var matrix = Matrix.Zero();
  4696. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4697. return matrix;
  4698. };
  4699. /**
  4700. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4701. */
  4702. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4703. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4704. var n = znear;
  4705. var f = zfar;
  4706. var t = 1.0 / (Math.tan(fov * 0.5));
  4707. var a = isVerticalFovFixed ? (t / aspect) : t;
  4708. var b = isVerticalFovFixed ? t : (t * aspect);
  4709. var c = (f + n) / (f - n);
  4710. var d = -2.0 * f * n / (f - n);
  4711. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  4712. };
  4713. /**
  4714. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4715. */
  4716. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4717. var matrix = Matrix.Zero();
  4718. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4719. return matrix;
  4720. };
  4721. /**
  4722. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4723. */
  4724. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4725. //alternatively this could be expressed as:
  4726. // m = PerspectiveFovLHToRef
  4727. // m[10] *= -1.0;
  4728. // m[11] *= -1.0;
  4729. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4730. var n = znear;
  4731. var f = zfar;
  4732. var t = 1.0 / (Math.tan(fov * 0.5));
  4733. var a = isVerticalFovFixed ? (t / aspect) : t;
  4734. var b = isVerticalFovFixed ? t : (t * aspect);
  4735. var c = -(f + n) / (f - n);
  4736. var d = -2 * f * n / (f - n);
  4737. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  4738. };
  4739. /**
  4740. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4741. */
  4742. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4743. if (rightHanded === void 0) { rightHanded = false; }
  4744. var rightHandedFactor = rightHanded ? -1 : 1;
  4745. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4746. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4747. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4748. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4749. var xScale = 2.0 / (leftTan + rightTan);
  4750. var yScale = 2.0 / (upTan + downTan);
  4751. result.m[0] = xScale;
  4752. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4753. result.m[5] = yScale;
  4754. result.m[6] = result.m[7] = 0.0;
  4755. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4756. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4757. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4758. result.m[10] = -zfar / (znear - zfar);
  4759. result.m[11] = 1.0 * rightHandedFactor;
  4760. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4761. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4762. // result.m[14] = (znear * zfar) / (znear - zfar);
  4763. result._markAsUpdated();
  4764. };
  4765. /**
  4766. * Returns the final transformation matrix : world * view * projection * viewport
  4767. */
  4768. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4769. var cw = viewport.width;
  4770. var ch = viewport.height;
  4771. var cx = viewport.x;
  4772. var cy = viewport.y;
  4773. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  4774. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4775. };
  4776. /**
  4777. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4778. */
  4779. Matrix.GetAsMatrix2x2 = function (matrix) {
  4780. return new Float32Array([
  4781. matrix.m[0], matrix.m[1],
  4782. matrix.m[4], matrix.m[5]
  4783. ]);
  4784. };
  4785. /**
  4786. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4787. */
  4788. Matrix.GetAsMatrix3x3 = function (matrix) {
  4789. return new Float32Array([
  4790. matrix.m[0], matrix.m[1], matrix.m[2],
  4791. matrix.m[4], matrix.m[5], matrix.m[6],
  4792. matrix.m[8], matrix.m[9], matrix.m[10]
  4793. ]);
  4794. };
  4795. /**
  4796. * Compute the transpose of the passed Matrix.
  4797. * Returns a new Matrix.
  4798. */
  4799. Matrix.Transpose = function (matrix) {
  4800. var result = new Matrix();
  4801. Matrix.TransposeToRef(matrix, result);
  4802. return result;
  4803. };
  4804. /**
  4805. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4806. */
  4807. Matrix.TransposeToRef = function (matrix, result) {
  4808. result.m[0] = matrix.m[0];
  4809. result.m[1] = matrix.m[4];
  4810. result.m[2] = matrix.m[8];
  4811. result.m[3] = matrix.m[12];
  4812. result.m[4] = matrix.m[1];
  4813. result.m[5] = matrix.m[5];
  4814. result.m[6] = matrix.m[9];
  4815. result.m[7] = matrix.m[13];
  4816. result.m[8] = matrix.m[2];
  4817. result.m[9] = matrix.m[6];
  4818. result.m[10] = matrix.m[10];
  4819. result.m[11] = matrix.m[14];
  4820. result.m[12] = matrix.m[3];
  4821. result.m[13] = matrix.m[7];
  4822. result.m[14] = matrix.m[11];
  4823. result.m[15] = matrix.m[15];
  4824. };
  4825. /**
  4826. * Returns a new Matrix as the reflection matrix across the passed plane.
  4827. */
  4828. Matrix.Reflection = function (plane) {
  4829. var matrix = new Matrix();
  4830. Matrix.ReflectionToRef(plane, matrix);
  4831. return matrix;
  4832. };
  4833. /**
  4834. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4835. */
  4836. Matrix.ReflectionToRef = function (plane, result) {
  4837. plane.normalize();
  4838. var x = plane.normal.x;
  4839. var y = plane.normal.y;
  4840. var z = plane.normal.z;
  4841. var temp = -2 * x;
  4842. var temp2 = -2 * y;
  4843. var temp3 = -2 * z;
  4844. result.m[0] = (temp * x) + 1;
  4845. result.m[1] = temp2 * x;
  4846. result.m[2] = temp3 * x;
  4847. result.m[3] = 0.0;
  4848. result.m[4] = temp * y;
  4849. result.m[5] = (temp2 * y) + 1;
  4850. result.m[6] = temp3 * y;
  4851. result.m[7] = 0.0;
  4852. result.m[8] = temp * z;
  4853. result.m[9] = temp2 * z;
  4854. result.m[10] = (temp3 * z) + 1;
  4855. result.m[11] = 0.0;
  4856. result.m[12] = temp * plane.d;
  4857. result.m[13] = temp2 * plane.d;
  4858. result.m[14] = temp3 * plane.d;
  4859. result.m[15] = 1.0;
  4860. result._markAsUpdated();
  4861. };
  4862. /**
  4863. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4864. */
  4865. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4866. result.m[0] = xaxis.x;
  4867. result.m[1] = xaxis.y;
  4868. result.m[2] = xaxis.z;
  4869. result.m[3] = 0.0;
  4870. result.m[4] = yaxis.x;
  4871. result.m[5] = yaxis.y;
  4872. result.m[6] = yaxis.z;
  4873. result.m[7] = 0.0;
  4874. result.m[8] = zaxis.x;
  4875. result.m[9] = zaxis.y;
  4876. result.m[10] = zaxis.z;
  4877. result.m[11] = 0.0;
  4878. result.m[12] = 0.0;
  4879. result.m[13] = 0.0;
  4880. result.m[14] = 0.0;
  4881. result.m[15] = 1.0;
  4882. result._markAsUpdated();
  4883. };
  4884. /**
  4885. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4886. */
  4887. Matrix.FromQuaternionToRef = function (quat, result) {
  4888. var xx = quat.x * quat.x;
  4889. var yy = quat.y * quat.y;
  4890. var zz = quat.z * quat.z;
  4891. var xy = quat.x * quat.y;
  4892. var zw = quat.z * quat.w;
  4893. var zx = quat.z * quat.x;
  4894. var yw = quat.y * quat.w;
  4895. var yz = quat.y * quat.z;
  4896. var xw = quat.x * quat.w;
  4897. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4898. result.m[1] = 2.0 * (xy + zw);
  4899. result.m[2] = 2.0 * (zx - yw);
  4900. result.m[3] = 0.0;
  4901. result.m[4] = 2.0 * (xy - zw);
  4902. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4903. result.m[6] = 2.0 * (yz + xw);
  4904. result.m[7] = 0.0;
  4905. result.m[8] = 2.0 * (zx + yw);
  4906. result.m[9] = 2.0 * (yz - xw);
  4907. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4908. result.m[11] = 0.0;
  4909. result.m[12] = 0.0;
  4910. result.m[13] = 0.0;
  4911. result.m[14] = 0.0;
  4912. result.m[15] = 1.0;
  4913. result._markAsUpdated();
  4914. };
  4915. Matrix._tempQuaternion = new Quaternion();
  4916. Matrix._xAxis = Vector3.Zero();
  4917. Matrix._yAxis = Vector3.Zero();
  4918. Matrix._zAxis = Vector3.Zero();
  4919. Matrix._updateFlagSeed = 0;
  4920. Matrix._identityReadOnly = Matrix.Identity();
  4921. return Matrix;
  4922. }());
  4923. BABYLON.Matrix = Matrix;
  4924. var Plane = /** @class */ (function () {
  4925. /**
  4926. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4927. */
  4928. function Plane(a, b, c, d) {
  4929. this.normal = new Vector3(a, b, c);
  4930. this.d = d;
  4931. }
  4932. /**
  4933. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4934. */
  4935. Plane.prototype.asArray = function () {
  4936. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4937. };
  4938. // Methods
  4939. /**
  4940. * Returns a new plane copied from the current Plane.
  4941. */
  4942. Plane.prototype.clone = function () {
  4943. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4944. };
  4945. /**
  4946. * Returns the string "Plane".
  4947. */
  4948. Plane.prototype.getClassName = function () {
  4949. return "Plane";
  4950. };
  4951. /**
  4952. * Returns the Plane hash code.
  4953. */
  4954. Plane.prototype.getHashCode = function () {
  4955. var hash = this.normal.getHashCode();
  4956. hash = (hash * 397) ^ (this.d || 0);
  4957. return hash;
  4958. };
  4959. /**
  4960. * Normalize the current Plane in place.
  4961. * Returns the updated Plane.
  4962. */
  4963. Plane.prototype.normalize = function () {
  4964. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4965. var magnitude = 0.0;
  4966. if (norm !== 0) {
  4967. magnitude = 1.0 / norm;
  4968. }
  4969. this.normal.x *= magnitude;
  4970. this.normal.y *= magnitude;
  4971. this.normal.z *= magnitude;
  4972. this.d *= magnitude;
  4973. return this;
  4974. };
  4975. /**
  4976. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4977. */
  4978. Plane.prototype.transform = function (transformation) {
  4979. var transposedMatrix = Matrix.Transpose(transformation);
  4980. var x = this.normal.x;
  4981. var y = this.normal.y;
  4982. var z = this.normal.z;
  4983. var d = this.d;
  4984. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4985. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4986. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4987. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4988. return new Plane(normalX, normalY, normalZ, finalD);
  4989. };
  4990. /**
  4991. * Returns the dot product (float) of the point coordinates and the plane normal.
  4992. */
  4993. Plane.prototype.dotCoordinate = function (point) {
  4994. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4995. };
  4996. /**
  4997. * Updates the current Plane from the plane defined by the three passed points.
  4998. * Returns the updated Plane.
  4999. */
  5000. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5001. var x1 = point2.x - point1.x;
  5002. var y1 = point2.y - point1.y;
  5003. var z1 = point2.z - point1.z;
  5004. var x2 = point3.x - point1.x;
  5005. var y2 = point3.y - point1.y;
  5006. var z2 = point3.z - point1.z;
  5007. var yz = (y1 * z2) - (z1 * y2);
  5008. var xz = (z1 * x2) - (x1 * z2);
  5009. var xy = (x1 * y2) - (y1 * x2);
  5010. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5011. var invPyth;
  5012. if (pyth !== 0) {
  5013. invPyth = 1.0 / pyth;
  5014. }
  5015. else {
  5016. invPyth = 0.0;
  5017. }
  5018. this.normal.x = yz * invPyth;
  5019. this.normal.y = xz * invPyth;
  5020. this.normal.z = xy * invPyth;
  5021. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5022. return this;
  5023. };
  5024. /**
  5025. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5026. */
  5027. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5028. var dot = Vector3.Dot(this.normal, direction);
  5029. return (dot <= epsilon);
  5030. };
  5031. /**
  5032. * Returns the signed distance (float) from the passed point to the Plane.
  5033. */
  5034. Plane.prototype.signedDistanceTo = function (point) {
  5035. return Vector3.Dot(point, this.normal) + this.d;
  5036. };
  5037. // Statics
  5038. /**
  5039. * Returns a new Plane from the passed array.
  5040. */
  5041. Plane.FromArray = function (array) {
  5042. return new Plane(array[0], array[1], array[2], array[3]);
  5043. };
  5044. /**
  5045. * Returns a new Plane defined by the three passed points.
  5046. */
  5047. Plane.FromPoints = function (point1, point2, point3) {
  5048. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5049. result.copyFromPoints(point1, point2, point3);
  5050. return result;
  5051. };
  5052. /**
  5053. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5054. * Note : the vector "normal" is updated because normalized.
  5055. */
  5056. Plane.FromPositionAndNormal = function (origin, normal) {
  5057. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5058. normal.normalize();
  5059. result.normal = normal;
  5060. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5061. return result;
  5062. };
  5063. /**
  5064. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5065. */
  5066. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5067. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5068. return Vector3.Dot(point, normal) + d;
  5069. };
  5070. return Plane;
  5071. }());
  5072. BABYLON.Plane = Plane;
  5073. var Viewport = /** @class */ (function () {
  5074. /**
  5075. * Creates a Viewport object located at (x, y) and sized (width, height).
  5076. */
  5077. function Viewport(x, y, width, height) {
  5078. this.x = x;
  5079. this.y = y;
  5080. this.width = width;
  5081. this.height = height;
  5082. }
  5083. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5084. if (renderWidthOrEngine.getRenderWidth) {
  5085. var engine = renderWidthOrEngine;
  5086. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5087. }
  5088. var renderWidth = renderWidthOrEngine;
  5089. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5090. };
  5091. /**
  5092. * Returns a new Viewport copied from the current one.
  5093. */
  5094. Viewport.prototype.clone = function () {
  5095. return new Viewport(this.x, this.y, this.width, this.height);
  5096. };
  5097. return Viewport;
  5098. }());
  5099. BABYLON.Viewport = Viewport;
  5100. var Frustum = /** @class */ (function () {
  5101. function Frustum() {
  5102. }
  5103. /**
  5104. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5105. */
  5106. Frustum.GetPlanes = function (transform) {
  5107. var frustumPlanes = [];
  5108. for (var index = 0; index < 6; index++) {
  5109. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5110. }
  5111. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5112. return frustumPlanes;
  5113. };
  5114. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5115. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5116. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5117. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5118. frustumPlane.d = transform.m[15] + transform.m[14];
  5119. frustumPlane.normalize();
  5120. };
  5121. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5122. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5123. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5124. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5125. frustumPlane.d = transform.m[15] - transform.m[14];
  5126. frustumPlane.normalize();
  5127. };
  5128. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5129. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5130. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5131. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5132. frustumPlane.d = transform.m[15] + transform.m[12];
  5133. frustumPlane.normalize();
  5134. };
  5135. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5136. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5137. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5138. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5139. frustumPlane.d = transform.m[15] - transform.m[12];
  5140. frustumPlane.normalize();
  5141. };
  5142. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5143. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5144. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5145. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5146. frustumPlane.d = transform.m[15] - transform.m[13];
  5147. frustumPlane.normalize();
  5148. };
  5149. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5150. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5151. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5152. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5153. frustumPlane.d = transform.m[15] + transform.m[13];
  5154. frustumPlane.normalize();
  5155. };
  5156. /**
  5157. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5158. */
  5159. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5160. // Near
  5161. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5162. // Far
  5163. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5164. // Left
  5165. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5166. // Right
  5167. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5168. // Top
  5169. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5170. // Bottom
  5171. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5172. };
  5173. return Frustum;
  5174. }());
  5175. BABYLON.Frustum = Frustum;
  5176. var Space;
  5177. (function (Space) {
  5178. Space[Space["LOCAL"] = 0] = "LOCAL";
  5179. Space[Space["WORLD"] = 1] = "WORLD";
  5180. Space[Space["BONE"] = 2] = "BONE";
  5181. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5182. var Axis = /** @class */ (function () {
  5183. function Axis() {
  5184. }
  5185. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5186. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5187. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5188. return Axis;
  5189. }());
  5190. BABYLON.Axis = Axis;
  5191. ;
  5192. var BezierCurve = /** @class */ (function () {
  5193. function BezierCurve() {
  5194. }
  5195. /**
  5196. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5197. */
  5198. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5199. // Extract X (which is equal to time here)
  5200. var f0 = 1 - 3 * x2 + 3 * x1;
  5201. var f1 = 3 * x2 - 6 * x1;
  5202. var f2 = 3 * x1;
  5203. var refinedT = t;
  5204. for (var i = 0; i < 5; i++) {
  5205. var refinedT2 = refinedT * refinedT;
  5206. var refinedT3 = refinedT2 * refinedT;
  5207. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5208. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5209. refinedT -= (x - t) * slope;
  5210. refinedT = Math.min(1, Math.max(0, refinedT));
  5211. }
  5212. // Resolve cubic bezier for the given x
  5213. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5214. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5215. Math.pow(refinedT, 3);
  5216. };
  5217. return BezierCurve;
  5218. }());
  5219. BABYLON.BezierCurve = BezierCurve;
  5220. var Orientation;
  5221. (function (Orientation) {
  5222. Orientation[Orientation["CW"] = 0] = "CW";
  5223. Orientation[Orientation["CCW"] = 1] = "CCW";
  5224. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5225. var Angle = /** @class */ (function () {
  5226. /**
  5227. * Creates an Angle object of "radians" radians (float).
  5228. */
  5229. function Angle(radians) {
  5230. var _this = this;
  5231. /**
  5232. * Returns the Angle value in degrees (float).
  5233. */
  5234. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5235. /**
  5236. * Returns the Angle value in radians (float).
  5237. */
  5238. this.radians = function () { return _this._radians; };
  5239. this._radians = radians;
  5240. if (this._radians < 0.0)
  5241. this._radians += (2.0 * Math.PI);
  5242. }
  5243. /**
  5244. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5245. */
  5246. Angle.BetweenTwoPoints = function (a, b) {
  5247. var delta = b.subtract(a);
  5248. var theta = Math.atan2(delta.y, delta.x);
  5249. return new Angle(theta);
  5250. };
  5251. /**
  5252. * Returns a new Angle object from the passed float in radians.
  5253. */
  5254. Angle.FromRadians = function (radians) {
  5255. return new Angle(radians);
  5256. };
  5257. /**
  5258. * Returns a new Angle object from the passed float in degrees.
  5259. */
  5260. Angle.FromDegrees = function (degrees) {
  5261. return new Angle(degrees * Math.PI / 180.0);
  5262. };
  5263. return Angle;
  5264. }());
  5265. BABYLON.Angle = Angle;
  5266. var Arc2 = /** @class */ (function () {
  5267. /**
  5268. * Creates an Arc object from the three passed points : start, middle and end.
  5269. */
  5270. function Arc2(startPoint, midPoint, endPoint) {
  5271. this.startPoint = startPoint;
  5272. this.midPoint = midPoint;
  5273. this.endPoint = endPoint;
  5274. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5275. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5276. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5277. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5278. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  5279. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5280. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5281. var a1 = this.startAngle.degrees();
  5282. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5283. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5284. // angles correction
  5285. if (a2 - a1 > +180.0)
  5286. a2 -= 360.0;
  5287. if (a2 - a1 < -180.0)
  5288. a2 += 360.0;
  5289. if (a3 - a2 > +180.0)
  5290. a3 -= 360.0;
  5291. if (a3 - a2 < -180.0)
  5292. a3 += 360.0;
  5293. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5294. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5295. }
  5296. return Arc2;
  5297. }());
  5298. BABYLON.Arc2 = Arc2;
  5299. var Path2 = /** @class */ (function () {
  5300. /**
  5301. * Creates a Path2 object from the starting 2D coordinates x and y.
  5302. */
  5303. function Path2(x, y) {
  5304. this._points = new Array();
  5305. this._length = 0.0;
  5306. this.closed = false;
  5307. this._points.push(new Vector2(x, y));
  5308. }
  5309. /**
  5310. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5311. * Returns the updated Path2.
  5312. */
  5313. Path2.prototype.addLineTo = function (x, y) {
  5314. if (this.closed) {
  5315. //Tools.Error("cannot add lines to closed paths");
  5316. return this;
  5317. }
  5318. var newPoint = new Vector2(x, y);
  5319. var previousPoint = this._points[this._points.length - 1];
  5320. this._points.push(newPoint);
  5321. this._length += newPoint.subtract(previousPoint).length();
  5322. return this;
  5323. };
  5324. /**
  5325. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  5326. * Returns the updated Path2.
  5327. */
  5328. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5329. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5330. if (this.closed) {
  5331. //Tools.Error("cannot add arcs to closed paths");
  5332. return this;
  5333. }
  5334. var startPoint = this._points[this._points.length - 1];
  5335. var midPoint = new Vector2(midX, midY);
  5336. var endPoint = new Vector2(endX, endY);
  5337. var arc = new Arc2(startPoint, midPoint, endPoint);
  5338. var increment = arc.angle.radians() / numberOfSegments;
  5339. if (arc.orientation === Orientation.CW)
  5340. increment *= -1;
  5341. var currentAngle = arc.startAngle.radians() + increment;
  5342. for (var i = 0; i < numberOfSegments; i++) {
  5343. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5344. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5345. this.addLineTo(x, y);
  5346. currentAngle += increment;
  5347. }
  5348. return this;
  5349. };
  5350. /**
  5351. * Closes the Path2.
  5352. * Returns the Path2.
  5353. */
  5354. Path2.prototype.close = function () {
  5355. this.closed = true;
  5356. return this;
  5357. };
  5358. /**
  5359. * Returns the Path2 total length (float).
  5360. */
  5361. Path2.prototype.length = function () {
  5362. var result = this._length;
  5363. if (!this.closed) {
  5364. var lastPoint = this._points[this._points.length - 1];
  5365. var firstPoint = this._points[0];
  5366. result += (firstPoint.subtract(lastPoint).length());
  5367. }
  5368. return result;
  5369. };
  5370. /**
  5371. * Returns the Path2 internal array of points.
  5372. */
  5373. Path2.prototype.getPoints = function () {
  5374. return this._points;
  5375. };
  5376. /**
  5377. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5378. */
  5379. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5380. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5381. //Tools.Error("normalized length position should be between 0 and 1.");
  5382. return Vector2.Zero();
  5383. }
  5384. var lengthPosition = normalizedLengthPosition * this.length();
  5385. var previousOffset = 0;
  5386. for (var i = 0; i < this._points.length; i++) {
  5387. var j = (i + 1) % this._points.length;
  5388. var a = this._points[i];
  5389. var b = this._points[j];
  5390. var bToA = b.subtract(a);
  5391. var nextOffset = (bToA.length() + previousOffset);
  5392. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5393. var dir = bToA.normalize();
  5394. var localOffset = lengthPosition - previousOffset;
  5395. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5396. }
  5397. previousOffset = nextOffset;
  5398. }
  5399. //Tools.Error("internal error");
  5400. return Vector2.Zero();
  5401. };
  5402. /**
  5403. * Returns a new Path2 starting at the coordinates (x, y).
  5404. */
  5405. Path2.StartingAt = function (x, y) {
  5406. return new Path2(x, y);
  5407. };
  5408. return Path2;
  5409. }());
  5410. BABYLON.Path2 = Path2;
  5411. var Path3D = /** @class */ (function () {
  5412. /**
  5413. * new Path3D(path, normal, raw)
  5414. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5415. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5416. * path : an array of Vector3, the curve axis of the Path3D
  5417. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5418. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5419. */
  5420. function Path3D(path, firstNormal, raw) {
  5421. if (firstNormal === void 0) { firstNormal = null; }
  5422. this.path = path;
  5423. this._curve = new Array();
  5424. this._distances = new Array();
  5425. this._tangents = new Array();
  5426. this._normals = new Array();
  5427. this._binormals = new Array();
  5428. for (var p = 0; p < path.length; p++) {
  5429. this._curve[p] = path[p].clone(); // hard copy
  5430. }
  5431. this._raw = raw || false;
  5432. this._compute(firstNormal);
  5433. }
  5434. /**
  5435. * Returns the Path3D array of successive Vector3 designing its curve.
  5436. */
  5437. Path3D.prototype.getCurve = function () {
  5438. return this._curve;
  5439. };
  5440. /**
  5441. * Returns an array populated with tangent vectors on each Path3D curve point.
  5442. */
  5443. Path3D.prototype.getTangents = function () {
  5444. return this._tangents;
  5445. };
  5446. /**
  5447. * Returns an array populated with normal vectors on each Path3D curve point.
  5448. */
  5449. Path3D.prototype.getNormals = function () {
  5450. return this._normals;
  5451. };
  5452. /**
  5453. * Returns an array populated with binormal vectors on each Path3D curve point.
  5454. */
  5455. Path3D.prototype.getBinormals = function () {
  5456. return this._binormals;
  5457. };
  5458. /**
  5459. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5460. */
  5461. Path3D.prototype.getDistances = function () {
  5462. return this._distances;
  5463. };
  5464. /**
  5465. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5466. * Returns the same object updated.
  5467. */
  5468. Path3D.prototype.update = function (path, firstNormal) {
  5469. if (firstNormal === void 0) { firstNormal = null; }
  5470. for (var p = 0; p < path.length; p++) {
  5471. this._curve[p].x = path[p].x;
  5472. this._curve[p].y = path[p].y;
  5473. this._curve[p].z = path[p].z;
  5474. }
  5475. this._compute(firstNormal);
  5476. return this;
  5477. };
  5478. // private function compute() : computes tangents, normals and binormals
  5479. Path3D.prototype._compute = function (firstNormal) {
  5480. var l = this._curve.length;
  5481. // first and last tangents
  5482. this._tangents[0] = this._getFirstNonNullVector(0);
  5483. if (!this._raw) {
  5484. this._tangents[0].normalize();
  5485. }
  5486. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5487. if (!this._raw) {
  5488. this._tangents[l - 1].normalize();
  5489. }
  5490. // normals and binormals at first point : arbitrary vector with _normalVector()
  5491. var tg0 = this._tangents[0];
  5492. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5493. this._normals[0] = pp0;
  5494. if (!this._raw) {
  5495. this._normals[0].normalize();
  5496. }
  5497. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5498. if (!this._raw) {
  5499. this._binormals[0].normalize();
  5500. }
  5501. this._distances[0] = 0.0;
  5502. // normals and binormals : next points
  5503. var prev; // previous vector (segment)
  5504. var cur; // current vector (segment)
  5505. var curTang; // current tangent
  5506. // previous normal
  5507. var prevBinor; // previous binormal
  5508. for (var i = 1; i < l; i++) {
  5509. // tangents
  5510. prev = this._getLastNonNullVector(i);
  5511. if (i < l - 1) {
  5512. cur = this._getFirstNonNullVector(i);
  5513. this._tangents[i] = prev.add(cur);
  5514. this._tangents[i].normalize();
  5515. }
  5516. this._distances[i] = this._distances[i - 1] + prev.length();
  5517. // normals and binormals
  5518. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5519. curTang = this._tangents[i];
  5520. prevBinor = this._binormals[i - 1];
  5521. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5522. if (!this._raw) {
  5523. this._normals[i].normalize();
  5524. }
  5525. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5526. if (!this._raw) {
  5527. this._binormals[i].normalize();
  5528. }
  5529. }
  5530. };
  5531. // private function getFirstNonNullVector(index)
  5532. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5533. Path3D.prototype._getFirstNonNullVector = function (index) {
  5534. var i = 1;
  5535. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5536. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5537. i++;
  5538. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5539. }
  5540. return nNVector;
  5541. };
  5542. // private function getLastNonNullVector(index)
  5543. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5544. Path3D.prototype._getLastNonNullVector = function (index) {
  5545. var i = 1;
  5546. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5547. while (nLVector.length() === 0 && index > i + 1) {
  5548. i++;
  5549. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5550. }
  5551. return nLVector;
  5552. };
  5553. // private function normalVector(v0, vt, va) :
  5554. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5555. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5556. Path3D.prototype._normalVector = function (v0, vt, va) {
  5557. var normal0;
  5558. var tgl = vt.length();
  5559. if (tgl === 0.0) {
  5560. tgl = 1.0;
  5561. }
  5562. if (va === undefined || va === null) {
  5563. var point;
  5564. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5565. point = new Vector3(0.0, -1.0, 0.0);
  5566. }
  5567. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5568. point = new Vector3(1.0, 0.0, 0.0);
  5569. }
  5570. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5571. point = new Vector3(0.0, 0.0, 1.0);
  5572. }
  5573. else {
  5574. point = Vector3.Zero();
  5575. }
  5576. normal0 = Vector3.Cross(vt, point);
  5577. }
  5578. else {
  5579. normal0 = Vector3.Cross(vt, va);
  5580. Vector3.CrossToRef(normal0, vt, normal0);
  5581. }
  5582. normal0.normalize();
  5583. return normal0;
  5584. };
  5585. return Path3D;
  5586. }());
  5587. BABYLON.Path3D = Path3D;
  5588. var Curve3 = /** @class */ (function () {
  5589. /**
  5590. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5591. * A Curve3 is designed from a series of successive Vector3.
  5592. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5593. */
  5594. function Curve3(points) {
  5595. this._length = 0.0;
  5596. this._points = points;
  5597. this._length = this._computeLength(points);
  5598. }
  5599. /**
  5600. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5601. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5602. * @param v1 (Vector3) the control point
  5603. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5604. * @param nbPoints (integer) the wanted number of points in the curve
  5605. */
  5606. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5607. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5608. var bez = new Array();
  5609. var equation = function (t, val0, val1, val2) {
  5610. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5611. return res;
  5612. };
  5613. for (var i = 0; i <= nbPoints; i++) {
  5614. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  5615. }
  5616. return new Curve3(bez);
  5617. };
  5618. /**
  5619. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5620. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5621. * @param v1 (Vector3) the first control point
  5622. * @param v2 (Vector3) the second control point
  5623. * @param v3 (Vector3) the end point of the Cubic Bezier
  5624. * @param nbPoints (integer) the wanted number of points in the curve
  5625. */
  5626. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5627. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5628. var bez = new Array();
  5629. var equation = function (t, val0, val1, val2, val3) {
  5630. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  5631. return res;
  5632. };
  5633. for (var i = 0; i <= nbPoints; i++) {
  5634. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  5635. }
  5636. return new Curve3(bez);
  5637. };
  5638. /**
  5639. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5640. * @param p1 (Vector3) the origin point of the Hermite Spline
  5641. * @param t1 (Vector3) the tangent vector at the origin point
  5642. * @param p2 (Vector3) the end point of the Hermite Spline
  5643. * @param t2 (Vector3) the tangent vector at the end point
  5644. * @param nbPoints (integer) the wanted number of points in the curve
  5645. */
  5646. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5647. var hermite = new Array();
  5648. var step = 1.0 / nbPoints;
  5649. for (var i = 0; i <= nbPoints; i++) {
  5650. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5651. }
  5652. return new Curve3(hermite);
  5653. };
  5654. /**
  5655. * Returns a Curve3 object along a CatmullRom Spline curve :
  5656. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5657. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5658. */
  5659. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5660. var totalPoints = new Array();
  5661. totalPoints.push(points[0].clone());
  5662. Array.prototype.push.apply(totalPoints, points);
  5663. totalPoints.push(points[points.length - 1].clone());
  5664. var catmullRom = new Array();
  5665. var step = 1.0 / nbPoints;
  5666. var amount = 0.0;
  5667. for (var i = 0; i < totalPoints.length - 3; i++) {
  5668. amount = 0;
  5669. for (var c = 0; c < nbPoints; c++) {
  5670. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5671. amount += step;
  5672. }
  5673. }
  5674. i--;
  5675. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5676. return new Curve3(catmullRom);
  5677. };
  5678. /**
  5679. * Returns the Curve3 stored array of successive Vector3
  5680. */
  5681. Curve3.prototype.getPoints = function () {
  5682. return this._points;
  5683. };
  5684. /**
  5685. * Returns the computed length (float) of the curve.
  5686. */
  5687. Curve3.prototype.length = function () {
  5688. return this._length;
  5689. };
  5690. /**
  5691. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5692. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5693. * curveA and curveB keep unchanged.
  5694. */
  5695. Curve3.prototype.continue = function (curve) {
  5696. var lastPoint = this._points[this._points.length - 1];
  5697. var continuedPoints = this._points.slice();
  5698. var curvePoints = curve.getPoints();
  5699. for (var i = 1; i < curvePoints.length; i++) {
  5700. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5701. }
  5702. var continuedCurve = new Curve3(continuedPoints);
  5703. return continuedCurve;
  5704. };
  5705. Curve3.prototype._computeLength = function (path) {
  5706. var l = 0;
  5707. for (var i = 1; i < path.length; i++) {
  5708. l += (path[i].subtract(path[i - 1])).length();
  5709. }
  5710. return l;
  5711. };
  5712. return Curve3;
  5713. }());
  5714. BABYLON.Curve3 = Curve3;
  5715. // Vertex formats
  5716. var PositionNormalVertex = /** @class */ (function () {
  5717. function PositionNormalVertex(position, normal) {
  5718. if (position === void 0) { position = Vector3.Zero(); }
  5719. if (normal === void 0) { normal = Vector3.Up(); }
  5720. this.position = position;
  5721. this.normal = normal;
  5722. }
  5723. PositionNormalVertex.prototype.clone = function () {
  5724. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5725. };
  5726. return PositionNormalVertex;
  5727. }());
  5728. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5729. var PositionNormalTextureVertex = /** @class */ (function () {
  5730. function PositionNormalTextureVertex(position, normal, uv) {
  5731. if (position === void 0) { position = Vector3.Zero(); }
  5732. if (normal === void 0) { normal = Vector3.Up(); }
  5733. if (uv === void 0) { uv = Vector2.Zero(); }
  5734. this.position = position;
  5735. this.normal = normal;
  5736. this.uv = uv;
  5737. }
  5738. PositionNormalTextureVertex.prototype.clone = function () {
  5739. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5740. };
  5741. return PositionNormalTextureVertex;
  5742. }());
  5743. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5744. // Temporary pre-allocated objects for engine internal use
  5745. // usage in any internal function :
  5746. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5747. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5748. var Tmp = /** @class */ (function () {
  5749. function Tmp() {
  5750. }
  5751. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5752. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5753. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5754. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5755. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5756. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5757. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5758. Matrix.Zero(), Matrix.Zero(),
  5759. Matrix.Zero(), Matrix.Zero(),
  5760. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5761. return Tmp;
  5762. }());
  5763. BABYLON.Tmp = Tmp;
  5764. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5765. var MathTmp = /** @class */ (function () {
  5766. function MathTmp() {
  5767. }
  5768. MathTmp.Vector3 = [Vector3.Zero()];
  5769. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5770. MathTmp.Quaternion = [Quaternion.Zero()];
  5771. return MathTmp;
  5772. }());
  5773. })(BABYLON || (BABYLON = {}));
  5774. //# sourceMappingURL=babylon.math.js.map
  5775. var BABYLON;
  5776. (function (BABYLON) {
  5777. var Scalar = /** @class */ (function () {
  5778. function Scalar() {
  5779. }
  5780. /**
  5781. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5782. */
  5783. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5784. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5785. var num = a - b;
  5786. return -epsilon <= num && num <= epsilon;
  5787. };
  5788. /**
  5789. * Returns a string : the upper case translation of the number i to hexadecimal.
  5790. */
  5791. Scalar.ToHex = function (i) {
  5792. var str = i.toString(16);
  5793. if (i <= 15) {
  5794. return ("0" + str).toUpperCase();
  5795. }
  5796. return str.toUpperCase();
  5797. };
  5798. /**
  5799. * Returns -1 if value is negative and +1 is value is positive.
  5800. * Returns the value itself if it's equal to zero.
  5801. */
  5802. Scalar.Sign = function (value) {
  5803. value = +value; // convert to a number
  5804. if (value === 0 || isNaN(value))
  5805. return value;
  5806. return value > 0 ? 1 : -1;
  5807. };
  5808. /**
  5809. * Returns the value itself if it's between min and max.
  5810. * Returns min if the value is lower than min.
  5811. * Returns max if the value is greater than max.
  5812. */
  5813. Scalar.Clamp = function (value, min, max) {
  5814. if (min === void 0) { min = 0; }
  5815. if (max === void 0) { max = 1; }
  5816. return Math.min(max, Math.max(min, value));
  5817. };
  5818. /**
  5819. * Returns the log2 of value.
  5820. */
  5821. Scalar.Log2 = function (value) {
  5822. return Math.log(value) * Math.LOG2E;
  5823. };
  5824. /**
  5825. * Loops the value, so that it is never larger than length and never smaller than 0.
  5826. *
  5827. * This is similar to the modulo operator but it works with floating point numbers.
  5828. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5829. * With t = 5 and length = 2.5, the result would be 0.0.
  5830. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5831. */
  5832. Scalar.Repeat = function (value, length) {
  5833. return value - Math.floor(value / length) * length;
  5834. };
  5835. /**
  5836. * Normalize the value between 0.0 and 1.0 using min and max values
  5837. */
  5838. Scalar.Normalize = function (value, min, max) {
  5839. return (value - min) / (max - min);
  5840. };
  5841. /**
  5842. * Denormalize the value from 0.0 and 1.0 using min and max values
  5843. */
  5844. Scalar.Denormalize = function (normalized, min, max) {
  5845. return (normalized * (max - min) + min);
  5846. };
  5847. /**
  5848. * Calculates the shortest difference between two given angles given in degrees.
  5849. */
  5850. Scalar.DeltaAngle = function (current, target) {
  5851. var num = Scalar.Repeat(target - current, 360.0);
  5852. if (num > 180.0) {
  5853. num -= 360.0;
  5854. }
  5855. return num;
  5856. };
  5857. /**
  5858. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5859. *
  5860. * The returned value will move back and forth between 0 and length
  5861. */
  5862. Scalar.PingPong = function (tx, length) {
  5863. var t = Scalar.Repeat(tx, length * 2.0);
  5864. return length - Math.abs(t - length);
  5865. };
  5866. /**
  5867. * Interpolates between min and max with smoothing at the limits.
  5868. *
  5869. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5870. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5871. */
  5872. Scalar.SmoothStep = function (from, to, tx) {
  5873. var t = Scalar.Clamp(tx);
  5874. t = -2.0 * t * t * t + 3.0 * t * t;
  5875. return to * t + from * (1.0 - t);
  5876. };
  5877. /**
  5878. * Moves a value current towards target.
  5879. *
  5880. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5881. * Negative values of maxDelta pushes the value away from target.
  5882. */
  5883. Scalar.MoveTowards = function (current, target, maxDelta) {
  5884. var result = 0;
  5885. if (Math.abs(target - current) <= maxDelta) {
  5886. result = target;
  5887. }
  5888. else {
  5889. result = current + Scalar.Sign(target - current) * maxDelta;
  5890. }
  5891. return result;
  5892. };
  5893. /**
  5894. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5895. *
  5896. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5897. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5898. */
  5899. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5900. var num = Scalar.DeltaAngle(current, target);
  5901. var result = 0;
  5902. if (-maxDelta < num && num < maxDelta) {
  5903. result = target;
  5904. }
  5905. else {
  5906. target = current + num;
  5907. result = Scalar.MoveTowards(current, target, maxDelta);
  5908. }
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5913. */
  5914. Scalar.Lerp = function (start, end, amount) {
  5915. return start + ((end - start) * amount);
  5916. };
  5917. /**
  5918. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5919. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5920. */
  5921. Scalar.LerpAngle = function (start, end, amount) {
  5922. var num = Scalar.Repeat(end - start, 360.0);
  5923. if (num > 180.0) {
  5924. num -= 360.0;
  5925. }
  5926. return start + num * Scalar.Clamp(amount);
  5927. };
  5928. /**
  5929. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5930. */
  5931. Scalar.InverseLerp = function (a, b, value) {
  5932. var result = 0;
  5933. if (a != b) {
  5934. result = Scalar.Clamp((value - a) / (b - a));
  5935. }
  5936. else {
  5937. result = 0.0;
  5938. }
  5939. return result;
  5940. };
  5941. /**
  5942. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5943. */
  5944. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5945. var squared = amount * amount;
  5946. var cubed = amount * squared;
  5947. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5948. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5949. var part3 = (cubed - (2.0 * squared)) + amount;
  5950. var part4 = cubed - squared;
  5951. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5952. };
  5953. /**
  5954. * Returns a random float number between and min and max values
  5955. */
  5956. Scalar.RandomRange = function (min, max) {
  5957. if (min === max)
  5958. return min;
  5959. return ((Math.random() * (max - min)) + min);
  5960. };
  5961. /**
  5962. * This function returns percentage of a number in a given range.
  5963. *
  5964. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5965. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5966. */
  5967. Scalar.RangeToPercent = function (number, min, max) {
  5968. return ((number - min) / (max - min));
  5969. };
  5970. /**
  5971. * This function returns number that corresponds to the percentage in a given range.
  5972. *
  5973. * PercentToRange(0.34,0,100) will return 34.
  5974. */
  5975. Scalar.PercentToRange = function (percent, min, max) {
  5976. return ((max - min) * percent + min);
  5977. };
  5978. /**
  5979. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5980. * @param angle The angle to normalize in radian.
  5981. * @return The converted angle.
  5982. */
  5983. Scalar.NormalizeRadians = function (angle) {
  5984. // More precise but slower version kept for reference.
  5985. // angle = angle % Tools.TwoPi;
  5986. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5987. //if (angle > Math.PI) {
  5988. // angle -= Tools.TwoPi;
  5989. //}
  5990. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5991. return angle;
  5992. };
  5993. /**
  5994. * Two pi constants convenient for computation.
  5995. */
  5996. Scalar.TwoPi = Math.PI * 2;
  5997. return Scalar;
  5998. }());
  5999. BABYLON.Scalar = Scalar;
  6000. })(BABYLON || (BABYLON = {}));
  6001. //# sourceMappingURL=babylon.math.scalar.js.map
  6002. //# sourceMappingURL=babylon.mixins.js.map
  6003. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6004. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6005. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6006. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6007. //# sourceMappingURL=babylon.webgl2.js.map
  6008. var BABYLON;
  6009. (function (BABYLON) {
  6010. var __decoratorInitialStore = {};
  6011. var __mergedStore = {};
  6012. var _copySource = function (creationFunction, source, instanciate) {
  6013. var destination = creationFunction();
  6014. // Tags
  6015. if (BABYLON.Tags) {
  6016. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6017. }
  6018. var classStore = getMergedStore(destination);
  6019. // Properties
  6020. for (var property in classStore) {
  6021. var propertyDescriptor = classStore[property];
  6022. var sourceProperty = source[property];
  6023. var propertyType = propertyDescriptor.type;
  6024. if (sourceProperty !== undefined && sourceProperty !== null) {
  6025. switch (propertyType) {
  6026. case 0: // Value
  6027. case 6:// Mesh reference
  6028. destination[property] = sourceProperty;
  6029. break;
  6030. case 1:// Texture
  6031. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6032. break;
  6033. case 2: // Color3
  6034. case 3: // FresnelParameters
  6035. case 4: // Vector2
  6036. case 5: // Vector3
  6037. case 7: // Color Curves
  6038. case 10:// Quaternion
  6039. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6040. break;
  6041. }
  6042. }
  6043. }
  6044. return destination;
  6045. };
  6046. function getDirectStore(target) {
  6047. var classKey = target.getClassName();
  6048. if (!__decoratorInitialStore[classKey]) {
  6049. __decoratorInitialStore[classKey] = {};
  6050. }
  6051. return __decoratorInitialStore[classKey];
  6052. }
  6053. /**
  6054. * Return the list of properties flagged as serializable
  6055. * @param target: host object
  6056. */
  6057. function getMergedStore(target) {
  6058. var classKey = target.getClassName();
  6059. if (__mergedStore[classKey]) {
  6060. return __mergedStore[classKey];
  6061. }
  6062. __mergedStore[classKey] = {};
  6063. var store = __mergedStore[classKey];
  6064. var currentTarget = target;
  6065. var currentKey = classKey;
  6066. while (currentKey) {
  6067. var initialStore = __decoratorInitialStore[currentKey];
  6068. for (var property in initialStore) {
  6069. store[property] = initialStore[property];
  6070. }
  6071. var parent_1 = void 0;
  6072. var done = false;
  6073. do {
  6074. parent_1 = Object.getPrototypeOf(currentTarget);
  6075. if (!parent_1.getClassName) {
  6076. done = true;
  6077. break;
  6078. }
  6079. if (parent_1.getClassName() !== currentKey) {
  6080. break;
  6081. }
  6082. currentTarget = parent_1;
  6083. } while (parent_1);
  6084. if (done) {
  6085. break;
  6086. }
  6087. currentKey = parent_1.getClassName();
  6088. currentTarget = parent_1;
  6089. }
  6090. return store;
  6091. }
  6092. function generateSerializableMember(type, sourceName) {
  6093. return function (target, propertyKey) {
  6094. var classStore = getDirectStore(target);
  6095. if (!classStore[propertyKey]) {
  6096. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6097. }
  6098. };
  6099. }
  6100. function generateExpandMember(setCallback, targetKey) {
  6101. if (targetKey === void 0) { targetKey = null; }
  6102. return function (target, propertyKey) {
  6103. var key = targetKey || ("_" + propertyKey);
  6104. Object.defineProperty(target, propertyKey, {
  6105. get: function () {
  6106. return this[key];
  6107. },
  6108. set: function (value) {
  6109. if (this[key] === value) {
  6110. return;
  6111. }
  6112. this[key] = value;
  6113. target[setCallback].apply(this);
  6114. },
  6115. enumerable: true,
  6116. configurable: true
  6117. });
  6118. };
  6119. }
  6120. function expandToProperty(callback, targetKey) {
  6121. if (targetKey === void 0) { targetKey = null; }
  6122. return generateExpandMember(callback, targetKey);
  6123. }
  6124. BABYLON.expandToProperty = expandToProperty;
  6125. function serialize(sourceName) {
  6126. return generateSerializableMember(0, sourceName); // value member
  6127. }
  6128. BABYLON.serialize = serialize;
  6129. function serializeAsTexture(sourceName) {
  6130. return generateSerializableMember(1, sourceName); // texture member
  6131. }
  6132. BABYLON.serializeAsTexture = serializeAsTexture;
  6133. function serializeAsColor3(sourceName) {
  6134. return generateSerializableMember(2, sourceName); // color3 member
  6135. }
  6136. BABYLON.serializeAsColor3 = serializeAsColor3;
  6137. function serializeAsFresnelParameters(sourceName) {
  6138. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6139. }
  6140. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6141. function serializeAsVector2(sourceName) {
  6142. return generateSerializableMember(4, sourceName); // vector2 member
  6143. }
  6144. BABYLON.serializeAsVector2 = serializeAsVector2;
  6145. function serializeAsVector3(sourceName) {
  6146. return generateSerializableMember(5, sourceName); // vector3 member
  6147. }
  6148. BABYLON.serializeAsVector3 = serializeAsVector3;
  6149. function serializeAsMeshReference(sourceName) {
  6150. return generateSerializableMember(6, sourceName); // mesh reference member
  6151. }
  6152. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6153. function serializeAsColorCurves(sourceName) {
  6154. return generateSerializableMember(7, sourceName); // color curves
  6155. }
  6156. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6157. function serializeAsColor4(sourceName) {
  6158. return generateSerializableMember(8, sourceName); // color 4
  6159. }
  6160. BABYLON.serializeAsColor4 = serializeAsColor4;
  6161. function serializeAsImageProcessingConfiguration(sourceName) {
  6162. return generateSerializableMember(9, sourceName); // image processing
  6163. }
  6164. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6165. function serializeAsQuaternion(sourceName) {
  6166. return generateSerializableMember(10, sourceName); // quaternion member
  6167. }
  6168. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6169. var SerializationHelper = /** @class */ (function () {
  6170. function SerializationHelper() {
  6171. }
  6172. SerializationHelper.Serialize = function (entity, serializationObject) {
  6173. if (!serializationObject) {
  6174. serializationObject = {};
  6175. }
  6176. // Tags
  6177. if (BABYLON.Tags) {
  6178. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6179. }
  6180. var serializedProperties = getMergedStore(entity);
  6181. // Properties
  6182. for (var property in serializedProperties) {
  6183. var propertyDescriptor = serializedProperties[property];
  6184. var targetPropertyName = propertyDescriptor.sourceName || property;
  6185. var propertyType = propertyDescriptor.type;
  6186. var sourceProperty = entity[property];
  6187. if (sourceProperty !== undefined && sourceProperty !== null) {
  6188. switch (propertyType) {
  6189. case 0:// Value
  6190. serializationObject[targetPropertyName] = sourceProperty;
  6191. break;
  6192. case 1:// Texture
  6193. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6194. break;
  6195. case 2:// Color3
  6196. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6197. break;
  6198. case 3:// FresnelParameters
  6199. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6200. break;
  6201. case 4:// Vector2
  6202. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6203. break;
  6204. case 5:// Vector3
  6205. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6206. break;
  6207. case 6:// Mesh reference
  6208. serializationObject[targetPropertyName] = sourceProperty.id;
  6209. break;
  6210. case 7:// Color Curves
  6211. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6212. break;
  6213. case 8:// Color 4
  6214. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6215. break;
  6216. case 9:// Image Processing
  6217. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6218. break;
  6219. }
  6220. }
  6221. }
  6222. return serializationObject;
  6223. };
  6224. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6225. if (rootUrl === void 0) { rootUrl = null; }
  6226. var destination = creationFunction();
  6227. if (!rootUrl) {
  6228. rootUrl = "";
  6229. }
  6230. // Tags
  6231. if (BABYLON.Tags) {
  6232. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6233. }
  6234. var classStore = getMergedStore(destination);
  6235. // Properties
  6236. for (var property in classStore) {
  6237. var propertyDescriptor = classStore[property];
  6238. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6239. var propertyType = propertyDescriptor.type;
  6240. if (sourceProperty !== undefined && sourceProperty !== null) {
  6241. var dest = destination;
  6242. switch (propertyType) {
  6243. case 0:// Value
  6244. dest[property] = sourceProperty;
  6245. break;
  6246. case 1:// Texture
  6247. if (scene) {
  6248. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6249. }
  6250. break;
  6251. case 2:// Color3
  6252. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6253. break;
  6254. case 3:// FresnelParameters
  6255. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6256. break;
  6257. case 4:// Vector2
  6258. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6259. break;
  6260. case 5:// Vector3
  6261. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6262. break;
  6263. case 6:// Mesh reference
  6264. if (scene) {
  6265. dest[property] = scene.getLastMeshByID(sourceProperty);
  6266. }
  6267. break;
  6268. case 7:// Color Curves
  6269. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6270. break;
  6271. case 8:// Color 4
  6272. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6273. break;
  6274. case 9:// Image Processing
  6275. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6276. break;
  6277. }
  6278. }
  6279. }
  6280. return destination;
  6281. };
  6282. SerializationHelper.Clone = function (creationFunction, source) {
  6283. return _copySource(creationFunction, source, false);
  6284. };
  6285. SerializationHelper.Instanciate = function (creationFunction, source) {
  6286. return _copySource(creationFunction, source, true);
  6287. };
  6288. return SerializationHelper;
  6289. }());
  6290. BABYLON.SerializationHelper = SerializationHelper;
  6291. })(BABYLON || (BABYLON = {}));
  6292. //# sourceMappingURL=babylon.decorators.js.map
  6293. var BABYLON;
  6294. (function (BABYLON) {
  6295. /**
  6296. * A class serves as a medium between the observable and its observers
  6297. */
  6298. var EventState = /** @class */ (function () {
  6299. /**
  6300. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6301. */
  6302. function EventState(mask, skipNextObservers, target, currentTarget) {
  6303. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6304. this.initalize(mask, skipNextObservers, target, currentTarget);
  6305. }
  6306. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6307. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6308. this.mask = mask;
  6309. this.skipNextObservers = skipNextObservers;
  6310. this.target = target;
  6311. this.currentTarget = currentTarget;
  6312. return this;
  6313. };
  6314. return EventState;
  6315. }());
  6316. BABYLON.EventState = EventState;
  6317. /**
  6318. * Represent an Observer registered to a given Observable object.
  6319. */
  6320. var Observer = /** @class */ (function () {
  6321. function Observer(callback, mask, scope) {
  6322. if (scope === void 0) { scope = null; }
  6323. this.callback = callback;
  6324. this.mask = mask;
  6325. this.scope = scope;
  6326. }
  6327. return Observer;
  6328. }());
  6329. BABYLON.Observer = Observer;
  6330. /**
  6331. * Represent a list of observers registered to multiple Observables object.
  6332. */
  6333. var MultiObserver = /** @class */ (function () {
  6334. function MultiObserver() {
  6335. }
  6336. MultiObserver.prototype.dispose = function () {
  6337. if (this._observers && this._observables) {
  6338. for (var index = 0; index < this._observers.length; index++) {
  6339. this._observables[index].remove(this._observers[index]);
  6340. }
  6341. }
  6342. this._observers = null;
  6343. this._observables = null;
  6344. };
  6345. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6346. if (mask === void 0) { mask = -1; }
  6347. if (scope === void 0) { scope = null; }
  6348. var result = new MultiObserver();
  6349. result._observers = new Array();
  6350. result._observables = observables;
  6351. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6352. var observable = observables_1[_i];
  6353. var observer = observable.add(callback, mask, false, scope);
  6354. if (observer) {
  6355. result._observers.push(observer);
  6356. }
  6357. }
  6358. return result;
  6359. };
  6360. return MultiObserver;
  6361. }());
  6362. BABYLON.MultiObserver = MultiObserver;
  6363. /**
  6364. * The Observable class is a simple implementation of the Observable pattern.
  6365. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  6366. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6367. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  6368. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  6369. */
  6370. var Observable = /** @class */ (function () {
  6371. function Observable(onObserverAdded) {
  6372. this._observers = new Array();
  6373. this._eventState = new EventState(0);
  6374. if (onObserverAdded) {
  6375. this._onObserverAdded = onObserverAdded;
  6376. }
  6377. }
  6378. /**
  6379. * Create a new Observer with the specified callback
  6380. * @param callback the callback that will be executed for that Observer
  6381. * @param mask the mask used to filter observers
  6382. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  6383. * @param scope optional scope for the callback to be called from
  6384. */
  6385. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6386. if (mask === void 0) { mask = -1; }
  6387. if (insertFirst === void 0) { insertFirst = false; }
  6388. if (scope === void 0) { scope = null; }
  6389. if (!callback) {
  6390. return null;
  6391. }
  6392. var observer = new Observer(callback, mask, scope);
  6393. if (insertFirst) {
  6394. this._observers.unshift(observer);
  6395. }
  6396. else {
  6397. this._observers.push(observer);
  6398. }
  6399. if (this._onObserverAdded) {
  6400. this._onObserverAdded(observer);
  6401. }
  6402. return observer;
  6403. };
  6404. /**
  6405. * Remove an Observer from the Observable object
  6406. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6407. */
  6408. Observable.prototype.remove = function (observer) {
  6409. if (!observer) {
  6410. return false;
  6411. }
  6412. var index = this._observers.indexOf(observer);
  6413. if (index !== -1) {
  6414. this._observers.splice(index, 1);
  6415. return true;
  6416. }
  6417. return false;
  6418. };
  6419. /**
  6420. * Remove a callback from the Observable object
  6421. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6422. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6423. */
  6424. Observable.prototype.removeCallback = function (callback, scope) {
  6425. for (var index = 0; index < this._observers.length; index++) {
  6426. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6427. this._observers.splice(index, 1);
  6428. return true;
  6429. }
  6430. }
  6431. return false;
  6432. };
  6433. /**
  6434. * Notify all Observers by calling their respective callback with the given data
  6435. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6436. * @param eventData
  6437. * @param mask
  6438. */
  6439. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6440. if (mask === void 0) { mask = -1; }
  6441. if (!this._observers.length) {
  6442. return true;
  6443. }
  6444. var state = this._eventState;
  6445. state.mask = mask;
  6446. state.target = target;
  6447. state.currentTarget = currentTarget;
  6448. state.skipNextObservers = false;
  6449. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6450. var obs = _a[_i];
  6451. if (obs.mask & mask) {
  6452. if (obs.scope) {
  6453. obs.callback.apply(obs.scope, [eventData, state]);
  6454. }
  6455. else {
  6456. obs.callback(eventData, state);
  6457. }
  6458. }
  6459. if (state.skipNextObservers) {
  6460. return false;
  6461. }
  6462. }
  6463. return true;
  6464. };
  6465. /**
  6466. * Notify a specific observer
  6467. * @param eventData
  6468. * @param mask
  6469. */
  6470. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6471. if (mask === void 0) { mask = -1; }
  6472. var state = this._eventState;
  6473. state.mask = mask;
  6474. state.skipNextObservers = false;
  6475. observer.callback(eventData, state);
  6476. };
  6477. /**
  6478. * return true is the Observable has at least one Observer registered
  6479. */
  6480. Observable.prototype.hasObservers = function () {
  6481. return this._observers.length > 0;
  6482. };
  6483. /**
  6484. * Clear the list of observers
  6485. */
  6486. Observable.prototype.clear = function () {
  6487. this._observers = new Array();
  6488. this._onObserverAdded = null;
  6489. };
  6490. /**
  6491. * Clone the current observable
  6492. */
  6493. Observable.prototype.clone = function () {
  6494. var result = new Observable();
  6495. result._observers = this._observers.slice(0);
  6496. return result;
  6497. };
  6498. /**
  6499. * Does this observable handles observer registered with a given mask
  6500. * @param {number} trigger - the mask to be tested
  6501. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6502. **/
  6503. Observable.prototype.hasSpecificMask = function (mask) {
  6504. if (mask === void 0) { mask = -1; }
  6505. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6506. var obs = _a[_i];
  6507. if (obs.mask & mask || obs.mask === mask) {
  6508. return true;
  6509. }
  6510. }
  6511. return false;
  6512. };
  6513. return Observable;
  6514. }());
  6515. BABYLON.Observable = Observable;
  6516. })(BABYLON || (BABYLON = {}));
  6517. //# sourceMappingURL=babylon.observable.js.map
  6518. var BABYLON;
  6519. (function (BABYLON) {
  6520. var SmartArray = /** @class */ (function () {
  6521. function SmartArray(capacity) {
  6522. this.length = 0;
  6523. this.data = new Array(capacity);
  6524. this._id = SmartArray._GlobalId++;
  6525. }
  6526. SmartArray.prototype.push = function (value) {
  6527. this.data[this.length++] = value;
  6528. if (this.length > this.data.length) {
  6529. this.data.length *= 2;
  6530. }
  6531. };
  6532. SmartArray.prototype.forEach = function (func) {
  6533. for (var index = 0; index < this.length; index++) {
  6534. func(this.data[index]);
  6535. }
  6536. };
  6537. SmartArray.prototype.sort = function (compareFn) {
  6538. this.data.sort(compareFn);
  6539. };
  6540. SmartArray.prototype.reset = function () {
  6541. this.length = 0;
  6542. };
  6543. SmartArray.prototype.dispose = function () {
  6544. this.reset();
  6545. if (this.data) {
  6546. this.data.length = 0;
  6547. this.data = [];
  6548. }
  6549. };
  6550. SmartArray.prototype.concat = function (array) {
  6551. if (array.length === 0) {
  6552. return;
  6553. }
  6554. if (this.length + array.length > this.data.length) {
  6555. this.data.length = (this.length + array.length) * 2;
  6556. }
  6557. for (var index = 0; index < array.length; index++) {
  6558. this.data[this.length++] = (array.data || array)[index];
  6559. }
  6560. };
  6561. SmartArray.prototype.indexOf = function (value) {
  6562. var position = this.data.indexOf(value);
  6563. if (position >= this.length) {
  6564. return -1;
  6565. }
  6566. return position;
  6567. };
  6568. SmartArray.prototype.contains = function (value) {
  6569. return this.data.indexOf(value) !== -1;
  6570. };
  6571. // Statics
  6572. SmartArray._GlobalId = 0;
  6573. return SmartArray;
  6574. }());
  6575. BABYLON.SmartArray = SmartArray;
  6576. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6577. __extends(SmartArrayNoDuplicate, _super);
  6578. function SmartArrayNoDuplicate() {
  6579. var _this = _super !== null && _super.apply(this, arguments) || this;
  6580. _this._duplicateId = 0;
  6581. return _this;
  6582. }
  6583. SmartArrayNoDuplicate.prototype.push = function (value) {
  6584. _super.prototype.push.call(this, value);
  6585. if (!value.__smartArrayFlags) {
  6586. value.__smartArrayFlags = {};
  6587. }
  6588. value.__smartArrayFlags[this._id] = this._duplicateId;
  6589. };
  6590. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6591. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6592. return false;
  6593. }
  6594. this.push(value);
  6595. return true;
  6596. };
  6597. SmartArrayNoDuplicate.prototype.reset = function () {
  6598. _super.prototype.reset.call(this);
  6599. this._duplicateId++;
  6600. };
  6601. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6602. if (array.length === 0) {
  6603. return;
  6604. }
  6605. if (this.length + array.length > this.data.length) {
  6606. this.data.length = (this.length + array.length) * 2;
  6607. }
  6608. for (var index = 0; index < array.length; index++) {
  6609. var item = (array.data || array)[index];
  6610. this.pushNoDuplicate(item);
  6611. }
  6612. };
  6613. return SmartArrayNoDuplicate;
  6614. }(SmartArray));
  6615. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6616. })(BABYLON || (BABYLON = {}));
  6617. //# sourceMappingURL=babylon.smartArray.js.map
  6618. var BABYLON;
  6619. (function (BABYLON) {
  6620. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6621. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6622. var LoadFileError = /** @class */ (function (_super) {
  6623. __extends(LoadFileError, _super);
  6624. function LoadFileError(message, request) {
  6625. var _this = _super.call(this, message) || this;
  6626. _this.request = request;
  6627. _this.name = "LoadFileError";
  6628. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6629. return _this;
  6630. }
  6631. // Polyfill for Object.setPrototypeOf if necessary.
  6632. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6633. return LoadFileError;
  6634. }(Error));
  6635. BABYLON.LoadFileError = LoadFileError;
  6636. var RetryStrategy = /** @class */ (function () {
  6637. function RetryStrategy() {
  6638. }
  6639. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6640. if (maxRetries === void 0) { maxRetries = 3; }
  6641. if (baseInterval === void 0) { baseInterval = 500; }
  6642. return function (url, request, retryIndex) {
  6643. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6644. return -1;
  6645. }
  6646. return Math.pow(2, retryIndex) * baseInterval;
  6647. };
  6648. };
  6649. return RetryStrategy;
  6650. }());
  6651. BABYLON.RetryStrategy = RetryStrategy;
  6652. // Screenshots
  6653. var screenshotCanvas;
  6654. var cloneValue = function (source, destinationObject) {
  6655. if (!source)
  6656. return null;
  6657. if (source instanceof BABYLON.Mesh) {
  6658. return null;
  6659. }
  6660. if (source instanceof BABYLON.SubMesh) {
  6661. return source.clone(destinationObject);
  6662. }
  6663. else if (source.clone) {
  6664. return source.clone();
  6665. }
  6666. return null;
  6667. };
  6668. var Tools = /** @class */ (function () {
  6669. function Tools() {
  6670. }
  6671. /**
  6672. * Interpolates between a and b via alpha
  6673. * @param a The lower value (returned when alpha = 0)
  6674. * @param b The upper value (returned when alpha = 1)
  6675. * @param alpha The interpolation-factor
  6676. * @return The mixed value
  6677. */
  6678. Tools.Mix = function (a, b, alpha) {
  6679. return a * (1 - alpha) + b * alpha;
  6680. };
  6681. Tools.Instantiate = function (className) {
  6682. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6683. return Tools.RegisteredExternalClasses[className];
  6684. }
  6685. var arr = className.split(".");
  6686. var fn = (window || this);
  6687. for (var i = 0, len = arr.length; i < len; i++) {
  6688. fn = fn[arr[i]];
  6689. }
  6690. if (typeof fn !== "function") {
  6691. return null;
  6692. }
  6693. return fn;
  6694. };
  6695. Tools.SetImmediate = function (action) {
  6696. if (window.setImmediate) {
  6697. window.setImmediate(action);
  6698. }
  6699. else {
  6700. setTimeout(action, 1);
  6701. }
  6702. };
  6703. Tools.IsExponentOfTwo = function (value) {
  6704. var count = 1;
  6705. do {
  6706. count *= 2;
  6707. } while (count < value);
  6708. return count === value;
  6709. };
  6710. /**
  6711. * Find the next highest power of two.
  6712. * @param x Number to start search from.
  6713. * @return Next highest power of two.
  6714. */
  6715. Tools.CeilingPOT = function (x) {
  6716. x--;
  6717. x |= x >> 1;
  6718. x |= x >> 2;
  6719. x |= x >> 4;
  6720. x |= x >> 8;
  6721. x |= x >> 16;
  6722. x++;
  6723. return x;
  6724. };
  6725. /**
  6726. * Find the next lowest power of two.
  6727. * @param x Number to start search from.
  6728. * @return Next lowest power of two.
  6729. */
  6730. Tools.FloorPOT = function (x) {
  6731. x = x | (x >> 1);
  6732. x = x | (x >> 2);
  6733. x = x | (x >> 4);
  6734. x = x | (x >> 8);
  6735. x = x | (x >> 16);
  6736. return x - (x >> 1);
  6737. };
  6738. /**
  6739. * Find the nearest power of two.
  6740. * @param x Number to start search from.
  6741. * @return Next nearest power of two.
  6742. */
  6743. Tools.NearestPOT = function (x) {
  6744. var c = Tools.CeilingPOT(x);
  6745. var f = Tools.FloorPOT(x);
  6746. return (c - x) > (x - f) ? f : c;
  6747. };
  6748. Tools.GetExponentOfTwo = function (value, max, mode) {
  6749. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6750. var pot;
  6751. switch (mode) {
  6752. case BABYLON.Engine.SCALEMODE_FLOOR:
  6753. pot = Tools.FloorPOT(value);
  6754. break;
  6755. case BABYLON.Engine.SCALEMODE_NEAREST:
  6756. pot = Tools.NearestPOT(value);
  6757. break;
  6758. case BABYLON.Engine.SCALEMODE_CEILING:
  6759. default:
  6760. pot = Tools.CeilingPOT(value);
  6761. break;
  6762. }
  6763. return Math.min(pot, max);
  6764. };
  6765. Tools.GetFilename = function (path) {
  6766. var index = path.lastIndexOf("/");
  6767. if (index < 0)
  6768. return path;
  6769. return path.substring(index + 1);
  6770. };
  6771. Tools.GetFolderPath = function (uri) {
  6772. var index = uri.lastIndexOf("/");
  6773. if (index < 0)
  6774. return "";
  6775. return uri.substring(0, index + 1);
  6776. };
  6777. Tools.GetDOMTextContent = function (element) {
  6778. var result = "";
  6779. var child = element.firstChild;
  6780. while (child) {
  6781. if (child.nodeType === 3) {
  6782. result += child.textContent;
  6783. }
  6784. child = child.nextSibling;
  6785. }
  6786. return result;
  6787. };
  6788. Tools.ToDegrees = function (angle) {
  6789. return angle * 180 / Math.PI;
  6790. };
  6791. Tools.ToRadians = function (angle) {
  6792. return angle * Math.PI / 180;
  6793. };
  6794. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6795. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6796. var output = "";
  6797. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6798. var i = 0;
  6799. var bytes = new Uint8Array(buffer);
  6800. while (i < bytes.length) {
  6801. chr1 = bytes[i++];
  6802. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6803. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6804. enc1 = chr1 >> 2;
  6805. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6806. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6807. enc4 = chr3 & 63;
  6808. if (isNaN(chr2)) {
  6809. enc3 = enc4 = 64;
  6810. }
  6811. else if (isNaN(chr3)) {
  6812. enc4 = 64;
  6813. }
  6814. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6815. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6816. }
  6817. return "data:image/png;base64," + output;
  6818. };
  6819. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6820. if (bias === void 0) { bias = null; }
  6821. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6822. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6823. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6824. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6825. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6826. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6827. }
  6828. if (bias) {
  6829. minimum.x -= minimum.x * bias.x + bias.y;
  6830. minimum.y -= minimum.y * bias.x + bias.y;
  6831. minimum.z -= minimum.z * bias.x + bias.y;
  6832. maximum.x += maximum.x * bias.x + bias.y;
  6833. maximum.y += maximum.y * bias.x + bias.y;
  6834. maximum.z += maximum.z * bias.x + bias.y;
  6835. }
  6836. return {
  6837. minimum: minimum,
  6838. maximum: maximum
  6839. };
  6840. };
  6841. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6842. if (bias === void 0) { bias = null; }
  6843. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6844. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6845. if (!stride) {
  6846. stride = 3;
  6847. }
  6848. for (var index = start; index < start + count; index++) {
  6849. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6850. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6851. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6852. }
  6853. if (bias) {
  6854. minimum.x -= minimum.x * bias.x + bias.y;
  6855. minimum.y -= minimum.y * bias.x + bias.y;
  6856. minimum.z -= minimum.z * bias.x + bias.y;
  6857. maximum.x += maximum.x * bias.x + bias.y;
  6858. maximum.y += maximum.y * bias.x + bias.y;
  6859. maximum.z += maximum.z * bias.x + bias.y;
  6860. }
  6861. return {
  6862. minimum: minimum,
  6863. maximum: maximum
  6864. };
  6865. };
  6866. Tools.Vector2ArrayFeeder = function (array) {
  6867. return function (index) {
  6868. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6869. var length = isFloatArray ? array.length / 2 : array.length;
  6870. if (index >= length) {
  6871. return null;
  6872. }
  6873. if (isFloatArray) {
  6874. var fa = array;
  6875. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6876. }
  6877. var a = array;
  6878. return a[index];
  6879. };
  6880. };
  6881. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6882. if (bias === void 0) { bias = null; }
  6883. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6884. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6885. var i = 0;
  6886. var cur = feeder(i++);
  6887. while (cur) {
  6888. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6889. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6890. cur = feeder(i++);
  6891. }
  6892. if (bias) {
  6893. minimum.x -= minimum.x * bias.x + bias.y;
  6894. minimum.y -= minimum.y * bias.x + bias.y;
  6895. maximum.x += maximum.x * bias.x + bias.y;
  6896. maximum.y += maximum.y * bias.x + bias.y;
  6897. }
  6898. return {
  6899. minimum: minimum,
  6900. maximum: maximum
  6901. };
  6902. };
  6903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6904. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6905. return null;
  6906. return Array.isArray(obj) ? obj : [obj];
  6907. };
  6908. // Misc.
  6909. Tools.GetPointerPrefix = function () {
  6910. var eventPrefix = "pointer";
  6911. // Check if pointer events are supported
  6912. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6913. eventPrefix = "mouse";
  6914. }
  6915. return eventPrefix;
  6916. };
  6917. /**
  6918. * @param func - the function to be called
  6919. * @param requester - the object that will request the next frame. Falls back to window.
  6920. */
  6921. Tools.QueueNewFrame = function (func, requester) {
  6922. if (!Tools.IsWindowObjectExist()) {
  6923. return setTimeout(func, 16);
  6924. }
  6925. if (!requester) {
  6926. requester = window;
  6927. }
  6928. if (requester.requestAnimationFrame) {
  6929. return requester.requestAnimationFrame(func);
  6930. }
  6931. else if (requester.msRequestAnimationFrame) {
  6932. return requester.msRequestAnimationFrame(func);
  6933. }
  6934. else if (requester.webkitRequestAnimationFrame) {
  6935. return requester.webkitRequestAnimationFrame(func);
  6936. }
  6937. else if (requester.mozRequestAnimationFrame) {
  6938. return requester.mozRequestAnimationFrame(func);
  6939. }
  6940. else if (requester.oRequestAnimationFrame) {
  6941. return requester.oRequestAnimationFrame(func);
  6942. }
  6943. else {
  6944. return window.setTimeout(func, 16);
  6945. }
  6946. };
  6947. Tools.RequestFullscreen = function (element) {
  6948. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6949. if (!requestFunction)
  6950. return;
  6951. requestFunction.call(element);
  6952. };
  6953. Tools.ExitFullscreen = function () {
  6954. if (document.exitFullscreen) {
  6955. document.exitFullscreen();
  6956. }
  6957. else if (document.mozCancelFullScreen) {
  6958. document.mozCancelFullScreen();
  6959. }
  6960. else if (document.webkitCancelFullScreen) {
  6961. document.webkitCancelFullScreen();
  6962. }
  6963. else if (document.msCancelFullScreen) {
  6964. document.msCancelFullScreen();
  6965. }
  6966. };
  6967. Tools.SetCorsBehavior = function (url, element) {
  6968. if (url && url.indexOf("data:") === 0) {
  6969. return;
  6970. }
  6971. if (Tools.CorsBehavior) {
  6972. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6973. element.crossOrigin = Tools.CorsBehavior;
  6974. }
  6975. else {
  6976. var result = Tools.CorsBehavior(url);
  6977. if (result) {
  6978. element.crossOrigin = result;
  6979. }
  6980. }
  6981. }
  6982. };
  6983. // External files
  6984. Tools.CleanUrl = function (url) {
  6985. url = url.replace(/#/mg, "%23");
  6986. return url;
  6987. };
  6988. Tools.LoadImage = function (url, onLoad, onError, database) {
  6989. if (url instanceof ArrayBuffer) {
  6990. url = Tools.EncodeArrayBufferTobase64(url);
  6991. }
  6992. url = Tools.CleanUrl(url);
  6993. url = Tools.PreprocessUrl(url);
  6994. var img = new Image();
  6995. Tools.SetCorsBehavior(url, img);
  6996. img.onload = function () {
  6997. onLoad(img);
  6998. };
  6999. img.onerror = function (err) {
  7000. Tools.Error("Error while trying to load image: " + url);
  7001. if (onError) {
  7002. onError("Error while trying to load image: " + url, err);
  7003. }
  7004. };
  7005. var noIndexedDB = function () {
  7006. img.src = url;
  7007. };
  7008. var loadFromIndexedDB = function () {
  7009. if (database) {
  7010. database.loadImageFromDB(url, img);
  7011. }
  7012. };
  7013. //ANY database to do!
  7014. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7015. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7016. }
  7017. else {
  7018. if (url.indexOf("file:") !== -1) {
  7019. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7020. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7021. try {
  7022. var blobURL;
  7023. try {
  7024. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7025. }
  7026. catch (ex) {
  7027. // Chrome doesn't support oneTimeOnly parameter
  7028. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7029. }
  7030. img.src = blobURL;
  7031. }
  7032. catch (e) {
  7033. img.src = "";
  7034. }
  7035. return img;
  7036. }
  7037. }
  7038. noIndexedDB();
  7039. }
  7040. return img;
  7041. };
  7042. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7043. url = Tools.CleanUrl(url);
  7044. url = Tools.PreprocessUrl(url);
  7045. // If file and file input are set
  7046. if (url.indexOf("file:") !== -1) {
  7047. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7048. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7049. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7050. }
  7051. }
  7052. var loadUrl = Tools.BaseUrl + url;
  7053. var aborted = false;
  7054. var fileRequest = {
  7055. onCompleteObservable: new BABYLON.Observable(),
  7056. abort: function () { return aborted = true; },
  7057. };
  7058. var requestFile = function () {
  7059. var request = new XMLHttpRequest();
  7060. var retryHandle = null;
  7061. fileRequest.abort = function () {
  7062. aborted = true;
  7063. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7064. request.abort();
  7065. }
  7066. if (retryHandle !== null) {
  7067. clearTimeout(retryHandle);
  7068. retryHandle = null;
  7069. }
  7070. };
  7071. var retryLoop = function (retryIndex) {
  7072. request.open('GET', loadUrl, true);
  7073. if (useArrayBuffer) {
  7074. request.responseType = "arraybuffer";
  7075. }
  7076. if (onProgress) {
  7077. request.addEventListener("progress", onProgress);
  7078. }
  7079. var onLoadEnd = function () {
  7080. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7081. };
  7082. request.addEventListener("loadend", onLoadEnd);
  7083. var onReadyStateChange = function () {
  7084. if (aborted) {
  7085. return;
  7086. }
  7087. // In case of undefined state in some browsers.
  7088. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7089. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7090. request.removeEventListener("readystatechange", onReadyStateChange);
  7091. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7092. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7093. return;
  7094. }
  7095. var retryStrategy = Tools.DefaultRetryStrategy;
  7096. if (retryStrategy) {
  7097. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7098. if (waitTime !== -1) {
  7099. // Prevent the request from completing for retry.
  7100. request.removeEventListener("loadend", onLoadEnd);
  7101. request = new XMLHttpRequest();
  7102. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7103. return;
  7104. }
  7105. }
  7106. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7107. if (onError) {
  7108. onError(request, e);
  7109. }
  7110. else {
  7111. throw e;
  7112. }
  7113. }
  7114. };
  7115. request.addEventListener("readystatechange", onReadyStateChange);
  7116. request.send();
  7117. };
  7118. retryLoop(0);
  7119. };
  7120. // Caching all files
  7121. if (database && database.enableSceneOffline) {
  7122. var noIndexedDB_1 = function () {
  7123. if (!aborted) {
  7124. requestFile();
  7125. }
  7126. };
  7127. var loadFromIndexedDB = function () {
  7128. // TODO: database needs to support aborting and should return a IFileRequest
  7129. if (aborted) {
  7130. return;
  7131. }
  7132. if (database) {
  7133. database.loadFileFromDB(url, function (data) {
  7134. if (!aborted) {
  7135. onSuccess(data);
  7136. }
  7137. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7138. }, onProgress ? function (event) {
  7139. if (!aborted) {
  7140. onProgress(event);
  7141. }
  7142. } : undefined, noIndexedDB_1, useArrayBuffer);
  7143. }
  7144. };
  7145. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7146. }
  7147. else {
  7148. requestFile();
  7149. }
  7150. return fileRequest;
  7151. };
  7152. /**
  7153. * Load a script (identified by an url). When the url returns, the
  7154. * content of this file is added into a new script element, attached to the DOM (body element)
  7155. */
  7156. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7157. var head = document.getElementsByTagName('head')[0];
  7158. var script = document.createElement('script');
  7159. script.type = 'text/javascript';
  7160. script.src = scriptUrl;
  7161. script.onload = function () {
  7162. if (onSuccess) {
  7163. onSuccess();
  7164. }
  7165. };
  7166. script.onerror = function (e) {
  7167. if (onError) {
  7168. onError("Unable to load script", e);
  7169. }
  7170. };
  7171. head.appendChild(script);
  7172. };
  7173. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7174. var reader = new FileReader();
  7175. var request = {
  7176. onCompleteObservable: new BABYLON.Observable(),
  7177. abort: function () { return reader.abort(); },
  7178. };
  7179. reader.onloadend = function (e) {
  7180. request.onCompleteObservable.notifyObservers(request);
  7181. };
  7182. reader.onload = function (e) {
  7183. //target doesn't have result from ts 1.3
  7184. callback(e.target['result']);
  7185. };
  7186. reader.onprogress = progressCallback;
  7187. reader.readAsDataURL(fileToLoad);
  7188. return request;
  7189. };
  7190. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7191. var reader = new FileReader();
  7192. var request = {
  7193. onCompleteObservable: new BABYLON.Observable(),
  7194. abort: function () { return reader.abort(); },
  7195. };
  7196. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7197. reader.onerror = function (e) {
  7198. Tools.Log("Error while reading file: " + fileToLoad.name);
  7199. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7200. };
  7201. reader.onload = function (e) {
  7202. //target doesn't have result from ts 1.3
  7203. callback(e.target['result']);
  7204. };
  7205. if (progressCallBack) {
  7206. reader.onprogress = progressCallBack;
  7207. }
  7208. if (!useArrayBuffer) {
  7209. // Asynchronous read
  7210. reader.readAsText(fileToLoad);
  7211. }
  7212. else {
  7213. reader.readAsArrayBuffer(fileToLoad);
  7214. }
  7215. return request;
  7216. };
  7217. //returns a downloadable url to a file content.
  7218. Tools.FileAsURL = function (content) {
  7219. var fileBlob = new Blob([content]);
  7220. var url = window.URL || window.webkitURL;
  7221. var link = url.createObjectURL(fileBlob);
  7222. return link;
  7223. };
  7224. // Misc.
  7225. Tools.Format = function (value, decimals) {
  7226. if (decimals === void 0) { decimals = 2; }
  7227. return value.toFixed(decimals);
  7228. };
  7229. Tools.CheckExtends = function (v, min, max) {
  7230. if (v.x < min.x)
  7231. min.x = v.x;
  7232. if (v.y < min.y)
  7233. min.y = v.y;
  7234. if (v.z < min.z)
  7235. min.z = v.z;
  7236. if (v.x > max.x)
  7237. max.x = v.x;
  7238. if (v.y > max.y)
  7239. max.y = v.y;
  7240. if (v.z > max.z)
  7241. max.z = v.z;
  7242. };
  7243. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7244. for (var prop in source) {
  7245. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7246. continue;
  7247. }
  7248. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7249. continue;
  7250. }
  7251. var sourceValue = source[prop];
  7252. var typeOfSourceValue = typeof sourceValue;
  7253. if (typeOfSourceValue === "function") {
  7254. continue;
  7255. }
  7256. if (typeOfSourceValue === "object") {
  7257. if (sourceValue instanceof Array) {
  7258. destination[prop] = [];
  7259. if (sourceValue.length > 0) {
  7260. if (typeof sourceValue[0] == "object") {
  7261. for (var index = 0; index < sourceValue.length; index++) {
  7262. var clonedValue = cloneValue(sourceValue[index], destination);
  7263. if (destination[prop].indexOf(clonedValue) === -1) {
  7264. destination[prop].push(clonedValue);
  7265. }
  7266. }
  7267. }
  7268. else {
  7269. destination[prop] = sourceValue.slice(0);
  7270. }
  7271. }
  7272. }
  7273. else {
  7274. destination[prop] = cloneValue(sourceValue, destination);
  7275. }
  7276. }
  7277. else {
  7278. destination[prop] = sourceValue;
  7279. }
  7280. }
  7281. };
  7282. Tools.IsEmpty = function (obj) {
  7283. for (var i in obj) {
  7284. if (obj.hasOwnProperty(i)) {
  7285. return false;
  7286. }
  7287. }
  7288. return true;
  7289. };
  7290. Tools.RegisterTopRootEvents = function (events) {
  7291. for (var index = 0; index < events.length; index++) {
  7292. var event = events[index];
  7293. window.addEventListener(event.name, event.handler, false);
  7294. try {
  7295. if (window.parent) {
  7296. window.parent.addEventListener(event.name, event.handler, false);
  7297. }
  7298. }
  7299. catch (e) {
  7300. // Silently fails...
  7301. }
  7302. }
  7303. };
  7304. Tools.UnregisterTopRootEvents = function (events) {
  7305. for (var index = 0; index < events.length; index++) {
  7306. var event = events[index];
  7307. window.removeEventListener(event.name, event.handler);
  7308. try {
  7309. if (window.parent) {
  7310. window.parent.removeEventListener(event.name, event.handler);
  7311. }
  7312. }
  7313. catch (e) {
  7314. // Silently fails...
  7315. }
  7316. }
  7317. };
  7318. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7319. if (mimeType === void 0) { mimeType = "image/png"; }
  7320. // Read the contents of the framebuffer
  7321. var numberOfChannelsByLine = width * 4;
  7322. var halfHeight = height / 2;
  7323. //Reading datas from WebGL
  7324. var data = engine.readPixels(0, 0, width, height);
  7325. //To flip image on Y axis.
  7326. for (var i = 0; i < halfHeight; i++) {
  7327. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7328. var currentCell = j + i * numberOfChannelsByLine;
  7329. var targetLine = height - i - 1;
  7330. var targetCell = j + targetLine * numberOfChannelsByLine;
  7331. var temp = data[currentCell];
  7332. data[currentCell] = data[targetCell];
  7333. data[targetCell] = temp;
  7334. }
  7335. }
  7336. // Create a 2D canvas to store the result
  7337. if (!screenshotCanvas) {
  7338. screenshotCanvas = document.createElement('canvas');
  7339. }
  7340. screenshotCanvas.width = width;
  7341. screenshotCanvas.height = height;
  7342. var context = screenshotCanvas.getContext('2d');
  7343. if (context) {
  7344. // Copy the pixels to a 2D canvas
  7345. var imageData = context.createImageData(width, height);
  7346. var castData = (imageData.data);
  7347. castData.set(data);
  7348. context.putImageData(imageData, 0, 0);
  7349. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7350. }
  7351. };
  7352. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7353. if (mimeType === void 0) { mimeType = "image/png"; }
  7354. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7355. if (successCallback) {
  7356. successCallback(base64Image);
  7357. }
  7358. else {
  7359. // We need HTMLCanvasElement.toBlob for HD screenshots
  7360. if (!screenshotCanvas.toBlob) {
  7361. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7362. screenshotCanvas.toBlob = function (callback, type, quality) {
  7363. var _this = this;
  7364. setTimeout(function () {
  7365. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7366. for (var i = 0; i < len; i++) {
  7367. arr[i] = binStr.charCodeAt(i);
  7368. }
  7369. callback(new Blob([arr], { type: type || 'image/png' }));
  7370. });
  7371. };
  7372. }
  7373. screenshotCanvas.toBlob(function (blob) {
  7374. var url = URL.createObjectURL(blob);
  7375. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7376. if (("download" in document.createElement("a"))) {
  7377. var a = window.document.createElement("a");
  7378. a.href = url;
  7379. if (fileName) {
  7380. a.setAttribute("download", fileName);
  7381. }
  7382. else {
  7383. var date = new Date();
  7384. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7385. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7386. }
  7387. window.document.body.appendChild(a);
  7388. a.addEventListener("click", function () {
  7389. if (a.parentElement) {
  7390. a.parentElement.removeChild(a);
  7391. }
  7392. });
  7393. a.click();
  7394. }
  7395. else {
  7396. var newWindow = window.open("");
  7397. if (!newWindow)
  7398. return;
  7399. var img = newWindow.document.createElement("img");
  7400. img.onload = function () {
  7401. // no longer need to read the blob so it's revoked
  7402. URL.revokeObjectURL(url);
  7403. };
  7404. img.src = url;
  7405. newWindow.document.body.appendChild(img);
  7406. }
  7407. });
  7408. }
  7409. };
  7410. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7411. if (mimeType === void 0) { mimeType = "image/png"; }
  7412. var width;
  7413. var height;
  7414. // If a precision value is specified
  7415. if (size.precision) {
  7416. width = Math.round(engine.getRenderWidth() * size.precision);
  7417. height = Math.round(width / engine.getAspectRatio(camera));
  7418. }
  7419. else if (size.width && size.height) {
  7420. width = size.width;
  7421. height = size.height;
  7422. }
  7423. else if (size.width && !size.height) {
  7424. width = size.width;
  7425. height = Math.round(width / engine.getAspectRatio(camera));
  7426. }
  7427. else if (size.height && !size.width) {
  7428. height = size.height;
  7429. width = Math.round(height * engine.getAspectRatio(camera));
  7430. }
  7431. else if (!isNaN(size)) {
  7432. height = size;
  7433. width = size;
  7434. }
  7435. else {
  7436. Tools.Error("Invalid 'size' parameter !");
  7437. return;
  7438. }
  7439. if (!screenshotCanvas) {
  7440. screenshotCanvas = document.createElement('canvas');
  7441. }
  7442. screenshotCanvas.width = width;
  7443. screenshotCanvas.height = height;
  7444. var renderContext = screenshotCanvas.getContext("2d");
  7445. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7446. var newWidth = width;
  7447. var newHeight = newWidth / ratio;
  7448. if (newHeight > height) {
  7449. newHeight = height;
  7450. newWidth = newHeight * ratio;
  7451. }
  7452. var offsetX = Math.max(0, width - newWidth) / 2;
  7453. var offsetY = Math.max(0, height - newHeight) / 2;
  7454. var renderingCanvas = engine.getRenderingCanvas();
  7455. if (renderContext && renderingCanvas) {
  7456. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7457. }
  7458. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7459. };
  7460. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7461. if (mimeType === void 0) { mimeType = "image/png"; }
  7462. if (samples === void 0) { samples = 1; }
  7463. if (antialiasing === void 0) { antialiasing = false; }
  7464. var width;
  7465. var height;
  7466. //If a precision value is specified
  7467. if (size.precision) {
  7468. width = Math.round(engine.getRenderWidth() * size.precision);
  7469. height = Math.round(width / engine.getAspectRatio(camera));
  7470. size = { width: width, height: height };
  7471. }
  7472. else if (size.width && size.height) {
  7473. width = size.width;
  7474. height = size.height;
  7475. }
  7476. else if (size.width && !size.height) {
  7477. width = size.width;
  7478. height = Math.round(width / engine.getAspectRatio(camera));
  7479. size = { width: width, height: height };
  7480. }
  7481. else if (size.height && !size.width) {
  7482. height = size.height;
  7483. width = Math.round(height * engine.getAspectRatio(camera));
  7484. size = { width: width, height: height };
  7485. }
  7486. else if (!isNaN(size)) {
  7487. height = size;
  7488. width = size;
  7489. }
  7490. else {
  7491. Tools.Error("Invalid 'size' parameter !");
  7492. return;
  7493. }
  7494. var scene = camera.getScene();
  7495. var previousCamera = null;
  7496. if (scene.activeCamera !== camera) {
  7497. previousCamera = scene.activeCamera;
  7498. scene.activeCamera = camera;
  7499. }
  7500. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7501. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7502. texture.renderList = null;
  7503. texture.samples = samples;
  7504. if (antialiasing) {
  7505. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7506. }
  7507. texture.onAfterRenderObservable.add(function () {
  7508. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7509. });
  7510. scene.incrementRenderId();
  7511. scene.resetCachedMaterial();
  7512. texture.render(true);
  7513. texture.dispose();
  7514. if (previousCamera) {
  7515. scene.activeCamera = previousCamera;
  7516. }
  7517. camera.getProjectionMatrix(true); // Force cache refresh;
  7518. };
  7519. // XHR response validator for local file scenario
  7520. Tools.ValidateXHRData = function (xhr, dataType) {
  7521. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7522. if (dataType === void 0) { dataType = 7; }
  7523. try {
  7524. if (dataType & 1) {
  7525. if (xhr.responseText && xhr.responseText.length > 0) {
  7526. return true;
  7527. }
  7528. else if (dataType === 1) {
  7529. return false;
  7530. }
  7531. }
  7532. if (dataType & 2) {
  7533. // Check header width and height since there is no "TGA" magic number
  7534. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7535. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7536. return true;
  7537. }
  7538. else if (dataType === 2) {
  7539. return false;
  7540. }
  7541. }
  7542. if (dataType & 4) {
  7543. // Check for the "DDS" magic number
  7544. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7545. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7546. return true;
  7547. }
  7548. else {
  7549. return false;
  7550. }
  7551. }
  7552. }
  7553. catch (e) {
  7554. // Global protection
  7555. }
  7556. return false;
  7557. };
  7558. /**
  7559. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7560. * Be aware Math.random() could cause collisions, but:
  7561. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  7562. */
  7563. Tools.RandomId = function () {
  7564. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7565. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7566. return v.toString(16);
  7567. });
  7568. };
  7569. Object.defineProperty(Tools, "NoneLogLevel", {
  7570. get: function () {
  7571. return Tools._NoneLogLevel;
  7572. },
  7573. enumerable: true,
  7574. configurable: true
  7575. });
  7576. Object.defineProperty(Tools, "MessageLogLevel", {
  7577. get: function () {
  7578. return Tools._MessageLogLevel;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(Tools, "WarningLogLevel", {
  7584. get: function () {
  7585. return Tools._WarningLogLevel;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. Object.defineProperty(Tools, "ErrorLogLevel", {
  7591. get: function () {
  7592. return Tools._ErrorLogLevel;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(Tools, "AllLogLevel", {
  7598. get: function () {
  7599. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7600. },
  7601. enumerable: true,
  7602. configurable: true
  7603. });
  7604. Tools._AddLogEntry = function (entry) {
  7605. Tools._LogCache = entry + Tools._LogCache;
  7606. if (Tools.OnNewCacheEntry) {
  7607. Tools.OnNewCacheEntry(entry);
  7608. }
  7609. };
  7610. Tools._FormatMessage = function (message) {
  7611. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7612. var date = new Date();
  7613. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7614. };
  7615. Tools._LogDisabled = function (message) {
  7616. // nothing to do
  7617. };
  7618. Tools._LogEnabled = function (message) {
  7619. var formattedMessage = Tools._FormatMessage(message);
  7620. console.log("BJS - " + formattedMessage);
  7621. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7622. Tools._AddLogEntry(entry);
  7623. };
  7624. Tools._WarnDisabled = function (message) {
  7625. // nothing to do
  7626. };
  7627. Tools._WarnEnabled = function (message) {
  7628. var formattedMessage = Tools._FormatMessage(message);
  7629. console.warn("BJS - " + formattedMessage);
  7630. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7631. Tools._AddLogEntry(entry);
  7632. };
  7633. Tools._ErrorDisabled = function (message) {
  7634. // nothing to do
  7635. };
  7636. Tools._ErrorEnabled = function (message) {
  7637. Tools.errorsCount++;
  7638. var formattedMessage = Tools._FormatMessage(message);
  7639. console.error("BJS - " + formattedMessage);
  7640. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7641. Tools._AddLogEntry(entry);
  7642. };
  7643. Object.defineProperty(Tools, "LogCache", {
  7644. get: function () {
  7645. return Tools._LogCache;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Tools.ClearLogCache = function () {
  7651. Tools._LogCache = "";
  7652. Tools.errorsCount = 0;
  7653. };
  7654. Object.defineProperty(Tools, "LogLevels", {
  7655. set: function (level) {
  7656. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7657. Tools.Log = Tools._LogEnabled;
  7658. }
  7659. else {
  7660. Tools.Log = Tools._LogDisabled;
  7661. }
  7662. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7663. Tools.Warn = Tools._WarnEnabled;
  7664. }
  7665. else {
  7666. Tools.Warn = Tools._WarnDisabled;
  7667. }
  7668. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7669. Tools.Error = Tools._ErrorEnabled;
  7670. }
  7671. else {
  7672. Tools.Error = Tools._ErrorDisabled;
  7673. }
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Tools.IsWindowObjectExist = function () {
  7679. return (typeof window) !== "undefined";
  7680. };
  7681. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7682. get: function () {
  7683. return Tools._PerformanceNoneLogLevel;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7689. get: function () {
  7690. return Tools._PerformanceUserMarkLogLevel;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7696. get: function () {
  7697. return Tools._PerformanceConsoleLogLevel;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7703. set: function (level) {
  7704. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7705. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7706. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7707. return;
  7708. }
  7709. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7710. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7711. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7712. return;
  7713. }
  7714. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7715. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7721. };
  7722. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7723. };
  7724. Tools._StartUserMark = function (counterName, condition) {
  7725. if (condition === void 0) { condition = true; }
  7726. if (!Tools._performance) {
  7727. if (!Tools.IsWindowObjectExist()) {
  7728. return;
  7729. }
  7730. Tools._performance = window.performance;
  7731. }
  7732. if (!condition || !Tools._performance.mark) {
  7733. return;
  7734. }
  7735. Tools._performance.mark(counterName + "-Begin");
  7736. };
  7737. Tools._EndUserMark = function (counterName, condition) {
  7738. if (condition === void 0) { condition = true; }
  7739. if (!condition || !Tools._performance.mark) {
  7740. return;
  7741. }
  7742. Tools._performance.mark(counterName + "-End");
  7743. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7744. };
  7745. Tools._StartPerformanceConsole = function (counterName, condition) {
  7746. if (condition === void 0) { condition = true; }
  7747. if (!condition) {
  7748. return;
  7749. }
  7750. Tools._StartUserMark(counterName, condition);
  7751. if (console.time) {
  7752. console.time(counterName);
  7753. }
  7754. };
  7755. Tools._EndPerformanceConsole = function (counterName, condition) {
  7756. if (condition === void 0) { condition = true; }
  7757. if (!condition) {
  7758. return;
  7759. }
  7760. Tools._EndUserMark(counterName, condition);
  7761. if (console.time) {
  7762. console.timeEnd(counterName);
  7763. }
  7764. };
  7765. Object.defineProperty(Tools, "Now", {
  7766. get: function () {
  7767. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7768. return window.performance.now();
  7769. }
  7770. return new Date().getTime();
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. /**
  7776. * This method will return the name of the class used to create the instance of the given object.
  7777. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7778. * @param object the object to get the class name from
  7779. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7780. */
  7781. Tools.GetClassName = function (object, isType) {
  7782. if (isType === void 0) { isType = false; }
  7783. var name = null;
  7784. if (!isType && object.getClassName) {
  7785. name = object.getClassName();
  7786. }
  7787. else {
  7788. if (object instanceof Object) {
  7789. var classObj = isType ? object : Object.getPrototypeOf(object);
  7790. name = classObj.constructor["__bjsclassName__"];
  7791. }
  7792. if (!name) {
  7793. name = typeof object;
  7794. }
  7795. }
  7796. return name;
  7797. };
  7798. Tools.First = function (array, predicate) {
  7799. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7800. var el = array_1[_i];
  7801. if (predicate(el)) {
  7802. return el;
  7803. }
  7804. }
  7805. return null;
  7806. };
  7807. /**
  7808. * This method will return the name of the full name of the class, including its owning module (if any).
  7809. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  7810. * @param object the object to get the class name from
  7811. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  7812. */
  7813. Tools.getFullClassName = function (object, isType) {
  7814. if (isType === void 0) { isType = false; }
  7815. var className = null;
  7816. var moduleName = null;
  7817. if (!isType && object.getClassName) {
  7818. className = object.getClassName();
  7819. }
  7820. else {
  7821. if (object instanceof Object) {
  7822. var classObj = isType ? object : Object.getPrototypeOf(object);
  7823. className = classObj.constructor["__bjsclassName__"];
  7824. moduleName = classObj.constructor["__bjsmoduleName__"];
  7825. }
  7826. if (!className) {
  7827. className = typeof object;
  7828. }
  7829. }
  7830. if (!className) {
  7831. return null;
  7832. }
  7833. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7834. };
  7835. /**
  7836. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  7837. * @param array
  7838. */
  7839. Tools.arrayOrStringFeeder = function (array) {
  7840. return function (index) {
  7841. if (index >= array.length) {
  7842. return null;
  7843. }
  7844. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7845. if (val && val.getHashCode) {
  7846. val = val.getHashCode();
  7847. }
  7848. if (typeof val === "string") {
  7849. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7850. }
  7851. return val;
  7852. };
  7853. };
  7854. /**
  7855. * Compute the hashCode of a stream of number
  7856. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7857. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7858. * @return the hash code computed
  7859. */
  7860. Tools.hashCodeFromStream = function (feeder) {
  7861. // Based from here: http://stackoverflow.com/a/7616484/802124
  7862. var hash = 0;
  7863. var index = 0;
  7864. var chr = feeder(index++);
  7865. while (chr != null) {
  7866. hash = ((hash << 5) - hash) + chr;
  7867. hash |= 0; // Convert to 32bit integer
  7868. chr = feeder(index++);
  7869. }
  7870. return hash;
  7871. };
  7872. Tools.BaseUrl = "";
  7873. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7874. /**
  7875. * Default behaviour for cors in the application.
  7876. * It can be a string if the expected behavior is identical in the entire app.
  7877. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7878. */
  7879. Tools.CorsBehavior = "anonymous";
  7880. Tools.UseFallbackTexture = true;
  7881. /**
  7882. * Use this object to register external classes like custom textures or material
  7883. * to allow the laoders to instantiate them
  7884. */
  7885. Tools.RegisteredExternalClasses = {};
  7886. // Used in case of a texture loading problem
  7887. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  7888. Tools.PreprocessUrl = function (url) {
  7889. return url;
  7890. };
  7891. // Logs
  7892. Tools._NoneLogLevel = 0;
  7893. Tools._MessageLogLevel = 1;
  7894. Tools._WarningLogLevel = 2;
  7895. Tools._ErrorLogLevel = 4;
  7896. Tools._LogCache = "";
  7897. Tools.errorsCount = 0;
  7898. Tools.Log = Tools._LogEnabled;
  7899. Tools.Warn = Tools._WarnEnabled;
  7900. Tools.Error = Tools._ErrorEnabled;
  7901. // Performances
  7902. Tools._PerformanceNoneLogLevel = 0;
  7903. Tools._PerformanceUserMarkLogLevel = 1;
  7904. Tools._PerformanceConsoleLogLevel = 2;
  7905. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7906. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7907. return Tools;
  7908. }());
  7909. BABYLON.Tools = Tools;
  7910. /**
  7911. * This class is used to track a performance counter which is number based.
  7912. * The user has access to many properties which give statistics of different nature
  7913. *
  7914. * The implementer can track two kinds of Performance Counter: time and count
  7915. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  7916. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  7917. */
  7918. var PerfCounter = /** @class */ (function () {
  7919. function PerfCounter() {
  7920. this._startMonitoringTime = 0;
  7921. this._min = 0;
  7922. this._max = 0;
  7923. this._average = 0;
  7924. this._lastSecAverage = 0;
  7925. this._current = 0;
  7926. this._totalValueCount = 0;
  7927. this._totalAccumulated = 0;
  7928. this._lastSecAccumulated = 0;
  7929. this._lastSecTime = 0;
  7930. this._lastSecValueCount = 0;
  7931. }
  7932. Object.defineProperty(PerfCounter.prototype, "min", {
  7933. /**
  7934. * Returns the smallest value ever
  7935. */
  7936. get: function () {
  7937. return this._min;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(PerfCounter.prototype, "max", {
  7943. /**
  7944. * Returns the biggest value ever
  7945. */
  7946. get: function () {
  7947. return this._max;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Object.defineProperty(PerfCounter.prototype, "average", {
  7953. /**
  7954. * Returns the average value since the performance counter is running
  7955. */
  7956. get: function () {
  7957. return this._average;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7963. /**
  7964. * Returns the average value of the last second the counter was monitored
  7965. */
  7966. get: function () {
  7967. return this._lastSecAverage;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(PerfCounter.prototype, "current", {
  7973. /**
  7974. * Returns the current value
  7975. */
  7976. get: function () {
  7977. return this._current;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(PerfCounter.prototype, "total", {
  7983. get: function () {
  7984. return this._totalAccumulated;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(PerfCounter.prototype, "count", {
  7990. get: function () {
  7991. return this._totalValueCount;
  7992. },
  7993. enumerable: true,
  7994. configurable: true
  7995. });
  7996. /**
  7997. * Call this method to start monitoring a new frame.
  7998. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  7999. */
  8000. PerfCounter.prototype.fetchNewFrame = function () {
  8001. this._totalValueCount++;
  8002. this._current = 0;
  8003. this._lastSecValueCount++;
  8004. };
  8005. /**
  8006. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8007. * @param newCount the count value to add to the monitored count
  8008. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  8009. */
  8010. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8011. if (!PerfCounter.Enabled) {
  8012. return;
  8013. }
  8014. this._current += newCount;
  8015. if (fetchResult) {
  8016. this._fetchResult();
  8017. }
  8018. };
  8019. /**
  8020. * Start monitoring this performance counter
  8021. */
  8022. PerfCounter.prototype.beginMonitoring = function () {
  8023. if (!PerfCounter.Enabled) {
  8024. return;
  8025. }
  8026. this._startMonitoringTime = Tools.Now;
  8027. };
  8028. /**
  8029. * Compute the time lapsed since the previous beginMonitoring() call.
  8030. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  8031. */
  8032. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8033. if (newFrame === void 0) { newFrame = true; }
  8034. if (!PerfCounter.Enabled) {
  8035. return;
  8036. }
  8037. if (newFrame) {
  8038. this.fetchNewFrame();
  8039. }
  8040. var currentTime = Tools.Now;
  8041. this._current = currentTime - this._startMonitoringTime;
  8042. if (newFrame) {
  8043. this._fetchResult();
  8044. }
  8045. };
  8046. PerfCounter.prototype._fetchResult = function () {
  8047. this._totalAccumulated += this._current;
  8048. this._lastSecAccumulated += this._current;
  8049. // Min/Max update
  8050. this._min = Math.min(this._min, this._current);
  8051. this._max = Math.max(this._max, this._current);
  8052. this._average = this._totalAccumulated / this._totalValueCount;
  8053. // Reset last sec?
  8054. var now = Tools.Now;
  8055. if ((now - this._lastSecTime) > 1000) {
  8056. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8057. this._lastSecTime = now;
  8058. this._lastSecAccumulated = 0;
  8059. this._lastSecValueCount = 0;
  8060. }
  8061. };
  8062. PerfCounter.Enabled = true;
  8063. return PerfCounter;
  8064. }());
  8065. BABYLON.PerfCounter = PerfCounter;
  8066. /**
  8067. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8068. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8069. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8070. * @param name The name of the class, case should be preserved
  8071. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8072. */
  8073. function className(name, module) {
  8074. return function (target) {
  8075. target["__bjsclassName__"] = name;
  8076. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8077. };
  8078. }
  8079. BABYLON.className = className;
  8080. /**
  8081. * An implementation of a loop for asynchronous functions.
  8082. */
  8083. var AsyncLoop = /** @class */ (function () {
  8084. /**
  8085. * Constroctor.
  8086. * @param iterations the number of iterations.
  8087. * @param _fn the function to run each iteration
  8088. * @param _successCallback the callback that will be called upon succesful execution
  8089. * @param offset starting offset.
  8090. */
  8091. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8092. if (offset === void 0) { offset = 0; }
  8093. this.iterations = iterations;
  8094. this._fn = _fn;
  8095. this._successCallback = _successCallback;
  8096. this.index = offset - 1;
  8097. this._done = false;
  8098. }
  8099. /**
  8100. * Execute the next iteration. Must be called after the last iteration was finished.
  8101. */
  8102. AsyncLoop.prototype.executeNext = function () {
  8103. if (!this._done) {
  8104. if (this.index + 1 < this.iterations) {
  8105. ++this.index;
  8106. this._fn(this);
  8107. }
  8108. else {
  8109. this.breakLoop();
  8110. }
  8111. }
  8112. };
  8113. /**
  8114. * Break the loop and run the success callback.
  8115. */
  8116. AsyncLoop.prototype.breakLoop = function () {
  8117. this._done = true;
  8118. this._successCallback();
  8119. };
  8120. /**
  8121. * Helper function
  8122. */
  8123. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8124. if (offset === void 0) { offset = 0; }
  8125. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8126. loop.executeNext();
  8127. return loop;
  8128. };
  8129. /**
  8130. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8131. * @param iterations total number of iterations
  8132. * @param syncedIterations number of synchronous iterations in each async iteration.
  8133. * @param fn the function to call each iteration.
  8134. * @param callback a success call back that will be called when iterating stops.
  8135. * @param breakFunction a break condition (optional)
  8136. * @param timeout timeout settings for the setTimeout function. default - 0.
  8137. * @constructor
  8138. */
  8139. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8140. if (timeout === void 0) { timeout = 0; }
  8141. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8142. if (breakFunction && breakFunction())
  8143. loop.breakLoop();
  8144. else {
  8145. setTimeout(function () {
  8146. for (var i = 0; i < syncedIterations; ++i) {
  8147. var iteration = (loop.index * syncedIterations) + i;
  8148. if (iteration >= iterations)
  8149. break;
  8150. fn(iteration);
  8151. if (breakFunction && breakFunction()) {
  8152. loop.breakLoop();
  8153. break;
  8154. }
  8155. }
  8156. loop.executeNext();
  8157. }, timeout);
  8158. }
  8159. }, callback);
  8160. };
  8161. return AsyncLoop;
  8162. }());
  8163. BABYLON.AsyncLoop = AsyncLoop;
  8164. })(BABYLON || (BABYLON = {}));
  8165. //# sourceMappingURL=babylon.tools.js.map
  8166. var BABYLON;
  8167. (function (BABYLON) {
  8168. var _AlphaState = /** @class */ (function () {
  8169. /**
  8170. * Initializes the state.
  8171. */
  8172. function _AlphaState() {
  8173. this._isAlphaBlendDirty = false;
  8174. this._isBlendFunctionParametersDirty = false;
  8175. this._isBlendEquationParametersDirty = false;
  8176. this._isBlendConstantsDirty = false;
  8177. this._alphaBlend = false;
  8178. this._blendFunctionParameters = new Array(4);
  8179. this._blendEquationParameters = new Array(2);
  8180. this._blendConstants = new Array(4);
  8181. this.reset();
  8182. }
  8183. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8184. get: function () {
  8185. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8191. get: function () {
  8192. return this._alphaBlend;
  8193. },
  8194. set: function (value) {
  8195. if (this._alphaBlend === value) {
  8196. return;
  8197. }
  8198. this._alphaBlend = value;
  8199. this._isAlphaBlendDirty = true;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8205. if (this._blendConstants[0] === r &&
  8206. this._blendConstants[1] === g &&
  8207. this._blendConstants[2] === b &&
  8208. this._blendConstants[3] === a) {
  8209. return;
  8210. }
  8211. this._blendConstants[0] = r;
  8212. this._blendConstants[1] = g;
  8213. this._blendConstants[2] = b;
  8214. this._blendConstants[3] = a;
  8215. this._isBlendConstantsDirty = true;
  8216. };
  8217. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8218. if (this._blendFunctionParameters[0] === value0 &&
  8219. this._blendFunctionParameters[1] === value1 &&
  8220. this._blendFunctionParameters[2] === value2 &&
  8221. this._blendFunctionParameters[3] === value3) {
  8222. return;
  8223. }
  8224. this._blendFunctionParameters[0] = value0;
  8225. this._blendFunctionParameters[1] = value1;
  8226. this._blendFunctionParameters[2] = value2;
  8227. this._blendFunctionParameters[3] = value3;
  8228. this._isBlendFunctionParametersDirty = true;
  8229. };
  8230. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8231. if (this._blendEquationParameters[0] === rgb &&
  8232. this._blendEquationParameters[1] === alpha) {
  8233. return;
  8234. }
  8235. this._blendEquationParameters[0] = rgb;
  8236. this._blendEquationParameters[1] = alpha;
  8237. this._isBlendEquationParametersDirty = true;
  8238. };
  8239. _AlphaState.prototype.reset = function () {
  8240. this._alphaBlend = false;
  8241. this._blendFunctionParameters[0] = null;
  8242. this._blendFunctionParameters[1] = null;
  8243. this._blendFunctionParameters[2] = null;
  8244. this._blendFunctionParameters[3] = null;
  8245. this._blendEquationParameters[0] = null;
  8246. this._blendEquationParameters[1] = null;
  8247. this._blendConstants[0] = null;
  8248. this._blendConstants[1] = null;
  8249. this._blendConstants[2] = null;
  8250. this._blendConstants[3] = null;
  8251. this._isAlphaBlendDirty = true;
  8252. this._isBlendFunctionParametersDirty = false;
  8253. this._isBlendEquationParametersDirty = false;
  8254. this._isBlendConstantsDirty = false;
  8255. };
  8256. _AlphaState.prototype.apply = function (gl) {
  8257. if (!this.isDirty) {
  8258. return;
  8259. }
  8260. // Alpha blend
  8261. if (this._isAlphaBlendDirty) {
  8262. if (this._alphaBlend) {
  8263. gl.enable(gl.BLEND);
  8264. }
  8265. else {
  8266. gl.disable(gl.BLEND);
  8267. }
  8268. this._isAlphaBlendDirty = false;
  8269. }
  8270. // Alpha function
  8271. if (this._isBlendFunctionParametersDirty) {
  8272. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8273. this._isBlendFunctionParametersDirty = false;
  8274. }
  8275. // Alpha equation
  8276. if (this._isBlendEquationParametersDirty) {
  8277. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8278. this._isBlendEquationParametersDirty = false;
  8279. }
  8280. // Constants
  8281. if (this._isBlendConstantsDirty) {
  8282. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8283. this._isBlendConstantsDirty = false;
  8284. }
  8285. };
  8286. return _AlphaState;
  8287. }());
  8288. BABYLON._AlphaState = _AlphaState;
  8289. })(BABYLON || (BABYLON = {}));
  8290. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8291. var BABYLON;
  8292. (function (BABYLON) {
  8293. var _DepthCullingState = /** @class */ (function () {
  8294. /**
  8295. * Initializes the state.
  8296. */
  8297. function _DepthCullingState() {
  8298. this._isDepthTestDirty = false;
  8299. this._isDepthMaskDirty = false;
  8300. this._isDepthFuncDirty = false;
  8301. this._isCullFaceDirty = false;
  8302. this._isCullDirty = false;
  8303. this._isZOffsetDirty = false;
  8304. this._isFrontFaceDirty = false;
  8305. this.reset();
  8306. }
  8307. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8308. get: function () {
  8309. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8310. },
  8311. enumerable: true,
  8312. configurable: true
  8313. });
  8314. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8315. get: function () {
  8316. return this._zOffset;
  8317. },
  8318. set: function (value) {
  8319. if (this._zOffset === value) {
  8320. return;
  8321. }
  8322. this._zOffset = value;
  8323. this._isZOffsetDirty = true;
  8324. },
  8325. enumerable: true,
  8326. configurable: true
  8327. });
  8328. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8329. get: function () {
  8330. return this._cullFace;
  8331. },
  8332. set: function (value) {
  8333. if (this._cullFace === value) {
  8334. return;
  8335. }
  8336. this._cullFace = value;
  8337. this._isCullFaceDirty = true;
  8338. },
  8339. enumerable: true,
  8340. configurable: true
  8341. });
  8342. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8343. get: function () {
  8344. return this._cull;
  8345. },
  8346. set: function (value) {
  8347. if (this._cull === value) {
  8348. return;
  8349. }
  8350. this._cull = value;
  8351. this._isCullDirty = true;
  8352. },
  8353. enumerable: true,
  8354. configurable: true
  8355. });
  8356. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8357. get: function () {
  8358. return this._depthFunc;
  8359. },
  8360. set: function (value) {
  8361. if (this._depthFunc === value) {
  8362. return;
  8363. }
  8364. this._depthFunc = value;
  8365. this._isDepthFuncDirty = true;
  8366. },
  8367. enumerable: true,
  8368. configurable: true
  8369. });
  8370. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8371. get: function () {
  8372. return this._depthMask;
  8373. },
  8374. set: function (value) {
  8375. if (this._depthMask === value) {
  8376. return;
  8377. }
  8378. this._depthMask = value;
  8379. this._isDepthMaskDirty = true;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8385. get: function () {
  8386. return this._depthTest;
  8387. },
  8388. set: function (value) {
  8389. if (this._depthTest === value) {
  8390. return;
  8391. }
  8392. this._depthTest = value;
  8393. this._isDepthTestDirty = true;
  8394. },
  8395. enumerable: true,
  8396. configurable: true
  8397. });
  8398. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8399. get: function () {
  8400. return this._frontFace;
  8401. },
  8402. set: function (value) {
  8403. if (this._frontFace === value) {
  8404. return;
  8405. }
  8406. this._frontFace = value;
  8407. this._isFrontFaceDirty = true;
  8408. },
  8409. enumerable: true,
  8410. configurable: true
  8411. });
  8412. _DepthCullingState.prototype.reset = function () {
  8413. this._depthMask = true;
  8414. this._depthTest = true;
  8415. this._depthFunc = null;
  8416. this._cullFace = null;
  8417. this._cull = null;
  8418. this._zOffset = 0;
  8419. this._frontFace = null;
  8420. this._isDepthTestDirty = true;
  8421. this._isDepthMaskDirty = true;
  8422. this._isDepthFuncDirty = false;
  8423. this._isCullFaceDirty = false;
  8424. this._isCullDirty = false;
  8425. this._isZOffsetDirty = false;
  8426. this._isFrontFaceDirty = false;
  8427. };
  8428. _DepthCullingState.prototype.apply = function (gl) {
  8429. if (!this.isDirty) {
  8430. return;
  8431. }
  8432. // Cull
  8433. if (this._isCullDirty) {
  8434. if (this.cull) {
  8435. gl.enable(gl.CULL_FACE);
  8436. }
  8437. else {
  8438. gl.disable(gl.CULL_FACE);
  8439. }
  8440. this._isCullDirty = false;
  8441. }
  8442. // Cull face
  8443. if (this._isCullFaceDirty) {
  8444. gl.cullFace(this.cullFace);
  8445. this._isCullFaceDirty = false;
  8446. }
  8447. // Depth mask
  8448. if (this._isDepthMaskDirty) {
  8449. gl.depthMask(this.depthMask);
  8450. this._isDepthMaskDirty = false;
  8451. }
  8452. // Depth test
  8453. if (this._isDepthTestDirty) {
  8454. if (this.depthTest) {
  8455. gl.enable(gl.DEPTH_TEST);
  8456. }
  8457. else {
  8458. gl.disable(gl.DEPTH_TEST);
  8459. }
  8460. this._isDepthTestDirty = false;
  8461. }
  8462. // Depth func
  8463. if (this._isDepthFuncDirty) {
  8464. gl.depthFunc(this.depthFunc);
  8465. this._isDepthFuncDirty = false;
  8466. }
  8467. // zOffset
  8468. if (this._isZOffsetDirty) {
  8469. if (this.zOffset) {
  8470. gl.enable(gl.POLYGON_OFFSET_FILL);
  8471. gl.polygonOffset(this.zOffset, 0);
  8472. }
  8473. else {
  8474. gl.disable(gl.POLYGON_OFFSET_FILL);
  8475. }
  8476. this._isZOffsetDirty = false;
  8477. }
  8478. // Front face
  8479. if (this._isFrontFaceDirty) {
  8480. gl.frontFace(this.frontFace);
  8481. this._isFrontFaceDirty = false;
  8482. }
  8483. };
  8484. return _DepthCullingState;
  8485. }());
  8486. BABYLON._DepthCullingState = _DepthCullingState;
  8487. })(BABYLON || (BABYLON = {}));
  8488. //# sourceMappingURL=babylon.depthCullingState.js.map
  8489. var BABYLON;
  8490. (function (BABYLON) {
  8491. var _StencilState = /** @class */ (function () {
  8492. function _StencilState() {
  8493. this._isStencilTestDirty = false;
  8494. this._isStencilMaskDirty = false;
  8495. this._isStencilFuncDirty = false;
  8496. this._isStencilOpDirty = false;
  8497. this.reset();
  8498. }
  8499. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8500. get: function () {
  8501. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8507. get: function () {
  8508. return this._stencilFunc;
  8509. },
  8510. set: function (value) {
  8511. if (this._stencilFunc === value) {
  8512. return;
  8513. }
  8514. this._stencilFunc = value;
  8515. this._isStencilFuncDirty = true;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8521. get: function () {
  8522. return this._stencilFuncRef;
  8523. },
  8524. set: function (value) {
  8525. if (this._stencilFuncRef === value) {
  8526. return;
  8527. }
  8528. this._stencilFuncRef = value;
  8529. this._isStencilFuncDirty = true;
  8530. },
  8531. enumerable: true,
  8532. configurable: true
  8533. });
  8534. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8535. get: function () {
  8536. return this._stencilFuncMask;
  8537. },
  8538. set: function (value) {
  8539. if (this._stencilFuncMask === value) {
  8540. return;
  8541. }
  8542. this._stencilFuncMask = value;
  8543. this._isStencilFuncDirty = true;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8549. get: function () {
  8550. return this._stencilOpStencilFail;
  8551. },
  8552. set: function (value) {
  8553. if (this._stencilOpStencilFail === value) {
  8554. return;
  8555. }
  8556. this._stencilOpStencilFail = value;
  8557. this._isStencilOpDirty = true;
  8558. },
  8559. enumerable: true,
  8560. configurable: true
  8561. });
  8562. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8563. get: function () {
  8564. return this._stencilOpDepthFail;
  8565. },
  8566. set: function (value) {
  8567. if (this._stencilOpDepthFail === value) {
  8568. return;
  8569. }
  8570. this._stencilOpDepthFail = value;
  8571. this._isStencilOpDirty = true;
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8577. get: function () {
  8578. return this._stencilOpStencilDepthPass;
  8579. },
  8580. set: function (value) {
  8581. if (this._stencilOpStencilDepthPass === value) {
  8582. return;
  8583. }
  8584. this._stencilOpStencilDepthPass = value;
  8585. this._isStencilOpDirty = true;
  8586. },
  8587. enumerable: true,
  8588. configurable: true
  8589. });
  8590. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8591. get: function () {
  8592. return this._stencilMask;
  8593. },
  8594. set: function (value) {
  8595. if (this._stencilMask === value) {
  8596. return;
  8597. }
  8598. this._stencilMask = value;
  8599. this._isStencilMaskDirty = true;
  8600. },
  8601. enumerable: true,
  8602. configurable: true
  8603. });
  8604. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8605. get: function () {
  8606. return this._stencilTest;
  8607. },
  8608. set: function (value) {
  8609. if (this._stencilTest === value) {
  8610. return;
  8611. }
  8612. this._stencilTest = value;
  8613. this._isStencilTestDirty = true;
  8614. },
  8615. enumerable: true,
  8616. configurable: true
  8617. });
  8618. _StencilState.prototype.reset = function () {
  8619. this._stencilTest = false;
  8620. this._stencilMask = 0xFF;
  8621. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8622. this._stencilFuncRef = 1;
  8623. this._stencilFuncMask = 0xFF;
  8624. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8625. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8626. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8627. this._isStencilTestDirty = true;
  8628. this._isStencilMaskDirty = true;
  8629. this._isStencilFuncDirty = true;
  8630. this._isStencilOpDirty = true;
  8631. };
  8632. _StencilState.prototype.apply = function (gl) {
  8633. if (!this.isDirty) {
  8634. return;
  8635. }
  8636. // Stencil test
  8637. if (this._isStencilTestDirty) {
  8638. if (this.stencilTest) {
  8639. gl.enable(gl.STENCIL_TEST);
  8640. }
  8641. else {
  8642. gl.disable(gl.STENCIL_TEST);
  8643. }
  8644. this._isStencilTestDirty = false;
  8645. }
  8646. // Stencil mask
  8647. if (this._isStencilMaskDirty) {
  8648. gl.stencilMask(this.stencilMask);
  8649. this._isStencilMaskDirty = false;
  8650. }
  8651. // Stencil func
  8652. if (this._isStencilFuncDirty) {
  8653. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8654. this._isStencilFuncDirty = false;
  8655. }
  8656. // Stencil op
  8657. if (this._isStencilOpDirty) {
  8658. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8659. this._isStencilOpDirty = false;
  8660. }
  8661. };
  8662. return _StencilState;
  8663. }());
  8664. BABYLON._StencilState = _StencilState;
  8665. })(BABYLON || (BABYLON = {}));
  8666. //# sourceMappingURL=babylon.stencilState.js.map
  8667. var BABYLON;
  8668. (function (BABYLON) {
  8669. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8670. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8671. };
  8672. var compileRawShader = function (gl, source, type) {
  8673. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8674. gl.shaderSource(shader, source);
  8675. gl.compileShader(shader);
  8676. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8677. var log = gl.getShaderInfoLog(shader);
  8678. if (log) {
  8679. throw new Error(log);
  8680. }
  8681. }
  8682. if (!shader) {
  8683. throw new Error("Something went wrong while compile the shader.");
  8684. }
  8685. return shader;
  8686. };
  8687. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8688. var magFilter = gl.NEAREST;
  8689. var minFilter = gl.NEAREST;
  8690. switch (samplingMode) {
  8691. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8692. magFilter = gl.LINEAR;
  8693. if (generateMipMaps) {
  8694. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8695. }
  8696. else {
  8697. minFilter = gl.LINEAR;
  8698. }
  8699. break;
  8700. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8701. magFilter = gl.LINEAR;
  8702. if (generateMipMaps) {
  8703. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8704. }
  8705. else {
  8706. minFilter = gl.LINEAR;
  8707. }
  8708. break;
  8709. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8710. magFilter = gl.NEAREST;
  8711. if (generateMipMaps) {
  8712. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8713. }
  8714. else {
  8715. minFilter = gl.NEAREST;
  8716. }
  8717. break;
  8718. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8719. magFilter = gl.NEAREST;
  8720. if (generateMipMaps) {
  8721. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8722. }
  8723. else {
  8724. minFilter = gl.NEAREST;
  8725. }
  8726. break;
  8727. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8728. magFilter = gl.NEAREST;
  8729. if (generateMipMaps) {
  8730. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8731. }
  8732. else {
  8733. minFilter = gl.LINEAR;
  8734. }
  8735. break;
  8736. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8737. magFilter = gl.NEAREST;
  8738. if (generateMipMaps) {
  8739. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8740. }
  8741. else {
  8742. minFilter = gl.LINEAR;
  8743. }
  8744. break;
  8745. case BABYLON.Texture.NEAREST_LINEAR:
  8746. magFilter = gl.NEAREST;
  8747. minFilter = gl.LINEAR;
  8748. break;
  8749. case BABYLON.Texture.NEAREST_NEAREST:
  8750. magFilter = gl.NEAREST;
  8751. minFilter = gl.NEAREST;
  8752. break;
  8753. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8754. magFilter = gl.LINEAR;
  8755. if (generateMipMaps) {
  8756. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8757. }
  8758. else {
  8759. minFilter = gl.NEAREST;
  8760. }
  8761. break;
  8762. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8763. magFilter = gl.LINEAR;
  8764. if (generateMipMaps) {
  8765. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8766. }
  8767. else {
  8768. minFilter = gl.NEAREST;
  8769. }
  8770. break;
  8771. case BABYLON.Texture.LINEAR_LINEAR:
  8772. magFilter = gl.LINEAR;
  8773. minFilter = gl.LINEAR;
  8774. break;
  8775. case BABYLON.Texture.LINEAR_NEAREST:
  8776. magFilter = gl.LINEAR;
  8777. minFilter = gl.NEAREST;
  8778. break;
  8779. }
  8780. return {
  8781. min: minFilter,
  8782. mag: magFilter
  8783. };
  8784. };
  8785. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8786. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8787. var img;
  8788. var onload = function () {
  8789. loadedImages[index] = img;
  8790. loadedImages._internalCount++;
  8791. if (scene) {
  8792. scene._removePendingData(img);
  8793. }
  8794. if (loadedImages._internalCount === 6) {
  8795. onfinish(loadedImages);
  8796. }
  8797. };
  8798. var onerror = function (message, exception) {
  8799. if (scene) {
  8800. scene._removePendingData(img);
  8801. }
  8802. if (onErrorCallBack) {
  8803. onErrorCallBack(message, exception);
  8804. }
  8805. };
  8806. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8807. if (scene) {
  8808. scene._addPendingData(img);
  8809. }
  8810. };
  8811. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8812. if (onError === void 0) { onError = null; }
  8813. var loadedImages = [];
  8814. loadedImages._internalCount = 0;
  8815. for (var index = 0; index < 6; index++) {
  8816. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8817. }
  8818. };
  8819. var BufferPointer = /** @class */ (function () {
  8820. function BufferPointer() {
  8821. }
  8822. return BufferPointer;
  8823. }());
  8824. var InstancingAttributeInfo = /** @class */ (function () {
  8825. function InstancingAttributeInfo() {
  8826. }
  8827. return InstancingAttributeInfo;
  8828. }());
  8829. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8830. /**
  8831. * Define options used to create a render target texture
  8832. */
  8833. var RenderTargetCreationOptions = /** @class */ (function () {
  8834. function RenderTargetCreationOptions() {
  8835. }
  8836. return RenderTargetCreationOptions;
  8837. }());
  8838. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8839. /**
  8840. * Regroup several parameters relative to the browser in use
  8841. */
  8842. var EngineCapabilities = /** @class */ (function () {
  8843. function EngineCapabilities() {
  8844. }
  8845. return EngineCapabilities;
  8846. }());
  8847. BABYLON.EngineCapabilities = EngineCapabilities;
  8848. /**
  8849. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8850. */
  8851. var Engine = /** @class */ (function () {
  8852. /**
  8853. * @constructor
  8854. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8855. * @param {boolean} [antialias] - enable antialias
  8856. * @param options - further options to be sent to the getContext function
  8857. */
  8858. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8859. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8860. var _this = this;
  8861. // Public members
  8862. this.forcePOTTextures = false;
  8863. this.isFullscreen = false;
  8864. this.isPointerLock = false;
  8865. this.cullBackFaces = true;
  8866. this.renderEvenInBackground = true;
  8867. this.preventCacheWipeBetweenFrames = false;
  8868. // To enable/disable IDB support and avoid XHR on .manifest
  8869. this.enableOfflineSupport = false;
  8870. this.scenes = new Array();
  8871. this.postProcesses = new Array();
  8872. // Observables
  8873. /**
  8874. * Observable event triggered each time the rendering canvas is resized
  8875. */
  8876. this.onResizeObservable = new BABYLON.Observable();
  8877. /**
  8878. * Observable event triggered each time the canvas loses focus
  8879. */
  8880. this.onCanvasBlurObservable = new BABYLON.Observable();
  8881. /**
  8882. * Observable event triggered each time the canvas gains focus
  8883. */
  8884. this.onCanvasFocusObservable = new BABYLON.Observable();
  8885. /**
  8886. * Observable event triggered each time the canvas receives pointerout event
  8887. */
  8888. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8889. /**
  8890. * Observable event triggered before each texture is initialized
  8891. */
  8892. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8893. //WebVR
  8894. this._vrDisplay = undefined;
  8895. this._vrSupported = false;
  8896. this._vrExclusivePointerMode = false;
  8897. // Uniform buffers list
  8898. this.disableUniformBuffers = false;
  8899. this._uniformBuffers = new Array();
  8900. // Observables
  8901. /**
  8902. * Observable raised when the engine begins a new frame
  8903. */
  8904. this.onBeginFrameObservable = new BABYLON.Observable();
  8905. /**
  8906. * Observable raised when the engine ends the current frame
  8907. */
  8908. this.onEndFrameObservable = new BABYLON.Observable();
  8909. /**
  8910. * Observable raised when the engine is about to compile a shader
  8911. */
  8912. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8913. /**
  8914. * Observable raised when the engine has jsut compiled a shader
  8915. */
  8916. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8917. this._windowIsBackground = false;
  8918. this._webGLVersion = 1.0;
  8919. this._badOS = false;
  8920. this._badDesktopOS = false;
  8921. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8922. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8923. this.onVRRequestPresentStart = new BABYLON.Observable();
  8924. this._colorWrite = true;
  8925. this._drawCalls = new BABYLON.PerfCounter();
  8926. this._textureCollisions = new BABYLON.PerfCounter();
  8927. this._renderingQueueLaunched = false;
  8928. this._activeRenderLoops = new Array();
  8929. // Deterministic lockstepMaxSteps
  8930. this._deterministicLockstep = false;
  8931. this._lockstepMaxSteps = 4;
  8932. // Lost context
  8933. this.onContextLostObservable = new BABYLON.Observable();
  8934. this.onContextRestoredObservable = new BABYLON.Observable();
  8935. this._contextWasLost = false;
  8936. this._doNotHandleContextLost = false;
  8937. // FPS
  8938. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8939. this._fps = 60;
  8940. this._deltaTime = 0;
  8941. /**
  8942. * Turn this value on if you want to pause FPS computation when in background
  8943. */
  8944. this.disablePerformanceMonitorInBackground = false;
  8945. // States
  8946. this._depthCullingState = new BABYLON._DepthCullingState();
  8947. this._stencilState = new BABYLON._StencilState();
  8948. this._alphaState = new BABYLON._AlphaState();
  8949. this._alphaMode = Engine.ALPHA_DISABLE;
  8950. // Cache
  8951. this._internalTexturesCache = new Array();
  8952. this._boundTexturesCache = {};
  8953. this._boundTexturesStack = new Array();
  8954. this._compiledEffects = {};
  8955. this._vertexAttribArraysEnabled = [];
  8956. this._uintIndicesCurrentlySet = false;
  8957. this._currentBoundBuffer = new Array();
  8958. this._currentBufferPointers = new Array();
  8959. this._currentInstanceLocations = new Array();
  8960. this._currentInstanceBuffers = new Array();
  8961. this._vaoRecordInProgress = false;
  8962. this._mustWipeVertexAttributes = false;
  8963. this._nextFreeTextureSlots = new Array();
  8964. this._activeRequests = new Array();
  8965. // Hardware supported Compressed Textures
  8966. this._texturesSupported = new Array();
  8967. this._onVRFullScreenTriggered = function () {
  8968. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8969. //get the old size before we change
  8970. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8971. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8972. //get the width and height, change the render size
  8973. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8974. _this.setHardwareScalingLevel(1);
  8975. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8976. }
  8977. else {
  8978. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8979. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8980. }
  8981. };
  8982. this._boundUniforms = {};
  8983. var canvas = null;
  8984. Engine.Instances.push(this);
  8985. if (!canvasOrContext) {
  8986. return;
  8987. }
  8988. options = options || {};
  8989. if (canvasOrContext.getContext) {
  8990. canvas = canvasOrContext;
  8991. this._renderingCanvas = canvas;
  8992. if (antialias != null) {
  8993. options.antialias = antialias;
  8994. }
  8995. if (options.deterministicLockstep === undefined) {
  8996. options.deterministicLockstep = false;
  8997. }
  8998. if (options.lockstepMaxSteps === undefined) {
  8999. options.lockstepMaxSteps = 4;
  9000. }
  9001. if (options.preserveDrawingBuffer === undefined) {
  9002. options.preserveDrawingBuffer = false;
  9003. }
  9004. if (options.audioEngine === undefined) {
  9005. options.audioEngine = true;
  9006. }
  9007. if (options.stencil === undefined) {
  9008. options.stencil = true;
  9009. }
  9010. this._deterministicLockstep = options.deterministicLockstep;
  9011. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9012. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9013. // Exceptions
  9014. if (navigator && navigator.userAgent) {
  9015. var ua = navigator.userAgent;
  9016. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9017. var exception = _a[_i];
  9018. var key = exception.key;
  9019. var targets = exception.targets;
  9020. if (ua.indexOf(key) > -1) {
  9021. if (exception.capture && exception.captureConstraint) {
  9022. var capture = exception.capture;
  9023. var constraint = exception.captureConstraint;
  9024. var regex = new RegExp(capture);
  9025. var matches = regex.exec(ua);
  9026. if (matches && matches.length > 0) {
  9027. var capturedValue = parseInt(matches[matches.length - 1]);
  9028. if (capturedValue >= constraint) {
  9029. continue;
  9030. }
  9031. }
  9032. }
  9033. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9034. var target = targets_1[_b];
  9035. switch (target) {
  9036. case "uniformBuffer":
  9037. this.disableUniformBuffers = true;
  9038. break;
  9039. }
  9040. }
  9041. break;
  9042. }
  9043. }
  9044. }
  9045. // GL
  9046. if (!options.disableWebGL2Support) {
  9047. try {
  9048. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9049. if (this._gl) {
  9050. this._webGLVersion = 2.0;
  9051. }
  9052. }
  9053. catch (e) {
  9054. // Do nothing
  9055. }
  9056. }
  9057. if (!this._gl) {
  9058. if (!canvas) {
  9059. throw new Error("The provided canvas is null or undefined.");
  9060. }
  9061. try {
  9062. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9063. }
  9064. catch (e) {
  9065. throw new Error("WebGL not supported");
  9066. }
  9067. }
  9068. if (!this._gl) {
  9069. throw new Error("WebGL not supported");
  9070. }
  9071. this._onCanvasFocus = function () {
  9072. _this.onCanvasFocusObservable.notifyObservers(_this);
  9073. };
  9074. this._onCanvasBlur = function () {
  9075. _this.onCanvasBlurObservable.notifyObservers(_this);
  9076. };
  9077. canvas.addEventListener("focus", this._onCanvasFocus);
  9078. canvas.addEventListener("blur", this._onCanvasBlur);
  9079. this._onBlur = function () {
  9080. if (_this.disablePerformanceMonitorInBackground) {
  9081. _this._performanceMonitor.disable();
  9082. }
  9083. _this._windowIsBackground = true;
  9084. };
  9085. this._onFocus = function () {
  9086. if (_this.disablePerformanceMonitorInBackground) {
  9087. _this._performanceMonitor.enable();
  9088. }
  9089. _this._windowIsBackground = false;
  9090. };
  9091. this._onCanvasPointerOut = function () {
  9092. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9093. };
  9094. window.addEventListener("blur", this._onBlur);
  9095. window.addEventListener("focus", this._onFocus);
  9096. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9097. // Context lost
  9098. if (!this._doNotHandleContextLost) {
  9099. this._onContextLost = function (evt) {
  9100. evt.preventDefault();
  9101. _this._contextWasLost = true;
  9102. BABYLON.Tools.Warn("WebGL context lost.");
  9103. _this.onContextLostObservable.notifyObservers(_this);
  9104. };
  9105. this._onContextRestored = function (evt) {
  9106. // Adding a timeout to avoid race condition at browser level
  9107. setTimeout(function () {
  9108. // Rebuild gl context
  9109. _this._initGLContext();
  9110. // Rebuild effects
  9111. _this._rebuildEffects();
  9112. // Rebuild textures
  9113. _this._rebuildInternalTextures();
  9114. // Rebuild buffers
  9115. _this._rebuildBuffers();
  9116. // Cache
  9117. _this.wipeCaches(true);
  9118. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9119. _this.onContextRestoredObservable.notifyObservers(_this);
  9120. _this._contextWasLost = false;
  9121. }, 0);
  9122. };
  9123. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9124. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9125. }
  9126. }
  9127. else {
  9128. this._gl = canvasOrContext;
  9129. this._renderingCanvas = this._gl.canvas;
  9130. if (this._gl.renderbufferStorageMultisample) {
  9131. this._webGLVersion = 2.0;
  9132. }
  9133. options.stencil = this._gl.getContextAttributes().stencil;
  9134. }
  9135. // Viewport
  9136. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9137. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9138. this.resize();
  9139. this._isStencilEnable = options.stencil ? true : false;
  9140. this._initGLContext();
  9141. if (canvas) {
  9142. // Fullscreen
  9143. this._onFullscreenChange = function () {
  9144. if (document.fullscreen !== undefined) {
  9145. _this.isFullscreen = document.fullscreen;
  9146. }
  9147. else if (document.mozFullScreen !== undefined) {
  9148. _this.isFullscreen = document.mozFullScreen;
  9149. }
  9150. else if (document.webkitIsFullScreen !== undefined) {
  9151. _this.isFullscreen = document.webkitIsFullScreen;
  9152. }
  9153. else if (document.msIsFullScreen !== undefined) {
  9154. _this.isFullscreen = document.msIsFullScreen;
  9155. }
  9156. // Pointer lock
  9157. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9158. canvas.requestPointerLock = canvas.requestPointerLock ||
  9159. canvas.msRequestPointerLock ||
  9160. canvas.mozRequestPointerLock ||
  9161. canvas.webkitRequestPointerLock;
  9162. if (canvas.requestPointerLock) {
  9163. canvas.requestPointerLock();
  9164. }
  9165. }
  9166. };
  9167. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9168. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9169. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9170. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9171. // Pointer lock
  9172. this._onPointerLockChange = function () {
  9173. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9174. document.webkitPointerLockElement === canvas ||
  9175. document.msPointerLockElement === canvas ||
  9176. document.pointerLockElement === canvas);
  9177. };
  9178. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9179. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9180. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9181. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9182. this._onVRDisplayPointerRestricted = function () {
  9183. if (canvas) {
  9184. canvas.requestPointerLock();
  9185. }
  9186. };
  9187. this._onVRDisplayPointerUnrestricted = function () {
  9188. document.exitPointerLock();
  9189. };
  9190. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9191. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9192. }
  9193. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9194. Engine.audioEngine = new BABYLON.AudioEngine();
  9195. }
  9196. // Prepare buffer pointers
  9197. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9198. this._currentBufferPointers[i] = new BufferPointer();
  9199. }
  9200. // Load WebVR Devices
  9201. if (options.autoEnableWebVR) {
  9202. this.initWebVR();
  9203. }
  9204. // Detect if we are running on a faulty buggy OS.
  9205. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9206. // Detect if we are running on a faulty buggy desktop OS.
  9207. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9208. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9209. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9210. }
  9211. Object.defineProperty(Engine, "LastCreatedEngine", {
  9212. get: function () {
  9213. if (Engine.Instances.length === 0) {
  9214. return null;
  9215. }
  9216. return Engine.Instances[Engine.Instances.length - 1];
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(Engine, "LastCreatedScene", {
  9222. get: function () {
  9223. var lastCreatedEngine = Engine.LastCreatedEngine;
  9224. if (!lastCreatedEngine) {
  9225. return null;
  9226. }
  9227. if (lastCreatedEngine.scenes.length === 0) {
  9228. return null;
  9229. }
  9230. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. /**
  9236. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9237. */
  9238. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9239. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9240. var engine = Engine.Instances[engineIndex];
  9241. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9242. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9243. }
  9244. }
  9245. };
  9246. Object.defineProperty(Engine, "NEVER", {
  9247. get: function () {
  9248. return Engine._NEVER;
  9249. },
  9250. enumerable: true,
  9251. configurable: true
  9252. });
  9253. Object.defineProperty(Engine, "ALWAYS", {
  9254. get: function () {
  9255. return Engine._ALWAYS;
  9256. },
  9257. enumerable: true,
  9258. configurable: true
  9259. });
  9260. Object.defineProperty(Engine, "LESS", {
  9261. get: function () {
  9262. return Engine._LESS;
  9263. },
  9264. enumerable: true,
  9265. configurable: true
  9266. });
  9267. Object.defineProperty(Engine, "EQUAL", {
  9268. get: function () {
  9269. return Engine._EQUAL;
  9270. },
  9271. enumerable: true,
  9272. configurable: true
  9273. });
  9274. Object.defineProperty(Engine, "LEQUAL", {
  9275. get: function () {
  9276. return Engine._LEQUAL;
  9277. },
  9278. enumerable: true,
  9279. configurable: true
  9280. });
  9281. Object.defineProperty(Engine, "GREATER", {
  9282. get: function () {
  9283. return Engine._GREATER;
  9284. },
  9285. enumerable: true,
  9286. configurable: true
  9287. });
  9288. Object.defineProperty(Engine, "GEQUAL", {
  9289. get: function () {
  9290. return Engine._GEQUAL;
  9291. },
  9292. enumerable: true,
  9293. configurable: true
  9294. });
  9295. Object.defineProperty(Engine, "NOTEQUAL", {
  9296. get: function () {
  9297. return Engine._NOTEQUAL;
  9298. },
  9299. enumerable: true,
  9300. configurable: true
  9301. });
  9302. Object.defineProperty(Engine, "KEEP", {
  9303. get: function () {
  9304. return Engine._KEEP;
  9305. },
  9306. enumerable: true,
  9307. configurable: true
  9308. });
  9309. Object.defineProperty(Engine, "REPLACE", {
  9310. get: function () {
  9311. return Engine._REPLACE;
  9312. },
  9313. enumerable: true,
  9314. configurable: true
  9315. });
  9316. Object.defineProperty(Engine, "INCR", {
  9317. get: function () {
  9318. return Engine._INCR;
  9319. },
  9320. enumerable: true,
  9321. configurable: true
  9322. });
  9323. Object.defineProperty(Engine, "DECR", {
  9324. get: function () {
  9325. return Engine._DECR;
  9326. },
  9327. enumerable: true,
  9328. configurable: true
  9329. });
  9330. Object.defineProperty(Engine, "INVERT", {
  9331. get: function () {
  9332. return Engine._INVERT;
  9333. },
  9334. enumerable: true,
  9335. configurable: true
  9336. });
  9337. Object.defineProperty(Engine, "INCR_WRAP", {
  9338. get: function () {
  9339. return Engine._INCR_WRAP;
  9340. },
  9341. enumerable: true,
  9342. configurable: true
  9343. });
  9344. Object.defineProperty(Engine, "DECR_WRAP", {
  9345. get: function () {
  9346. return Engine._DECR_WRAP;
  9347. },
  9348. enumerable: true,
  9349. configurable: true
  9350. });
  9351. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9352. get: function () {
  9353. return Engine._ALPHA_DISABLE;
  9354. },
  9355. enumerable: true,
  9356. configurable: true
  9357. });
  9358. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9359. get: function () {
  9360. return Engine._ALPHA_ONEONE;
  9361. },
  9362. enumerable: true,
  9363. configurable: true
  9364. });
  9365. Object.defineProperty(Engine, "ALPHA_ADD", {
  9366. get: function () {
  9367. return Engine._ALPHA_ADD;
  9368. },
  9369. enumerable: true,
  9370. configurable: true
  9371. });
  9372. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9373. get: function () {
  9374. return Engine._ALPHA_COMBINE;
  9375. },
  9376. enumerable: true,
  9377. configurable: true
  9378. });
  9379. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9380. get: function () {
  9381. return Engine._ALPHA_SUBTRACT;
  9382. },
  9383. enumerable: true,
  9384. configurable: true
  9385. });
  9386. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9387. get: function () {
  9388. return Engine._ALPHA_MULTIPLY;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9394. get: function () {
  9395. return Engine._ALPHA_MAXIMIZED;
  9396. },
  9397. enumerable: true,
  9398. configurable: true
  9399. });
  9400. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9401. get: function () {
  9402. return Engine._ALPHA_PREMULTIPLIED;
  9403. },
  9404. enumerable: true,
  9405. configurable: true
  9406. });
  9407. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9408. get: function () {
  9409. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9410. },
  9411. enumerable: true,
  9412. configurable: true
  9413. });
  9414. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9415. get: function () {
  9416. return Engine._ALPHA_INTERPOLATE;
  9417. },
  9418. enumerable: true,
  9419. configurable: true
  9420. });
  9421. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9422. get: function () {
  9423. return Engine._ALPHA_SCREENMODE;
  9424. },
  9425. enumerable: true,
  9426. configurable: true
  9427. });
  9428. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9429. get: function () {
  9430. return Engine._DELAYLOADSTATE_NONE;
  9431. },
  9432. enumerable: true,
  9433. configurable: true
  9434. });
  9435. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9436. get: function () {
  9437. return Engine._DELAYLOADSTATE_LOADED;
  9438. },
  9439. enumerable: true,
  9440. configurable: true
  9441. });
  9442. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9443. get: function () {
  9444. return Engine._DELAYLOADSTATE_LOADING;
  9445. },
  9446. enumerable: true,
  9447. configurable: true
  9448. });
  9449. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9450. get: function () {
  9451. return Engine._DELAYLOADSTATE_NOTLOADED;
  9452. },
  9453. enumerable: true,
  9454. configurable: true
  9455. });
  9456. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9457. get: function () {
  9458. return Engine._TEXTUREFORMAT_ALPHA;
  9459. },
  9460. enumerable: true,
  9461. configurable: true
  9462. });
  9463. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9464. get: function () {
  9465. return Engine._TEXTUREFORMAT_LUMINANCE;
  9466. },
  9467. enumerable: true,
  9468. configurable: true
  9469. });
  9470. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9471. get: function () {
  9472. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9473. },
  9474. enumerable: true,
  9475. configurable: true
  9476. });
  9477. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9478. get: function () {
  9479. return Engine._TEXTUREFORMAT_RGB;
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9485. get: function () {
  9486. return Engine._TEXTUREFORMAT_RGBA;
  9487. },
  9488. enumerable: true,
  9489. configurable: true
  9490. });
  9491. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9492. get: function () {
  9493. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9494. },
  9495. enumerable: true,
  9496. configurable: true
  9497. });
  9498. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9499. get: function () {
  9500. return Engine._TEXTURETYPE_FLOAT;
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9506. get: function () {
  9507. return Engine._TEXTURETYPE_HALF_FLOAT;
  9508. },
  9509. enumerable: true,
  9510. configurable: true
  9511. });
  9512. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9513. get: function () {
  9514. return Engine._SCALEMODE_FLOOR;
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9520. get: function () {
  9521. return Engine._SCALEMODE_NEAREST;
  9522. },
  9523. enumerable: true,
  9524. configurable: true
  9525. });
  9526. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9527. get: function () {
  9528. return Engine._SCALEMODE_CEILING;
  9529. },
  9530. enumerable: true,
  9531. configurable: true
  9532. });
  9533. Object.defineProperty(Engine, "Version", {
  9534. get: function () {
  9535. return "3.2.0-alpha2";
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9541. get: function () {
  9542. return this._vrExclusivePointerMode;
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9548. get: function () {
  9549. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9555. get: function () {
  9556. return this._webGLVersion < 2 || this.forcePOTTextures;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Engine.prototype, "badOS", {
  9562. get: function () {
  9563. return this._badOS;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9569. get: function () {
  9570. return this._badDesktopOS;
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9576. get: function () {
  9577. return this._performanceMonitor;
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9583. get: function () {
  9584. return this._texturesSupported;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9590. get: function () {
  9591. return this._textureFormatInUse;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(Engine.prototype, "currentViewport", {
  9597. get: function () {
  9598. return this._cachedViewport;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9604. // Empty texture
  9605. get: function () {
  9606. if (!this._emptyTexture) {
  9607. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9608. }
  9609. return this._emptyTexture;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9615. get: function () {
  9616. if (!this._emptyTexture3D) {
  9617. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9618. }
  9619. return this._emptyTexture3D;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9625. get: function () {
  9626. if (!this._emptyCubeTexture) {
  9627. var faceData = new Uint8Array(4);
  9628. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9629. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9630. }
  9631. return this._emptyCubeTexture;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. Engine.prototype._rebuildInternalTextures = function () {
  9637. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9638. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9639. var internalTexture = currentState_1[_i];
  9640. internalTexture._rebuild();
  9641. }
  9642. };
  9643. Engine.prototype._rebuildEffects = function () {
  9644. for (var key in this._compiledEffects) {
  9645. var effect = this._compiledEffects[key];
  9646. effect._prepareEffect();
  9647. }
  9648. BABYLON.Effect.ResetCache();
  9649. };
  9650. Engine.prototype._rebuildBuffers = function () {
  9651. // Index / Vertex
  9652. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9653. var scene = _a[_i];
  9654. scene.resetCachedMaterial();
  9655. scene._rebuildGeometries();
  9656. scene._rebuildTextures();
  9657. }
  9658. // Uniforms
  9659. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9660. var uniformBuffer = _c[_b];
  9661. uniformBuffer._rebuild();
  9662. }
  9663. };
  9664. Engine.prototype._initGLContext = function () {
  9665. // Caps
  9666. this._caps = new EngineCapabilities();
  9667. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9668. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9669. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9670. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9671. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9672. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9673. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9674. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9675. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9676. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9677. // Infos
  9678. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9679. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9680. if (rendererInfo != null) {
  9681. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9682. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9683. }
  9684. if (!this._glVendor) {
  9685. this._glVendor = "Unknown vendor";
  9686. }
  9687. if (!this._glRenderer) {
  9688. this._glRenderer = "Unknown renderer";
  9689. }
  9690. // Constants
  9691. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9692. if (this._gl.RGBA16F !== 0x881A) {
  9693. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9694. }
  9695. if (this._gl.RGBA32F !== 0x8814) {
  9696. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9697. }
  9698. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9699. this._gl.DEPTH24_STENCIL8 = 35056;
  9700. }
  9701. // Extensions
  9702. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9703. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9704. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9705. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9706. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9707. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9708. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9709. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  9710. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9711. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9712. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9713. this._caps.highPrecisionShaderSupported = true;
  9714. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9715. if (this._caps.timerQuery) {
  9716. if (this._webGLVersion === 1) {
  9717. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9718. }
  9719. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9720. }
  9721. // Checks if some of the format renders first to allow the use of webgl inspector.
  9722. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9723. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9724. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9725. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9726. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9727. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9728. if (this._webGLVersion > 1) {
  9729. this._gl.HALF_FLOAT_OES = 0x140B;
  9730. }
  9731. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9732. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9733. // Draw buffers
  9734. if (this._webGLVersion > 1) {
  9735. this._caps.drawBuffersExtension = true;
  9736. }
  9737. else {
  9738. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9739. if (drawBuffersExtension !== null) {
  9740. this._caps.drawBuffersExtension = true;
  9741. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9742. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9743. for (var i = 0; i < 16; i++) {
  9744. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9745. }
  9746. }
  9747. else {
  9748. this._caps.drawBuffersExtension = false;
  9749. }
  9750. }
  9751. // Depth Texture
  9752. if (this._webGLVersion > 1) {
  9753. this._caps.depthTextureExtension = true;
  9754. }
  9755. else {
  9756. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9757. if (depthTextureExtension != null) {
  9758. this._caps.depthTextureExtension = true;
  9759. }
  9760. }
  9761. // Vertex array object
  9762. if (this._webGLVersion > 1) {
  9763. this._caps.vertexArrayObject = true;
  9764. }
  9765. else {
  9766. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9767. if (vertexArrayObjectExtension != null) {
  9768. this._caps.vertexArrayObject = true;
  9769. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9770. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9771. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9772. }
  9773. else {
  9774. this._caps.vertexArrayObject = false;
  9775. }
  9776. }
  9777. // Instances count
  9778. if (this._webGLVersion > 1) {
  9779. this._caps.instancedArrays = true;
  9780. }
  9781. else {
  9782. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9783. if (instanceExtension != null) {
  9784. this._caps.instancedArrays = true;
  9785. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9786. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9787. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9788. }
  9789. else {
  9790. this._caps.instancedArrays = false;
  9791. }
  9792. }
  9793. // Intelligently add supported compressed formats in order to check for.
  9794. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9795. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9796. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9797. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9798. if (this._caps.astc)
  9799. this.texturesSupported.push('-astc.ktx');
  9800. if (this._caps.s3tc)
  9801. this.texturesSupported.push('-dxt.ktx');
  9802. if (this._caps.pvrtc)
  9803. this.texturesSupported.push('-pvrtc.ktx');
  9804. if (this._caps.etc2)
  9805. this.texturesSupported.push('-etc2.ktx');
  9806. if (this._caps.etc1)
  9807. this.texturesSupported.push('-etc1.ktx');
  9808. if (this._gl.getShaderPrecisionFormat) {
  9809. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9810. if (highp) {
  9811. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9812. }
  9813. }
  9814. // Depth buffer
  9815. this.setDepthBuffer(true);
  9816. this.setDepthFunctionToLessOrEqual();
  9817. this.setDepthWrite(true);
  9818. // Texture maps
  9819. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9820. this._nextFreeTextureSlots.push(slot);
  9821. }
  9822. };
  9823. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9824. get: function () {
  9825. return this._webGLVersion;
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9831. /**
  9832. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9833. */
  9834. get: function () {
  9835. return this._isStencilEnable;
  9836. },
  9837. enumerable: true,
  9838. configurable: true
  9839. });
  9840. Engine.prototype._prepareWorkingCanvas = function () {
  9841. if (this._workingCanvas) {
  9842. return;
  9843. }
  9844. this._workingCanvas = document.createElement("canvas");
  9845. var context = this._workingCanvas.getContext("2d");
  9846. if (context) {
  9847. this._workingContext = context;
  9848. }
  9849. };
  9850. Engine.prototype.resetTextureCache = function () {
  9851. for (var key in this._boundTexturesCache) {
  9852. var boundTexture = this._boundTexturesCache[key];
  9853. if (boundTexture) {
  9854. this._removeDesignatedSlot(boundTexture);
  9855. }
  9856. this._boundTexturesCache[key] = null;
  9857. }
  9858. this._nextFreeTextureSlots = [];
  9859. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9860. this._nextFreeTextureSlots.push(slot);
  9861. }
  9862. this._activeChannel = -1;
  9863. };
  9864. Engine.prototype.isDeterministicLockStep = function () {
  9865. return this._deterministicLockstep;
  9866. };
  9867. Engine.prototype.getLockstepMaxSteps = function () {
  9868. return this._lockstepMaxSteps;
  9869. };
  9870. Engine.prototype.getGlInfo = function () {
  9871. return {
  9872. vendor: this._glVendor,
  9873. renderer: this._glRenderer,
  9874. version: this._glVersion
  9875. };
  9876. };
  9877. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9878. if (useScreen === void 0) { useScreen = false; }
  9879. var viewport = camera.viewport;
  9880. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9881. };
  9882. Engine.prototype.getRenderWidth = function (useScreen) {
  9883. if (useScreen === void 0) { useScreen = false; }
  9884. if (!useScreen && this._currentRenderTarget) {
  9885. return this._currentRenderTarget.width;
  9886. }
  9887. return this._gl.drawingBufferWidth;
  9888. };
  9889. Engine.prototype.getRenderHeight = function (useScreen) {
  9890. if (useScreen === void 0) { useScreen = false; }
  9891. if (!useScreen && this._currentRenderTarget) {
  9892. return this._currentRenderTarget.height;
  9893. }
  9894. return this._gl.drawingBufferHeight;
  9895. };
  9896. Engine.prototype.getRenderingCanvas = function () {
  9897. return this._renderingCanvas;
  9898. };
  9899. Engine.prototype.getRenderingCanvasClientRect = function () {
  9900. if (!this._renderingCanvas) {
  9901. return null;
  9902. }
  9903. return this._renderingCanvas.getBoundingClientRect();
  9904. };
  9905. Engine.prototype.setHardwareScalingLevel = function (level) {
  9906. this._hardwareScalingLevel = level;
  9907. this.resize();
  9908. };
  9909. Engine.prototype.getHardwareScalingLevel = function () {
  9910. return this._hardwareScalingLevel;
  9911. };
  9912. Engine.prototype.getLoadedTexturesCache = function () {
  9913. return this._internalTexturesCache;
  9914. };
  9915. Engine.prototype.getCaps = function () {
  9916. return this._caps;
  9917. };
  9918. Object.defineProperty(Engine.prototype, "drawCalls", {
  9919. /** The number of draw calls submitted last frame */
  9920. get: function () {
  9921. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9922. return 0;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9928. get: function () {
  9929. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9930. return null;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Engine.prototype.getDepthFunction = function () {
  9936. return this._depthCullingState.depthFunc;
  9937. };
  9938. Engine.prototype.setDepthFunction = function (depthFunc) {
  9939. this._depthCullingState.depthFunc = depthFunc;
  9940. };
  9941. Engine.prototype.setDepthFunctionToGreater = function () {
  9942. this._depthCullingState.depthFunc = this._gl.GREATER;
  9943. };
  9944. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9945. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9946. };
  9947. Engine.prototype.setDepthFunctionToLess = function () {
  9948. this._depthCullingState.depthFunc = this._gl.LESS;
  9949. };
  9950. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9951. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9952. };
  9953. Engine.prototype.getStencilBuffer = function () {
  9954. return this._stencilState.stencilTest;
  9955. };
  9956. Engine.prototype.setStencilBuffer = function (enable) {
  9957. this._stencilState.stencilTest = enable;
  9958. };
  9959. Engine.prototype.getStencilMask = function () {
  9960. return this._stencilState.stencilMask;
  9961. };
  9962. Engine.prototype.setStencilMask = function (mask) {
  9963. this._stencilState.stencilMask = mask;
  9964. };
  9965. Engine.prototype.getStencilFunction = function () {
  9966. return this._stencilState.stencilFunc;
  9967. };
  9968. Engine.prototype.getStencilFunctionReference = function () {
  9969. return this._stencilState.stencilFuncRef;
  9970. };
  9971. Engine.prototype.getStencilFunctionMask = function () {
  9972. return this._stencilState.stencilFuncMask;
  9973. };
  9974. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9975. this._stencilState.stencilFunc = stencilFunc;
  9976. };
  9977. Engine.prototype.setStencilFunctionReference = function (reference) {
  9978. this._stencilState.stencilFuncRef = reference;
  9979. };
  9980. Engine.prototype.setStencilFunctionMask = function (mask) {
  9981. this._stencilState.stencilFuncMask = mask;
  9982. };
  9983. Engine.prototype.getStencilOperationFail = function () {
  9984. return this._stencilState.stencilOpStencilFail;
  9985. };
  9986. Engine.prototype.getStencilOperationDepthFail = function () {
  9987. return this._stencilState.stencilOpDepthFail;
  9988. };
  9989. Engine.prototype.getStencilOperationPass = function () {
  9990. return this._stencilState.stencilOpStencilDepthPass;
  9991. };
  9992. Engine.prototype.setStencilOperationFail = function (operation) {
  9993. this._stencilState.stencilOpStencilFail = operation;
  9994. };
  9995. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9996. this._stencilState.stencilOpDepthFail = operation;
  9997. };
  9998. Engine.prototype.setStencilOperationPass = function (operation) {
  9999. this._stencilState.stencilOpStencilDepthPass = operation;
  10000. };
  10001. Engine.prototype.setDitheringState = function (value) {
  10002. if (value) {
  10003. this._gl.enable(this._gl.DITHER);
  10004. }
  10005. else {
  10006. this._gl.disable(this._gl.DITHER);
  10007. }
  10008. };
  10009. Engine.prototype.setRasterizerState = function (value) {
  10010. if (value) {
  10011. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10012. }
  10013. else {
  10014. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10015. }
  10016. };
  10017. /**
  10018. * stop executing a render loop function and remove it from the execution array
  10019. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10020. */
  10021. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10022. if (!renderFunction) {
  10023. this._activeRenderLoops = [];
  10024. return;
  10025. }
  10026. var index = this._activeRenderLoops.indexOf(renderFunction);
  10027. if (index >= 0) {
  10028. this._activeRenderLoops.splice(index, 1);
  10029. }
  10030. };
  10031. Engine.prototype._renderLoop = function () {
  10032. if (!this._contextWasLost) {
  10033. var shouldRender = true;
  10034. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10035. shouldRender = false;
  10036. }
  10037. if (shouldRender) {
  10038. // Start new frame
  10039. this.beginFrame();
  10040. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10041. var renderFunction = this._activeRenderLoops[index];
  10042. renderFunction();
  10043. }
  10044. // Present
  10045. this.endFrame();
  10046. }
  10047. }
  10048. if (this._activeRenderLoops.length > 0) {
  10049. // Register new frame
  10050. var requester = null;
  10051. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10052. requester = this._vrDisplay;
  10053. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10054. }
  10055. else {
  10056. this._renderingQueueLaunched = false;
  10057. }
  10058. };
  10059. /**
  10060. * Register and execute a render loop. The engine can have more than one render function.
  10061. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10062. * @example
  10063. * engine.runRenderLoop(function () {
  10064. * scene.render()
  10065. * })
  10066. */
  10067. Engine.prototype.runRenderLoop = function (renderFunction) {
  10068. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10069. return;
  10070. }
  10071. this._activeRenderLoops.push(renderFunction);
  10072. if (!this._renderingQueueLaunched) {
  10073. this._renderingQueueLaunched = true;
  10074. this._bindedRenderFunction = this._renderLoop.bind(this);
  10075. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10076. }
  10077. };
  10078. /**
  10079. * Toggle full screen mode.
  10080. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10081. * @param {any} options - an options object to be sent to the requestFullscreen function
  10082. */
  10083. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10084. if (this.isFullscreen) {
  10085. BABYLON.Tools.ExitFullscreen();
  10086. }
  10087. else {
  10088. this._pointerLockRequested = requestPointerLock;
  10089. if (this._renderingCanvas) {
  10090. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10091. }
  10092. }
  10093. };
  10094. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10095. if (stencil === void 0) { stencil = false; }
  10096. this.applyStates();
  10097. var mode = 0;
  10098. if (backBuffer && color) {
  10099. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10100. mode |= this._gl.COLOR_BUFFER_BIT;
  10101. }
  10102. if (depth) {
  10103. this._gl.clearDepth(1.0);
  10104. mode |= this._gl.DEPTH_BUFFER_BIT;
  10105. }
  10106. if (stencil) {
  10107. this._gl.clearStencil(0);
  10108. mode |= this._gl.STENCIL_BUFFER_BIT;
  10109. }
  10110. this._gl.clear(mode);
  10111. };
  10112. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10113. var gl = this._gl;
  10114. // Save state
  10115. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10116. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10117. // Change state
  10118. gl.enable(gl.SCISSOR_TEST);
  10119. gl.scissor(x, y, width, height);
  10120. // Clear
  10121. this.clear(clearColor, true, true, true);
  10122. // Restore state
  10123. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10124. if (curScissor === true) {
  10125. gl.enable(gl.SCISSOR_TEST);
  10126. }
  10127. else {
  10128. gl.disable(gl.SCISSOR_TEST);
  10129. }
  10130. };
  10131. /**
  10132. * Set the WebGL's viewport
  10133. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10134. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10135. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10136. */
  10137. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10138. var width = requiredWidth || this.getRenderWidth();
  10139. var height = requiredHeight || this.getRenderHeight();
  10140. var x = viewport.x || 0;
  10141. var y = viewport.y || 0;
  10142. this._cachedViewport = viewport;
  10143. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10144. };
  10145. /**
  10146. * Directly set the WebGL Viewport
  10147. * The x, y, width & height are directly passed to the WebGL call
  10148. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  10149. */
  10150. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10151. var currentViewport = this._cachedViewport;
  10152. this._cachedViewport = null;
  10153. this._gl.viewport(x, y, width, height);
  10154. return currentViewport;
  10155. };
  10156. Engine.prototype.beginFrame = function () {
  10157. this.onBeginFrameObservable.notifyObservers(this);
  10158. this._measureFps();
  10159. };
  10160. Engine.prototype.endFrame = function () {
  10161. //force a flush in case we are using a bad OS.
  10162. if (this._badOS) {
  10163. this.flushFramebuffer();
  10164. }
  10165. //submit frame to the vr device, if enabled
  10166. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10167. // TODO: We should only submit the frame if we read frameData successfully.
  10168. this._vrDisplay.submitFrame();
  10169. }
  10170. this.onEndFrameObservable.notifyObservers(this);
  10171. };
  10172. /**
  10173. * resize the view according to the canvas' size.
  10174. * @example
  10175. * window.addEventListener("resize", function () {
  10176. * engine.resize();
  10177. * });
  10178. */
  10179. Engine.prototype.resize = function () {
  10180. // We're not resizing the size of the canvas while in VR mode & presenting
  10181. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10182. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10183. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10184. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10185. }
  10186. };
  10187. /**
  10188. * force a specific size of the canvas
  10189. * @param {number} width - the new canvas' width
  10190. * @param {number} height - the new canvas' height
  10191. */
  10192. Engine.prototype.setSize = function (width, height) {
  10193. if (!this._renderingCanvas) {
  10194. return;
  10195. }
  10196. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10197. return;
  10198. }
  10199. this._renderingCanvas.width = width;
  10200. this._renderingCanvas.height = height;
  10201. for (var index = 0; index < this.scenes.length; index++) {
  10202. var scene = this.scenes[index];
  10203. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10204. var cam = scene.cameras[camIndex];
  10205. cam._currentRenderId = 0;
  10206. }
  10207. }
  10208. if (this.onResizeObservable.hasObservers) {
  10209. this.onResizeObservable.notifyObservers(this);
  10210. }
  10211. };
  10212. // WebVR functions
  10213. Engine.prototype.isVRDevicePresent = function () {
  10214. return !!this._vrDisplay;
  10215. };
  10216. Engine.prototype.getVRDevice = function () {
  10217. return this._vrDisplay;
  10218. };
  10219. Engine.prototype.initWebVR = function () {
  10220. var _this = this;
  10221. var notifyObservers = function () {
  10222. var eventArgs = {
  10223. vrDisplay: _this._vrDisplay,
  10224. vrSupported: _this._vrSupported
  10225. };
  10226. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10227. };
  10228. if (!this._onVrDisplayConnect) {
  10229. this._onVrDisplayConnect = function (event) {
  10230. _this._vrDisplay = event.display;
  10231. notifyObservers();
  10232. };
  10233. this._onVrDisplayDisconnect = function () {
  10234. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10235. _this._vrDisplay = undefined;
  10236. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10237. notifyObservers();
  10238. };
  10239. this._onVrDisplayPresentChange = function () {
  10240. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10241. };
  10242. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10243. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10244. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10245. }
  10246. this._getVRDisplays(notifyObservers);
  10247. return this.onVRDisplayChangedObservable;
  10248. };
  10249. Engine.prototype.enableVR = function () {
  10250. var _this = this;
  10251. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10252. var onResolved = function () {
  10253. _this.onVRRequestPresentComplete.notifyObservers(true);
  10254. _this._onVRFullScreenTriggered();
  10255. };
  10256. var onRejected = function () {
  10257. _this.onVRRequestPresentComplete.notifyObservers(false);
  10258. };
  10259. this.onVRRequestPresentStart.notifyObservers(this);
  10260. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10261. }
  10262. };
  10263. Engine.prototype.disableVR = function () {
  10264. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10265. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10266. }
  10267. };
  10268. Engine.prototype._getVRDisplays = function (callback) {
  10269. var _this = this;
  10270. var getWebVRDevices = function (devices) {
  10271. _this._vrSupported = true;
  10272. // note that devices may actually be an empty array. This is fine;
  10273. // we expect this._vrDisplay to be undefined in this case.
  10274. return _this._vrDisplay = devices[0];
  10275. };
  10276. if (navigator.getVRDisplays) {
  10277. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10278. // TODO: System CANNOT support WebVR, despite API presence.
  10279. _this._vrSupported = false;
  10280. callback();
  10281. });
  10282. }
  10283. else {
  10284. // TODO: Browser does not support WebVR
  10285. this._vrDisplay = undefined;
  10286. this._vrSupported = false;
  10287. callback();
  10288. }
  10289. };
  10290. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10291. if (this._currentRenderTarget) {
  10292. this.unBindFramebuffer(this._currentRenderTarget);
  10293. }
  10294. this._currentRenderTarget = texture;
  10295. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10296. var gl = this._gl;
  10297. if (texture.isCube) {
  10298. if (faceIndex === undefined) {
  10299. faceIndex = 0;
  10300. }
  10301. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10302. }
  10303. if (this._cachedViewport && !forceFullscreenViewport) {
  10304. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10305. }
  10306. else {
  10307. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10308. }
  10309. this.wipeCaches();
  10310. };
  10311. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10312. if (this._currentFramebuffer !== framebuffer) {
  10313. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10314. this._currentFramebuffer = framebuffer;
  10315. }
  10316. };
  10317. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10318. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10319. this._currentRenderTarget = null;
  10320. // If MSAA, we need to bitblt back to main texture
  10321. var gl = this._gl;
  10322. if (texture._MSAAFramebuffer) {
  10323. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10324. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10325. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10326. }
  10327. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10328. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10329. gl.generateMipmap(gl.TEXTURE_2D);
  10330. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10331. }
  10332. if (onBeforeUnbind) {
  10333. if (texture._MSAAFramebuffer) {
  10334. // Bind the correct framebuffer
  10335. this.bindUnboundFramebuffer(texture._framebuffer);
  10336. }
  10337. onBeforeUnbind();
  10338. }
  10339. this.bindUnboundFramebuffer(null);
  10340. };
  10341. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10342. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10343. this._currentRenderTarget = null;
  10344. // If MSAA, we need to bitblt back to main texture
  10345. var gl = this._gl;
  10346. if (textures[0]._MSAAFramebuffer) {
  10347. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10348. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10349. var attachments = textures[0]._attachments;
  10350. if (!attachments) {
  10351. attachments = new Array(textures.length);
  10352. textures[0]._attachments = attachments;
  10353. }
  10354. for (var i = 0; i < textures.length; i++) {
  10355. var texture = textures[i];
  10356. for (var j = 0; j < attachments.length; j++) {
  10357. attachments[j] = gl.NONE;
  10358. }
  10359. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10360. gl.readBuffer(attachments[i]);
  10361. gl.drawBuffers(attachments);
  10362. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10363. }
  10364. for (var i = 0; i < attachments.length; i++) {
  10365. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10366. }
  10367. gl.drawBuffers(attachments);
  10368. }
  10369. for (var i = 0; i < textures.length; i++) {
  10370. var texture = textures[i];
  10371. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10372. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10373. gl.generateMipmap(gl.TEXTURE_2D);
  10374. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10375. }
  10376. }
  10377. if (onBeforeUnbind) {
  10378. if (textures[0]._MSAAFramebuffer) {
  10379. // Bind the correct framebuffer
  10380. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10381. }
  10382. onBeforeUnbind();
  10383. }
  10384. this.bindUnboundFramebuffer(null);
  10385. };
  10386. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10387. if (texture.generateMipMaps) {
  10388. var gl = this._gl;
  10389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10390. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10391. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10392. }
  10393. };
  10394. Engine.prototype.flushFramebuffer = function () {
  10395. this._gl.flush();
  10396. };
  10397. Engine.prototype.restoreDefaultFramebuffer = function () {
  10398. if (this._currentRenderTarget) {
  10399. this.unBindFramebuffer(this._currentRenderTarget);
  10400. }
  10401. else {
  10402. this.bindUnboundFramebuffer(null);
  10403. }
  10404. if (this._cachedViewport) {
  10405. this.setViewport(this._cachedViewport);
  10406. }
  10407. this.wipeCaches();
  10408. };
  10409. // UBOs
  10410. Engine.prototype.createUniformBuffer = function (elements) {
  10411. var ubo = this._gl.createBuffer();
  10412. if (!ubo) {
  10413. throw new Error("Unable to create uniform buffer");
  10414. }
  10415. this.bindUniformBuffer(ubo);
  10416. if (elements instanceof Float32Array) {
  10417. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10418. }
  10419. else {
  10420. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10421. }
  10422. this.bindUniformBuffer(null);
  10423. ubo.references = 1;
  10424. return ubo;
  10425. };
  10426. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10427. var ubo = this._gl.createBuffer();
  10428. if (!ubo) {
  10429. throw new Error("Unable to create dynamic uniform buffer");
  10430. }
  10431. this.bindUniformBuffer(ubo);
  10432. if (elements instanceof Float32Array) {
  10433. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10434. }
  10435. else {
  10436. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10437. }
  10438. this.bindUniformBuffer(null);
  10439. ubo.references = 1;
  10440. return ubo;
  10441. };
  10442. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10443. this.bindUniformBuffer(uniformBuffer);
  10444. if (offset === undefined) {
  10445. offset = 0;
  10446. }
  10447. if (count === undefined) {
  10448. if (elements instanceof Float32Array) {
  10449. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10450. }
  10451. else {
  10452. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10453. }
  10454. }
  10455. else {
  10456. if (elements instanceof Float32Array) {
  10457. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10458. }
  10459. else {
  10460. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10461. }
  10462. }
  10463. this.bindUniformBuffer(null);
  10464. };
  10465. // VBOs
  10466. Engine.prototype._resetVertexBufferBinding = function () {
  10467. this.bindArrayBuffer(null);
  10468. this._cachedVertexBuffers = null;
  10469. };
  10470. Engine.prototype.createVertexBuffer = function (vertices) {
  10471. var vbo = this._gl.createBuffer();
  10472. if (!vbo) {
  10473. throw new Error("Unable to create vertex buffer");
  10474. }
  10475. this.bindArrayBuffer(vbo);
  10476. if (vertices instanceof Float32Array) {
  10477. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10478. }
  10479. else {
  10480. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10481. }
  10482. this._resetVertexBufferBinding();
  10483. vbo.references = 1;
  10484. return vbo;
  10485. };
  10486. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10487. var vbo = this._gl.createBuffer();
  10488. if (!vbo) {
  10489. throw new Error("Unable to create dynamic vertex buffer");
  10490. }
  10491. this.bindArrayBuffer(vbo);
  10492. if (vertices instanceof Float32Array) {
  10493. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10494. }
  10495. else {
  10496. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10497. }
  10498. this._resetVertexBufferBinding();
  10499. vbo.references = 1;
  10500. return vbo;
  10501. };
  10502. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10503. if (offset === void 0) { offset = 0; }
  10504. // Force cache update
  10505. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10506. this.bindIndexBuffer(indexBuffer);
  10507. var arrayBuffer;
  10508. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10509. arrayBuffer = indices;
  10510. }
  10511. else {
  10512. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10513. }
  10514. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10515. this._resetIndexBufferBinding();
  10516. };
  10517. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10518. this.bindArrayBuffer(vertexBuffer);
  10519. if (offset === undefined) {
  10520. offset = 0;
  10521. }
  10522. if (count === undefined) {
  10523. if (vertices instanceof Float32Array) {
  10524. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10525. }
  10526. else {
  10527. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10528. }
  10529. }
  10530. else {
  10531. if (vertices instanceof Float32Array) {
  10532. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10533. }
  10534. else {
  10535. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10536. }
  10537. }
  10538. this._resetVertexBufferBinding();
  10539. };
  10540. Engine.prototype._resetIndexBufferBinding = function () {
  10541. this.bindIndexBuffer(null);
  10542. this._cachedIndexBuffer = null;
  10543. };
  10544. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10545. var vbo = this._gl.createBuffer();
  10546. if (!vbo) {
  10547. throw new Error("Unable to create index buffer");
  10548. }
  10549. this.bindIndexBuffer(vbo);
  10550. // Check for 32 bits indices
  10551. var arrayBuffer;
  10552. var need32Bits = false;
  10553. if (indices instanceof Uint16Array) {
  10554. arrayBuffer = indices;
  10555. }
  10556. else {
  10557. //check 32 bit support
  10558. if (this._caps.uintIndices) {
  10559. if (indices instanceof Uint32Array) {
  10560. arrayBuffer = indices;
  10561. need32Bits = true;
  10562. }
  10563. else {
  10564. //number[] or Int32Array, check if 32 bit is necessary
  10565. for (var index = 0; index < indices.length; index++) {
  10566. if (indices[index] > 65535) {
  10567. need32Bits = true;
  10568. break;
  10569. }
  10570. }
  10571. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10572. }
  10573. }
  10574. else {
  10575. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10576. arrayBuffer = new Uint16Array(indices);
  10577. }
  10578. }
  10579. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10580. this._resetIndexBufferBinding();
  10581. vbo.references = 1;
  10582. vbo.is32Bits = need32Bits;
  10583. return vbo;
  10584. };
  10585. Engine.prototype.bindArrayBuffer = function (buffer) {
  10586. if (!this._vaoRecordInProgress) {
  10587. this._unbindVertexArrayObject();
  10588. }
  10589. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10590. };
  10591. Engine.prototype.bindUniformBuffer = function (buffer) {
  10592. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10593. };
  10594. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10595. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10596. };
  10597. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10598. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10599. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10600. };
  10601. ;
  10602. Engine.prototype.bindIndexBuffer = function (buffer) {
  10603. if (!this._vaoRecordInProgress) {
  10604. this._unbindVertexArrayObject();
  10605. }
  10606. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10607. };
  10608. Engine.prototype.bindBuffer = function (buffer, target) {
  10609. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10610. this._gl.bindBuffer(target, buffer);
  10611. this._currentBoundBuffer[target] = buffer;
  10612. }
  10613. };
  10614. Engine.prototype.updateArrayBuffer = function (data) {
  10615. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10616. };
  10617. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10618. var pointer = this._currentBufferPointers[indx];
  10619. var changed = false;
  10620. if (!pointer.active) {
  10621. changed = true;
  10622. pointer.active = true;
  10623. pointer.index = indx;
  10624. pointer.size = size;
  10625. pointer.type = type;
  10626. pointer.normalized = normalized;
  10627. pointer.stride = stride;
  10628. pointer.offset = offset;
  10629. pointer.buffer = buffer;
  10630. }
  10631. else {
  10632. if (pointer.buffer !== buffer) {
  10633. pointer.buffer = buffer;
  10634. changed = true;
  10635. }
  10636. if (pointer.size !== size) {
  10637. pointer.size = size;
  10638. changed = true;
  10639. }
  10640. if (pointer.type !== type) {
  10641. pointer.type = type;
  10642. changed = true;
  10643. }
  10644. if (pointer.normalized !== normalized) {
  10645. pointer.normalized = normalized;
  10646. changed = true;
  10647. }
  10648. if (pointer.stride !== stride) {
  10649. pointer.stride = stride;
  10650. changed = true;
  10651. }
  10652. if (pointer.offset !== offset) {
  10653. pointer.offset = offset;
  10654. changed = true;
  10655. }
  10656. }
  10657. if (changed || this._vaoRecordInProgress) {
  10658. this.bindArrayBuffer(buffer);
  10659. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10660. }
  10661. };
  10662. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10663. if (indexBuffer == null) {
  10664. return;
  10665. }
  10666. if (this._cachedIndexBuffer !== indexBuffer) {
  10667. this._cachedIndexBuffer = indexBuffer;
  10668. this.bindIndexBuffer(indexBuffer);
  10669. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10670. }
  10671. };
  10672. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10673. var attributes = effect.getAttributesNames();
  10674. if (!this._vaoRecordInProgress) {
  10675. this._unbindVertexArrayObject();
  10676. }
  10677. this.unbindAllAttributes();
  10678. for (var index = 0; index < attributes.length; index++) {
  10679. var order = effect.getAttributeLocation(index);
  10680. if (order >= 0) {
  10681. var vertexBuffer = vertexBuffers[attributes[index]];
  10682. if (!vertexBuffer) {
  10683. continue;
  10684. }
  10685. this._gl.enableVertexAttribArray(order);
  10686. if (!this._vaoRecordInProgress) {
  10687. this._vertexAttribArraysEnabled[order] = true;
  10688. }
  10689. var buffer = vertexBuffer.getBuffer();
  10690. if (buffer) {
  10691. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10692. if (vertexBuffer.getIsInstanced()) {
  10693. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10694. if (!this._vaoRecordInProgress) {
  10695. this._currentInstanceLocations.push(order);
  10696. this._currentInstanceBuffers.push(buffer);
  10697. }
  10698. }
  10699. }
  10700. }
  10701. }
  10702. };
  10703. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10704. var vao = this._gl.createVertexArray();
  10705. this._vaoRecordInProgress = true;
  10706. this._gl.bindVertexArray(vao);
  10707. this._mustWipeVertexAttributes = true;
  10708. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10709. this.bindIndexBuffer(indexBuffer);
  10710. this._vaoRecordInProgress = false;
  10711. this._gl.bindVertexArray(null);
  10712. return vao;
  10713. };
  10714. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10715. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10716. this._cachedVertexArrayObject = vertexArrayObject;
  10717. this._gl.bindVertexArray(vertexArrayObject);
  10718. this._cachedVertexBuffers = null;
  10719. this._cachedIndexBuffer = null;
  10720. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10721. this._mustWipeVertexAttributes = true;
  10722. }
  10723. };
  10724. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10725. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10726. this._cachedVertexBuffers = vertexBuffer;
  10727. this._cachedEffectForVertexBuffers = effect;
  10728. var attributesCount = effect.getAttributesCount();
  10729. this._unbindVertexArrayObject();
  10730. this.unbindAllAttributes();
  10731. var offset = 0;
  10732. for (var index = 0; index < attributesCount; index++) {
  10733. if (index < vertexDeclaration.length) {
  10734. var order = effect.getAttributeLocation(index);
  10735. if (order >= 0) {
  10736. this._gl.enableVertexAttribArray(order);
  10737. this._vertexAttribArraysEnabled[order] = true;
  10738. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10739. }
  10740. offset += vertexDeclaration[index] * 4;
  10741. }
  10742. }
  10743. }
  10744. this._bindIndexBufferWithCache(indexBuffer);
  10745. };
  10746. Engine.prototype._unbindVertexArrayObject = function () {
  10747. if (!this._cachedVertexArrayObject) {
  10748. return;
  10749. }
  10750. this._cachedVertexArrayObject = null;
  10751. this._gl.bindVertexArray(null);
  10752. };
  10753. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10754. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10755. this._cachedVertexBuffers = vertexBuffers;
  10756. this._cachedEffectForVertexBuffers = effect;
  10757. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10758. }
  10759. this._bindIndexBufferWithCache(indexBuffer);
  10760. };
  10761. Engine.prototype.unbindInstanceAttributes = function () {
  10762. var boundBuffer;
  10763. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10764. var instancesBuffer = this._currentInstanceBuffers[i];
  10765. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10766. boundBuffer = instancesBuffer;
  10767. this.bindArrayBuffer(instancesBuffer);
  10768. }
  10769. var offsetLocation = this._currentInstanceLocations[i];
  10770. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10771. }
  10772. this._currentInstanceBuffers.length = 0;
  10773. this._currentInstanceLocations.length = 0;
  10774. };
  10775. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10776. this._gl.deleteVertexArray(vao);
  10777. };
  10778. Engine.prototype._releaseBuffer = function (buffer) {
  10779. buffer.references--;
  10780. if (buffer.references === 0) {
  10781. this._gl.deleteBuffer(buffer);
  10782. return true;
  10783. }
  10784. return false;
  10785. };
  10786. Engine.prototype.createInstancesBuffer = function (capacity) {
  10787. var buffer = this._gl.createBuffer();
  10788. if (!buffer) {
  10789. throw new Error("Unable to create instance buffer");
  10790. }
  10791. buffer.capacity = capacity;
  10792. this.bindArrayBuffer(buffer);
  10793. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10794. return buffer;
  10795. };
  10796. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10797. this._gl.deleteBuffer(buffer);
  10798. };
  10799. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10800. this.bindArrayBuffer(instancesBuffer);
  10801. if (data) {
  10802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10803. }
  10804. if (offsetLocations[0].index !== undefined) {
  10805. var stride = 0;
  10806. for (var i = 0; i < offsetLocations.length; i++) {
  10807. var ai = offsetLocations[i];
  10808. stride += ai.attributeSize * 4;
  10809. }
  10810. for (var i = 0; i < offsetLocations.length; i++) {
  10811. var ai = offsetLocations[i];
  10812. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10813. this._gl.enableVertexAttribArray(ai.index);
  10814. this._vertexAttribArraysEnabled[ai.index] = true;
  10815. }
  10816. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10817. this._gl.vertexAttribDivisor(ai.index, 1);
  10818. this._currentInstanceLocations.push(ai.index);
  10819. this._currentInstanceBuffers.push(instancesBuffer);
  10820. }
  10821. }
  10822. else {
  10823. for (var index = 0; index < 4; index++) {
  10824. var offsetLocation = offsetLocations[index];
  10825. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10826. this._gl.enableVertexAttribArray(offsetLocation);
  10827. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10828. }
  10829. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10830. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10831. this._currentInstanceLocations.push(offsetLocation);
  10832. this._currentInstanceBuffers.push(instancesBuffer);
  10833. }
  10834. }
  10835. };
  10836. Engine.prototype.applyStates = function () {
  10837. this._depthCullingState.apply(this._gl);
  10838. this._stencilState.apply(this._gl);
  10839. this._alphaState.apply(this._gl);
  10840. };
  10841. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10842. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10843. };
  10844. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10845. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10846. };
  10847. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10848. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10849. };
  10850. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10851. // Apply states
  10852. this.applyStates();
  10853. this._drawCalls.addCount(1, false);
  10854. // Render
  10855. var drawMode = this.DrawMode(fillMode);
  10856. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10857. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10858. if (instancesCount) {
  10859. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10860. }
  10861. else {
  10862. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10863. }
  10864. };
  10865. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10866. // Apply states
  10867. this.applyStates();
  10868. this._drawCalls.addCount(1, false);
  10869. var drawMode = this.DrawMode(fillMode);
  10870. if (instancesCount) {
  10871. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10872. }
  10873. else {
  10874. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10875. }
  10876. };
  10877. Engine.prototype.DrawMode = function (fillMode) {
  10878. switch (fillMode) {
  10879. // Triangle views
  10880. case BABYLON.Material.TriangleFillMode:
  10881. return this._gl.TRIANGLES;
  10882. case BABYLON.Material.PointFillMode:
  10883. return this._gl.POINTS;
  10884. case BABYLON.Material.WireFrameFillMode:
  10885. return this._gl.LINES;
  10886. // Draw modes
  10887. case BABYLON.Material.PointListDrawMode:
  10888. return this._gl.POINTS;
  10889. case BABYLON.Material.LineListDrawMode:
  10890. return this._gl.LINES;
  10891. case BABYLON.Material.LineLoopDrawMode:
  10892. return this._gl.LINE_LOOP;
  10893. case BABYLON.Material.LineStripDrawMode:
  10894. return this._gl.LINE_STRIP;
  10895. case BABYLON.Material.TriangleStripDrawMode:
  10896. return this._gl.TRIANGLE_STRIP;
  10897. case BABYLON.Material.TriangleFanDrawMode:
  10898. return this._gl.TRIANGLE_FAN;
  10899. default:
  10900. return this._gl.TRIANGLES;
  10901. }
  10902. };
  10903. // Shaders
  10904. Engine.prototype._releaseEffect = function (effect) {
  10905. if (this._compiledEffects[effect._key]) {
  10906. delete this._compiledEffects[effect._key];
  10907. this._deleteProgram(effect.getProgram());
  10908. }
  10909. };
  10910. Engine.prototype._deleteProgram = function (program) {
  10911. if (program) {
  10912. program.__SPECTOR_rebuildProgram = null;
  10913. if (program.transformFeedback) {
  10914. this.deleteTransformFeedback(program.transformFeedback);
  10915. program.transformFeedback = null;
  10916. }
  10917. this._gl.deleteProgram(program);
  10918. }
  10919. };
  10920. /**
  10921. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10922. * @param samplers An array of string used to represent textures
  10923. */
  10924. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10925. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10926. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10927. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10928. if (this._compiledEffects[name]) {
  10929. var compiledEffect = this._compiledEffects[name];
  10930. if (onCompiled && compiledEffect.isReady()) {
  10931. onCompiled(compiledEffect);
  10932. }
  10933. return compiledEffect;
  10934. }
  10935. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10936. effect._key = name;
  10937. this._compiledEffects[name] = effect;
  10938. return effect;
  10939. };
  10940. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10941. if (uniformsNames === void 0) { uniformsNames = []; }
  10942. if (samplers === void 0) { samplers = []; }
  10943. if (defines === void 0) { defines = ""; }
  10944. return this.createEffect({
  10945. vertex: "particles",
  10946. fragmentElement: fragmentName
  10947. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10948. };
  10949. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10950. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10951. context = context || this._gl;
  10952. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10953. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10954. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10955. };
  10956. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10957. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10958. context = context || this._gl;
  10959. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10960. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10961. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10962. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10963. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10964. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10965. return program;
  10966. };
  10967. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10968. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10969. var shaderProgram = context.createProgram();
  10970. if (!shaderProgram) {
  10971. throw new Error("Unable to create program");
  10972. }
  10973. context.attachShader(shaderProgram, vertexShader);
  10974. context.attachShader(shaderProgram, fragmentShader);
  10975. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10976. var transformFeedback = this.createTransformFeedback();
  10977. this.bindTransformFeedback(transformFeedback);
  10978. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10979. shaderProgram.transformFeedback = transformFeedback;
  10980. }
  10981. context.linkProgram(shaderProgram);
  10982. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10983. this.bindTransformFeedback(null);
  10984. }
  10985. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10986. if (!linked) {
  10987. context.validateProgram(shaderProgram);
  10988. var error = context.getProgramInfoLog(shaderProgram);
  10989. if (error) {
  10990. throw new Error(error);
  10991. }
  10992. }
  10993. context.deleteShader(vertexShader);
  10994. context.deleteShader(fragmentShader);
  10995. return shaderProgram;
  10996. };
  10997. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10998. var results = new Array();
  10999. for (var index = 0; index < uniformsNames.length; index++) {
  11000. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11001. }
  11002. return results;
  11003. };
  11004. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11005. var results = [];
  11006. for (var index = 0; index < attributesNames.length; index++) {
  11007. try {
  11008. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11009. }
  11010. catch (e) {
  11011. results.push(-1);
  11012. }
  11013. }
  11014. return results;
  11015. };
  11016. Engine.prototype.enableEffect = function (effect) {
  11017. if (!effect) {
  11018. return;
  11019. }
  11020. // Use program
  11021. this.bindSamplers(effect);
  11022. this._currentEffect = effect;
  11023. if (effect.onBind) {
  11024. effect.onBind(effect);
  11025. }
  11026. effect.onBindObservable.notifyObservers(effect);
  11027. };
  11028. Engine.prototype.setIntArray = function (uniform, array) {
  11029. if (!uniform)
  11030. return;
  11031. this._gl.uniform1iv(uniform, array);
  11032. };
  11033. Engine.prototype.setIntArray2 = function (uniform, array) {
  11034. if (!uniform || array.length % 2 !== 0)
  11035. return;
  11036. this._gl.uniform2iv(uniform, array);
  11037. };
  11038. Engine.prototype.setIntArray3 = function (uniform, array) {
  11039. if (!uniform || array.length % 3 !== 0)
  11040. return;
  11041. this._gl.uniform3iv(uniform, array);
  11042. };
  11043. Engine.prototype.setIntArray4 = function (uniform, array) {
  11044. if (!uniform || array.length % 4 !== 0)
  11045. return;
  11046. this._gl.uniform4iv(uniform, array);
  11047. };
  11048. Engine.prototype.setFloatArray = function (uniform, array) {
  11049. if (!uniform)
  11050. return;
  11051. this._gl.uniform1fv(uniform, array);
  11052. };
  11053. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11054. if (!uniform || array.length % 2 !== 0)
  11055. return;
  11056. this._gl.uniform2fv(uniform, array);
  11057. };
  11058. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11059. if (!uniform || array.length % 3 !== 0)
  11060. return;
  11061. this._gl.uniform3fv(uniform, array);
  11062. };
  11063. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11064. if (!uniform || array.length % 4 !== 0)
  11065. return;
  11066. this._gl.uniform4fv(uniform, array);
  11067. };
  11068. Engine.prototype.setArray = function (uniform, array) {
  11069. if (!uniform)
  11070. return;
  11071. this._gl.uniform1fv(uniform, array);
  11072. };
  11073. Engine.prototype.setArray2 = function (uniform, array) {
  11074. if (!uniform || array.length % 2 !== 0)
  11075. return;
  11076. this._gl.uniform2fv(uniform, array);
  11077. };
  11078. Engine.prototype.setArray3 = function (uniform, array) {
  11079. if (!uniform || array.length % 3 !== 0)
  11080. return;
  11081. this._gl.uniform3fv(uniform, array);
  11082. };
  11083. Engine.prototype.setArray4 = function (uniform, array) {
  11084. if (!uniform || array.length % 4 !== 0)
  11085. return;
  11086. this._gl.uniform4fv(uniform, array);
  11087. };
  11088. Engine.prototype.setMatrices = function (uniform, matrices) {
  11089. if (!uniform)
  11090. return;
  11091. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11092. };
  11093. Engine.prototype.setMatrix = function (uniform, matrix) {
  11094. if (!uniform)
  11095. return;
  11096. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11097. };
  11098. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11099. if (!uniform)
  11100. return;
  11101. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11102. };
  11103. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11104. if (!uniform)
  11105. return;
  11106. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11107. };
  11108. Engine.prototype.setInt = function (uniform, value) {
  11109. if (!uniform)
  11110. return;
  11111. this._gl.uniform1i(uniform, value);
  11112. };
  11113. Engine.prototype.setFloat = function (uniform, value) {
  11114. if (!uniform)
  11115. return;
  11116. this._gl.uniform1f(uniform, value);
  11117. };
  11118. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11119. if (!uniform)
  11120. return;
  11121. this._gl.uniform2f(uniform, x, y);
  11122. };
  11123. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11124. if (!uniform)
  11125. return;
  11126. this._gl.uniform3f(uniform, x, y, z);
  11127. };
  11128. Engine.prototype.setBool = function (uniform, bool) {
  11129. if (!uniform)
  11130. return;
  11131. this._gl.uniform1i(uniform, bool);
  11132. };
  11133. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11134. if (!uniform)
  11135. return;
  11136. this._gl.uniform4f(uniform, x, y, z, w);
  11137. };
  11138. Engine.prototype.setColor3 = function (uniform, color3) {
  11139. if (!uniform)
  11140. return;
  11141. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11142. };
  11143. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11144. if (!uniform)
  11145. return;
  11146. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11147. };
  11148. // States
  11149. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11150. if (zOffset === void 0) { zOffset = 0; }
  11151. if (reverseSide === void 0) { reverseSide = false; }
  11152. // Culling
  11153. if (this._depthCullingState.cull !== culling || force) {
  11154. this._depthCullingState.cull = culling;
  11155. }
  11156. // Cull face
  11157. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11158. if (this._depthCullingState.cullFace !== cullFace || force) {
  11159. this._depthCullingState.cullFace = cullFace;
  11160. }
  11161. // Z offset
  11162. this.setZOffset(zOffset);
  11163. // Front face
  11164. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11165. if (this._depthCullingState.frontFace !== frontFace || force) {
  11166. this._depthCullingState.frontFace = frontFace;
  11167. }
  11168. };
  11169. Engine.prototype.setZOffset = function (value) {
  11170. this._depthCullingState.zOffset = value;
  11171. };
  11172. Engine.prototype.getZOffset = function () {
  11173. return this._depthCullingState.zOffset;
  11174. };
  11175. Engine.prototype.setDepthBuffer = function (enable) {
  11176. this._depthCullingState.depthTest = enable;
  11177. };
  11178. Engine.prototype.getDepthWrite = function () {
  11179. return this._depthCullingState.depthMask;
  11180. };
  11181. Engine.prototype.setDepthWrite = function (enable) {
  11182. this._depthCullingState.depthMask = enable;
  11183. };
  11184. Engine.prototype.setColorWrite = function (enable) {
  11185. this._gl.colorMask(enable, enable, enable, enable);
  11186. this._colorWrite = enable;
  11187. };
  11188. Engine.prototype.getColorWrite = function () {
  11189. return this._colorWrite;
  11190. };
  11191. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11192. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11193. };
  11194. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11195. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11196. if (this._alphaMode === mode) {
  11197. return;
  11198. }
  11199. switch (mode) {
  11200. case Engine.ALPHA_DISABLE:
  11201. this._alphaState.alphaBlend = false;
  11202. break;
  11203. case Engine.ALPHA_PREMULTIPLIED:
  11204. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11205. this._alphaState.alphaBlend = true;
  11206. break;
  11207. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11208. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11209. this._alphaState.alphaBlend = true;
  11210. break;
  11211. case Engine.ALPHA_COMBINE:
  11212. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11213. this._alphaState.alphaBlend = true;
  11214. break;
  11215. case Engine.ALPHA_ONEONE:
  11216. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11217. this._alphaState.alphaBlend = true;
  11218. break;
  11219. case Engine.ALPHA_ADD:
  11220. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11221. this._alphaState.alphaBlend = true;
  11222. break;
  11223. case Engine.ALPHA_SUBTRACT:
  11224. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11225. this._alphaState.alphaBlend = true;
  11226. break;
  11227. case Engine.ALPHA_MULTIPLY:
  11228. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11229. this._alphaState.alphaBlend = true;
  11230. break;
  11231. case Engine.ALPHA_MAXIMIZED:
  11232. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11233. this._alphaState.alphaBlend = true;
  11234. break;
  11235. case Engine.ALPHA_INTERPOLATE:
  11236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11237. this._alphaState.alphaBlend = true;
  11238. break;
  11239. case Engine.ALPHA_SCREENMODE:
  11240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11241. this._alphaState.alphaBlend = true;
  11242. break;
  11243. }
  11244. if (!noDepthWriteChange) {
  11245. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11246. }
  11247. this._alphaMode = mode;
  11248. };
  11249. Engine.prototype.getAlphaMode = function () {
  11250. return this._alphaMode;
  11251. };
  11252. Engine.prototype.setAlphaTesting = function (enable) {
  11253. this._alphaTest = enable;
  11254. };
  11255. Engine.prototype.getAlphaTesting = function () {
  11256. return !!this._alphaTest;
  11257. };
  11258. // Textures
  11259. Engine.prototype.wipeCaches = function (bruteForce) {
  11260. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11261. return;
  11262. }
  11263. this._currentEffect = null;
  11264. // 6/8/2017: deltakosh: Should not be required anymore.
  11265. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11266. if (bruteForce) {
  11267. this.resetTextureCache();
  11268. this._currentProgram = null;
  11269. this._stencilState.reset();
  11270. this._depthCullingState.reset();
  11271. this.setDepthFunctionToLessOrEqual();
  11272. this._alphaState.reset();
  11273. }
  11274. this._resetVertexBufferBinding();
  11275. this._cachedIndexBuffer = null;
  11276. this._cachedEffectForVertexBuffers = null;
  11277. this._unbindVertexArrayObject();
  11278. this.bindIndexBuffer(null);
  11279. };
  11280. /**
  11281. * Set the compressed texture format to use, based on the formats you have, and the formats
  11282. * supported by the hardware / browser.
  11283. *
  11284. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11285. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11286. * to API arguments needed to compressed textures. This puts the burden on the container
  11287. * generator to house the arcane code for determining these for current & future formats.
  11288. *
  11289. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11290. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11291. *
  11292. * Note: The result of this call is not taken into account when a texture is base64.
  11293. *
  11294. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11295. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11296. *
  11297. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11298. * @returns The extension selected.
  11299. */
  11300. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11301. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11302. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11303. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11304. return this._textureFormatInUse = this._texturesSupported[i];
  11305. }
  11306. }
  11307. }
  11308. // actively set format to nothing, to allow this to be called more than once
  11309. // and possibly fail the 2nd time
  11310. this._textureFormatInUse = null;
  11311. return null;
  11312. };
  11313. Engine.prototype._createTexture = function () {
  11314. var texture = this._gl.createTexture();
  11315. if (!texture) {
  11316. throw new Error("Unable to create texture");
  11317. }
  11318. return texture;
  11319. };
  11320. /**
  11321. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11322. * @param {string} urlArg- This contains one of the following:
  11323. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11324. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11325. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11326. *
  11327. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11328. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11329. * @param {Scene} scene- Needed for loading to the correct scene.
  11330. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11331. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11332. * @param {callback} onError- Optional callback to be called upon failure.
  11333. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11334. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11335. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11336. *
  11337. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11338. */
  11339. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11340. var _this = this;
  11341. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11342. if (onLoad === void 0) { onLoad = null; }
  11343. if (onError === void 0) { onError = null; }
  11344. if (buffer === void 0) { buffer = null; }
  11345. if (fallBack === void 0) { fallBack = null; }
  11346. if (format === void 0) { format = null; }
  11347. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11348. var fromData = url.substr(0, 5) === "data:";
  11349. var fromBlob = url.substr(0, 5) === "blob:";
  11350. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11351. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11352. // establish the file extension, if possible
  11353. var lastDot = url.lastIndexOf('.');
  11354. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11355. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11356. var isTGA = (extension === ".tga");
  11357. // determine if a ktx file should be substituted
  11358. var isKTX = false;
  11359. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11360. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11361. isKTX = true;
  11362. }
  11363. if (scene) {
  11364. scene._addPendingData(texture);
  11365. }
  11366. texture.url = url;
  11367. texture.generateMipMaps = !noMipmap;
  11368. texture.samplingMode = samplingMode;
  11369. texture.invertY = invertY;
  11370. if (!this._doNotHandleContextLost) {
  11371. // Keep a link to the buffer only if we plan to handle context lost
  11372. texture._buffer = buffer;
  11373. }
  11374. var onLoadObserver = null;
  11375. if (onLoad && !fallBack) {
  11376. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11377. }
  11378. if (!fallBack)
  11379. this._internalTexturesCache.push(texture);
  11380. var onerror = function (message, exception) {
  11381. if (scene) {
  11382. scene._removePendingData(texture);
  11383. }
  11384. if (onLoadObserver) {
  11385. texture.onLoadedObservable.remove(onLoadObserver);
  11386. }
  11387. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11388. if (isKTX) {
  11389. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11390. }
  11391. else if (BABYLON.Tools.UseFallbackTexture) {
  11392. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11393. }
  11394. if (onError) {
  11395. onError(message || "Unknown error", exception);
  11396. }
  11397. };
  11398. var callback = null;
  11399. // processing for non-image formats
  11400. if (isKTX || isTGA || isDDS) {
  11401. if (isKTX) {
  11402. callback = function (data) {
  11403. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11404. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11405. ktx.uploadLevels(_this._gl, !noMipmap);
  11406. return false;
  11407. }, samplingMode);
  11408. };
  11409. }
  11410. else if (isTGA) {
  11411. callback = function (arrayBuffer) {
  11412. var data = new Uint8Array(arrayBuffer);
  11413. var header = BABYLON.TGATools.GetTGAHeader(data);
  11414. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11415. BABYLON.TGATools.UploadContent(_this._gl, data);
  11416. return false;
  11417. }, samplingMode);
  11418. };
  11419. }
  11420. else if (isDDS) {
  11421. callback = function (data) {
  11422. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11423. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11424. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11425. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11426. return false;
  11427. }, samplingMode);
  11428. };
  11429. }
  11430. if (!buffer) {
  11431. this._loadFile(url, function (data) {
  11432. if (callback) {
  11433. callback(data);
  11434. }
  11435. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11436. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11437. });
  11438. }
  11439. else {
  11440. if (callback) {
  11441. callback(buffer);
  11442. }
  11443. }
  11444. // image format processing
  11445. }
  11446. else {
  11447. var onload = function (img) {
  11448. if (fromBlob && !_this._doNotHandleContextLost) {
  11449. // We need to store the image if we need to rebuild the texture
  11450. // in case of a webgl context lost
  11451. texture._buffer = img;
  11452. }
  11453. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11454. var gl = _this._gl;
  11455. var isPot = (img.width === potWidth && img.height === potHeight);
  11456. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11457. if (isPot) {
  11458. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11459. return false;
  11460. }
  11461. // Using shaders to rescale because canvas.drawImage is lossy
  11462. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11463. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11464. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11465. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11469. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11470. _this._releaseTexture(source);
  11471. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11472. continuationCallback();
  11473. });
  11474. return true;
  11475. }, samplingMode);
  11476. };
  11477. if (!fromData || isBase64)
  11478. if (buffer instanceof HTMLImageElement) {
  11479. onload(buffer);
  11480. }
  11481. else {
  11482. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11483. }
  11484. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11485. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11486. else
  11487. onload(buffer);
  11488. }
  11489. return texture;
  11490. };
  11491. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11492. var _this = this;
  11493. var rtt = this.createRenderTargetTexture({
  11494. width: destination.width,
  11495. height: destination.height,
  11496. }, {
  11497. generateMipMaps: false,
  11498. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11499. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11500. generateDepthBuffer: false,
  11501. generateStencilBuffer: false
  11502. });
  11503. if (!this._rescalePostProcess) {
  11504. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11505. }
  11506. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11507. _this._rescalePostProcess.onApply = function (effect) {
  11508. effect._bindTexture("textureSampler", source);
  11509. };
  11510. var hostingScene = scene;
  11511. if (!hostingScene) {
  11512. hostingScene = _this.scenes[_this.scenes.length - 1];
  11513. }
  11514. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11515. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11516. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11517. _this.unBindFramebuffer(rtt);
  11518. _this._releaseTexture(rtt);
  11519. if (onComplete) {
  11520. onComplete();
  11521. }
  11522. });
  11523. };
  11524. Engine.prototype._getInternalFormat = function (format) {
  11525. var internalFormat = this._gl.RGBA;
  11526. switch (format) {
  11527. case Engine.TEXTUREFORMAT_ALPHA:
  11528. internalFormat = this._gl.ALPHA;
  11529. break;
  11530. case Engine.TEXTUREFORMAT_LUMINANCE:
  11531. internalFormat = this._gl.LUMINANCE;
  11532. break;
  11533. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11534. internalFormat = this._gl.LUMINANCE_ALPHA;
  11535. break;
  11536. case Engine.TEXTUREFORMAT_RGB:
  11537. internalFormat = this._gl.RGB;
  11538. break;
  11539. case Engine.TEXTUREFORMAT_RGBA:
  11540. internalFormat = this._gl.RGBA;
  11541. break;
  11542. }
  11543. return internalFormat;
  11544. };
  11545. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11546. if (compression === void 0) { compression = null; }
  11547. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11548. if (!texture) {
  11549. return;
  11550. }
  11551. var internalFormat = this._getInternalFormat(format);
  11552. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11553. var textureType = this._getWebGLTextureType(type);
  11554. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11555. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11556. if (!this._doNotHandleContextLost) {
  11557. texture._bufferView = data;
  11558. texture.format = format;
  11559. texture.type = type;
  11560. texture.invertY = invertY;
  11561. texture._compression = compression;
  11562. }
  11563. if (texture.width % 4 !== 0) {
  11564. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11565. }
  11566. if (compression && data) {
  11567. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11568. }
  11569. else {
  11570. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11571. }
  11572. if (texture.generateMipMaps) {
  11573. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11574. }
  11575. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11576. // this.resetTextureCache();
  11577. texture.isReady = true;
  11578. };
  11579. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11580. if (compression === void 0) { compression = null; }
  11581. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11582. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11583. texture.baseWidth = width;
  11584. texture.baseHeight = height;
  11585. texture.width = width;
  11586. texture.height = height;
  11587. texture.format = format;
  11588. texture.generateMipMaps = generateMipMaps;
  11589. texture.samplingMode = samplingMode;
  11590. texture.invertY = invertY;
  11591. texture._compression = compression;
  11592. texture.type = type;
  11593. if (!this._doNotHandleContextLost) {
  11594. texture._bufferView = data;
  11595. }
  11596. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11598. // Filters
  11599. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11601. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11602. if (generateMipMaps) {
  11603. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11604. }
  11605. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11606. this._internalTexturesCache.push(texture);
  11607. return texture;
  11608. };
  11609. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11611. texture.baseWidth = width;
  11612. texture.baseHeight = height;
  11613. if (generateMipMaps) {
  11614. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11615. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11616. }
  11617. // this.resetTextureCache();
  11618. texture.width = width;
  11619. texture.height = height;
  11620. texture.isReady = false;
  11621. texture.generateMipMaps = generateMipMaps;
  11622. texture.samplingMode = samplingMode;
  11623. this.updateTextureSamplingMode(samplingMode, texture);
  11624. this._internalTexturesCache.push(texture);
  11625. return texture;
  11626. };
  11627. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11628. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11629. if (texture.isCube) {
  11630. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11631. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11632. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11633. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11634. }
  11635. else if (texture.is3D) {
  11636. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11637. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11638. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11639. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11640. }
  11641. else {
  11642. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11645. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11646. }
  11647. texture.samplingMode = samplingMode;
  11648. };
  11649. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11650. if (premulAlpha === void 0) { premulAlpha = false; }
  11651. if (!texture) {
  11652. return;
  11653. }
  11654. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11655. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11656. if (premulAlpha) {
  11657. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11658. }
  11659. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11660. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11661. if (texture.generateMipMaps) {
  11662. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11663. }
  11664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11665. if (premulAlpha) {
  11666. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11667. }
  11668. texture.isReady = true;
  11669. };
  11670. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11671. if (!texture || texture._isDisabled) {
  11672. return;
  11673. }
  11674. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11675. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11676. try {
  11677. // Testing video texture support
  11678. if (this._videoTextureSupported === undefined) {
  11679. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11680. if (this._gl.getError() !== 0) {
  11681. this._videoTextureSupported = false;
  11682. }
  11683. else {
  11684. this._videoTextureSupported = true;
  11685. }
  11686. }
  11687. // Copy video through the current working canvas if video texture is not supported
  11688. if (!this._videoTextureSupported) {
  11689. if (!texture._workingCanvas) {
  11690. texture._workingCanvas = document.createElement("canvas");
  11691. var context = texture._workingCanvas.getContext("2d");
  11692. if (!context) {
  11693. throw new Error("Unable to get 2d context");
  11694. }
  11695. texture._workingContext = context;
  11696. texture._workingCanvas.width = texture.width;
  11697. texture._workingCanvas.height = texture.height;
  11698. }
  11699. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11700. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11701. }
  11702. else {
  11703. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11704. }
  11705. if (texture.generateMipMaps) {
  11706. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11707. }
  11708. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11709. // this.resetTextureCache();
  11710. texture.isReady = true;
  11711. }
  11712. catch (ex) {
  11713. // Something unexpected
  11714. // Let's disable the texture
  11715. texture._isDisabled = true;
  11716. }
  11717. };
  11718. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11719. var fullOptions = new RenderTargetCreationOptions();
  11720. if (options !== undefined && typeof options === "object") {
  11721. fullOptions.generateMipMaps = options.generateMipMaps;
  11722. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11723. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11724. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11725. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11726. }
  11727. else {
  11728. fullOptions.generateMipMaps = options;
  11729. fullOptions.generateDepthBuffer = true;
  11730. fullOptions.generateStencilBuffer = false;
  11731. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11732. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11733. }
  11734. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11735. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11736. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11737. }
  11738. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11739. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11740. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11741. }
  11742. var gl = this._gl;
  11743. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11744. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11745. var width = size.width || size;
  11746. var height = size.height || size;
  11747. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11748. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11749. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11750. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11751. }
  11752. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11754. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11756. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11757. // Create the framebuffer
  11758. var framebuffer = gl.createFramebuffer();
  11759. this.bindUnboundFramebuffer(framebuffer);
  11760. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11761. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11762. if (fullOptions.generateMipMaps) {
  11763. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11764. }
  11765. // Unbind
  11766. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11767. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11768. this.bindUnboundFramebuffer(null);
  11769. texture._framebuffer = framebuffer;
  11770. texture.baseWidth = width;
  11771. texture.baseHeight = height;
  11772. texture.width = width;
  11773. texture.height = height;
  11774. texture.isReady = true;
  11775. texture.samples = 1;
  11776. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11777. texture.samplingMode = fullOptions.samplingMode;
  11778. texture.type = fullOptions.type;
  11779. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11780. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11781. // this.resetTextureCache();
  11782. this._internalTexturesCache.push(texture);
  11783. return texture;
  11784. };
  11785. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11786. var generateMipMaps = false;
  11787. var generateDepthBuffer = true;
  11788. var generateStencilBuffer = false;
  11789. var generateDepthTexture = false;
  11790. var textureCount = 1;
  11791. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11792. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11793. var types = [], samplingModes = [];
  11794. if (options !== undefined) {
  11795. generateMipMaps = options.generateMipMaps;
  11796. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11797. generateStencilBuffer = options.generateStencilBuffer;
  11798. generateDepthTexture = options.generateDepthTexture;
  11799. textureCount = options.textureCount || 1;
  11800. if (options.types) {
  11801. types = options.types;
  11802. }
  11803. if (options.samplingModes) {
  11804. samplingModes = options.samplingModes;
  11805. }
  11806. }
  11807. var gl = this._gl;
  11808. // Create the framebuffer
  11809. var framebuffer = gl.createFramebuffer();
  11810. this.bindUnboundFramebuffer(framebuffer);
  11811. var width = size.width || size;
  11812. var height = size.height || size;
  11813. var textures = [];
  11814. var attachments = [];
  11815. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11816. for (var i = 0; i < textureCount; i++) {
  11817. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11818. var type = types[i] || defaultType;
  11819. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11820. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11821. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11822. }
  11823. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11824. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11825. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11826. }
  11827. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11828. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11829. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11830. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11831. }
  11832. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11833. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11834. textures.push(texture);
  11835. attachments.push(attachment);
  11836. gl.activeTexture(gl["TEXTURE" + i]);
  11837. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11839. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11840. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11842. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11843. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11844. if (generateMipMaps) {
  11845. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11846. }
  11847. // Unbind
  11848. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11849. texture._framebuffer = framebuffer;
  11850. texture._depthStencilBuffer = depthStencilBuffer;
  11851. texture.baseWidth = width;
  11852. texture.baseHeight = height;
  11853. texture.width = width;
  11854. texture.height = height;
  11855. texture.isReady = true;
  11856. texture.samples = 1;
  11857. texture.generateMipMaps = generateMipMaps;
  11858. texture.samplingMode = samplingMode;
  11859. texture.type = type;
  11860. texture._generateDepthBuffer = generateDepthBuffer;
  11861. texture._generateStencilBuffer = generateStencilBuffer;
  11862. texture._attachments = attachments;
  11863. this._internalTexturesCache.push(texture);
  11864. }
  11865. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11866. // Depth texture
  11867. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11868. gl.activeTexture(gl.TEXTURE0);
  11869. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11874. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  11875. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11876. depthTexture._framebuffer = framebuffer;
  11877. depthTexture.baseWidth = width;
  11878. depthTexture.baseHeight = height;
  11879. depthTexture.width = width;
  11880. depthTexture.height = height;
  11881. depthTexture.isReady = true;
  11882. depthTexture.samples = 1;
  11883. depthTexture.generateMipMaps = generateMipMaps;
  11884. depthTexture.samplingMode = gl.NEAREST;
  11885. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11886. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11887. textures.push(depthTexture);
  11888. this._internalTexturesCache.push(depthTexture);
  11889. }
  11890. gl.drawBuffers(attachments);
  11891. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11892. this.bindUnboundFramebuffer(null);
  11893. this.resetTextureCache();
  11894. return textures;
  11895. };
  11896. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11897. if (samples === void 0) { samples = 1; }
  11898. var depthStencilBuffer = null;
  11899. var gl = this._gl;
  11900. // Create the depth/stencil buffer
  11901. if (generateStencilBuffer) {
  11902. depthStencilBuffer = gl.createRenderbuffer();
  11903. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11904. if (samples > 1) {
  11905. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11906. }
  11907. else {
  11908. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11909. }
  11910. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11911. }
  11912. else if (generateDepthBuffer) {
  11913. depthStencilBuffer = gl.createRenderbuffer();
  11914. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11915. if (samples > 1) {
  11916. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11917. }
  11918. else {
  11919. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11920. }
  11921. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11922. }
  11923. return depthStencilBuffer;
  11924. };
  11925. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11926. if (this.webGLVersion < 2 || !texture) {
  11927. return 1;
  11928. }
  11929. if (texture.samples === samples) {
  11930. return samples;
  11931. }
  11932. var gl = this._gl;
  11933. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11934. // Dispose previous render buffers
  11935. if (texture._depthStencilBuffer) {
  11936. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11937. texture._depthStencilBuffer = null;
  11938. }
  11939. if (texture._MSAAFramebuffer) {
  11940. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11941. texture._MSAAFramebuffer = null;
  11942. }
  11943. if (texture._MSAARenderBuffer) {
  11944. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11945. texture._MSAARenderBuffer = null;
  11946. }
  11947. if (samples > 1) {
  11948. var framebuffer = gl.createFramebuffer();
  11949. if (!framebuffer) {
  11950. throw new Error("Unable to create multi sampled framebuffer");
  11951. }
  11952. texture._MSAAFramebuffer = framebuffer;
  11953. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11954. var colorRenderbuffer = gl.createRenderbuffer();
  11955. if (!colorRenderbuffer) {
  11956. throw new Error("Unable to create multi sampled framebuffer");
  11957. }
  11958. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11959. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11960. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11961. texture._MSAARenderBuffer = colorRenderbuffer;
  11962. }
  11963. else {
  11964. this.bindUnboundFramebuffer(texture._framebuffer);
  11965. }
  11966. texture.samples = samples;
  11967. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11968. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11969. this.bindUnboundFramebuffer(null);
  11970. return samples;
  11971. };
  11972. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11973. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11974. return 1;
  11975. }
  11976. if (textures[0].samples === samples) {
  11977. return samples;
  11978. }
  11979. var gl = this._gl;
  11980. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11981. // Dispose previous render buffers
  11982. if (textures[0]._depthStencilBuffer) {
  11983. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11984. textures[0]._depthStencilBuffer = null;
  11985. }
  11986. if (textures[0]._MSAAFramebuffer) {
  11987. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11988. textures[0]._MSAAFramebuffer = null;
  11989. }
  11990. for (var i = 0; i < textures.length; i++) {
  11991. if (textures[i]._MSAARenderBuffer) {
  11992. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11993. textures[i]._MSAARenderBuffer = null;
  11994. }
  11995. }
  11996. if (samples > 1) {
  11997. var framebuffer = gl.createFramebuffer();
  11998. if (!framebuffer) {
  11999. throw new Error("Unable to create multi sampled framebuffer");
  12000. }
  12001. this.bindUnboundFramebuffer(framebuffer);
  12002. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12003. var attachments = [];
  12004. for (var i = 0; i < textures.length; i++) {
  12005. var texture = textures[i];
  12006. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12007. var colorRenderbuffer = gl.createRenderbuffer();
  12008. if (!colorRenderbuffer) {
  12009. throw new Error("Unable to create multi sampled framebuffer");
  12010. }
  12011. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12012. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12013. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12014. texture._MSAAFramebuffer = framebuffer;
  12015. texture._MSAARenderBuffer = colorRenderbuffer;
  12016. texture.samples = samples;
  12017. texture._depthStencilBuffer = depthStencilBuffer;
  12018. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12019. attachments.push(attachment);
  12020. }
  12021. gl.drawBuffers(attachments);
  12022. }
  12023. else {
  12024. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12025. }
  12026. this.bindUnboundFramebuffer(null);
  12027. return samples;
  12028. };
  12029. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12030. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12031. };
  12032. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12033. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12034. };
  12035. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12036. var gl = this._gl;
  12037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12038. var generateMipMaps = true;
  12039. var generateDepthBuffer = true;
  12040. var generateStencilBuffer = false;
  12041. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12042. if (options !== undefined) {
  12043. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12044. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12045. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12046. if (options.samplingMode !== undefined) {
  12047. samplingMode = options.samplingMode;
  12048. }
  12049. }
  12050. texture.isCube = true;
  12051. texture.generateMipMaps = generateMipMaps;
  12052. texture.samples = 1;
  12053. texture.samplingMode = samplingMode;
  12054. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12056. for (var face = 0; face < 6; face++) {
  12057. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12058. }
  12059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12063. // Create the framebuffer
  12064. var framebuffer = gl.createFramebuffer();
  12065. this.bindUnboundFramebuffer(framebuffer);
  12066. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12067. // Mipmaps
  12068. if (texture.generateMipMaps) {
  12069. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12070. }
  12071. // Unbind
  12072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12073. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12074. this.bindUnboundFramebuffer(null);
  12075. texture._framebuffer = framebuffer;
  12076. texture.width = size;
  12077. texture.height = size;
  12078. texture.isReady = true;
  12079. //this.resetTextureCache();
  12080. this._internalTexturesCache.push(texture);
  12081. return texture;
  12082. };
  12083. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12084. var _this = this;
  12085. if (onLoad === void 0) { onLoad = null; }
  12086. if (onError === void 0) { onError = null; }
  12087. if (forcedExtension === void 0) { forcedExtension = null; }
  12088. var callback = function (loadData) {
  12089. if (!loadData) {
  12090. if (onLoad) {
  12091. onLoad(null);
  12092. }
  12093. return;
  12094. }
  12095. var texture = loadData.texture;
  12096. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12097. texture._lodGenerationScale = scale;
  12098. texture._lodGenerationOffset = offset;
  12099. if (_this._caps.textureLOD) {
  12100. // Do not add extra process if texture lod is supported.
  12101. if (onLoad) {
  12102. onLoad(texture);
  12103. }
  12104. return;
  12105. }
  12106. var mipSlices = 3;
  12107. var gl = _this._gl;
  12108. var width = loadData.width;
  12109. if (!width) {
  12110. return;
  12111. }
  12112. var textures = [];
  12113. for (var i = 0; i < mipSlices; i++) {
  12114. //compute LOD from even spacing in smoothness (matching shader calculation)
  12115. var smoothness = i / (mipSlices - 1);
  12116. var roughness = 1 - smoothness;
  12117. var minLODIndex = offset; // roughness = 0
  12118. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12119. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12120. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12121. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12122. glTextureFromLod.isCube = true;
  12123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12128. if (loadData.isDDS) {
  12129. var info = loadData.info;
  12130. var data = loadData.data;
  12131. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12132. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12133. }
  12134. else {
  12135. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12136. }
  12137. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12138. // Wrap in a base texture for easy binding.
  12139. var lodTexture = new BABYLON.BaseTexture(scene);
  12140. lodTexture.isCube = true;
  12141. lodTexture._texture = glTextureFromLod;
  12142. glTextureFromLod.isReady = true;
  12143. textures.push(lodTexture);
  12144. }
  12145. texture._lodTextureHigh = textures[2];
  12146. texture._lodTextureMid = textures[1];
  12147. texture._lodTextureLow = textures[0];
  12148. if (onLoad) {
  12149. onLoad(texture);
  12150. }
  12151. };
  12152. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12153. };
  12154. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12155. var _this = this;
  12156. if (onLoad === void 0) { onLoad = null; }
  12157. if (onError === void 0) { onError = null; }
  12158. if (forcedExtension === void 0) { forcedExtension = null; }
  12159. var gl = this._gl;
  12160. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12161. texture.isCube = true;
  12162. texture.url = rootUrl;
  12163. texture.generateMipMaps = !noMipmap;
  12164. if (!this._doNotHandleContextLost) {
  12165. texture._extension = forcedExtension;
  12166. texture._files = files;
  12167. }
  12168. var isKTX = false;
  12169. var isDDS = false;
  12170. var lastDot = rootUrl.lastIndexOf('.');
  12171. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12172. if (this._textureFormatInUse) {
  12173. extension = this._textureFormatInUse;
  12174. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12175. isKTX = true;
  12176. }
  12177. else {
  12178. isDDS = (extension === ".dds");
  12179. }
  12180. var onerror = function (request, exception) {
  12181. if (onError && request) {
  12182. onError(request.status + " " + request.statusText, exception);
  12183. }
  12184. };
  12185. if (isKTX) {
  12186. this._loadFile(rootUrl, function (data) {
  12187. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12188. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12189. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12190. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12191. ktx.uploadLevels(_this._gl, !noMipmap);
  12192. _this.setCubeMapTextureParams(gl, loadMipmap);
  12193. texture.width = ktx.pixelWidth;
  12194. texture.height = ktx.pixelHeight;
  12195. texture.isReady = true;
  12196. }, undefined, undefined, true, onerror);
  12197. }
  12198. else if (isDDS) {
  12199. if (files && files.length === 6) {
  12200. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12201. var info;
  12202. var loadMipmap = false;
  12203. var width = 0;
  12204. for (var index = 0; index < imgs.length; index++) {
  12205. var data = imgs[index];
  12206. info = BABYLON.DDSTools.GetDDSInfo(data);
  12207. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12208. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12210. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12211. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12212. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12213. }
  12214. texture.width = info.width;
  12215. texture.height = info.height;
  12216. texture.type = info.textureType;
  12217. width = info.width;
  12218. }
  12219. _this.setCubeMapTextureParams(gl, loadMipmap);
  12220. texture.isReady = true;
  12221. if (onLoad) {
  12222. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12223. }
  12224. }, files, onError);
  12225. }
  12226. else {
  12227. this._loadFile(rootUrl, function (data) {
  12228. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12229. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12230. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12231. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12232. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12233. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12234. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12235. }
  12236. _this.setCubeMapTextureParams(gl, loadMipmap);
  12237. texture.width = info.width;
  12238. texture.height = info.height;
  12239. texture.isReady = true;
  12240. texture.type = info.textureType;
  12241. if (onLoad) {
  12242. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12243. }
  12244. }, undefined, undefined, true, onerror);
  12245. }
  12246. }
  12247. else {
  12248. if (!files) {
  12249. throw new Error("Cannot load cubemap because files were not defined");
  12250. }
  12251. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12252. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12253. var height = width;
  12254. _this._prepareWorkingCanvas();
  12255. if (!_this._workingCanvas || !_this._workingContext) {
  12256. return;
  12257. }
  12258. _this._workingCanvas.width = width;
  12259. _this._workingCanvas.height = height;
  12260. var faces = [
  12261. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12262. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12263. ];
  12264. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12265. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12266. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12267. for (var index = 0; index < faces.length; index++) {
  12268. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12269. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12270. }
  12271. if (!noMipmap) {
  12272. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12273. }
  12274. _this.setCubeMapTextureParams(gl, !noMipmap);
  12275. texture.width = width;
  12276. texture.height = height;
  12277. texture.isReady = true;
  12278. if (format) {
  12279. texture.format = format;
  12280. }
  12281. texture.onLoadedObservable.notifyObservers(texture);
  12282. texture.onLoadedObservable.clear();
  12283. if (onLoad) {
  12284. onLoad();
  12285. }
  12286. }, files, onError);
  12287. }
  12288. this._internalTexturesCache.push(texture);
  12289. return texture;
  12290. };
  12291. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12296. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12297. // this.resetTextureCache();
  12298. };
  12299. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12300. if (compression === void 0) { compression = null; }
  12301. if (level === void 0) { level = 0; }
  12302. texture._bufferViewArray = data;
  12303. texture.format = format;
  12304. texture.type = type;
  12305. texture.invertY = invertY;
  12306. texture._compression = compression;
  12307. var gl = this._gl;
  12308. var textureType = this._getWebGLTextureType(type);
  12309. var internalFormat = this._getInternalFormat(format);
  12310. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12311. var needConversion = false;
  12312. if (internalFormat === gl.RGB) {
  12313. internalFormat = gl.RGBA;
  12314. needConversion = true;
  12315. }
  12316. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12317. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12318. if (texture.width % 4 !== 0) {
  12319. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12320. }
  12321. // Data are known to be in +X +Y +Z -X -Y -Z
  12322. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12323. var faceData = data[faceIndex];
  12324. if (compression) {
  12325. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12326. }
  12327. else {
  12328. if (needConversion) {
  12329. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12330. }
  12331. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12332. }
  12333. }
  12334. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12335. if (isPot && texture.generateMipMaps && level === 0) {
  12336. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12337. }
  12338. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12339. // this.resetTextureCache();
  12340. texture.isReady = true;
  12341. };
  12342. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12343. if (compression === void 0) { compression = null; }
  12344. var gl = this._gl;
  12345. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12346. texture.isCube = true;
  12347. texture.generateMipMaps = generateMipMaps;
  12348. texture.format = format;
  12349. texture.type = type;
  12350. if (!this._doNotHandleContextLost) {
  12351. texture._bufferViewArray = data;
  12352. }
  12353. var textureType = this._getWebGLTextureType(type);
  12354. var internalFormat = this._getInternalFormat(format);
  12355. if (internalFormat === gl.RGB) {
  12356. internalFormat = gl.RGBA;
  12357. }
  12358. var width = size;
  12359. var height = width;
  12360. texture.width = width;
  12361. texture.height = height;
  12362. // Double check on POT to generate Mips.
  12363. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12364. if (!isPot) {
  12365. generateMipMaps = false;
  12366. }
  12367. // Upload data if needed. The texture won't be ready until then.
  12368. if (data) {
  12369. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12370. }
  12371. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12372. // Filters
  12373. if (data && generateMipMaps) {
  12374. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12375. }
  12376. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12377. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12378. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12379. }
  12380. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12383. }
  12384. else {
  12385. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12387. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12388. }
  12389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12391. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12392. return texture;
  12393. };
  12394. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12395. var _this = this;
  12396. if (onLoad === void 0) { onLoad = null; }
  12397. if (onError === void 0) { onError = null; }
  12398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12399. if (invertY === void 0) { invertY = false; }
  12400. var gl = this._gl;
  12401. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12402. scene._addPendingData(texture);
  12403. texture.url = url;
  12404. this._internalTexturesCache.push(texture);
  12405. var onerror = function (request, exception) {
  12406. scene._removePendingData(texture);
  12407. if (onError && request) {
  12408. onError(request.status + " " + request.statusText, exception);
  12409. }
  12410. };
  12411. var internalCallback = function (data) {
  12412. var width = texture.width;
  12413. var faceDataArrays = callback(data);
  12414. if (!faceDataArrays) {
  12415. return;
  12416. }
  12417. if (mipmmapGenerator) {
  12418. var textureType = _this._getWebGLTextureType(type);
  12419. var internalFormat = _this._getInternalFormat(format);
  12420. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12421. var needConversion = false;
  12422. if (internalFormat === gl.RGB) {
  12423. internalFormat = gl.RGBA;
  12424. needConversion = true;
  12425. }
  12426. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12428. var mipData = mipmmapGenerator(faceDataArrays);
  12429. for (var level = 0; level < mipData.length; level++) {
  12430. var mipSize = width >> level;
  12431. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12432. var mipFaceData = mipData[level][faceIndex];
  12433. if (needConversion) {
  12434. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12435. }
  12436. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12437. }
  12438. }
  12439. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12440. }
  12441. else {
  12442. texture.generateMipMaps = !noMipmap;
  12443. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12444. }
  12445. texture.isReady = true;
  12446. // this.resetTextureCache();
  12447. scene._removePendingData(texture);
  12448. if (onLoad) {
  12449. onLoad();
  12450. }
  12451. };
  12452. this._loadFile(url, function (data) {
  12453. internalCallback(data);
  12454. }, undefined, scene.database, true, onerror);
  12455. return texture;
  12456. };
  12457. ;
  12458. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12459. if (compression === void 0) { compression = null; }
  12460. var internalFormat = this._getInternalFormat(format);
  12461. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12462. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12463. if (!this._doNotHandleContextLost) {
  12464. texture._bufferView = data;
  12465. texture.format = format;
  12466. texture.invertY = invertY;
  12467. texture._compression = compression;
  12468. }
  12469. if (texture.width % 4 !== 0) {
  12470. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12471. }
  12472. if (compression && data) {
  12473. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12474. }
  12475. else {
  12476. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12477. }
  12478. if (texture.generateMipMaps) {
  12479. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12480. }
  12481. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12482. // this.resetTextureCache();
  12483. texture.isReady = true;
  12484. };
  12485. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12486. if (compression === void 0) { compression = null; }
  12487. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12488. texture.baseWidth = width;
  12489. texture.baseHeight = height;
  12490. texture.baseDepth = depth;
  12491. texture.width = width;
  12492. texture.height = height;
  12493. texture.depth = depth;
  12494. texture.format = format;
  12495. texture.generateMipMaps = generateMipMaps;
  12496. texture.samplingMode = samplingMode;
  12497. texture.is3D = true;
  12498. if (!this._doNotHandleContextLost) {
  12499. texture._bufferView = data;
  12500. }
  12501. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12502. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12503. // Filters
  12504. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12505. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12507. if (generateMipMaps) {
  12508. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12509. }
  12510. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12511. this._internalTexturesCache.push(texture);
  12512. return texture;
  12513. };
  12514. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12515. var gl = this._gl;
  12516. if (!gl) {
  12517. return;
  12518. }
  12519. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12522. if (!noMipmap && !isCompressed) {
  12523. gl.generateMipmap(gl.TEXTURE_2D);
  12524. }
  12525. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12526. // this.resetTextureCache();
  12527. if (scene) {
  12528. scene._removePendingData(texture);
  12529. }
  12530. texture.onLoadedObservable.notifyObservers(texture);
  12531. texture.onLoadedObservable.clear();
  12532. };
  12533. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12534. var _this = this;
  12535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12536. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12537. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12538. var gl = this._gl;
  12539. if (!gl) {
  12540. return;
  12541. }
  12542. if (!texture._webGLTexture) {
  12543. // this.resetTextureCache();
  12544. if (scene) {
  12545. scene._removePendingData(texture);
  12546. }
  12547. return;
  12548. }
  12549. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12550. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12551. texture.baseWidth = width;
  12552. texture.baseHeight = height;
  12553. texture.width = potWidth;
  12554. texture.height = potHeight;
  12555. texture.isReady = true;
  12556. if (processFunction(potWidth, potHeight, function () {
  12557. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12558. })) {
  12559. // Returning as texture needs extra async steps
  12560. return;
  12561. }
  12562. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12563. };
  12564. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12565. // Create new RGBA data container.
  12566. var rgbaData;
  12567. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12568. rgbaData = new Float32Array(width * height * 4);
  12569. }
  12570. else {
  12571. rgbaData = new Uint32Array(width * height * 4);
  12572. }
  12573. // Convert each pixel.
  12574. for (var x = 0; x < width; x++) {
  12575. for (var y = 0; y < height; y++) {
  12576. var index = (y * width + x) * 3;
  12577. var newIndex = (y * width + x) * 4;
  12578. // Map Old Value to new value.
  12579. rgbaData[newIndex + 0] = rgbData[index + 0];
  12580. rgbaData[newIndex + 1] = rgbData[index + 1];
  12581. rgbaData[newIndex + 2] = rgbData[index + 2];
  12582. // Add fully opaque alpha channel.
  12583. rgbaData[newIndex + 3] = 1;
  12584. }
  12585. }
  12586. return rgbaData;
  12587. };
  12588. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12589. var gl = this._gl;
  12590. if (texture._framebuffer) {
  12591. gl.deleteFramebuffer(texture._framebuffer);
  12592. texture._framebuffer = null;
  12593. }
  12594. if (texture._depthStencilBuffer) {
  12595. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12596. texture._depthStencilBuffer = null;
  12597. }
  12598. if (texture._MSAAFramebuffer) {
  12599. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12600. texture._MSAAFramebuffer = null;
  12601. }
  12602. if (texture._MSAARenderBuffer) {
  12603. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12604. texture._MSAARenderBuffer = null;
  12605. }
  12606. };
  12607. Engine.prototype._releaseTexture = function (texture) {
  12608. var gl = this._gl;
  12609. this._releaseFramebufferObjects(texture);
  12610. gl.deleteTexture(texture._webGLTexture);
  12611. // Unbind channels
  12612. this.unbindAllTextures();
  12613. var index = this._internalTexturesCache.indexOf(texture);
  12614. if (index !== -1) {
  12615. this._internalTexturesCache.splice(index, 1);
  12616. }
  12617. // Integrated fixed lod samplers.
  12618. if (texture._lodTextureHigh) {
  12619. texture._lodTextureHigh.dispose();
  12620. }
  12621. if (texture._lodTextureMid) {
  12622. texture._lodTextureMid.dispose();
  12623. }
  12624. if (texture._lodTextureLow) {
  12625. texture._lodTextureLow.dispose();
  12626. }
  12627. };
  12628. Engine.prototype.setProgram = function (program) {
  12629. if (this._currentProgram !== program) {
  12630. this._gl.useProgram(program);
  12631. this._currentProgram = program;
  12632. }
  12633. };
  12634. Engine.prototype.bindSamplers = function (effect) {
  12635. this.setProgram(effect.getProgram());
  12636. var samplers = effect.getSamplers();
  12637. for (var index = 0; index < samplers.length; index++) {
  12638. var uniform = effect.getUniform(samplers[index]);
  12639. if (uniform) {
  12640. this._boundUniforms[index] = uniform;
  12641. }
  12642. }
  12643. this._currentEffect = null;
  12644. };
  12645. Engine.prototype._activateTextureChannel = function (channel) {
  12646. if (this._activeChannel !== channel && channel > -1) {
  12647. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12648. this._activeChannel = channel;
  12649. }
  12650. };
  12651. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12652. var index = this._boundTexturesStack.indexOf(internalTexture);
  12653. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12654. this._boundTexturesStack.splice(index, 1);
  12655. this._boundTexturesStack.push(internalTexture);
  12656. }
  12657. };
  12658. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12659. var currentSlot = internalTexture._designatedSlot;
  12660. internalTexture._designatedSlot = -1;
  12661. var index = this._boundTexturesStack.indexOf(internalTexture);
  12662. if (index > -1) {
  12663. this._boundTexturesStack.splice(index, 1);
  12664. if (currentSlot > -1) {
  12665. this._boundTexturesCache[currentSlot] = null;
  12666. this._nextFreeTextureSlots.push(currentSlot);
  12667. }
  12668. }
  12669. return currentSlot;
  12670. };
  12671. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12672. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12673. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12674. var isTextureForRendering = texture && texture._initialSlot > -1;
  12675. if (currentTextureBound !== texture) {
  12676. if (currentTextureBound) {
  12677. this._removeDesignatedSlot(currentTextureBound);
  12678. }
  12679. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12680. if (this._activeChannel >= 0) {
  12681. this._boundTexturesCache[this._activeChannel] = texture;
  12682. if (isTextureForRendering) {
  12683. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12684. if (slotIndex > -1) {
  12685. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12686. }
  12687. this._boundTexturesStack.push(texture);
  12688. }
  12689. }
  12690. }
  12691. if (isTextureForRendering && this._activeChannel > -1) {
  12692. texture._designatedSlot = this._activeChannel;
  12693. if (!doNotBindUniformToTextureChannel) {
  12694. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12695. }
  12696. }
  12697. };
  12698. Engine.prototype._bindTexture = function (channel, texture) {
  12699. if (channel < 0) {
  12700. return;
  12701. }
  12702. if (texture) {
  12703. channel = this._getCorrectTextureChannel(channel, texture);
  12704. }
  12705. this._activateTextureChannel(channel);
  12706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12707. };
  12708. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12709. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12710. };
  12711. Engine.prototype.unbindAllTextures = function () {
  12712. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  12713. this._activateTextureChannel(channel);
  12714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12715. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12716. if (this.webGLVersion > 1) {
  12717. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12718. }
  12719. }
  12720. };
  12721. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12722. if (channel < 0) {
  12723. return;
  12724. }
  12725. if (uniform) {
  12726. this._boundUniforms[channel] = uniform;
  12727. }
  12728. this._setTexture(channel, texture);
  12729. };
  12730. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12731. if (!internalTexture) {
  12732. return -1;
  12733. }
  12734. internalTexture._initialSlot = channel;
  12735. if (channel !== internalTexture._designatedSlot) {
  12736. if (internalTexture._designatedSlot > -1) {
  12737. return internalTexture._designatedSlot;
  12738. }
  12739. else {
  12740. // No slot for this texture, let's pick a new one (if we find a free slot)
  12741. if (this._nextFreeTextureSlots.length) {
  12742. return this._nextFreeTextureSlots[0];
  12743. }
  12744. // We need to recycle the oldest bound texture, sorry.
  12745. this._textureCollisions.addCount(1, false);
  12746. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12747. }
  12748. }
  12749. return channel;
  12750. };
  12751. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12752. var uniform = this._boundUniforms[sourceSlot];
  12753. this._gl.uniform1i(uniform, destination);
  12754. };
  12755. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12756. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12757. // Not ready?
  12758. if (!texture) {
  12759. if (this._boundTexturesCache[channel] != null) {
  12760. this._activateTextureChannel(channel);
  12761. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12762. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12763. if (this.webGLVersion > 1) {
  12764. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12765. }
  12766. }
  12767. return false;
  12768. }
  12769. // Video
  12770. var alreadyActivated = false;
  12771. if (texture.video) {
  12772. this._activateTextureChannel(channel);
  12773. alreadyActivated = true;
  12774. texture.update();
  12775. }
  12776. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12777. texture.delayLoad();
  12778. return false;
  12779. }
  12780. var internalTexture;
  12781. if (texture.isReady()) {
  12782. internalTexture = texture.getInternalTexture();
  12783. }
  12784. else if (texture.isCube) {
  12785. internalTexture = this.emptyCubeTexture;
  12786. }
  12787. else if (texture.is3D) {
  12788. internalTexture = this.emptyTexture3D;
  12789. }
  12790. else {
  12791. internalTexture = this.emptyTexture;
  12792. }
  12793. if (!isPartOfTextureArray) {
  12794. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12795. }
  12796. if (this._boundTexturesCache[channel] === internalTexture) {
  12797. this._moveBoundTextureOnTop(internalTexture);
  12798. if (!isPartOfTextureArray) {
  12799. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12800. }
  12801. return false;
  12802. }
  12803. if (!alreadyActivated) {
  12804. this._activateTextureChannel(channel);
  12805. }
  12806. if (internalTexture && internalTexture.is3D) {
  12807. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12808. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12809. internalTexture._cachedWrapU = texture.wrapU;
  12810. switch (texture.wrapU) {
  12811. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12812. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12813. break;
  12814. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12815. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12816. break;
  12817. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12819. break;
  12820. }
  12821. }
  12822. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12823. internalTexture._cachedWrapV = texture.wrapV;
  12824. switch (texture.wrapV) {
  12825. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12826. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12827. break;
  12828. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12829. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12830. break;
  12831. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12832. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12833. break;
  12834. }
  12835. }
  12836. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12837. internalTexture._cachedWrapR = texture.wrapR;
  12838. switch (texture.wrapV) {
  12839. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12840. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12841. break;
  12842. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12843. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12844. break;
  12845. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12846. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12847. break;
  12848. }
  12849. }
  12850. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12851. }
  12852. else if (internalTexture && internalTexture.isCube) {
  12853. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12854. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12855. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12856. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12857. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12858. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12859. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12860. }
  12861. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12862. }
  12863. else {
  12864. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12865. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12866. internalTexture._cachedWrapU = texture.wrapU;
  12867. switch (texture.wrapU) {
  12868. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12869. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12870. break;
  12871. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12873. break;
  12874. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12876. break;
  12877. }
  12878. }
  12879. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12880. internalTexture._cachedWrapV = texture.wrapV;
  12881. switch (texture.wrapV) {
  12882. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12884. break;
  12885. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12887. break;
  12888. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12890. break;
  12891. }
  12892. }
  12893. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12894. }
  12895. return true;
  12896. };
  12897. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12898. if (channel < 0 || !uniform) {
  12899. return;
  12900. }
  12901. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12902. this._textureUnits = new Int32Array(textures.length);
  12903. }
  12904. for (var i = 0; i < textures.length; i++) {
  12905. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12906. }
  12907. this._gl.uniform1iv(uniform, this._textureUnits);
  12908. for (var index = 0; index < textures.length; index++) {
  12909. this._setTexture(this._textureUnits[index], textures[index], true);
  12910. }
  12911. };
  12912. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12913. var internalTexture = texture.getInternalTexture();
  12914. if (!internalTexture) {
  12915. return;
  12916. }
  12917. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12918. var value = texture.anisotropicFilteringLevel;
  12919. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12920. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12921. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12922. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12923. }
  12924. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12925. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12926. internalTexture._cachedAnisotropicFilteringLevel = value;
  12927. }
  12928. };
  12929. Engine.prototype.readPixels = function (x, y, width, height) {
  12930. var data = new Uint8Array(height * width * 4);
  12931. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12932. return data;
  12933. };
  12934. /**
  12935. * Add an externaly attached data from its key.
  12936. * This method call will fail and return false, if such key already exists.
  12937. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12938. * @param key the unique key that identifies the data
  12939. * @param data the data object to associate to the key for this Engine instance
  12940. * @return true if no such key were already present and the data was added successfully, false otherwise
  12941. */
  12942. Engine.prototype.addExternalData = function (key, data) {
  12943. if (!this._externalData) {
  12944. this._externalData = new BABYLON.StringDictionary();
  12945. }
  12946. return this._externalData.add(key, data);
  12947. };
  12948. /**
  12949. * Get an externaly attached data from its key
  12950. * @param key the unique key that identifies the data
  12951. * @return the associated data, if present (can be null), or undefined if not present
  12952. */
  12953. Engine.prototype.getExternalData = function (key) {
  12954. if (!this._externalData) {
  12955. this._externalData = new BABYLON.StringDictionary();
  12956. }
  12957. return this._externalData.get(key);
  12958. };
  12959. /**
  12960. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12961. * @param key the unique key that identifies the data
  12962. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12963. * @return the associated data, can be null if the factory returned null.
  12964. */
  12965. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12966. if (!this._externalData) {
  12967. this._externalData = new BABYLON.StringDictionary();
  12968. }
  12969. return this._externalData.getOrAddWithFactory(key, factory);
  12970. };
  12971. /**
  12972. * Remove an externaly attached data from the Engine instance
  12973. * @param key the unique key that identifies the data
  12974. * @return true if the data was successfully removed, false if it doesn't exist
  12975. */
  12976. Engine.prototype.removeExternalData = function (key) {
  12977. if (!this._externalData) {
  12978. this._externalData = new BABYLON.StringDictionary();
  12979. }
  12980. return this._externalData.remove(key);
  12981. };
  12982. Engine.prototype.unbindAllAttributes = function () {
  12983. if (this._mustWipeVertexAttributes) {
  12984. this._mustWipeVertexAttributes = false;
  12985. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12986. this._gl.disableVertexAttribArray(i);
  12987. this._vertexAttribArraysEnabled[i] = false;
  12988. this._currentBufferPointers[i].active = false;
  12989. }
  12990. return;
  12991. }
  12992. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12993. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12994. continue;
  12995. }
  12996. this._gl.disableVertexAttribArray(i);
  12997. this._vertexAttribArraysEnabled[i] = false;
  12998. this._currentBufferPointers[i].active = false;
  12999. }
  13000. };
  13001. Engine.prototype.releaseEffects = function () {
  13002. for (var name in this._compiledEffects) {
  13003. this._deleteProgram(this._compiledEffects[name]._program);
  13004. }
  13005. this._compiledEffects = {};
  13006. };
  13007. // Dispose
  13008. Engine.prototype.dispose = function () {
  13009. this.hideLoadingUI();
  13010. this.stopRenderLoop();
  13011. // Release postProcesses
  13012. while (this.postProcesses.length) {
  13013. this.postProcesses[0].dispose();
  13014. }
  13015. // Empty texture
  13016. if (this._emptyTexture) {
  13017. this._releaseTexture(this._emptyTexture);
  13018. this._emptyTexture = null;
  13019. }
  13020. if (this._emptyCubeTexture) {
  13021. this._releaseTexture(this._emptyCubeTexture);
  13022. this._emptyCubeTexture = null;
  13023. }
  13024. // Rescale PP
  13025. if (this._rescalePostProcess) {
  13026. this._rescalePostProcess.dispose();
  13027. }
  13028. // Release scenes
  13029. while (this.scenes.length) {
  13030. this.scenes[0].dispose();
  13031. }
  13032. // Release audio engine
  13033. if (Engine.audioEngine) {
  13034. Engine.audioEngine.dispose();
  13035. }
  13036. // Release effects
  13037. this.releaseEffects();
  13038. // Unbind
  13039. this.unbindAllAttributes();
  13040. if (this._dummyFramebuffer) {
  13041. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13042. }
  13043. //WebVR
  13044. this.disableVR();
  13045. // Events
  13046. if (BABYLON.Tools.IsWindowObjectExist()) {
  13047. window.removeEventListener("blur", this._onBlur);
  13048. window.removeEventListener("focus", this._onFocus);
  13049. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13050. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13051. if (this._renderingCanvas) {
  13052. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13053. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13054. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13055. if (!this._doNotHandleContextLost) {
  13056. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13057. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13058. }
  13059. }
  13060. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13061. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13062. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13063. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13064. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13065. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13066. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13067. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13068. if (this._onVrDisplayConnect) {
  13069. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13070. if (this._onVrDisplayDisconnect) {
  13071. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13072. }
  13073. if (this._onVrDisplayPresentChange) {
  13074. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13075. }
  13076. this._onVrDisplayConnect = null;
  13077. this._onVrDisplayDisconnect = null;
  13078. }
  13079. }
  13080. // Remove from Instances
  13081. var index = Engine.Instances.indexOf(this);
  13082. if (index >= 0) {
  13083. Engine.Instances.splice(index, 1);
  13084. }
  13085. this._workingCanvas = null;
  13086. this._workingContext = null;
  13087. this._currentBufferPointers = [];
  13088. this._renderingCanvas = null;
  13089. this._currentProgram = null;
  13090. this.onResizeObservable.clear();
  13091. this.onCanvasBlurObservable.clear();
  13092. this.onCanvasFocusObservable.clear();
  13093. this.onCanvasPointerOutObservable.clear();
  13094. this.onBeginFrameObservable.clear();
  13095. this.onEndFrameObservable.clear();
  13096. BABYLON.Effect.ResetCache();
  13097. // Abort active requests
  13098. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13099. var request = _a[_i];
  13100. request.abort();
  13101. }
  13102. };
  13103. // Loading screen
  13104. Engine.prototype.displayLoadingUI = function () {
  13105. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13106. return;
  13107. }
  13108. var loadingScreen = this.loadingScreen;
  13109. if (loadingScreen) {
  13110. loadingScreen.displayLoadingUI();
  13111. }
  13112. };
  13113. Engine.prototype.hideLoadingUI = function () {
  13114. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13115. return;
  13116. }
  13117. var loadingScreen = this.loadingScreen;
  13118. if (loadingScreen) {
  13119. loadingScreen.hideLoadingUI();
  13120. }
  13121. };
  13122. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13123. get: function () {
  13124. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13125. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13126. return this._loadingScreen;
  13127. },
  13128. set: function (loadingScreen) {
  13129. this._loadingScreen = loadingScreen;
  13130. },
  13131. enumerable: true,
  13132. configurable: true
  13133. });
  13134. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13135. set: function (text) {
  13136. this.loadingScreen.loadingUIText = text;
  13137. },
  13138. enumerable: true,
  13139. configurable: true
  13140. });
  13141. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13142. set: function (color) {
  13143. this.loadingScreen.loadingUIBackgroundColor = color;
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. Engine.prototype.attachContextLostEvent = function (callback) {
  13149. if (this._renderingCanvas) {
  13150. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13151. }
  13152. };
  13153. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13154. if (this._renderingCanvas) {
  13155. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13156. }
  13157. };
  13158. Engine.prototype.getVertexShaderSource = function (program) {
  13159. var shaders = this._gl.getAttachedShaders(program);
  13160. if (!shaders) {
  13161. return null;
  13162. }
  13163. return this._gl.getShaderSource(shaders[0]);
  13164. };
  13165. Engine.prototype.getFragmentShaderSource = function (program) {
  13166. var shaders = this._gl.getAttachedShaders(program);
  13167. if (!shaders) {
  13168. return null;
  13169. }
  13170. return this._gl.getShaderSource(shaders[1]);
  13171. };
  13172. Engine.prototype.getError = function () {
  13173. return this._gl.getError();
  13174. };
  13175. // FPS
  13176. Engine.prototype.getFps = function () {
  13177. return this._fps;
  13178. };
  13179. Engine.prototype.getDeltaTime = function () {
  13180. return this._deltaTime;
  13181. };
  13182. Engine.prototype._measureFps = function () {
  13183. this._performanceMonitor.sampleFrame();
  13184. this._fps = this._performanceMonitor.averageFPS;
  13185. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13186. };
  13187. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13188. if (faceIndex === void 0) { faceIndex = -1; }
  13189. var gl = this._gl;
  13190. if (!this._dummyFramebuffer) {
  13191. var dummy = gl.createFramebuffer();
  13192. if (!dummy) {
  13193. throw new Error("Unable to create dummy framebuffer");
  13194. }
  13195. this._dummyFramebuffer = dummy;
  13196. }
  13197. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13198. if (faceIndex > -1) {
  13199. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13200. }
  13201. else {
  13202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13203. }
  13204. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13205. var buffer;
  13206. switch (readType) {
  13207. case gl.UNSIGNED_BYTE:
  13208. buffer = new Uint8Array(4 * width * height);
  13209. readType = gl.UNSIGNED_BYTE;
  13210. break;
  13211. default:
  13212. buffer = new Float32Array(4 * width * height);
  13213. readType = gl.FLOAT;
  13214. break;
  13215. }
  13216. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13217. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13218. return buffer;
  13219. };
  13220. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13221. if (this._webGLVersion > 1) {
  13222. return this._caps.colorBufferFloat;
  13223. }
  13224. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13225. };
  13226. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13227. if (this._webGLVersion > 1) {
  13228. return this._caps.colorBufferFloat;
  13229. }
  13230. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13231. };
  13232. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13233. Engine.prototype._canRenderToFramebuffer = function (type) {
  13234. var gl = this._gl;
  13235. //clear existing errors
  13236. while (gl.getError() !== gl.NO_ERROR) { }
  13237. var successful = true;
  13238. var texture = gl.createTexture();
  13239. gl.bindTexture(gl.TEXTURE_2D, texture);
  13240. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13243. var fb = gl.createFramebuffer();
  13244. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13245. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13246. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13247. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13248. successful = successful && (gl.getError() === gl.NO_ERROR);
  13249. //try render by clearing frame buffer's color buffer
  13250. if (successful) {
  13251. gl.clear(gl.COLOR_BUFFER_BIT);
  13252. successful = successful && (gl.getError() === gl.NO_ERROR);
  13253. }
  13254. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13255. if (successful) {
  13256. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13257. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13258. var readFormat = gl.RGBA;
  13259. var readType = gl.UNSIGNED_BYTE;
  13260. var buffer = new Uint8Array(4);
  13261. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13262. successful = successful && (gl.getError() === gl.NO_ERROR);
  13263. }
  13264. //clean up
  13265. gl.deleteTexture(texture);
  13266. gl.deleteFramebuffer(fb);
  13267. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13268. //clear accumulated errors
  13269. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13270. return successful;
  13271. };
  13272. Engine.prototype._getWebGLTextureType = function (type) {
  13273. if (type === Engine.TEXTURETYPE_FLOAT) {
  13274. return this._gl.FLOAT;
  13275. }
  13276. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13277. // Add Half Float Constant.
  13278. return this._gl.HALF_FLOAT_OES;
  13279. }
  13280. return this._gl.UNSIGNED_BYTE;
  13281. };
  13282. ;
  13283. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13284. if (this._webGLVersion === 1) {
  13285. return this._gl.RGBA;
  13286. }
  13287. if (type === Engine.TEXTURETYPE_FLOAT) {
  13288. return this._gl.RGBA32F;
  13289. }
  13290. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13291. return this._gl.RGBA16F;
  13292. }
  13293. return this._gl.RGBA;
  13294. };
  13295. ;
  13296. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13297. if (type === Engine.TEXTURETYPE_FLOAT) {
  13298. return this._gl.RGBA32F;
  13299. }
  13300. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13301. return this._gl.RGBA16F;
  13302. }
  13303. return this._gl.RGBA8;
  13304. };
  13305. ;
  13306. Engine.prototype.createQuery = function () {
  13307. return this._gl.createQuery();
  13308. };
  13309. Engine.prototype.deleteQuery = function (query) {
  13310. this._gl.deleteQuery(query);
  13311. return this;
  13312. };
  13313. Engine.prototype.isQueryResultAvailable = function (query) {
  13314. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13315. };
  13316. Engine.prototype.getQueryResult = function (query) {
  13317. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13318. };
  13319. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13320. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13321. this._gl.beginQuery(glAlgorithm, query);
  13322. return this;
  13323. };
  13324. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13325. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13326. this._gl.endQuery(glAlgorithm);
  13327. return this;
  13328. };
  13329. /* Time queries */
  13330. Engine.prototype._createTimeQuery = function () {
  13331. var timerQuery = this._caps.timerQuery;
  13332. if (timerQuery.createQueryEXT) {
  13333. return timerQuery.createQueryEXT();
  13334. }
  13335. return this.createQuery();
  13336. };
  13337. Engine.prototype._deleteTimeQuery = function (query) {
  13338. var timerQuery = this._caps.timerQuery;
  13339. if (timerQuery.deleteQueryEXT) {
  13340. timerQuery.deleteQueryEXT(query);
  13341. return;
  13342. }
  13343. this.deleteQuery(query);
  13344. };
  13345. Engine.prototype._getTimeQueryResult = function (query) {
  13346. var timerQuery = this._caps.timerQuery;
  13347. if (timerQuery.getQueryObjectEXT) {
  13348. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13349. }
  13350. return this.getQueryResult(query);
  13351. };
  13352. Engine.prototype._getTimeQueryAvailability = function (query) {
  13353. var timerQuery = this._caps.timerQuery;
  13354. if (timerQuery.getQueryObjectEXT) {
  13355. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13356. }
  13357. return this.isQueryResultAvailable(query);
  13358. };
  13359. Engine.prototype.startTimeQuery = function () {
  13360. var timerQuery = this._caps.timerQuery;
  13361. if (!timerQuery) {
  13362. return null;
  13363. }
  13364. var token = new BABYLON._TimeToken();
  13365. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13366. if (this._caps.canUseTimestampForTimerQuery) {
  13367. token._startTimeQuery = this._createTimeQuery();
  13368. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13369. }
  13370. else {
  13371. if (this._currentNonTimestampToken) {
  13372. return this._currentNonTimestampToken;
  13373. }
  13374. token._timeElapsedQuery = this._createTimeQuery();
  13375. if (timerQuery.beginQueryEXT) {
  13376. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13377. }
  13378. else {
  13379. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13380. }
  13381. this._currentNonTimestampToken = token;
  13382. }
  13383. return token;
  13384. };
  13385. Engine.prototype.endTimeQuery = function (token) {
  13386. var timerQuery = this._caps.timerQuery;
  13387. if (!timerQuery || !token) {
  13388. return -1;
  13389. }
  13390. if (this._caps.canUseTimestampForTimerQuery) {
  13391. if (!token._startTimeQuery) {
  13392. return -1;
  13393. }
  13394. if (!token._endTimeQuery) {
  13395. token._endTimeQuery = this._createTimeQuery();
  13396. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13397. }
  13398. }
  13399. else if (!token._timeElapsedQueryEnded) {
  13400. if (!token._timeElapsedQuery) {
  13401. return -1;
  13402. }
  13403. if (timerQuery.endQueryEXT) {
  13404. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13405. }
  13406. else {
  13407. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13408. }
  13409. token._timeElapsedQueryEnded = true;
  13410. }
  13411. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13412. var available = false;
  13413. if (token._endTimeQuery) {
  13414. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13415. }
  13416. else if (token._timeElapsedQuery) {
  13417. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13418. }
  13419. if (available && !disjoint) {
  13420. var result = 0;
  13421. if (this._caps.canUseTimestampForTimerQuery) {
  13422. if (!token._startTimeQuery || !token._endTimeQuery) {
  13423. return -1;
  13424. }
  13425. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13426. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13427. result = timeEnd - timeStart;
  13428. this._deleteTimeQuery(token._startTimeQuery);
  13429. this._deleteTimeQuery(token._endTimeQuery);
  13430. token._startTimeQuery = null;
  13431. token._endTimeQuery = null;
  13432. }
  13433. else {
  13434. if (!token._timeElapsedQuery) {
  13435. return -1;
  13436. }
  13437. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13438. this._deleteTimeQuery(token._timeElapsedQuery);
  13439. token._timeElapsedQuery = null;
  13440. token._timeElapsedQueryEnded = false;
  13441. this._currentNonTimestampToken = null;
  13442. }
  13443. return result;
  13444. }
  13445. return -1;
  13446. };
  13447. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13448. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13449. };
  13450. // Transform feedback
  13451. Engine.prototype.createTransformFeedback = function () {
  13452. return this._gl.createTransformFeedback();
  13453. };
  13454. Engine.prototype.deleteTransformFeedback = function (value) {
  13455. this._gl.deleteTransformFeedback(value);
  13456. };
  13457. Engine.prototype.bindTransformFeedback = function (value) {
  13458. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13459. };
  13460. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13461. if (usePoints === void 0) { usePoints = true; }
  13462. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13463. };
  13464. Engine.prototype.endTransformFeedback = function () {
  13465. this._gl.endTransformFeedback();
  13466. };
  13467. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13468. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13469. };
  13470. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13471. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13472. };
  13473. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13474. var _this = this;
  13475. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13476. this._activeRequests.push(request);
  13477. request.onCompleteObservable.add(function (request) {
  13478. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13479. });
  13480. return request;
  13481. };
  13482. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13483. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13484. var onload = function (data) {
  13485. loadedFiles[index] = data;
  13486. loadedFiles._internalCount++;
  13487. if (loadedFiles._internalCount === 6) {
  13488. onfinish(loadedFiles);
  13489. }
  13490. };
  13491. var onerror = function (request, exception) {
  13492. if (onErrorCallBack && request) {
  13493. onErrorCallBack(request.status + " " + request.statusText, exception);
  13494. }
  13495. };
  13496. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13497. };
  13498. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13499. if (onError === void 0) { onError = null; }
  13500. var loadedFiles = [];
  13501. loadedFiles._internalCount = 0;
  13502. for (var index = 0; index < 6; index++) {
  13503. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13504. }
  13505. };
  13506. // Statics
  13507. Engine.isSupported = function () {
  13508. try {
  13509. var tempcanvas = document.createElement("canvas");
  13510. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13511. return gl != null && !!window.WebGLRenderingContext;
  13512. }
  13513. catch (e) {
  13514. return false;
  13515. }
  13516. };
  13517. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13518. Engine.ExceptionList = [
  13519. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13520. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  13521. ];
  13522. Engine.Instances = new Array();
  13523. // Const statics
  13524. Engine._ALPHA_DISABLE = 0;
  13525. Engine._ALPHA_ADD = 1;
  13526. Engine._ALPHA_COMBINE = 2;
  13527. Engine._ALPHA_SUBTRACT = 3;
  13528. Engine._ALPHA_MULTIPLY = 4;
  13529. Engine._ALPHA_MAXIMIZED = 5;
  13530. Engine._ALPHA_ONEONE = 6;
  13531. Engine._ALPHA_PREMULTIPLIED = 7;
  13532. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13533. Engine._ALPHA_INTERPOLATE = 9;
  13534. Engine._ALPHA_SCREENMODE = 10;
  13535. Engine._DELAYLOADSTATE_NONE = 0;
  13536. Engine._DELAYLOADSTATE_LOADED = 1;
  13537. Engine._DELAYLOADSTATE_LOADING = 2;
  13538. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13539. Engine._TEXTUREFORMAT_ALPHA = 0;
  13540. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13541. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13542. Engine._TEXTUREFORMAT_RGB = 4;
  13543. Engine._TEXTUREFORMAT_RGBA = 5;
  13544. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13545. Engine._TEXTURETYPE_FLOAT = 1;
  13546. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13547. // Depht or Stencil test Constants.
  13548. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13549. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  13550. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  13551. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  13552. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  13553. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  13554. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  13555. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  13556. // Stencil Actions Constants.
  13557. Engine._KEEP = 0x1E00;
  13558. Engine._REPLACE = 0x1E01;
  13559. Engine._INCR = 0x1E02;
  13560. Engine._DECR = 0x1E03;
  13561. Engine._INVERT = 0x150A;
  13562. Engine._INCR_WRAP = 0x8507;
  13563. Engine._DECR_WRAP = 0x8508;
  13564. // Texture rescaling mode
  13565. Engine._SCALEMODE_FLOOR = 1;
  13566. Engine._SCALEMODE_NEAREST = 2;
  13567. Engine._SCALEMODE_CEILING = 3;
  13568. // Updatable statics so stick with vars here
  13569. Engine.CollisionsEpsilon = 0.001;
  13570. Engine.CodeRepository = "src/";
  13571. Engine.ShadersRepository = "src/Shaders/";
  13572. return Engine;
  13573. }());
  13574. BABYLON.Engine = Engine;
  13575. })(BABYLON || (BABYLON = {}));
  13576. //# sourceMappingURL=babylon.engine.js.map
  13577. var BABYLON;
  13578. (function (BABYLON) {
  13579. /**
  13580. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13581. */
  13582. var Node = /** @class */ (function () {
  13583. /**
  13584. * @constructor
  13585. * @param {string} name - the name and id to be given to this node
  13586. * @param {BABYLON.Scene} the scene this node will be added to
  13587. */
  13588. function Node(name, scene) {
  13589. if (scene === void 0) { scene = null; }
  13590. this.state = "";
  13591. this.metadata = null;
  13592. this.doNotSerialize = false;
  13593. this.animations = new Array();
  13594. this._ranges = {};
  13595. this._isEnabled = true;
  13596. this._isReady = true;
  13597. this._currentRenderId = -1;
  13598. this._parentRenderId = -1;
  13599. /**
  13600. * An event triggered when the mesh is disposed.
  13601. * @type {BABYLON.Observable}
  13602. */
  13603. this.onDisposeObservable = new BABYLON.Observable();
  13604. // Behaviors
  13605. this._behaviors = new Array();
  13606. this.name = name;
  13607. this.id = name;
  13608. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13609. this.uniqueId = this._scene.getUniqueId();
  13610. this._initCache();
  13611. }
  13612. Object.defineProperty(Node.prototype, "parent", {
  13613. get: function () {
  13614. return this._parentNode;
  13615. },
  13616. set: function (parent) {
  13617. if (this._parentNode === parent) {
  13618. return;
  13619. }
  13620. // Remove self from list of children of parent
  13621. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13622. var index = this._parentNode._children.indexOf(this);
  13623. if (index !== -1) {
  13624. this._parentNode._children.splice(index, 1);
  13625. }
  13626. }
  13627. // Store new parent
  13628. this._parentNode = parent;
  13629. // Add as child to new parent
  13630. if (this._parentNode) {
  13631. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13632. this._parentNode._children = new Array();
  13633. }
  13634. this._parentNode._children.push(this);
  13635. }
  13636. },
  13637. enumerable: true,
  13638. configurable: true
  13639. });
  13640. Node.prototype.getClassName = function () {
  13641. return "Node";
  13642. };
  13643. Object.defineProperty(Node.prototype, "onDispose", {
  13644. set: function (callback) {
  13645. if (this._onDisposeObserver) {
  13646. this.onDisposeObservable.remove(this._onDisposeObserver);
  13647. }
  13648. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13649. },
  13650. enumerable: true,
  13651. configurable: true
  13652. });
  13653. Node.prototype.getScene = function () {
  13654. return this._scene;
  13655. };
  13656. Node.prototype.getEngine = function () {
  13657. return this._scene.getEngine();
  13658. };
  13659. Node.prototype.addBehavior = function (behavior) {
  13660. var _this = this;
  13661. var index = this._behaviors.indexOf(behavior);
  13662. if (index !== -1) {
  13663. return this;
  13664. }
  13665. behavior.init();
  13666. if (this._scene.isLoading) {
  13667. // We defer the attach when the scene will be loaded
  13668. var observer = this._scene.onDataLoadedObservable.add(function () {
  13669. behavior.attach(_this);
  13670. setTimeout(function () {
  13671. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13672. _this._scene.onDataLoadedObservable.remove(observer);
  13673. }, 0);
  13674. });
  13675. }
  13676. else {
  13677. behavior.attach(this);
  13678. }
  13679. this._behaviors.push(behavior);
  13680. return this;
  13681. };
  13682. Node.prototype.removeBehavior = function (behavior) {
  13683. var index = this._behaviors.indexOf(behavior);
  13684. if (index === -1) {
  13685. return this;
  13686. }
  13687. this._behaviors[index].detach();
  13688. this._behaviors.splice(index, 1);
  13689. return this;
  13690. };
  13691. Object.defineProperty(Node.prototype, "behaviors", {
  13692. get: function () {
  13693. return this._behaviors;
  13694. },
  13695. enumerable: true,
  13696. configurable: true
  13697. });
  13698. Node.prototype.getBehaviorByName = function (name) {
  13699. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13700. var behavior = _a[_i];
  13701. if (behavior.name === name) {
  13702. return behavior;
  13703. }
  13704. }
  13705. return null;
  13706. };
  13707. // override it in derived class
  13708. Node.prototype.getWorldMatrix = function () {
  13709. return BABYLON.Matrix.Identity();
  13710. };
  13711. // override it in derived class if you add new variables to the cache
  13712. // and call the parent class method
  13713. Node.prototype._initCache = function () {
  13714. this._cache = {};
  13715. this._cache.parent = undefined;
  13716. };
  13717. Node.prototype.updateCache = function (force) {
  13718. if (!force && this.isSynchronized())
  13719. return;
  13720. this._cache.parent = this.parent;
  13721. this._updateCache();
  13722. };
  13723. // override it in derived class if you add new variables to the cache
  13724. // and call the parent class method if !ignoreParentClass
  13725. Node.prototype._updateCache = function (ignoreParentClass) {
  13726. };
  13727. // override it in derived class if you add new variables to the cache
  13728. Node.prototype._isSynchronized = function () {
  13729. return true;
  13730. };
  13731. Node.prototype._markSyncedWithParent = function () {
  13732. if (this.parent) {
  13733. this._parentRenderId = this.parent._currentRenderId;
  13734. }
  13735. };
  13736. Node.prototype.isSynchronizedWithParent = function () {
  13737. if (!this.parent) {
  13738. return true;
  13739. }
  13740. if (this._parentRenderId !== this.parent._currentRenderId) {
  13741. return false;
  13742. }
  13743. return this.parent.isSynchronized();
  13744. };
  13745. Node.prototype.isSynchronized = function (updateCache) {
  13746. var check = this.hasNewParent();
  13747. check = check || !this.isSynchronizedWithParent();
  13748. check = check || !this._isSynchronized();
  13749. if (updateCache)
  13750. this.updateCache(true);
  13751. return !check;
  13752. };
  13753. Node.prototype.hasNewParent = function (update) {
  13754. if (this._cache.parent === this.parent)
  13755. return false;
  13756. if (update)
  13757. this._cache.parent = this.parent;
  13758. return true;
  13759. };
  13760. /**
  13761. * Is this node ready to be used/rendered
  13762. * @return {boolean} is it ready
  13763. */
  13764. Node.prototype.isReady = function () {
  13765. return this._isReady;
  13766. };
  13767. /**
  13768. * Is this node enabled.
  13769. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  13770. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13771. * @return {boolean} whether this node (and its parent) is enabled.
  13772. * @see setEnabled
  13773. */
  13774. Node.prototype.isEnabled = function (checkAncestors) {
  13775. if (checkAncestors === void 0) { checkAncestors = true; }
  13776. if (checkAncestors === false) {
  13777. return this._isEnabled;
  13778. }
  13779. if (this._isEnabled === false) {
  13780. return false;
  13781. }
  13782. if (this.parent !== undefined && this.parent !== null) {
  13783. return this.parent.isEnabled(checkAncestors);
  13784. }
  13785. return true;
  13786. };
  13787. /**
  13788. * Set the enabled state of this node.
  13789. * @param {boolean} value - the new enabled state
  13790. * @see isEnabled
  13791. */
  13792. Node.prototype.setEnabled = function (value) {
  13793. this._isEnabled = value;
  13794. };
  13795. /**
  13796. * Is this node a descendant of the given node.
  13797. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13798. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13799. * @see parent
  13800. */
  13801. Node.prototype.isDescendantOf = function (ancestor) {
  13802. if (this.parent) {
  13803. if (this.parent === ancestor) {
  13804. return true;
  13805. }
  13806. return this.parent.isDescendantOf(ancestor);
  13807. }
  13808. return false;
  13809. };
  13810. /**
  13811. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13812. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13813. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13814. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13815. */
  13816. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13817. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13818. if (!this._children) {
  13819. return;
  13820. }
  13821. for (var index = 0; index < this._children.length; index++) {
  13822. var item = this._children[index];
  13823. if (!predicate || predicate(item)) {
  13824. results.push(item);
  13825. }
  13826. if (!directDescendantsOnly) {
  13827. item._getDescendants(results, false, predicate);
  13828. }
  13829. }
  13830. };
  13831. /**
  13832. * Will return all nodes that have this node as ascendant.
  13833. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13834. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13835. * @return {BABYLON.Node[]} all children nodes of all types.
  13836. */
  13837. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13838. var results = new Array();
  13839. this._getDescendants(results, directDescendantsOnly, predicate);
  13840. return results;
  13841. };
  13842. /**
  13843. * Get all child-meshes of this node.
  13844. */
  13845. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13846. var results = [];
  13847. this._getDescendants(results, directDescendantsOnly, function (node) {
  13848. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13849. });
  13850. return results;
  13851. };
  13852. /**
  13853. * Get all child-transformNodes of this node.
  13854. */
  13855. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13856. var results = [];
  13857. this._getDescendants(results, directDescendantsOnly, function (node) {
  13858. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13859. });
  13860. return results;
  13861. };
  13862. /**
  13863. * Get all direct children of this node.
  13864. */
  13865. Node.prototype.getChildren = function (predicate) {
  13866. return this.getDescendants(true, predicate);
  13867. };
  13868. Node.prototype._setReady = function (state) {
  13869. if (state === this._isReady) {
  13870. return;
  13871. }
  13872. if (!state) {
  13873. this._isReady = false;
  13874. return;
  13875. }
  13876. this._isReady = true;
  13877. if (this.onReady) {
  13878. this.onReady(this);
  13879. }
  13880. };
  13881. Node.prototype.getAnimationByName = function (name) {
  13882. for (var i = 0; i < this.animations.length; i++) {
  13883. var animation = this.animations[i];
  13884. if (animation.name === name) {
  13885. return animation;
  13886. }
  13887. }
  13888. return null;
  13889. };
  13890. Node.prototype.createAnimationRange = function (name, from, to) {
  13891. // check name not already in use
  13892. if (!this._ranges[name]) {
  13893. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13894. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13895. if (this.animations[i]) {
  13896. this.animations[i].createRange(name, from, to);
  13897. }
  13898. }
  13899. }
  13900. };
  13901. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13902. if (deleteFrames === void 0) { deleteFrames = true; }
  13903. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13904. if (this.animations[i]) {
  13905. this.animations[i].deleteRange(name, deleteFrames);
  13906. }
  13907. }
  13908. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13909. };
  13910. Node.prototype.getAnimationRange = function (name) {
  13911. return this._ranges[name];
  13912. };
  13913. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13914. var range = this.getAnimationRange(name);
  13915. if (!range) {
  13916. return;
  13917. }
  13918. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13919. };
  13920. Node.prototype.serializeAnimationRanges = function () {
  13921. var serializationRanges = [];
  13922. for (var name in this._ranges) {
  13923. var localRange = this._ranges[name];
  13924. if (!localRange) {
  13925. continue;
  13926. }
  13927. var range = {};
  13928. range.name = name;
  13929. range.from = localRange.from;
  13930. range.to = localRange.to;
  13931. serializationRanges.push(range);
  13932. }
  13933. return serializationRanges;
  13934. };
  13935. // override it in derived class
  13936. Node.prototype.computeWorldMatrix = function (force) {
  13937. return BABYLON.Matrix.Identity();
  13938. };
  13939. Node.prototype.dispose = function () {
  13940. this.parent = null;
  13941. // Callback
  13942. this.onDisposeObservable.notifyObservers(this);
  13943. this.onDisposeObservable.clear();
  13944. // Behaviors
  13945. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13946. var behavior = _a[_i];
  13947. behavior.detach();
  13948. }
  13949. this._behaviors = [];
  13950. };
  13951. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13952. if (parsedNode.ranges) {
  13953. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13954. var data = parsedNode.ranges[index];
  13955. node.createAnimationRange(data.name, data.from, data.to);
  13956. }
  13957. }
  13958. };
  13959. __decorate([
  13960. BABYLON.serialize()
  13961. ], Node.prototype, "name", void 0);
  13962. __decorate([
  13963. BABYLON.serialize()
  13964. ], Node.prototype, "id", void 0);
  13965. __decorate([
  13966. BABYLON.serialize()
  13967. ], Node.prototype, "uniqueId", void 0);
  13968. __decorate([
  13969. BABYLON.serialize()
  13970. ], Node.prototype, "state", void 0);
  13971. __decorate([
  13972. BABYLON.serialize()
  13973. ], Node.prototype, "metadata", void 0);
  13974. return Node;
  13975. }());
  13976. BABYLON.Node = Node;
  13977. })(BABYLON || (BABYLON = {}));
  13978. //# sourceMappingURL=babylon.node.js.map
  13979. var BABYLON;
  13980. (function (BABYLON) {
  13981. var BoundingSphere = /** @class */ (function () {
  13982. function BoundingSphere(minimum, maximum) {
  13983. this.minimum = minimum;
  13984. this.maximum = maximum;
  13985. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13986. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13987. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13988. this.radius = distance * 0.5;
  13989. this.centerWorld = BABYLON.Vector3.Zero();
  13990. this._update(BABYLON.Matrix.Identity());
  13991. }
  13992. // Methods
  13993. BoundingSphere.prototype._update = function (world) {
  13994. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13995. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13996. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13997. };
  13998. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13999. for (var i = 0; i < 6; i++) {
  14000. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14001. return false;
  14002. }
  14003. return true;
  14004. };
  14005. BoundingSphere.prototype.intersectsPoint = function (point) {
  14006. var x = this.centerWorld.x - point.x;
  14007. var y = this.centerWorld.y - point.y;
  14008. var z = this.centerWorld.z - point.z;
  14009. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14010. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14011. return false;
  14012. return true;
  14013. };
  14014. // Statics
  14015. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14016. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14017. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14018. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14019. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14020. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14021. return false;
  14022. return true;
  14023. };
  14024. return BoundingSphere;
  14025. }());
  14026. BABYLON.BoundingSphere = BoundingSphere;
  14027. })(BABYLON || (BABYLON = {}));
  14028. //# sourceMappingURL=babylon.boundingSphere.js.map
  14029. var BABYLON;
  14030. (function (BABYLON) {
  14031. var BoundingBox = /** @class */ (function () {
  14032. function BoundingBox(minimum, maximum) {
  14033. this.minimum = minimum;
  14034. this.maximum = maximum;
  14035. this.vectors = new Array();
  14036. this.vectorsWorld = new Array();
  14037. // Bounding vectors
  14038. this.vectors.push(this.minimum.clone());
  14039. this.vectors.push(this.maximum.clone());
  14040. this.vectors.push(this.minimum.clone());
  14041. this.vectors[2].x = this.maximum.x;
  14042. this.vectors.push(this.minimum.clone());
  14043. this.vectors[3].y = this.maximum.y;
  14044. this.vectors.push(this.minimum.clone());
  14045. this.vectors[4].z = this.maximum.z;
  14046. this.vectors.push(this.maximum.clone());
  14047. this.vectors[5].z = this.minimum.z;
  14048. this.vectors.push(this.maximum.clone());
  14049. this.vectors[6].x = this.minimum.x;
  14050. this.vectors.push(this.maximum.clone());
  14051. this.vectors[7].y = this.minimum.y;
  14052. // OBB
  14053. this.center = this.maximum.add(this.minimum).scale(0.5);
  14054. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14055. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14056. // World
  14057. for (var index = 0; index < this.vectors.length; index++) {
  14058. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14059. }
  14060. this.minimumWorld = BABYLON.Vector3.Zero();
  14061. this.maximumWorld = BABYLON.Vector3.Zero();
  14062. this.centerWorld = BABYLON.Vector3.Zero();
  14063. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14064. this._update(BABYLON.Matrix.Identity());
  14065. }
  14066. // Methods
  14067. BoundingBox.prototype.getWorldMatrix = function () {
  14068. return this._worldMatrix;
  14069. };
  14070. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14071. this._worldMatrix.copyFrom(matrix);
  14072. return this;
  14073. };
  14074. BoundingBox.prototype._update = function (world) {
  14075. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14076. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14077. for (var index = 0; index < this.vectors.length; index++) {
  14078. var v = this.vectorsWorld[index];
  14079. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14080. if (v.x < this.minimumWorld.x)
  14081. this.minimumWorld.x = v.x;
  14082. if (v.y < this.minimumWorld.y)
  14083. this.minimumWorld.y = v.y;
  14084. if (v.z < this.minimumWorld.z)
  14085. this.minimumWorld.z = v.z;
  14086. if (v.x > this.maximumWorld.x)
  14087. this.maximumWorld.x = v.x;
  14088. if (v.y > this.maximumWorld.y)
  14089. this.maximumWorld.y = v.y;
  14090. if (v.z > this.maximumWorld.z)
  14091. this.maximumWorld.z = v.z;
  14092. }
  14093. // Extend
  14094. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14095. this.extendSizeWorld.scaleInPlace(0.5);
  14096. // OBB
  14097. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14098. this.centerWorld.scaleInPlace(0.5);
  14099. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14100. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14101. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14102. this._worldMatrix = world;
  14103. };
  14104. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14105. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14106. };
  14107. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14108. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14109. };
  14110. BoundingBox.prototype.intersectsPoint = function (point) {
  14111. var delta = -BABYLON.Epsilon;
  14112. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14113. return false;
  14114. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14115. return false;
  14116. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14117. return false;
  14118. return true;
  14119. };
  14120. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14121. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14122. };
  14123. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14124. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14125. return false;
  14126. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14127. return false;
  14128. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14129. return false;
  14130. return true;
  14131. };
  14132. // Statics
  14133. BoundingBox.Intersects = function (box0, box1) {
  14134. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14135. return false;
  14136. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14137. return false;
  14138. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14139. return false;
  14140. return true;
  14141. };
  14142. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14143. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14144. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14145. return (num <= (sphereRadius * sphereRadius));
  14146. };
  14147. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14148. for (var p = 0; p < 6; p++) {
  14149. for (var i = 0; i < 8; i++) {
  14150. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14151. return false;
  14152. }
  14153. }
  14154. }
  14155. return true;
  14156. };
  14157. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14158. for (var p = 0; p < 6; p++) {
  14159. var inCount = 8;
  14160. for (var i = 0; i < 8; i++) {
  14161. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14162. --inCount;
  14163. }
  14164. else {
  14165. break;
  14166. }
  14167. }
  14168. if (inCount === 0)
  14169. return false;
  14170. }
  14171. return true;
  14172. };
  14173. return BoundingBox;
  14174. }());
  14175. BABYLON.BoundingBox = BoundingBox;
  14176. })(BABYLON || (BABYLON = {}));
  14177. //# sourceMappingURL=babylon.boundingBox.js.map
  14178. var BABYLON;
  14179. (function (BABYLON) {
  14180. var computeBoxExtents = function (axis, box) {
  14181. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14182. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14183. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14184. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14185. var r = r0 + r1 + r2;
  14186. return {
  14187. min: p - r,
  14188. max: p + r
  14189. };
  14190. };
  14191. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14192. var axisOverlap = function (axis, box0, box1) {
  14193. var result0 = computeBoxExtents(axis, box0);
  14194. var result1 = computeBoxExtents(axis, box1);
  14195. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14196. };
  14197. var BoundingInfo = /** @class */ (function () {
  14198. function BoundingInfo(minimum, maximum) {
  14199. this.minimum = minimum;
  14200. this.maximum = maximum;
  14201. this._isLocked = false;
  14202. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14203. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14204. }
  14205. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14206. get: function () {
  14207. return this._isLocked;
  14208. },
  14209. set: function (value) {
  14210. this._isLocked = value;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. // Methods
  14216. BoundingInfo.prototype.update = function (world) {
  14217. if (this._isLocked) {
  14218. return;
  14219. }
  14220. this.boundingBox._update(world);
  14221. this.boundingSphere._update(world);
  14222. };
  14223. /**
  14224. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14225. * @param center New center of the bounding info
  14226. * @param extend New extend of the bounding info
  14227. */
  14228. BoundingInfo.prototype.centerOn = function (center, extend) {
  14229. this.minimum = center.subtract(extend);
  14230. this.maximum = center.add(extend);
  14231. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14232. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14233. return this;
  14234. };
  14235. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14236. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14237. return false;
  14238. return this.boundingBox.isInFrustum(frustumPlanes);
  14239. };
  14240. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14241. /**
  14242. * Gets the world distance between the min and max points of the bounding box
  14243. */
  14244. get: function () {
  14245. var boundingBox = this.boundingBox;
  14246. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14247. return size.length();
  14248. },
  14249. enumerable: true,
  14250. configurable: true
  14251. });
  14252. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14253. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14254. };
  14255. BoundingInfo.prototype._checkCollision = function (collider) {
  14256. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14257. };
  14258. BoundingInfo.prototype.intersectsPoint = function (point) {
  14259. if (!this.boundingSphere.centerWorld) {
  14260. return false;
  14261. }
  14262. if (!this.boundingSphere.intersectsPoint(point)) {
  14263. return false;
  14264. }
  14265. if (!this.boundingBox.intersectsPoint(point)) {
  14266. return false;
  14267. }
  14268. return true;
  14269. };
  14270. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14271. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14272. return false;
  14273. }
  14274. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14275. return false;
  14276. }
  14277. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14278. return false;
  14279. }
  14280. if (!precise) {
  14281. return true;
  14282. }
  14283. var box0 = this.boundingBox;
  14284. var box1 = boundingInfo.boundingBox;
  14285. if (!axisOverlap(box0.directions[0], box0, box1))
  14286. return false;
  14287. if (!axisOverlap(box0.directions[1], box0, box1))
  14288. return false;
  14289. if (!axisOverlap(box0.directions[2], box0, box1))
  14290. return false;
  14291. if (!axisOverlap(box1.directions[0], box0, box1))
  14292. return false;
  14293. if (!axisOverlap(box1.directions[1], box0, box1))
  14294. return false;
  14295. if (!axisOverlap(box1.directions[2], box0, box1))
  14296. return false;
  14297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14298. return false;
  14299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14300. return false;
  14301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14302. return false;
  14303. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14304. return false;
  14305. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14306. return false;
  14307. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14308. return false;
  14309. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14310. return false;
  14311. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14312. return false;
  14313. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14314. return false;
  14315. return true;
  14316. };
  14317. return BoundingInfo;
  14318. }());
  14319. BABYLON.BoundingInfo = BoundingInfo;
  14320. })(BABYLON || (BABYLON = {}));
  14321. //# sourceMappingURL=babylon.boundingInfo.js.map
  14322. var BABYLON;
  14323. (function (BABYLON) {
  14324. var TransformNode = /** @class */ (function (_super) {
  14325. __extends(TransformNode, _super);
  14326. function TransformNode(name, scene, isPure) {
  14327. if (scene === void 0) { scene = null; }
  14328. if (isPure === void 0) { isPure = true; }
  14329. var _this = _super.call(this, name, scene) || this;
  14330. // Properties
  14331. _this._rotation = BABYLON.Vector3.Zero();
  14332. _this._scaling = BABYLON.Vector3.One();
  14333. _this._isDirty = false;
  14334. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14335. _this.scalingDeterminant = 1;
  14336. _this.infiniteDistance = false;
  14337. _this.position = BABYLON.Vector3.Zero();
  14338. _this._localWorld = BABYLON.Matrix.Zero();
  14339. _this._worldMatrix = BABYLON.Matrix.Zero();
  14340. _this._worldMatrixDeterminant = 0;
  14341. _this._absolutePosition = BABYLON.Vector3.Zero();
  14342. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14343. _this._postMultiplyPivotMatrix = false;
  14344. _this._isWorldMatrixFrozen = false;
  14345. /**
  14346. * An event triggered after the world matrix is updated
  14347. * @type {BABYLON.Observable}
  14348. */
  14349. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14350. _this._nonUniformScaling = false;
  14351. if (isPure) {
  14352. _this.getScene().addTransformNode(_this);
  14353. }
  14354. return _this;
  14355. }
  14356. Object.defineProperty(TransformNode.prototype, "rotation", {
  14357. /**
  14358. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14359. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14360. * Default : (0.0, 0.0, 0.0)
  14361. */
  14362. get: function () {
  14363. return this._rotation;
  14364. },
  14365. set: function (newRotation) {
  14366. this._rotation = newRotation;
  14367. },
  14368. enumerable: true,
  14369. configurable: true
  14370. });
  14371. Object.defineProperty(TransformNode.prototype, "scaling", {
  14372. /**
  14373. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14374. * Default : (1.0, 1.0, 1.0)
  14375. */
  14376. get: function () {
  14377. return this._scaling;
  14378. },
  14379. /**
  14380. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14381. * Default : (1.0, 1.0, 1.0)
  14382. */
  14383. set: function (newScaling) {
  14384. this._scaling = newScaling;
  14385. },
  14386. enumerable: true,
  14387. configurable: true
  14388. });
  14389. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14390. /**
  14391. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14392. * It's null by default.
  14393. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  14394. */
  14395. get: function () {
  14396. return this._rotationQuaternion;
  14397. },
  14398. set: function (quaternion) {
  14399. this._rotationQuaternion = quaternion;
  14400. //reset the rotation vector.
  14401. if (quaternion && this.rotation.length()) {
  14402. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14403. }
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. /**
  14409. * Returns the latest update of the World matrix
  14410. * Returns a Matrix.
  14411. */
  14412. TransformNode.prototype.getWorldMatrix = function () {
  14413. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14414. this.computeWorldMatrix();
  14415. }
  14416. return this._worldMatrix;
  14417. };
  14418. /**
  14419. * Returns the latest update of the World matrix determinant.
  14420. */
  14421. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14422. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14423. this.computeWorldMatrix();
  14424. }
  14425. return this._worldMatrixDeterminant;
  14426. };
  14427. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14428. /**
  14429. * Returns directly the latest state of the mesh World matrix.
  14430. * A Matrix is returned.
  14431. */
  14432. get: function () {
  14433. return this._worldMatrix;
  14434. },
  14435. enumerable: true,
  14436. configurable: true
  14437. });
  14438. /**
  14439. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14440. * Returns the AbstractMesh.
  14441. */
  14442. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14443. this._poseMatrix.copyFrom(matrix);
  14444. return this;
  14445. };
  14446. /**
  14447. * Returns the mesh Pose matrix.
  14448. * Returned object : Matrix
  14449. */
  14450. TransformNode.prototype.getPoseMatrix = function () {
  14451. return this._poseMatrix;
  14452. };
  14453. TransformNode.prototype._isSynchronized = function () {
  14454. if (this._isDirty) {
  14455. return false;
  14456. }
  14457. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14458. return false;
  14459. if (this._cache.pivotMatrixUpdated) {
  14460. return false;
  14461. }
  14462. if (this.infiniteDistance) {
  14463. return false;
  14464. }
  14465. if (!this._cache.position.equals(this.position))
  14466. return false;
  14467. if (this.rotationQuaternion) {
  14468. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14469. return false;
  14470. }
  14471. if (!this._cache.rotation.equals(this.rotation))
  14472. return false;
  14473. if (!this._cache.scaling.equals(this.scaling))
  14474. return false;
  14475. return true;
  14476. };
  14477. TransformNode.prototype._initCache = function () {
  14478. _super.prototype._initCache.call(this);
  14479. this._cache.localMatrixUpdated = false;
  14480. this._cache.position = BABYLON.Vector3.Zero();
  14481. this._cache.scaling = BABYLON.Vector3.Zero();
  14482. this._cache.rotation = BABYLON.Vector3.Zero();
  14483. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14484. this._cache.billboardMode = -1;
  14485. };
  14486. TransformNode.prototype.markAsDirty = function (property) {
  14487. if (property === "rotation") {
  14488. this.rotationQuaternion = null;
  14489. }
  14490. this._currentRenderId = Number.MAX_VALUE;
  14491. this._isDirty = true;
  14492. return this;
  14493. };
  14494. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14495. /**
  14496. * Returns the current mesh absolute position.
  14497. * Retuns a Vector3.
  14498. */
  14499. get: function () {
  14500. return this._absolutePosition;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. /**
  14506. * Sets a new pivot matrix to the mesh.
  14507. * Returns the AbstractMesh.
  14508. */
  14509. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14510. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14511. this._pivotMatrix = matrix.clone();
  14512. this._cache.pivotMatrixUpdated = true;
  14513. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14514. if (this._postMultiplyPivotMatrix) {
  14515. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14516. }
  14517. return this;
  14518. };
  14519. /**
  14520. * Returns the mesh pivot matrix.
  14521. * Default : Identity.
  14522. * A Matrix is returned.
  14523. */
  14524. TransformNode.prototype.getPivotMatrix = function () {
  14525. return this._pivotMatrix;
  14526. };
  14527. /**
  14528. * Prevents the World matrix to be computed any longer.
  14529. * Returns the AbstractMesh.
  14530. */
  14531. TransformNode.prototype.freezeWorldMatrix = function () {
  14532. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14533. this.computeWorldMatrix(true);
  14534. this._isWorldMatrixFrozen = true;
  14535. return this;
  14536. };
  14537. /**
  14538. * Allows back the World matrix computation.
  14539. * Returns the AbstractMesh.
  14540. */
  14541. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14542. this._isWorldMatrixFrozen = false;
  14543. this.computeWorldMatrix(true);
  14544. return this;
  14545. };
  14546. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14547. /**
  14548. * True if the World matrix has been frozen.
  14549. * Returns a boolean.
  14550. */
  14551. get: function () {
  14552. return this._isWorldMatrixFrozen;
  14553. },
  14554. enumerable: true,
  14555. configurable: true
  14556. });
  14557. /**
  14558. * Retuns the mesh absolute position in the World.
  14559. * Returns a Vector3.
  14560. */
  14561. TransformNode.prototype.getAbsolutePosition = function () {
  14562. this.computeWorldMatrix();
  14563. return this._absolutePosition;
  14564. };
  14565. /**
  14566. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14567. * Returns the AbstractMesh.
  14568. */
  14569. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14570. if (!absolutePosition) {
  14571. return this;
  14572. }
  14573. var absolutePositionX;
  14574. var absolutePositionY;
  14575. var absolutePositionZ;
  14576. if (absolutePosition.x === undefined) {
  14577. if (arguments.length < 3) {
  14578. return this;
  14579. }
  14580. absolutePositionX = arguments[0];
  14581. absolutePositionY = arguments[1];
  14582. absolutePositionZ = arguments[2];
  14583. }
  14584. else {
  14585. absolutePositionX = absolutePosition.x;
  14586. absolutePositionY = absolutePosition.y;
  14587. absolutePositionZ = absolutePosition.z;
  14588. }
  14589. if (this.parent) {
  14590. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14591. invertParentWorldMatrix.invert();
  14592. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14593. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14594. }
  14595. else {
  14596. this.position.x = absolutePositionX;
  14597. this.position.y = absolutePositionY;
  14598. this.position.z = absolutePositionZ;
  14599. }
  14600. return this;
  14601. };
  14602. /**
  14603. * Sets the mesh position in its local space.
  14604. * Returns the AbstractMesh.
  14605. */
  14606. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14607. this.computeWorldMatrix();
  14608. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14609. return this;
  14610. };
  14611. /**
  14612. * Returns the mesh position in the local space from the current World matrix values.
  14613. * Returns a new Vector3.
  14614. */
  14615. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14616. this.computeWorldMatrix();
  14617. var invLocalWorldMatrix = this._localWorld.clone();
  14618. invLocalWorldMatrix.invert();
  14619. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14620. };
  14621. /**
  14622. * Translates the mesh along the passed Vector3 in its local space.
  14623. * Returns the AbstractMesh.
  14624. */
  14625. TransformNode.prototype.locallyTranslate = function (vector3) {
  14626. this.computeWorldMatrix(true);
  14627. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14628. return this;
  14629. };
  14630. /**
  14631. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14632. * @param targetPoint the position (must be in same space as current mesh) to look at
  14633. * @param yawCor optional yaw (y-axis) correction in radians
  14634. * @param pitchCor optional pitch (x-axis) correction in radians
  14635. * @param rollCor optional roll (z-axis) correction in radians
  14636. * @param space the choosen space of the target
  14637. * @returns the TransformNode.
  14638. */
  14639. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14640. if (yawCor === void 0) { yawCor = 0; }
  14641. if (pitchCor === void 0) { pitchCor = 0; }
  14642. if (rollCor === void 0) { rollCor = 0; }
  14643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14644. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14645. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14646. targetPoint.subtractToRef(pos, dv);
  14647. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14648. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14649. var pitch = Math.atan2(dv.y, len);
  14650. if (this.rotationQuaternion) {
  14651. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14652. }
  14653. else {
  14654. this.rotation.x = pitch + pitchCor;
  14655. this.rotation.y = yaw + yawCor;
  14656. this.rotation.z = rollCor;
  14657. }
  14658. return this;
  14659. };
  14660. /**
  14661. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14662. * This Vector3 is expressed in the World space.
  14663. */
  14664. TransformNode.prototype.getDirection = function (localAxis) {
  14665. var result = BABYLON.Vector3.Zero();
  14666. this.getDirectionToRef(localAxis, result);
  14667. return result;
  14668. };
  14669. /**
  14670. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14671. * localAxis is expressed in the mesh local space.
  14672. * result is computed in the Wordl space from the mesh World matrix.
  14673. * Returns the AbstractMesh.
  14674. */
  14675. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14676. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14677. return this;
  14678. };
  14679. TransformNode.prototype.setPivotPoint = function (point, space) {
  14680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14681. if (this.getScene().getRenderId() == 0) {
  14682. this.computeWorldMatrix(true);
  14683. }
  14684. var wm = this.getWorldMatrix();
  14685. if (space == BABYLON.Space.WORLD) {
  14686. var tmat = BABYLON.Tmp.Matrix[0];
  14687. wm.invertToRef(tmat);
  14688. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14689. }
  14690. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14691. this._pivotMatrix.m[12] = -point.x;
  14692. this._pivotMatrix.m[13] = -point.y;
  14693. this._pivotMatrix.m[14] = -point.z;
  14694. this._cache.pivotMatrixUpdated = true;
  14695. return this;
  14696. };
  14697. /**
  14698. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14699. */
  14700. TransformNode.prototype.getPivotPoint = function () {
  14701. var point = BABYLON.Vector3.Zero();
  14702. this.getPivotPointToRef(point);
  14703. return point;
  14704. };
  14705. /**
  14706. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14707. * Returns the AbstractMesh.
  14708. */
  14709. TransformNode.prototype.getPivotPointToRef = function (result) {
  14710. result.x = -this._pivotMatrix.m[12];
  14711. result.y = -this._pivotMatrix.m[13];
  14712. result.z = -this._pivotMatrix.m[14];
  14713. return this;
  14714. };
  14715. /**
  14716. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14717. */
  14718. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14719. var point = BABYLON.Vector3.Zero();
  14720. this.getAbsolutePivotPointToRef(point);
  14721. return point;
  14722. };
  14723. /**
  14724. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14725. * Returns the AbstractMesh.
  14726. */
  14727. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14728. result.x = this._pivotMatrix.m[12];
  14729. result.y = this._pivotMatrix.m[13];
  14730. result.z = this._pivotMatrix.m[14];
  14731. this.getPivotPointToRef(result);
  14732. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14733. return this;
  14734. };
  14735. /**
  14736. * Defines the passed node as the parent of the current node.
  14737. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14738. * Returns the TransformNode.
  14739. */
  14740. TransformNode.prototype.setParent = function (node) {
  14741. if (node === null) {
  14742. var rotation = BABYLON.Tmp.Quaternion[0];
  14743. var position = BABYLON.Tmp.Vector3[0];
  14744. var scale = BABYLON.Tmp.Vector3[1];
  14745. if (this.parent && this.parent.computeWorldMatrix) {
  14746. this.parent.computeWorldMatrix(true);
  14747. }
  14748. this.computeWorldMatrix(true);
  14749. this.getWorldMatrix().decompose(scale, rotation, position);
  14750. if (this.rotationQuaternion) {
  14751. this.rotationQuaternion.copyFrom(rotation);
  14752. }
  14753. else {
  14754. rotation.toEulerAnglesToRef(this.rotation);
  14755. }
  14756. this.scaling.x = scale.x;
  14757. this.scaling.y = scale.y;
  14758. this.scaling.z = scale.z;
  14759. this.position.x = position.x;
  14760. this.position.y = position.y;
  14761. this.position.z = position.z;
  14762. }
  14763. else {
  14764. var rotation = BABYLON.Tmp.Quaternion[0];
  14765. var position = BABYLON.Tmp.Vector3[0];
  14766. var scale = BABYLON.Tmp.Vector3[1];
  14767. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14768. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14769. this.computeWorldMatrix(true);
  14770. node.computeWorldMatrix(true);
  14771. node.getWorldMatrix().invertToRef(invParentMatrix);
  14772. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14773. diffMatrix.decompose(scale, rotation, position);
  14774. if (this.rotationQuaternion) {
  14775. this.rotationQuaternion.copyFrom(rotation);
  14776. }
  14777. else {
  14778. rotation.toEulerAnglesToRef(this.rotation);
  14779. }
  14780. this.position.x = position.x;
  14781. this.position.y = position.y;
  14782. this.position.z = position.z;
  14783. this.scaling.x = scale.x;
  14784. this.scaling.y = scale.y;
  14785. this.scaling.z = scale.z;
  14786. }
  14787. this.parent = node;
  14788. return this;
  14789. };
  14790. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14791. get: function () {
  14792. return this._nonUniformScaling;
  14793. },
  14794. enumerable: true,
  14795. configurable: true
  14796. });
  14797. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14798. if (this._nonUniformScaling === value) {
  14799. return false;
  14800. }
  14801. this._nonUniformScaling = true;
  14802. return true;
  14803. };
  14804. /**
  14805. * Attach the current TransformNode to another TransformNode associated with a bone
  14806. * @param bone Bone affecting the TransformNode
  14807. * @param affectedTransformNode TransformNode associated with the bone
  14808. */
  14809. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14810. this._transformToBoneReferal = affectedTransformNode;
  14811. this.parent = bone;
  14812. if (bone.getWorldMatrix().determinant() < 0) {
  14813. this.scalingDeterminant *= -1;
  14814. }
  14815. return this;
  14816. };
  14817. TransformNode.prototype.detachFromBone = function () {
  14818. if (!this.parent) {
  14819. return this;
  14820. }
  14821. if (this.parent.getWorldMatrix().determinant() < 0) {
  14822. this.scalingDeterminant *= -1;
  14823. }
  14824. this._transformToBoneReferal = null;
  14825. this.parent = null;
  14826. return this;
  14827. };
  14828. /**
  14829. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14830. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14831. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14832. * The passed axis is also normalized.
  14833. * Returns the AbstractMesh.
  14834. */
  14835. TransformNode.prototype.rotate = function (axis, amount, space) {
  14836. axis.normalize();
  14837. if (!this.rotationQuaternion) {
  14838. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14839. this.rotation = BABYLON.Vector3.Zero();
  14840. }
  14841. var rotationQuaternion;
  14842. if (!space || space === BABYLON.Space.LOCAL) {
  14843. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14844. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14845. }
  14846. else {
  14847. if (this.parent) {
  14848. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14849. invertParentWorldMatrix.invert();
  14850. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14851. }
  14852. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14853. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14854. }
  14855. return this;
  14856. };
  14857. /**
  14858. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14859. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14860. * The passed axis is also normalized.
  14861. * Returns the AbstractMesh.
  14862. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14863. */
  14864. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14865. axis.normalize();
  14866. if (!this.rotationQuaternion) {
  14867. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14868. this.rotation.copyFromFloats(0, 0, 0);
  14869. }
  14870. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14871. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14872. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14873. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14874. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14875. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14876. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14877. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14878. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14879. return this;
  14880. };
  14881. /**
  14882. * Translates the mesh along the axis vector for the passed distance in the given space.
  14883. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14884. * Returns the AbstractMesh.
  14885. */
  14886. TransformNode.prototype.translate = function (axis, distance, space) {
  14887. var displacementVector = axis.scale(distance);
  14888. if (!space || space === BABYLON.Space.LOCAL) {
  14889. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14890. this.setPositionWithLocalVector(tempV3);
  14891. }
  14892. else {
  14893. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14894. }
  14895. return this;
  14896. };
  14897. /**
  14898. * Adds a rotation step to the mesh current rotation.
  14899. * x, y, z are Euler angles expressed in radians.
  14900. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14901. * This means this rotation is made in the mesh local space only.
  14902. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14903. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14904. * ```javascript
  14905. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14906. * ```
  14907. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14908. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  14909. * Returns the AbstractMesh.
  14910. */
  14911. TransformNode.prototype.addRotation = function (x, y, z) {
  14912. var rotationQuaternion;
  14913. if (this.rotationQuaternion) {
  14914. rotationQuaternion = this.rotationQuaternion;
  14915. }
  14916. else {
  14917. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14918. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14919. }
  14920. var accumulation = BABYLON.Tmp.Quaternion[0];
  14921. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14922. rotationQuaternion.multiplyInPlace(accumulation);
  14923. if (!this.rotationQuaternion) {
  14924. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14925. }
  14926. return this;
  14927. };
  14928. /**
  14929. * Computes the mesh World matrix and returns it.
  14930. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14931. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14932. * If the parameter `force`is set to `true`, the actual computation is done.
  14933. * Returns the mesh World Matrix.
  14934. */
  14935. TransformNode.prototype.computeWorldMatrix = function (force) {
  14936. if (this._isWorldMatrixFrozen) {
  14937. return this._worldMatrix;
  14938. }
  14939. if (!force && this.isSynchronized(true)) {
  14940. return this._worldMatrix;
  14941. }
  14942. this._cache.position.copyFrom(this.position);
  14943. this._cache.scaling.copyFrom(this.scaling);
  14944. this._cache.pivotMatrixUpdated = false;
  14945. this._cache.billboardMode = this.billboardMode;
  14946. this._currentRenderId = this.getScene().getRenderId();
  14947. this._isDirty = false;
  14948. // Scaling
  14949. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14950. // Rotation
  14951. //rotate, if quaternion is set and rotation was used
  14952. if (this.rotationQuaternion) {
  14953. var len = this.rotation.length();
  14954. if (len) {
  14955. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14956. this.rotation.copyFromFloats(0, 0, 0);
  14957. }
  14958. }
  14959. if (this.rotationQuaternion) {
  14960. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14961. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14962. }
  14963. else {
  14964. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14965. this._cache.rotation.copyFrom(this.rotation);
  14966. }
  14967. // Translation
  14968. var camera = this.getScene().activeCamera;
  14969. if (this.infiniteDistance && !this.parent && camera) {
  14970. var cameraWorldMatrix = camera.getWorldMatrix();
  14971. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14972. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14973. }
  14974. else {
  14975. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14976. }
  14977. // Composing transformations
  14978. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14979. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14980. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14981. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14982. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14983. // Need to decompose each rotation here
  14984. var currentPosition = BABYLON.Tmp.Vector3[3];
  14985. if (this.parent && this.parent.getWorldMatrix) {
  14986. if (this._transformToBoneReferal) {
  14987. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14988. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14989. }
  14990. else {
  14991. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14992. }
  14993. }
  14994. else {
  14995. currentPosition.copyFrom(this.position);
  14996. }
  14997. currentPosition.subtractInPlace(camera.globalPosition);
  14998. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14999. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15000. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15001. }
  15002. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15003. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15004. }
  15005. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15006. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15007. }
  15008. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15009. }
  15010. else {
  15011. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15012. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15013. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15014. }
  15015. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15016. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15017. }
  15018. // Local world
  15019. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15020. // Parent
  15021. if (this.parent && this.parent.getWorldMatrix) {
  15022. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15023. if (this._transformToBoneReferal) {
  15024. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15025. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15026. }
  15027. else {
  15028. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15029. }
  15030. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15031. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15032. this._worldMatrix.copyFrom(this._localWorld);
  15033. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15034. }
  15035. else {
  15036. if (this._transformToBoneReferal) {
  15037. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15038. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15039. }
  15040. else {
  15041. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15042. }
  15043. }
  15044. this._markSyncedWithParent();
  15045. }
  15046. else {
  15047. this._worldMatrix.copyFrom(this._localWorld);
  15048. }
  15049. // Post multiply inverse of pivotMatrix
  15050. if (this._postMultiplyPivotMatrix) {
  15051. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15052. }
  15053. // Normal matrix
  15054. if (this.scaling.isNonUniform) {
  15055. this._updateNonUniformScalingState(true);
  15056. }
  15057. else if (this.parent && this.parent._nonUniformScaling) {
  15058. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15059. }
  15060. else {
  15061. this._updateNonUniformScalingState(false);
  15062. }
  15063. this._afterComputeWorldMatrix();
  15064. // Absolute position
  15065. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15066. // Callbacks
  15067. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15068. if (!this._poseMatrix) {
  15069. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15070. }
  15071. // Cache the determinant
  15072. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15073. return this._worldMatrix;
  15074. };
  15075. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15076. };
  15077. /**
  15078. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15079. * @param func: callback function to add
  15080. *
  15081. * Returns the TransformNode.
  15082. */
  15083. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15084. this.onAfterWorldMatrixUpdateObservable.add(func);
  15085. return this;
  15086. };
  15087. /**
  15088. * Removes a registered callback function.
  15089. * Returns the TransformNode.
  15090. */
  15091. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15092. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15093. return this;
  15094. };
  15095. /**
  15096. * Clone the current transform node
  15097. * Returns the new transform node
  15098. * @param name Name of the new clone
  15099. * @param newParent New parent for the clone
  15100. * @param doNotCloneChildren Do not clone children hierarchy
  15101. */
  15102. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15103. var _this = this;
  15104. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15105. result.name = name;
  15106. result.id = name;
  15107. if (newParent) {
  15108. result.parent = newParent;
  15109. }
  15110. if (!doNotCloneChildren) {
  15111. // Children
  15112. var directDescendants = this.getDescendants(true);
  15113. for (var index = 0; index < directDescendants.length; index++) {
  15114. var child = directDescendants[index];
  15115. if (child.clone) {
  15116. child.clone(name + "." + child.name, result);
  15117. }
  15118. }
  15119. }
  15120. return result;
  15121. };
  15122. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15123. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15124. serializationObject.type = this.getClassName();
  15125. // Parent
  15126. if (this.parent) {
  15127. serializationObject.parentId = this.parent.id;
  15128. }
  15129. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15130. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15131. }
  15132. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15133. serializationObject.isEnabled = this.isEnabled();
  15134. // Parent
  15135. if (this.parent) {
  15136. serializationObject.parentId = this.parent.id;
  15137. }
  15138. return serializationObject;
  15139. };
  15140. // Statics
  15141. /**
  15142. * Returns a new TransformNode object parsed from the source provided.
  15143. * The parameter `parsedMesh` is the source.
  15144. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15145. */
  15146. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15147. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15148. if (BABYLON.Tags) {
  15149. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15150. }
  15151. if (parsedTransformNode.localMatrix) {
  15152. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15153. }
  15154. else if (parsedTransformNode.pivotMatrix) {
  15155. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15156. }
  15157. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15158. // Parent
  15159. if (parsedTransformNode.parentId) {
  15160. transformNode._waitingParentId = parsedTransformNode.parentId;
  15161. }
  15162. return transformNode;
  15163. };
  15164. /**
  15165. * Disposes the TransformNode.
  15166. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15167. * Returns nothing.
  15168. */
  15169. TransformNode.prototype.dispose = function (doNotRecurse) {
  15170. // Animations
  15171. this.getScene().stopAnimation(this);
  15172. // Remove from scene
  15173. this.getScene().removeTransformNode(this);
  15174. if (!doNotRecurse) {
  15175. // Children
  15176. var objects = this.getDescendants(true);
  15177. for (var index = 0; index < objects.length; index++) {
  15178. objects[index].dispose();
  15179. }
  15180. }
  15181. else {
  15182. var childMeshes = this.getChildMeshes(true);
  15183. for (index = 0; index < childMeshes.length; index++) {
  15184. var child = childMeshes[index];
  15185. child.parent = null;
  15186. child.computeWorldMatrix(true);
  15187. }
  15188. }
  15189. this.onAfterWorldMatrixUpdateObservable.clear();
  15190. _super.prototype.dispose.call(this);
  15191. };
  15192. // Statics
  15193. TransformNode.BILLBOARDMODE_NONE = 0;
  15194. TransformNode.BILLBOARDMODE_X = 1;
  15195. TransformNode.BILLBOARDMODE_Y = 2;
  15196. TransformNode.BILLBOARDMODE_Z = 4;
  15197. TransformNode.BILLBOARDMODE_ALL = 7;
  15198. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15199. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15200. __decorate([
  15201. BABYLON.serializeAsVector3()
  15202. ], TransformNode.prototype, "_rotation", void 0);
  15203. __decorate([
  15204. BABYLON.serializeAsQuaternion()
  15205. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15206. __decorate([
  15207. BABYLON.serializeAsVector3()
  15208. ], TransformNode.prototype, "_scaling", void 0);
  15209. __decorate([
  15210. BABYLON.serialize()
  15211. ], TransformNode.prototype, "billboardMode", void 0);
  15212. __decorate([
  15213. BABYLON.serialize()
  15214. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15215. __decorate([
  15216. BABYLON.serialize()
  15217. ], TransformNode.prototype, "infiniteDistance", void 0);
  15218. __decorate([
  15219. BABYLON.serializeAsVector3()
  15220. ], TransformNode.prototype, "position", void 0);
  15221. return TransformNode;
  15222. }(BABYLON.Node));
  15223. BABYLON.TransformNode = TransformNode;
  15224. })(BABYLON || (BABYLON = {}));
  15225. //# sourceMappingURL=babylon.transformNode.js.map
  15226. var BABYLON;
  15227. (function (BABYLON) {
  15228. var AbstractMesh = /** @class */ (function (_super) {
  15229. __extends(AbstractMesh, _super);
  15230. // Constructor
  15231. function AbstractMesh(name, scene) {
  15232. if (scene === void 0) { scene = null; }
  15233. var _this = _super.call(this, name, scene, false) || this;
  15234. _this._facetNb = 0; // facet number
  15235. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15236. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15237. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15238. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15239. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15240. _this._subDiv = {
  15241. max: 1,
  15242. X: 1,
  15243. Y: 1,
  15244. Z: 1
  15245. };
  15246. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15247. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15248. // Events
  15249. /**
  15250. * An event triggered when this mesh collides with another one
  15251. * @type {BABYLON.Observable}
  15252. */
  15253. _this.onCollideObservable = new BABYLON.Observable();
  15254. /**
  15255. * An event triggered when the collision's position changes
  15256. * @type {BABYLON.Observable}
  15257. */
  15258. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15259. /**
  15260. * An event triggered when material is changed
  15261. * @type {BABYLON.Observable}
  15262. */
  15263. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15264. // Properties
  15265. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15266. /**
  15267. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15268. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15269. * or
  15270. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  15271. * for more info check WebGl documentations
  15272. */
  15273. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15274. /**
  15275. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  15276. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15277. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15278. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  15279. */
  15280. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15281. /**
  15282. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  15283. * The default value is -1 which means don't break the query and wait till the result.
  15284. */
  15285. _this.occlusionRetryCount = -1;
  15286. _this._occlusionInternalRetryCounter = 0;
  15287. _this._isOccluded = false;
  15288. _this._isOcclusionQueryInProgress = false;
  15289. _this.visibility = 1.0;
  15290. _this.alphaIndex = Number.MAX_VALUE;
  15291. _this.isVisible = true;
  15292. _this.isPickable = true;
  15293. _this.showBoundingBox = false;
  15294. _this.showSubMeshesBoundingBox = false;
  15295. _this.isBlocker = false;
  15296. _this.enablePointerMoveEvents = false;
  15297. _this.renderingGroupId = 0;
  15298. _this._receiveShadows = false;
  15299. _this.renderOutline = false;
  15300. _this.outlineColor = BABYLON.Color3.Red();
  15301. _this.outlineWidth = 0.02;
  15302. _this.renderOverlay = false;
  15303. _this.overlayColor = BABYLON.Color3.Red();
  15304. _this.overlayAlpha = 0.5;
  15305. _this._hasVertexAlpha = false;
  15306. _this._useVertexColors = true;
  15307. _this._computeBonesUsingShaders = true;
  15308. _this._numBoneInfluencers = 4;
  15309. _this._applyFog = true;
  15310. _this.useOctreeForRenderingSelection = true;
  15311. _this.useOctreeForPicking = true;
  15312. _this.useOctreeForCollisions = true;
  15313. _this._layerMask = 0x0FFFFFFF;
  15314. /**
  15315. * True if the mesh must be rendered in any case.
  15316. */
  15317. _this.alwaysSelectAsActiveMesh = false;
  15318. /**
  15319. * This scene's action manager
  15320. * @type {BABYLON.ActionManager}
  15321. */
  15322. _this.actionManager = null;
  15323. // Physics
  15324. _this.physicsImpostor = null;
  15325. // Collisions
  15326. _this._checkCollisions = false;
  15327. _this._collisionMask = -1;
  15328. _this._collisionGroup = -1;
  15329. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15330. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15331. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15332. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15333. // Edges
  15334. _this.edgesWidth = 1;
  15335. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15336. // Cache
  15337. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15338. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15339. _this._isDisposed = false;
  15340. _this._renderId = 0;
  15341. _this._intersectionsInProgress = new Array();
  15342. _this._unIndexed = false;
  15343. _this._lightSources = new Array();
  15344. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15345. if (collidedMesh === void 0) { collidedMesh = null; }
  15346. //TODO move this to the collision coordinator!
  15347. if (_this.getScene().workerCollisions)
  15348. newPosition.multiplyInPlace(_this._collider._radius);
  15349. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15350. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15351. _this.position.addInPlace(_this._diffPositionForCollisions);
  15352. }
  15353. if (collidedMesh) {
  15354. _this.onCollideObservable.notifyObservers(collidedMesh);
  15355. }
  15356. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15357. };
  15358. _this.getScene().addMesh(_this);
  15359. _this._resyncLightSources();
  15360. return _this;
  15361. }
  15362. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15363. get: function () {
  15364. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15370. get: function () {
  15371. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15372. },
  15373. enumerable: true,
  15374. configurable: true
  15375. });
  15376. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15377. get: function () {
  15378. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15379. },
  15380. enumerable: true,
  15381. configurable: true
  15382. });
  15383. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15384. get: function () {
  15385. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15386. },
  15387. enumerable: true,
  15388. configurable: true
  15389. });
  15390. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15391. get: function () {
  15392. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15398. /**
  15399. * Read-only : the number of facets in the mesh
  15400. */
  15401. get: function () {
  15402. return this._facetNb;
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15408. /**
  15409. * The number (integer) of subdivisions per axis in the partioning space
  15410. */
  15411. get: function () {
  15412. return this._partitioningSubdivisions;
  15413. },
  15414. set: function (nb) {
  15415. this._partitioningSubdivisions = nb;
  15416. },
  15417. enumerable: true,
  15418. configurable: true
  15419. });
  15420. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15421. /**
  15422. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15423. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15424. */
  15425. get: function () {
  15426. return this._partitioningBBoxRatio;
  15427. },
  15428. set: function (ratio) {
  15429. this._partitioningBBoxRatio = ratio;
  15430. },
  15431. enumerable: true,
  15432. configurable: true
  15433. });
  15434. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15435. /**
  15436. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15437. * Works only for updatable meshes.
  15438. * Doesn't work with multi-materials.
  15439. */
  15440. get: function () {
  15441. return this._facetDepthSort;
  15442. },
  15443. set: function (sort) {
  15444. this._facetDepthSort = sort;
  15445. },
  15446. enumerable: true,
  15447. configurable: true
  15448. });
  15449. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15450. /**
  15451. * The location (Vector3) where the facet depth sort must be computed from.
  15452. * By default, the active camera position.
  15453. * Used only when facet depth sort is enabled.
  15454. */
  15455. get: function () {
  15456. return this._facetDepthSortFrom;
  15457. },
  15458. set: function (location) {
  15459. this._facetDepthSortFrom = location;
  15460. },
  15461. enumerable: true,
  15462. configurable: true
  15463. });
  15464. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15465. /**
  15466. * Read-only boolean : is the feature facetData enabled ?
  15467. */
  15468. get: function () {
  15469. return this._facetDataEnabled;
  15470. },
  15471. enumerable: true,
  15472. configurable: true
  15473. });
  15474. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15475. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15476. return false;
  15477. }
  15478. this._markSubMeshesAsMiscDirty();
  15479. return true;
  15480. };
  15481. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15482. set: function (callback) {
  15483. if (this._onCollideObserver) {
  15484. this.onCollideObservable.remove(this._onCollideObserver);
  15485. }
  15486. this._onCollideObserver = this.onCollideObservable.add(callback);
  15487. },
  15488. enumerable: true,
  15489. configurable: true
  15490. });
  15491. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15492. set: function (callback) {
  15493. if (this._onCollisionPositionChangeObserver) {
  15494. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15495. }
  15496. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15497. },
  15498. enumerable: true,
  15499. configurable: true
  15500. });
  15501. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15502. /**
  15503. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  15504. */
  15505. get: function () {
  15506. return this._isOccluded;
  15507. },
  15508. set: function (value) {
  15509. this._isOccluded = value;
  15510. },
  15511. enumerable: true,
  15512. configurable: true
  15513. });
  15514. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15515. /**
  15516. * Flag to check the progress status of the query
  15517. */
  15518. get: function () {
  15519. return this._isOcclusionQueryInProgress;
  15520. },
  15521. enumerable: true,
  15522. configurable: true
  15523. });
  15524. Object.defineProperty(AbstractMesh.prototype, "material", {
  15525. get: function () {
  15526. return this._material;
  15527. },
  15528. set: function (value) {
  15529. if (this._material === value) {
  15530. return;
  15531. }
  15532. this._material = value;
  15533. if (this.onMaterialChangedObservable.hasObservers) {
  15534. this.onMaterialChangedObservable.notifyObservers(this);
  15535. }
  15536. if (!this.subMeshes) {
  15537. return;
  15538. }
  15539. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15540. var subMesh = _a[_i];
  15541. subMesh.setEffect(null);
  15542. }
  15543. },
  15544. enumerable: true,
  15545. configurable: true
  15546. });
  15547. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15548. get: function () {
  15549. return this._receiveShadows;
  15550. },
  15551. set: function (value) {
  15552. if (this._receiveShadows === value) {
  15553. return;
  15554. }
  15555. this._receiveShadows = value;
  15556. this._markSubMeshesAsLightDirty();
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15562. get: function () {
  15563. return this._hasVertexAlpha;
  15564. },
  15565. set: function (value) {
  15566. if (this._hasVertexAlpha === value) {
  15567. return;
  15568. }
  15569. this._hasVertexAlpha = value;
  15570. this._markSubMeshesAsAttributesDirty();
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15576. get: function () {
  15577. return this._useVertexColors;
  15578. },
  15579. set: function (value) {
  15580. if (this._useVertexColors === value) {
  15581. return;
  15582. }
  15583. this._useVertexColors = value;
  15584. this._markSubMeshesAsAttributesDirty();
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15590. get: function () {
  15591. return this._computeBonesUsingShaders;
  15592. },
  15593. set: function (value) {
  15594. if (this._computeBonesUsingShaders === value) {
  15595. return;
  15596. }
  15597. this._computeBonesUsingShaders = value;
  15598. this._markSubMeshesAsAttributesDirty();
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15604. get: function () {
  15605. return this._numBoneInfluencers;
  15606. },
  15607. set: function (value) {
  15608. if (this._numBoneInfluencers === value) {
  15609. return;
  15610. }
  15611. this._numBoneInfluencers = value;
  15612. this._markSubMeshesAsAttributesDirty();
  15613. },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15618. get: function () {
  15619. return this._applyFog;
  15620. },
  15621. set: function (value) {
  15622. if (this._applyFog === value) {
  15623. return;
  15624. }
  15625. this._applyFog = value;
  15626. this._markSubMeshesAsMiscDirty();
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15632. get: function () {
  15633. return this._layerMask;
  15634. },
  15635. set: function (value) {
  15636. if (value === this._layerMask) {
  15637. return;
  15638. }
  15639. this._layerMask = value;
  15640. this._resyncLightSources();
  15641. },
  15642. enumerable: true,
  15643. configurable: true
  15644. });
  15645. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15646. get: function () {
  15647. return this._collisionMask;
  15648. },
  15649. set: function (mask) {
  15650. this._collisionMask = !isNaN(mask) ? mask : -1;
  15651. },
  15652. enumerable: true,
  15653. configurable: true
  15654. });
  15655. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15656. get: function () {
  15657. return this._collisionGroup;
  15658. },
  15659. set: function (mask) {
  15660. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15661. },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15666. get: function () {
  15667. return null;
  15668. },
  15669. enumerable: true,
  15670. configurable: true
  15671. });
  15672. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15673. get: function () {
  15674. return this._skeleton;
  15675. },
  15676. set: function (value) {
  15677. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15678. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15679. }
  15680. if (value && value.needInitialSkinMatrix) {
  15681. value._registerMeshWithPoseMatrix(this);
  15682. }
  15683. this._skeleton = value;
  15684. if (!this._skeleton) {
  15685. this._bonesTransformMatrices = null;
  15686. }
  15687. this._markSubMeshesAsAttributesDirty();
  15688. },
  15689. enumerable: true,
  15690. configurable: true
  15691. });
  15692. /**
  15693. * Boolean : true if the mesh has been disposed.
  15694. */
  15695. AbstractMesh.prototype.isDisposed = function () {
  15696. return this._isDisposed;
  15697. };
  15698. /**
  15699. * Returns the string "AbstractMesh"
  15700. */
  15701. AbstractMesh.prototype.getClassName = function () {
  15702. return "AbstractMesh";
  15703. };
  15704. /**
  15705. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15706. */
  15707. AbstractMesh.prototype.toString = function (fullDetails) {
  15708. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15709. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15710. if (this._skeleton) {
  15711. ret += ", skeleton: " + this._skeleton.name;
  15712. }
  15713. if (fullDetails) {
  15714. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15715. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15716. }
  15717. return ret;
  15718. };
  15719. AbstractMesh.prototype._rebuild = function () {
  15720. if (this._occlusionQuery) {
  15721. this._occlusionQuery = null;
  15722. }
  15723. if (this._edgesRenderer) {
  15724. this._edgesRenderer._rebuild();
  15725. }
  15726. if (!this.subMeshes) {
  15727. return;
  15728. }
  15729. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15730. var subMesh = _a[_i];
  15731. subMesh._rebuild();
  15732. }
  15733. };
  15734. AbstractMesh.prototype._resyncLightSources = function () {
  15735. this._lightSources.length = 0;
  15736. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15737. var light = _a[_i];
  15738. if (!light.isEnabled()) {
  15739. continue;
  15740. }
  15741. if (light.canAffectMesh(this)) {
  15742. this._lightSources.push(light);
  15743. }
  15744. }
  15745. this._markSubMeshesAsLightDirty();
  15746. };
  15747. AbstractMesh.prototype._resyncLighSource = function (light) {
  15748. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15749. var index = this._lightSources.indexOf(light);
  15750. if (index === -1) {
  15751. if (!isIn) {
  15752. return;
  15753. }
  15754. this._lightSources.push(light);
  15755. }
  15756. else {
  15757. if (isIn) {
  15758. return;
  15759. }
  15760. this._lightSources.splice(index, 1);
  15761. }
  15762. this._markSubMeshesAsLightDirty();
  15763. };
  15764. AbstractMesh.prototype._removeLightSource = function (light) {
  15765. var index = this._lightSources.indexOf(light);
  15766. if (index === -1) {
  15767. return;
  15768. }
  15769. this._lightSources.splice(index, 1);
  15770. };
  15771. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15772. if (!this.subMeshes) {
  15773. return;
  15774. }
  15775. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15776. var subMesh = _a[_i];
  15777. if (subMesh._materialDefines) {
  15778. func(subMesh._materialDefines);
  15779. }
  15780. }
  15781. };
  15782. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15783. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15784. };
  15785. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15786. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15787. };
  15788. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15789. if (!this.subMeshes) {
  15790. return;
  15791. }
  15792. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15793. var subMesh = _a[_i];
  15794. var material = subMesh.getMaterial();
  15795. if (material) {
  15796. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15797. }
  15798. }
  15799. };
  15800. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15801. /**
  15802. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15803. * Default : (1.0, 1.0, 1.0)
  15804. */
  15805. get: function () {
  15806. return this._scaling;
  15807. },
  15808. /**
  15809. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15810. * Default : (1.0, 1.0, 1.0)
  15811. */
  15812. set: function (newScaling) {
  15813. this._scaling = newScaling;
  15814. if (this.physicsImpostor) {
  15815. this.physicsImpostor.forceUpdate();
  15816. }
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. // Methods
  15822. /**
  15823. * Disables the mesh edger rendering mode.
  15824. * Returns the AbstractMesh.
  15825. */
  15826. AbstractMesh.prototype.disableEdgesRendering = function () {
  15827. if (this._edgesRenderer) {
  15828. this._edgesRenderer.dispose();
  15829. this._edgesRenderer = null;
  15830. }
  15831. return this;
  15832. };
  15833. /**
  15834. * Enables the edge rendering mode on the mesh.
  15835. * This mode makes the mesh edges visible.
  15836. * Returns the AbstractMesh.
  15837. */
  15838. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15839. if (epsilon === void 0) { epsilon = 0.95; }
  15840. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15841. this.disableEdgesRendering();
  15842. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15843. return this;
  15844. };
  15845. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15846. /**
  15847. * Returns true if the mesh is blocked. Used by the class Mesh.
  15848. * Returns the boolean `false` by default.
  15849. */
  15850. get: function () {
  15851. return false;
  15852. },
  15853. enumerable: true,
  15854. configurable: true
  15855. });
  15856. /**
  15857. * Returns the mesh itself by default, used by the class Mesh.
  15858. * Returned type : AbstractMesh
  15859. */
  15860. AbstractMesh.prototype.getLOD = function (camera) {
  15861. return this;
  15862. };
  15863. /**
  15864. * Returns 0 by default, used by the class Mesh.
  15865. * Returns an integer.
  15866. */
  15867. AbstractMesh.prototype.getTotalVertices = function () {
  15868. return 0;
  15869. };
  15870. /**
  15871. * Returns null by default, used by the class Mesh.
  15872. * Returned type : integer array
  15873. */
  15874. AbstractMesh.prototype.getIndices = function () {
  15875. return null;
  15876. };
  15877. /**
  15878. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15879. * Returned type : float array or Float32Array
  15880. */
  15881. AbstractMesh.prototype.getVerticesData = function (kind) {
  15882. return null;
  15883. };
  15884. /**
  15885. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15886. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15887. * The `data` are either a numeric array either a Float32Array.
  15888. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15889. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  15890. * Note that a new underlying VertexBuffer object is created each call.
  15891. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15892. *
  15893. * Possible `kind` values :
  15894. * - BABYLON.VertexBuffer.PositionKind
  15895. * - BABYLON.VertexBuffer.UVKind
  15896. * - BABYLON.VertexBuffer.UV2Kind
  15897. * - BABYLON.VertexBuffer.UV3Kind
  15898. * - BABYLON.VertexBuffer.UV4Kind
  15899. * - BABYLON.VertexBuffer.UV5Kind
  15900. * - BABYLON.VertexBuffer.UV6Kind
  15901. * - BABYLON.VertexBuffer.ColorKind
  15902. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15903. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15904. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15905. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15906. *
  15907. * Returns the Mesh.
  15908. */
  15909. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15910. return this;
  15911. };
  15912. /**
  15913. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15914. * If the mesh has no geometry, it is simply returned as it is.
  15915. * The `data` are either a numeric array either a Float32Array.
  15916. * No new underlying VertexBuffer object is created.
  15917. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15918. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15919. *
  15920. * Possible `kind` values :
  15921. * - BABYLON.VertexBuffer.PositionKind
  15922. * - BABYLON.VertexBuffer.UVKind
  15923. * - BABYLON.VertexBuffer.UV2Kind
  15924. * - BABYLON.VertexBuffer.UV3Kind
  15925. * - BABYLON.VertexBuffer.UV4Kind
  15926. * - BABYLON.VertexBuffer.UV5Kind
  15927. * - BABYLON.VertexBuffer.UV6Kind
  15928. * - BABYLON.VertexBuffer.ColorKind
  15929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15933. *
  15934. * Returns the Mesh.
  15935. */
  15936. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15937. return this;
  15938. };
  15939. /**
  15940. * Sets the mesh indices.
  15941. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15942. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15943. * This method creates a new index buffer each call.
  15944. * Returns the Mesh.
  15945. */
  15946. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15947. return this;
  15948. };
  15949. /** Returns false by default, used by the class Mesh.
  15950. * Returns a boolean
  15951. */
  15952. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15953. return false;
  15954. };
  15955. /**
  15956. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15957. * Returns a BoundingInfo
  15958. */
  15959. AbstractMesh.prototype.getBoundingInfo = function () {
  15960. if (this._masterMesh) {
  15961. return this._masterMesh.getBoundingInfo();
  15962. }
  15963. if (!this._boundingInfo) {
  15964. // this._boundingInfo is being created here
  15965. this._updateBoundingInfo();
  15966. }
  15967. // cannot be null.
  15968. return this._boundingInfo;
  15969. };
  15970. /**
  15971. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15972. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15973. */
  15974. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15975. if (includeDescendants === void 0) { includeDescendants = true; }
  15976. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15977. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15978. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15979. if (maxDimension === 0) {
  15980. return this;
  15981. }
  15982. var scale = 1 / maxDimension;
  15983. this.scaling.scaleInPlace(scale);
  15984. return this;
  15985. };
  15986. /**
  15987. * Sets a mesh new object BoundingInfo.
  15988. * Returns the AbstractMesh.
  15989. */
  15990. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15991. this._boundingInfo = boundingInfo;
  15992. return this;
  15993. };
  15994. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15995. get: function () {
  15996. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. AbstractMesh.prototype._preActivate = function () {
  16002. };
  16003. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16004. };
  16005. AbstractMesh.prototype._activate = function (renderId) {
  16006. this._renderId = renderId;
  16007. };
  16008. /**
  16009. * Returns the latest update of the World matrix
  16010. * Returns a Matrix.
  16011. */
  16012. AbstractMesh.prototype.getWorldMatrix = function () {
  16013. if (this._masterMesh) {
  16014. return this._masterMesh.getWorldMatrix();
  16015. }
  16016. return _super.prototype.getWorldMatrix.call(this);
  16017. };
  16018. /**
  16019. * Returns the latest update of the World matrix determinant.
  16020. */
  16021. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16022. if (this._masterMesh) {
  16023. return this._masterMesh._getWorldMatrixDeterminant();
  16024. }
  16025. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16026. };
  16027. // ================================== Point of View Movement =================================
  16028. /**
  16029. * Perform relative position change from the point of view of behind the front of the mesh.
  16030. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16031. * Supports definition of mesh facing forward or backward.
  16032. * @param {number} amountRight
  16033. * @param {number} amountUp
  16034. * @param {number} amountForward
  16035. *
  16036. * Returns the AbstractMesh.
  16037. */
  16038. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16039. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16040. return this;
  16041. };
  16042. /**
  16043. * Calculate relative position change from the point of view of behind the front of the mesh.
  16044. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16045. * Supports definition of mesh facing forward or backward.
  16046. * @param {number} amountRight
  16047. * @param {number} amountUp
  16048. * @param {number} amountForward
  16049. *
  16050. * Returns a new Vector3.
  16051. */
  16052. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16053. var rotMatrix = new BABYLON.Matrix();
  16054. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16055. rotQuaternion.toRotationMatrix(rotMatrix);
  16056. var translationDelta = BABYLON.Vector3.Zero();
  16057. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16059. return translationDelta;
  16060. };
  16061. // ================================== Point of View Rotation =================================
  16062. /**
  16063. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16064. * Supports definition of mesh facing forward or backward.
  16065. * @param {number} flipBack
  16066. * @param {number} twirlClockwise
  16067. * @param {number} tiltRight
  16068. *
  16069. * Returns the AbstractMesh.
  16070. */
  16071. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16072. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16073. return this;
  16074. };
  16075. /**
  16076. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16077. * Supports definition of mesh facing forward or backward.
  16078. * @param {number} flipBack
  16079. * @param {number} twirlClockwise
  16080. * @param {number} tiltRight
  16081. *
  16082. * Returns a new Vector3.
  16083. */
  16084. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16085. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16086. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16087. };
  16088. /**
  16089. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16090. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16091. */
  16092. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16093. if (includeDescendants === void 0) { includeDescendants = true; }
  16094. this.computeWorldMatrix(true);
  16095. var min;
  16096. var max;
  16097. var boundingInfo = this.getBoundingInfo();
  16098. if (!this.subMeshes) {
  16099. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16100. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16101. }
  16102. else {
  16103. min = boundingInfo.boundingBox.minimumWorld;
  16104. max = boundingInfo.boundingBox.maximumWorld;
  16105. }
  16106. if (includeDescendants) {
  16107. var descendants = this.getDescendants(false);
  16108. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16109. var descendant = descendants_1[_i];
  16110. var childMesh = descendant;
  16111. childMesh.computeWorldMatrix(true);
  16112. //make sure we have the needed params to get mix and max
  16113. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16114. continue;
  16115. }
  16116. var childBoundingInfo = childMesh.getBoundingInfo();
  16117. var boundingBox = childBoundingInfo.boundingBox;
  16118. var minBox = boundingBox.minimumWorld;
  16119. var maxBox = boundingBox.maximumWorld;
  16120. BABYLON.Tools.CheckExtends(minBox, min, max);
  16121. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16122. }
  16123. }
  16124. return {
  16125. min: min,
  16126. max: max
  16127. };
  16128. };
  16129. /**
  16130. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16131. * Returns the AbstractMesh.
  16132. */
  16133. AbstractMesh.prototype._updateBoundingInfo = function () {
  16134. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16135. this._boundingInfo.update(this.worldMatrixFromCache);
  16136. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16137. return this;
  16138. };
  16139. /**
  16140. * Update a mesh's children BoundingInfo objects only.
  16141. * Returns the AbstractMesh.
  16142. */
  16143. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16144. if (!this.subMeshes) {
  16145. return this;
  16146. }
  16147. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16148. var subMesh = this.subMeshes[subIndex];
  16149. if (!subMesh.IsGlobal) {
  16150. subMesh.updateBoundingInfo(matrix);
  16151. }
  16152. }
  16153. return this;
  16154. };
  16155. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16156. // Bounding info
  16157. this._updateBoundingInfo();
  16158. };
  16159. /**
  16160. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16161. * A mesh is in the frustum if its bounding box intersects the frustum.
  16162. * Boolean returned.
  16163. */
  16164. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16165. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16166. };
  16167. /**
  16168. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16169. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16170. * Boolean returned.
  16171. */
  16172. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16173. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16174. ;
  16175. };
  16176. /**
  16177. * True if the mesh intersects another mesh or a SolidParticle object.
  16178. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  16179. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16180. * Returns a boolean.
  16181. */
  16182. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16183. if (precise === void 0) { precise = false; }
  16184. if (!this._boundingInfo || !mesh._boundingInfo) {
  16185. return false;
  16186. }
  16187. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16188. return true;
  16189. }
  16190. if (includeDescendants) {
  16191. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16192. var child = _a[_i];
  16193. if (child.intersectsMesh(mesh, precise, true)) {
  16194. return true;
  16195. }
  16196. }
  16197. }
  16198. return false;
  16199. };
  16200. /**
  16201. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16202. * Returns a boolean.
  16203. */
  16204. AbstractMesh.prototype.intersectsPoint = function (point) {
  16205. if (!this._boundingInfo) {
  16206. return false;
  16207. }
  16208. return this._boundingInfo.intersectsPoint(point);
  16209. };
  16210. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16211. return this.physicsImpostor;
  16212. };
  16213. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16214. if (camera === void 0) { camera = null; }
  16215. if (!camera) {
  16216. camera = this.getScene().activeCamera;
  16217. }
  16218. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16219. };
  16220. /**
  16221. * Returns the distance from the mesh to the active camera.
  16222. * Returns a float.
  16223. */
  16224. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16225. if (camera === void 0) { camera = null; }
  16226. if (!camera) {
  16227. camera = this.getScene().activeCamera;
  16228. }
  16229. return this.absolutePosition.subtract(camera.position).length();
  16230. };
  16231. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16232. if (!this.physicsImpostor) {
  16233. return this;
  16234. }
  16235. this.physicsImpostor.applyImpulse(force, contactPoint);
  16236. return this;
  16237. };
  16238. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16239. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16240. return this;
  16241. }
  16242. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16243. mainPivot: pivot1,
  16244. connectedPivot: pivot2,
  16245. nativeParams: options
  16246. });
  16247. return this;
  16248. };
  16249. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16250. // Collisions
  16251. /**
  16252. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16253. * Default `false`.
  16254. */
  16255. get: function () {
  16256. return this._checkCollisions;
  16257. },
  16258. set: function (collisionEnabled) {
  16259. this._checkCollisions = collisionEnabled;
  16260. if (this.getScene().workerCollisions) {
  16261. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16262. }
  16263. },
  16264. enumerable: true,
  16265. configurable: true
  16266. });
  16267. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16268. /**
  16269. * Gets Collider object used to compute collisions (not physics)
  16270. */
  16271. get: function () {
  16272. return this._collider;
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16278. var globalPosition = this.getAbsolutePosition();
  16279. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16280. if (!this._collider) {
  16281. this._collider = new BABYLON.Collider();
  16282. }
  16283. this._collider._radius = this.ellipsoid;
  16284. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16285. return this;
  16286. };
  16287. // Submeshes octree
  16288. /**
  16289. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16290. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16291. * Returns an Octree of submeshes.
  16292. */
  16293. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16294. if (maxCapacity === void 0) { maxCapacity = 64; }
  16295. if (maxDepth === void 0) { maxDepth = 2; }
  16296. if (!this._submeshesOctree) {
  16297. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16298. }
  16299. this.computeWorldMatrix(true);
  16300. var boundingInfo = this.getBoundingInfo();
  16301. // Update octree
  16302. var bbox = boundingInfo.boundingBox;
  16303. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16304. return this._submeshesOctree;
  16305. };
  16306. // Collisions
  16307. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16308. this._generatePointsArray();
  16309. if (!this._positions) {
  16310. return this;
  16311. }
  16312. // Transformation
  16313. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16314. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16315. subMesh._lastColliderWorldVertices = [];
  16316. subMesh._trianglePlanes = [];
  16317. var start = subMesh.verticesStart;
  16318. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16319. for (var i = start; i < end; i++) {
  16320. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16321. }
  16322. }
  16323. // Collide
  16324. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16325. if (collider.collisionFound) {
  16326. collider.collidedMesh = this;
  16327. }
  16328. return this;
  16329. };
  16330. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16331. var subMeshes;
  16332. var len;
  16333. // Octrees
  16334. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16335. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16336. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16337. len = intersections.length;
  16338. subMeshes = intersections.data;
  16339. }
  16340. else {
  16341. subMeshes = this.subMeshes;
  16342. len = subMeshes.length;
  16343. }
  16344. for (var index = 0; index < len; index++) {
  16345. var subMesh = subMeshes[index];
  16346. // Bounding test
  16347. if (len > 1 && !subMesh._checkCollision(collider))
  16348. continue;
  16349. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16350. }
  16351. return this;
  16352. };
  16353. AbstractMesh.prototype._checkCollision = function (collider) {
  16354. // Bounding box test
  16355. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16356. return this;
  16357. // Transformation matrix
  16358. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16359. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16360. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16361. return this;
  16362. };
  16363. // Picking
  16364. AbstractMesh.prototype._generatePointsArray = function () {
  16365. return false;
  16366. };
  16367. /**
  16368. * Checks if the passed Ray intersects with the mesh.
  16369. * Returns an object PickingInfo.
  16370. */
  16371. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16372. var pickingInfo = new BABYLON.PickingInfo();
  16373. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16374. return pickingInfo;
  16375. }
  16376. if (!this._generatePointsArray()) {
  16377. return pickingInfo;
  16378. }
  16379. var intersectInfo = null;
  16380. // Octrees
  16381. var subMeshes;
  16382. var len;
  16383. if (this._submeshesOctree && this.useOctreeForPicking) {
  16384. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16385. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16386. len = intersections.length;
  16387. subMeshes = intersections.data;
  16388. }
  16389. else {
  16390. subMeshes = this.subMeshes;
  16391. len = subMeshes.length;
  16392. }
  16393. for (var index = 0; index < len; index++) {
  16394. var subMesh = subMeshes[index];
  16395. // Bounding test
  16396. if (len > 1 && !subMesh.canIntersects(ray))
  16397. continue;
  16398. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16399. if (currentIntersectInfo) {
  16400. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16401. intersectInfo = currentIntersectInfo;
  16402. intersectInfo.subMeshId = index;
  16403. if (fastCheck) {
  16404. break;
  16405. }
  16406. }
  16407. }
  16408. }
  16409. if (intersectInfo) {
  16410. // Get picked point
  16411. var world = this.getWorldMatrix();
  16412. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16413. var direction = ray.direction.clone();
  16414. direction = direction.scale(intersectInfo.distance);
  16415. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16416. var pickedPoint = worldOrigin.add(worldDirection);
  16417. // Return result
  16418. pickingInfo.hit = true;
  16419. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16420. pickingInfo.pickedPoint = pickedPoint;
  16421. pickingInfo.pickedMesh = this;
  16422. pickingInfo.bu = intersectInfo.bu || 0;
  16423. pickingInfo.bv = intersectInfo.bv || 0;
  16424. pickingInfo.faceId = intersectInfo.faceId;
  16425. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16426. return pickingInfo;
  16427. }
  16428. return pickingInfo;
  16429. };
  16430. /**
  16431. * Clones the mesh, used by the class Mesh.
  16432. * Just returns `null` for an AbstractMesh.
  16433. */
  16434. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16435. return null;
  16436. };
  16437. /**
  16438. * Disposes all the mesh submeshes.
  16439. * Returns the AbstractMesh.
  16440. */
  16441. AbstractMesh.prototype.releaseSubMeshes = function () {
  16442. if (this.subMeshes) {
  16443. while (this.subMeshes.length) {
  16444. this.subMeshes[0].dispose();
  16445. }
  16446. }
  16447. else {
  16448. this.subMeshes = new Array();
  16449. }
  16450. return this;
  16451. };
  16452. /**
  16453. * Disposes the AbstractMesh.
  16454. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16455. * Returns nothing.
  16456. */
  16457. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16458. var _this = this;
  16459. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16460. var index;
  16461. // Action manager
  16462. if (this.actionManager !== undefined && this.actionManager !== null) {
  16463. this.actionManager.dispose();
  16464. this.actionManager = null;
  16465. }
  16466. // Skeleton
  16467. this.skeleton = null;
  16468. // Physics
  16469. if (this.physicsImpostor) {
  16470. this.physicsImpostor.dispose();
  16471. }
  16472. // Intersections in progress
  16473. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16474. var other = this._intersectionsInProgress[index];
  16475. var pos = other._intersectionsInProgress.indexOf(this);
  16476. other._intersectionsInProgress.splice(pos, 1);
  16477. }
  16478. this._intersectionsInProgress = [];
  16479. // Lights
  16480. var lights = this.getScene().lights;
  16481. lights.forEach(function (light) {
  16482. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16483. if (meshIndex !== -1) {
  16484. light.includedOnlyMeshes.splice(meshIndex, 1);
  16485. }
  16486. meshIndex = light.excludedMeshes.indexOf(_this);
  16487. if (meshIndex !== -1) {
  16488. light.excludedMeshes.splice(meshIndex, 1);
  16489. }
  16490. // Shadow generators
  16491. var generator = light.getShadowGenerator();
  16492. if (generator) {
  16493. var shadowMap = generator.getShadowMap();
  16494. if (shadowMap && shadowMap.renderList) {
  16495. meshIndex = shadowMap.renderList.indexOf(_this);
  16496. if (meshIndex !== -1) {
  16497. shadowMap.renderList.splice(meshIndex, 1);
  16498. }
  16499. }
  16500. }
  16501. });
  16502. // Edges
  16503. if (this._edgesRenderer) {
  16504. this._edgesRenderer.dispose();
  16505. this._edgesRenderer = null;
  16506. }
  16507. // SubMeshes
  16508. if (this.getClassName() !== "InstancedMesh") {
  16509. this.releaseSubMeshes();
  16510. }
  16511. // Octree
  16512. var sceneOctree = this.getScene().selectionOctree;
  16513. if (sceneOctree !== undefined && sceneOctree !== null) {
  16514. var index = sceneOctree.dynamicContent.indexOf(this);
  16515. if (index !== -1) {
  16516. sceneOctree.dynamicContent.splice(index, 1);
  16517. }
  16518. }
  16519. // Query
  16520. var engine = this.getScene().getEngine();
  16521. if (this._occlusionQuery) {
  16522. this._isOcclusionQueryInProgress = false;
  16523. engine.deleteQuery(this._occlusionQuery);
  16524. this._occlusionQuery = null;
  16525. }
  16526. // Engine
  16527. engine.wipeCaches();
  16528. // Remove from scene
  16529. this.getScene().removeMesh(this);
  16530. if (disposeMaterialAndTextures) {
  16531. if (this.material) {
  16532. this.material.dispose(false, true);
  16533. }
  16534. }
  16535. if (!doNotRecurse) {
  16536. // Particles
  16537. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16538. if (this.getScene().particleSystems[index].emitter === this) {
  16539. this.getScene().particleSystems[index].dispose();
  16540. index--;
  16541. }
  16542. }
  16543. }
  16544. // facet data
  16545. if (this._facetDataEnabled) {
  16546. this.disableFacetData();
  16547. }
  16548. this.onAfterWorldMatrixUpdateObservable.clear();
  16549. this.onCollideObservable.clear();
  16550. this.onCollisionPositionChangeObservable.clear();
  16551. this._isDisposed = true;
  16552. _super.prototype.dispose.call(this, doNotRecurse);
  16553. };
  16554. /**
  16555. * Adds the passed mesh as a child to the current mesh.
  16556. * Returns the AbstractMesh.
  16557. */
  16558. AbstractMesh.prototype.addChild = function (mesh) {
  16559. mesh.setParent(this);
  16560. return this;
  16561. };
  16562. /**
  16563. * Removes the passed mesh from the current mesh children list.
  16564. * Returns the AbstractMesh.
  16565. */
  16566. AbstractMesh.prototype.removeChild = function (mesh) {
  16567. mesh.setParent(null);
  16568. return this;
  16569. };
  16570. // Facet data
  16571. /**
  16572. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16573. * Returns the AbstractMesh.
  16574. */
  16575. AbstractMesh.prototype._initFacetData = function () {
  16576. if (!this._facetNormals) {
  16577. this._facetNormals = new Array();
  16578. }
  16579. if (!this._facetPositions) {
  16580. this._facetPositions = new Array();
  16581. }
  16582. if (!this._facetPartitioning) {
  16583. this._facetPartitioning = new Array();
  16584. }
  16585. this._facetNb = (this.getIndices().length / 3) | 0;
  16586. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16587. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16588. for (var f = 0; f < this._facetNb; f++) {
  16589. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16590. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16591. }
  16592. this._facetDataEnabled = true;
  16593. return this;
  16594. };
  16595. /**
  16596. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16597. * This method can be called within the render loop.
  16598. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  16599. * Returns the AbstractMesh.
  16600. */
  16601. AbstractMesh.prototype.updateFacetData = function () {
  16602. if (!this._facetDataEnabled) {
  16603. this._initFacetData();
  16604. }
  16605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16606. var indices = this.getIndices();
  16607. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16608. var bInfo = this.getBoundingInfo();
  16609. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16610. // init arrays, matrix and sort function on first call
  16611. this._facetDepthSortEnabled = true;
  16612. if (indices instanceof Uint16Array) {
  16613. this._depthSortedIndices = new Uint16Array(indices);
  16614. }
  16615. else if (indices instanceof Uint32Array) {
  16616. this._depthSortedIndices = new Uint32Array(indices);
  16617. }
  16618. else {
  16619. var needs32bits = false;
  16620. for (var i = 0; i < indices.length; i++) {
  16621. if (indices[i] > 65535) {
  16622. needs32bits = true;
  16623. break;
  16624. }
  16625. }
  16626. if (needs32bits) {
  16627. this._depthSortedIndices = new Uint32Array(indices);
  16628. }
  16629. else {
  16630. this._depthSortedIndices = new Uint16Array(indices);
  16631. }
  16632. }
  16633. this._facetDepthSortFunction = function (f1, f2) {
  16634. return (f2.sqDistance - f1.sqDistance);
  16635. };
  16636. if (!this._facetDepthSortFrom) {
  16637. var camera = this.getScene().activeCamera;
  16638. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16639. }
  16640. this._depthSortedFacets = [];
  16641. for (var f = 0; f < this._facetNb; f++) {
  16642. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16643. this._depthSortedFacets.push(depthSortedFacet);
  16644. }
  16645. this._invertedMatrix = BABYLON.Matrix.Identity();
  16646. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16647. }
  16648. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16649. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16650. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16651. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16652. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16653. this._subDiv.max = this._partitioningSubdivisions;
  16654. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16655. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16656. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16657. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16658. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16659. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16660. // set the parameters for ComputeNormals()
  16661. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16662. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16663. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16664. this._facetParameters.bInfo = bInfo;
  16665. this._facetParameters.bbSize = this._bbSize;
  16666. this._facetParameters.subDiv = this._subDiv;
  16667. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16668. this._facetParameters.depthSort = this._facetDepthSort;
  16669. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16670. this.computeWorldMatrix(true);
  16671. this._worldMatrix.invertToRef(this._invertedMatrix);
  16672. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16673. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16674. }
  16675. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16676. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16677. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16678. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16679. var l = (this._depthSortedIndices.length / 3) | 0;
  16680. for (var f = 0; f < l; f++) {
  16681. var sind = this._depthSortedFacets[f].ind;
  16682. this._depthSortedIndices[f * 3] = indices[sind];
  16683. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16684. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16685. }
  16686. this.updateIndices(this._depthSortedIndices);
  16687. }
  16688. return this;
  16689. };
  16690. /**
  16691. * Returns the facetLocalNormals array.
  16692. * The normals are expressed in the mesh local space.
  16693. */
  16694. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16695. if (!this._facetNormals) {
  16696. this.updateFacetData();
  16697. }
  16698. return this._facetNormals;
  16699. };
  16700. /**
  16701. * Returns the facetLocalPositions array.
  16702. * The facet positions are expressed in the mesh local space.
  16703. */
  16704. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16705. if (!this._facetPositions) {
  16706. this.updateFacetData();
  16707. }
  16708. return this._facetPositions;
  16709. };
  16710. /**
  16711. * Returns the facetLocalPartioning array.
  16712. */
  16713. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16714. if (!this._facetPartitioning) {
  16715. this.updateFacetData();
  16716. }
  16717. return this._facetPartitioning;
  16718. };
  16719. /**
  16720. * Returns the i-th facet position in the world system.
  16721. * This method allocates a new Vector3 per call.
  16722. */
  16723. AbstractMesh.prototype.getFacetPosition = function (i) {
  16724. var pos = BABYLON.Vector3.Zero();
  16725. this.getFacetPositionToRef(i, pos);
  16726. return pos;
  16727. };
  16728. /**
  16729. * Sets the reference Vector3 with the i-th facet position in the world system.
  16730. * Returns the AbstractMesh.
  16731. */
  16732. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16733. var localPos = (this.getFacetLocalPositions())[i];
  16734. var world = this.getWorldMatrix();
  16735. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16736. return this;
  16737. };
  16738. /**
  16739. * Returns the i-th facet normal in the world system.
  16740. * This method allocates a new Vector3 per call.
  16741. */
  16742. AbstractMesh.prototype.getFacetNormal = function (i) {
  16743. var norm = BABYLON.Vector3.Zero();
  16744. this.getFacetNormalToRef(i, norm);
  16745. return norm;
  16746. };
  16747. /**
  16748. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16749. * Returns the AbstractMesh.
  16750. */
  16751. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16752. var localNorm = (this.getFacetLocalNormals())[i];
  16753. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16754. return this;
  16755. };
  16756. /**
  16757. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  16758. */
  16759. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16760. var bInfo = this.getBoundingInfo();
  16761. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16762. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16763. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16764. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16765. return null;
  16766. }
  16767. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16768. };
  16769. /**
  16770. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16771. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16772. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  16773. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16774. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  16775. */
  16776. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16777. if (checkFace === void 0) { checkFace = false; }
  16778. if (facing === void 0) { facing = true; }
  16779. var world = this.getWorldMatrix();
  16780. var invMat = BABYLON.Tmp.Matrix[5];
  16781. world.invertToRef(invMat);
  16782. var invVect = BABYLON.Tmp.Vector3[8];
  16783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16784. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16785. if (projected) {
  16786. // tranform the local computed projected vector to world coordinates
  16787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16788. }
  16789. return closest;
  16790. };
  16791. /**
  16792. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16793. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16794. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  16795. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16796. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  16797. */
  16798. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16799. if (checkFace === void 0) { checkFace = false; }
  16800. if (facing === void 0) { facing = true; }
  16801. var closest = null;
  16802. var tmpx = 0.0;
  16803. var tmpy = 0.0;
  16804. var tmpz = 0.0;
  16805. var d = 0.0; // tmp dot facet normal * facet position
  16806. var t0 = 0.0;
  16807. var projx = 0.0;
  16808. var projy = 0.0;
  16809. var projz = 0.0;
  16810. // Get all the facets in the same partitioning block than (x, y, z)
  16811. var facetPositions = this.getFacetLocalPositions();
  16812. var facetNormals = this.getFacetLocalNormals();
  16813. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16814. if (!facetsInBlock) {
  16815. return null;
  16816. }
  16817. // Get the closest facet to (x, y, z)
  16818. var shortest = Number.MAX_VALUE; // init distance vars
  16819. var tmpDistance = shortest;
  16820. var fib; // current facet in the block
  16821. var norm; // current facet normal
  16822. var p0; // current facet barycenter position
  16823. // loop on all the facets in the current partitioning block
  16824. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16825. fib = facetsInBlock[idx];
  16826. norm = facetNormals[fib];
  16827. p0 = facetPositions[fib];
  16828. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16829. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16830. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16831. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16832. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16833. projx = x + norm.x * t0;
  16834. projy = y + norm.y * t0;
  16835. projz = z + norm.z * t0;
  16836. tmpx = projx - x;
  16837. tmpy = projy - y;
  16838. tmpz = projz - z;
  16839. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16840. if (tmpDistance < shortest) {
  16841. shortest = tmpDistance;
  16842. closest = fib;
  16843. if (projected) {
  16844. projected.x = projx;
  16845. projected.y = projy;
  16846. projected.z = projz;
  16847. }
  16848. }
  16849. }
  16850. }
  16851. return closest;
  16852. };
  16853. /**
  16854. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16855. */
  16856. AbstractMesh.prototype.getFacetDataParameters = function () {
  16857. return this._facetParameters;
  16858. };
  16859. /**
  16860. * Disables the feature FacetData and frees the related memory.
  16861. * Returns the AbstractMesh.
  16862. */
  16863. AbstractMesh.prototype.disableFacetData = function () {
  16864. if (this._facetDataEnabled) {
  16865. this._facetDataEnabled = false;
  16866. this._facetPositions = new Array();
  16867. this._facetNormals = new Array();
  16868. this._facetPartitioning = new Array();
  16869. this._facetParameters = null;
  16870. this._depthSortedIndices = new Uint32Array(0);
  16871. }
  16872. return this;
  16873. };
  16874. /**
  16875. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16876. * Returns the mesh.
  16877. */
  16878. AbstractMesh.prototype.updateIndices = function (indices) {
  16879. return this;
  16880. };
  16881. /**
  16882. * The mesh Geometry. Actually used by the Mesh object.
  16883. * Returns a blank geometry object.
  16884. */
  16885. /**
  16886. * Creates new normals data for the mesh.
  16887. * @param updatable.
  16888. */
  16889. AbstractMesh.prototype.createNormals = function (updatable) {
  16890. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16891. var indices = this.getIndices();
  16892. var normals;
  16893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16894. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16895. }
  16896. else {
  16897. normals = [];
  16898. }
  16899. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16900. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16901. };
  16902. /**
  16903. * Align the mesh with a normal.
  16904. * Returns the mesh.
  16905. */
  16906. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16907. if (!upDirection) {
  16908. upDirection = BABYLON.Axis.Y;
  16909. }
  16910. var axisX = BABYLON.Tmp.Vector3[0];
  16911. var axisZ = BABYLON.Tmp.Vector3[1];
  16912. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16913. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16914. if (this.rotationQuaternion) {
  16915. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16916. }
  16917. else {
  16918. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16919. }
  16920. return this;
  16921. };
  16922. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16923. var engine = this.getEngine();
  16924. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16925. this._isOccluded = false;
  16926. return;
  16927. }
  16928. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16929. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16930. if (isOcclusionQueryAvailable) {
  16931. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16932. this._isOcclusionQueryInProgress = false;
  16933. this._occlusionInternalRetryCounter = 0;
  16934. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16935. }
  16936. else {
  16937. this._occlusionInternalRetryCounter++;
  16938. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16939. this._isOcclusionQueryInProgress = false;
  16940. this._occlusionInternalRetryCounter = 0;
  16941. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16942. // if strict continue the last state of the object.
  16943. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16944. }
  16945. else {
  16946. return;
  16947. }
  16948. }
  16949. }
  16950. var scene = this.getScene();
  16951. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16952. if (!this._occlusionQuery) {
  16953. this._occlusionQuery = engine.createQuery();
  16954. }
  16955. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16956. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16957. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16958. this._isOcclusionQueryInProgress = true;
  16959. };
  16960. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16961. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16962. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16963. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16964. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16965. return AbstractMesh;
  16966. }(BABYLON.TransformNode));
  16967. BABYLON.AbstractMesh = AbstractMesh;
  16968. })(BABYLON || (BABYLON = {}));
  16969. //# sourceMappingURL=babylon.abstractMesh.js.map
  16970. var BABYLON;
  16971. (function (BABYLON) {
  16972. var Light = /** @class */ (function (_super) {
  16973. __extends(Light, _super);
  16974. /**
  16975. * Creates a Light object in the scene.
  16976. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16977. */
  16978. function Light(name, scene) {
  16979. var _this = _super.call(this, name, scene) || this;
  16980. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16981. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16982. _this.intensity = 1.0;
  16983. _this.range = Number.MAX_VALUE;
  16984. /**
  16985. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16986. * of light.
  16987. */
  16988. _this._photometricScale = 1.0;
  16989. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16990. _this._radius = 0.00001;
  16991. _this.renderPriority = 0;
  16992. /**
  16993. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16994. * the current shadow generator.
  16995. */
  16996. _this.shadowEnabled = true;
  16997. _this._excludeWithLayerMask = 0;
  16998. _this._includeOnlyWithLayerMask = 0;
  16999. _this._lightmapMode = 0;
  17000. _this._excludedMeshesIds = new Array();
  17001. _this._includedOnlyMeshesIds = new Array();
  17002. _this.getScene().addLight(_this);
  17003. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17004. _this._buildUniformLayout();
  17005. _this.includedOnlyMeshes = new Array();
  17006. _this.excludedMeshes = new Array();
  17007. _this._resyncMeshes();
  17008. return _this;
  17009. }
  17010. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17011. /**
  17012. * If every light affecting the material is in this lightmapMode,
  17013. * material.lightmapTexture adds or multiplies
  17014. * (depends on material.useLightmapAsShadowmap)
  17015. * after every other light calculations.
  17016. */
  17017. get: function () {
  17018. return Light._LIGHTMAP_DEFAULT;
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17024. /**
  17025. * material.lightmapTexture as only diffuse lighting from this light
  17026. * adds pnly specular lighting from this light
  17027. * adds dynamic shadows
  17028. */
  17029. get: function () {
  17030. return Light._LIGHTMAP_SPECULAR;
  17031. },
  17032. enumerable: true,
  17033. configurable: true
  17034. });
  17035. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17036. /**
  17037. * material.lightmapTexture as only lighting
  17038. * no light calculation from this light
  17039. * only adds dynamic shadows from this light
  17040. */
  17041. get: function () {
  17042. return Light._LIGHTMAP_SHADOWSONLY;
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17048. /**
  17049. * Each light type uses the default quantity according to its type:
  17050. * point/spot lights use luminous intensity
  17051. * directional lights use illuminance
  17052. */
  17053. get: function () {
  17054. return Light._INTENSITYMODE_AUTOMATIC;
  17055. },
  17056. enumerable: true,
  17057. configurable: true
  17058. });
  17059. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17060. /**
  17061. * lumen (lm)
  17062. */
  17063. get: function () {
  17064. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17070. /**
  17071. * candela (lm/sr)
  17072. */
  17073. get: function () {
  17074. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17075. },
  17076. enumerable: true,
  17077. configurable: true
  17078. });
  17079. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17080. /**
  17081. * lux (lm/m^2)
  17082. */
  17083. get: function () {
  17084. return Light._INTENSITYMODE_ILLUMINANCE;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17090. /**
  17091. * nit (cd/m^2)
  17092. */
  17093. get: function () {
  17094. return Light._INTENSITYMODE_LUMINANCE;
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17100. /**
  17101. * Light type const id of the point light.
  17102. */
  17103. get: function () {
  17104. return Light._LIGHTTYPEID_POINTLIGHT;
  17105. },
  17106. enumerable: true,
  17107. configurable: true
  17108. });
  17109. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17110. /**
  17111. * Light type const id of the directional light.
  17112. */
  17113. get: function () {
  17114. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17115. },
  17116. enumerable: true,
  17117. configurable: true
  17118. });
  17119. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17120. /**
  17121. * Light type const id of the spot light.
  17122. */
  17123. get: function () {
  17124. return Light._LIGHTTYPEID_SPOTLIGHT;
  17125. },
  17126. enumerable: true,
  17127. configurable: true
  17128. });
  17129. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17130. /**
  17131. * Light type const id of the hemispheric light.
  17132. */
  17133. get: function () {
  17134. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(Light.prototype, "intensityMode", {
  17140. /**
  17141. * Gets the photometric scale used to interpret the intensity.
  17142. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17143. */
  17144. get: function () {
  17145. return this._intensityMode;
  17146. },
  17147. /**
  17148. * Sets the photometric scale used to interpret the intensity.
  17149. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17150. */
  17151. set: function (value) {
  17152. this._intensityMode = value;
  17153. this._computePhotometricScale();
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. ;
  17159. ;
  17160. Object.defineProperty(Light.prototype, "radius", {
  17161. /**
  17162. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17163. */
  17164. get: function () {
  17165. return this._radius;
  17166. },
  17167. /**
  17168. * sets the light radius used by PBR Materials to simulate soft area lights.
  17169. */
  17170. set: function (value) {
  17171. this._radius = value;
  17172. this._computePhotometricScale();
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. ;
  17178. ;
  17179. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17180. get: function () {
  17181. return this._includedOnlyMeshes;
  17182. },
  17183. set: function (value) {
  17184. this._includedOnlyMeshes = value;
  17185. this._hookArrayForIncludedOnly(value);
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17191. get: function () {
  17192. return this._excludedMeshes;
  17193. },
  17194. set: function (value) {
  17195. this._excludedMeshes = value;
  17196. this._hookArrayForExcluded(value);
  17197. },
  17198. enumerable: true,
  17199. configurable: true
  17200. });
  17201. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17202. get: function () {
  17203. return this._excludeWithLayerMask;
  17204. },
  17205. set: function (value) {
  17206. this._excludeWithLayerMask = value;
  17207. this._resyncMeshes();
  17208. },
  17209. enumerable: true,
  17210. configurable: true
  17211. });
  17212. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17213. get: function () {
  17214. return this._includeOnlyWithLayerMask;
  17215. },
  17216. set: function (value) {
  17217. this._includeOnlyWithLayerMask = value;
  17218. this._resyncMeshes();
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Object.defineProperty(Light.prototype, "lightmapMode", {
  17224. get: function () {
  17225. return this._lightmapMode;
  17226. },
  17227. set: function (value) {
  17228. if (this._lightmapMode === value) {
  17229. return;
  17230. }
  17231. this._lightmapMode = value;
  17232. this._markMeshesAsLightDirty();
  17233. },
  17234. enumerable: true,
  17235. configurable: true
  17236. });
  17237. Light.prototype._buildUniformLayout = function () {
  17238. // Overridden
  17239. };
  17240. /**
  17241. * Returns the string "Light".
  17242. */
  17243. Light.prototype.getClassName = function () {
  17244. return "Light";
  17245. };
  17246. /**
  17247. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17248. */
  17249. Light.prototype.toString = function (fullDetails) {
  17250. var ret = "Name: " + this.name;
  17251. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17252. if (this.animations) {
  17253. for (var i = 0; i < this.animations.length; i++) {
  17254. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17255. }
  17256. }
  17257. if (fullDetails) {
  17258. }
  17259. return ret;
  17260. };
  17261. /**
  17262. * Set the enabled state of this node.
  17263. * @param {boolean} value - the new enabled state
  17264. * @see isEnabled
  17265. */
  17266. Light.prototype.setEnabled = function (value) {
  17267. _super.prototype.setEnabled.call(this, value);
  17268. this._resyncMeshes();
  17269. };
  17270. /**
  17271. * Returns the Light associated shadow generator.
  17272. */
  17273. Light.prototype.getShadowGenerator = function () {
  17274. return this._shadowGenerator;
  17275. };
  17276. /**
  17277. * Returns a Vector3, the absolute light position in the World.
  17278. */
  17279. Light.prototype.getAbsolutePosition = function () {
  17280. return BABYLON.Vector3.Zero();
  17281. };
  17282. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17283. };
  17284. Light.prototype._getWorldMatrix = function () {
  17285. return BABYLON.Matrix.Identity();
  17286. };
  17287. /**
  17288. * Boolean : True if the light will affect the passed mesh.
  17289. */
  17290. Light.prototype.canAffectMesh = function (mesh) {
  17291. if (!mesh) {
  17292. return true;
  17293. }
  17294. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17295. return false;
  17296. }
  17297. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17298. return false;
  17299. }
  17300. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17301. return false;
  17302. }
  17303. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17304. return false;
  17305. }
  17306. return true;
  17307. };
  17308. /**
  17309. * Returns the light World matrix.
  17310. */
  17311. Light.prototype.getWorldMatrix = function () {
  17312. this._currentRenderId = this.getScene().getRenderId();
  17313. var worldMatrix = this._getWorldMatrix();
  17314. if (this.parent && this.parent.getWorldMatrix) {
  17315. if (!this._parentedWorldMatrix) {
  17316. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17317. }
  17318. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17319. this._markSyncedWithParent();
  17320. return this._parentedWorldMatrix;
  17321. }
  17322. return worldMatrix;
  17323. };
  17324. /**
  17325. * Sort function to order lights for rendering.
  17326. * @param a First Light object to compare to second.
  17327. * @param b Second Light object to compare first.
  17328. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17329. */
  17330. Light.compareLightsPriority = function (a, b) {
  17331. //shadow-casting lights have priority over non-shadow-casting lights
  17332. //the renderPrioirty is a secondary sort criterion
  17333. if (a.shadowEnabled !== b.shadowEnabled) {
  17334. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17335. }
  17336. return b.renderPriority - a.renderPriority;
  17337. };
  17338. /**
  17339. * Disposes the light.
  17340. */
  17341. Light.prototype.dispose = function () {
  17342. if (this._shadowGenerator) {
  17343. this._shadowGenerator.dispose();
  17344. this._shadowGenerator = null;
  17345. }
  17346. // Animations
  17347. this.getScene().stopAnimation(this);
  17348. this._uniformBuffer.dispose();
  17349. // Remove from scene
  17350. this.getScene().removeLight(this);
  17351. _super.prototype.dispose.call(this);
  17352. };
  17353. /**
  17354. * Returns the light type ID (integer).
  17355. */
  17356. Light.prototype.getTypeID = function () {
  17357. return 0;
  17358. };
  17359. /**
  17360. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17361. */
  17362. Light.prototype.getScaledIntensity = function () {
  17363. return this._photometricScale * this.intensity;
  17364. };
  17365. /**
  17366. * Returns a new Light object, named "name", from the current one.
  17367. */
  17368. Light.prototype.clone = function (name) {
  17369. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17370. if (!constructor) {
  17371. return null;
  17372. }
  17373. return BABYLON.SerializationHelper.Clone(constructor, this);
  17374. };
  17375. /**
  17376. * Serializes the current light into a Serialization object.
  17377. * Returns the serialized object.
  17378. */
  17379. Light.prototype.serialize = function () {
  17380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17381. // Type
  17382. serializationObject.type = this.getTypeID();
  17383. // Parent
  17384. if (this.parent) {
  17385. serializationObject.parentId = this.parent.id;
  17386. }
  17387. // Inclusion / exclusions
  17388. if (this.excludedMeshes.length > 0) {
  17389. serializationObject.excludedMeshesIds = [];
  17390. this.excludedMeshes.forEach(function (mesh) {
  17391. serializationObject.excludedMeshesIds.push(mesh.id);
  17392. });
  17393. }
  17394. if (this.includedOnlyMeshes.length > 0) {
  17395. serializationObject.includedOnlyMeshesIds = [];
  17396. this.includedOnlyMeshes.forEach(function (mesh) {
  17397. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17398. });
  17399. }
  17400. // Animations
  17401. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17402. serializationObject.ranges = this.serializeAnimationRanges();
  17403. return serializationObject;
  17404. };
  17405. /**
  17406. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17407. * This new light is named "name" and added to the passed scene.
  17408. */
  17409. Light.GetConstructorFromName = function (type, name, scene) {
  17410. switch (type) {
  17411. case 0:
  17412. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17413. case 1:
  17414. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17415. case 2:
  17416. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17417. case 3:
  17418. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17419. }
  17420. return null;
  17421. };
  17422. /**
  17423. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17424. */
  17425. Light.Parse = function (parsedLight, scene) {
  17426. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17427. if (!constructor) {
  17428. return null;
  17429. }
  17430. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17431. // Inclusion / exclusions
  17432. if (parsedLight.excludedMeshesIds) {
  17433. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17434. }
  17435. if (parsedLight.includedOnlyMeshesIds) {
  17436. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17437. }
  17438. // Parent
  17439. if (parsedLight.parentId) {
  17440. light._waitingParentId = parsedLight.parentId;
  17441. }
  17442. // Animations
  17443. if (parsedLight.animations) {
  17444. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17445. var parsedAnimation = parsedLight.animations[animationIndex];
  17446. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17447. }
  17448. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17449. }
  17450. if (parsedLight.autoAnimate) {
  17451. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17452. }
  17453. return light;
  17454. };
  17455. Light.prototype._hookArrayForExcluded = function (array) {
  17456. var _this = this;
  17457. var oldPush = array.push;
  17458. array.push = function () {
  17459. var items = [];
  17460. for (var _i = 0; _i < arguments.length; _i++) {
  17461. items[_i] = arguments[_i];
  17462. }
  17463. var result = oldPush.apply(array, items);
  17464. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17465. var item = items_1[_a];
  17466. item._resyncLighSource(_this);
  17467. }
  17468. return result;
  17469. };
  17470. var oldSplice = array.splice;
  17471. array.splice = function (index, deleteCount) {
  17472. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17473. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17474. var item = deleted_1[_i];
  17475. item._resyncLighSource(_this);
  17476. }
  17477. return deleted;
  17478. };
  17479. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17480. var item = array_1[_i];
  17481. item._resyncLighSource(this);
  17482. }
  17483. };
  17484. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17485. var _this = this;
  17486. var oldPush = array.push;
  17487. array.push = function () {
  17488. var items = [];
  17489. for (var _i = 0; _i < arguments.length; _i++) {
  17490. items[_i] = arguments[_i];
  17491. }
  17492. var result = oldPush.apply(array, items);
  17493. _this._resyncMeshes();
  17494. return result;
  17495. };
  17496. var oldSplice = array.splice;
  17497. array.splice = function (index, deleteCount) {
  17498. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17499. _this._resyncMeshes();
  17500. return deleted;
  17501. };
  17502. this._resyncMeshes();
  17503. };
  17504. Light.prototype._resyncMeshes = function () {
  17505. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17506. var mesh = _a[_i];
  17507. mesh._resyncLighSource(this);
  17508. }
  17509. };
  17510. Light.prototype._markMeshesAsLightDirty = function () {
  17511. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17512. var mesh = _a[_i];
  17513. if (mesh._lightSources.indexOf(this) !== -1) {
  17514. mesh._markSubMeshesAsLightDirty();
  17515. }
  17516. }
  17517. };
  17518. /**
  17519. * Recomputes the cached photometric scale if needed.
  17520. */
  17521. Light.prototype._computePhotometricScale = function () {
  17522. this._photometricScale = this._getPhotometricScale();
  17523. this.getScene().resetCachedMaterial();
  17524. };
  17525. /**
  17526. * Returns the Photometric Scale according to the light type and intensity mode.
  17527. */
  17528. Light.prototype._getPhotometricScale = function () {
  17529. var photometricScale = 0.0;
  17530. var lightTypeID = this.getTypeID();
  17531. //get photometric mode
  17532. var photometricMode = this.intensityMode;
  17533. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17534. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17535. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17536. }
  17537. else {
  17538. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17539. }
  17540. }
  17541. //compute photometric scale
  17542. switch (lightTypeID) {
  17543. case Light.LIGHTTYPEID_POINTLIGHT:
  17544. case Light.LIGHTTYPEID_SPOTLIGHT:
  17545. switch (photometricMode) {
  17546. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17547. photometricScale = 1.0 / (4.0 * Math.PI);
  17548. break;
  17549. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17550. photometricScale = 1.0;
  17551. break;
  17552. case Light.INTENSITYMODE_LUMINANCE:
  17553. photometricScale = this.radius * this.radius;
  17554. break;
  17555. }
  17556. break;
  17557. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17558. switch (photometricMode) {
  17559. case Light.INTENSITYMODE_ILLUMINANCE:
  17560. photometricScale = 1.0;
  17561. break;
  17562. case Light.INTENSITYMODE_LUMINANCE:
  17563. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17564. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17565. var apexAngleRadians = this.radius;
  17566. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17567. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17568. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17569. photometricScale = solidAngle;
  17570. break;
  17571. }
  17572. break;
  17573. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17574. // No fall off in hemisperic light.
  17575. photometricScale = 1.0;
  17576. break;
  17577. }
  17578. return photometricScale;
  17579. };
  17580. Light.prototype._reorderLightsInScene = function () {
  17581. var scene = this.getScene();
  17582. if (this._renderPriority != 0) {
  17583. scene.requireLightSorting = true;
  17584. }
  17585. this.getScene().sortLightsByPriority();
  17586. };
  17587. //lightmapMode Consts
  17588. Light._LIGHTMAP_DEFAULT = 0;
  17589. Light._LIGHTMAP_SPECULAR = 1;
  17590. Light._LIGHTMAP_SHADOWSONLY = 2;
  17591. // Intensity Mode Consts
  17592. Light._INTENSITYMODE_AUTOMATIC = 0;
  17593. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17594. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17595. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17596. Light._INTENSITYMODE_LUMINANCE = 4;
  17597. // Light types ids const.
  17598. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17599. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17600. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17601. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17602. __decorate([
  17603. BABYLON.serializeAsColor3()
  17604. ], Light.prototype, "diffuse", void 0);
  17605. __decorate([
  17606. BABYLON.serializeAsColor3()
  17607. ], Light.prototype, "specular", void 0);
  17608. __decorate([
  17609. BABYLON.serialize()
  17610. ], Light.prototype, "intensity", void 0);
  17611. __decorate([
  17612. BABYLON.serialize()
  17613. ], Light.prototype, "range", void 0);
  17614. __decorate([
  17615. BABYLON.serialize()
  17616. ], Light.prototype, "intensityMode", null);
  17617. __decorate([
  17618. BABYLON.serialize()
  17619. ], Light.prototype, "radius", null);
  17620. __decorate([
  17621. BABYLON.serialize()
  17622. ], Light.prototype, "_renderPriority", void 0);
  17623. __decorate([
  17624. BABYLON.expandToProperty("_reorderLightsInScene")
  17625. ], Light.prototype, "renderPriority", void 0);
  17626. __decorate([
  17627. BABYLON.serialize()
  17628. ], Light.prototype, "shadowEnabled", void 0);
  17629. __decorate([
  17630. BABYLON.serialize("excludeWithLayerMask")
  17631. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17632. __decorate([
  17633. BABYLON.serialize("includeOnlyWithLayerMask")
  17634. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17635. __decorate([
  17636. BABYLON.serialize("lightmapMode")
  17637. ], Light.prototype, "_lightmapMode", void 0);
  17638. return Light;
  17639. }(BABYLON.Node));
  17640. BABYLON.Light = Light;
  17641. })(BABYLON || (BABYLON = {}));
  17642. //# sourceMappingURL=babylon.light.js.map
  17643. var BABYLON;
  17644. (function (BABYLON) {
  17645. var Camera = /** @class */ (function (_super) {
  17646. __extends(Camera, _super);
  17647. function Camera(name, position, scene) {
  17648. var _this = _super.call(this, name, scene) || this;
  17649. _this.upVector = BABYLON.Vector3.Up();
  17650. _this.orthoLeft = null;
  17651. _this.orthoRight = null;
  17652. _this.orthoBottom = null;
  17653. _this.orthoTop = null;
  17654. /**
  17655. * default : 0.8
  17656. * FOV is set in Radians.
  17657. */
  17658. _this.fov = 0.8;
  17659. _this.minZ = 1;
  17660. _this.maxZ = 10000.0;
  17661. _this.inertia = 0.9;
  17662. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17663. _this.isIntermediate = false;
  17664. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17665. /**
  17666. * Restricts the camera to viewing objects with the same layerMask.
  17667. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17668. */
  17669. _this.layerMask = 0x0FFFFFFF;
  17670. /**
  17671. * default : FOVMODE_VERTICAL_FIXED
  17672. * fovMode sets the camera frustum bounds to the viewport bounds.
  17673. */
  17674. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17675. // Camera rig members
  17676. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17677. _this._rigCameras = new Array();
  17678. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17679. _this._skipRendering = false;
  17680. _this.customRenderTargets = new Array();
  17681. // Observables
  17682. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17683. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17684. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17685. _this.onRestoreStateObservable = new BABYLON.Observable();
  17686. // Cache
  17687. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17688. _this._projectionMatrix = new BABYLON.Matrix();
  17689. _this._doNotComputeProjectionMatrix = false;
  17690. _this._postProcesses = new Array();
  17691. _this._transformMatrix = BABYLON.Matrix.Zero();
  17692. _this._activeMeshes = new BABYLON.SmartArray(256);
  17693. _this._globalPosition = BABYLON.Vector3.Zero();
  17694. _this._refreshFrustumPlanes = true;
  17695. _this.getScene().addCamera(_this);
  17696. if (!_this.getScene().activeCamera) {
  17697. _this.getScene().activeCamera = _this;
  17698. }
  17699. _this.position = position;
  17700. return _this;
  17701. }
  17702. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17703. get: function () {
  17704. return Camera._PERSPECTIVE_CAMERA;
  17705. },
  17706. enumerable: true,
  17707. configurable: true
  17708. });
  17709. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17710. get: function () {
  17711. return Camera._ORTHOGRAPHIC_CAMERA;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17717. /**
  17718. * This is the default FOV mode for perspective cameras.
  17719. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17720. *
  17721. */
  17722. get: function () {
  17723. return Camera._FOVMODE_VERTICAL_FIXED;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17729. /**
  17730. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17731. *
  17732. */
  17733. get: function () {
  17734. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17740. get: function () {
  17741. return Camera._RIG_MODE_NONE;
  17742. },
  17743. enumerable: true,
  17744. configurable: true
  17745. });
  17746. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17747. get: function () {
  17748. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17754. get: function () {
  17755. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17761. get: function () {
  17762. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17768. get: function () {
  17769. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17775. get: function () {
  17776. return Camera._RIG_MODE_VR;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17782. get: function () {
  17783. return Camera._RIG_MODE_WEBVR;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. /**
  17789. * Store current camera state (fov, position, etc..)
  17790. */
  17791. Camera.prototype.storeState = function () {
  17792. this._stateStored = true;
  17793. this._storedFov = this.fov;
  17794. return this;
  17795. };
  17796. /**
  17797. * Restores the camera state values if it has been stored. You must call storeState() first
  17798. */
  17799. Camera.prototype._restoreStateValues = function () {
  17800. if (!this._stateStored) {
  17801. return false;
  17802. }
  17803. this.fov = this._storedFov;
  17804. return true;
  17805. };
  17806. /**
  17807. * Restored camera state. You must call storeState() first
  17808. */
  17809. Camera.prototype.restoreState = function () {
  17810. if (this._restoreStateValues()) {
  17811. this.onRestoreStateObservable.notifyObservers(this);
  17812. return true;
  17813. }
  17814. return false;
  17815. };
  17816. Camera.prototype.getClassName = function () {
  17817. return "Camera";
  17818. };
  17819. /**
  17820. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17821. */
  17822. Camera.prototype.toString = function (fullDetails) {
  17823. var ret = "Name: " + this.name;
  17824. ret += ", type: " + this.getClassName();
  17825. if (this.animations) {
  17826. for (var i = 0; i < this.animations.length; i++) {
  17827. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17828. }
  17829. }
  17830. if (fullDetails) {
  17831. }
  17832. return ret;
  17833. };
  17834. Object.defineProperty(Camera.prototype, "globalPosition", {
  17835. get: function () {
  17836. return this._globalPosition;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Camera.prototype.getActiveMeshes = function () {
  17842. return this._activeMeshes;
  17843. };
  17844. Camera.prototype.isActiveMesh = function (mesh) {
  17845. return (this._activeMeshes.indexOf(mesh) !== -1);
  17846. };
  17847. //Cache
  17848. Camera.prototype._initCache = function () {
  17849. _super.prototype._initCache.call(this);
  17850. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17851. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17852. this._cache.mode = undefined;
  17853. this._cache.minZ = undefined;
  17854. this._cache.maxZ = undefined;
  17855. this._cache.fov = undefined;
  17856. this._cache.fovMode = undefined;
  17857. this._cache.aspectRatio = undefined;
  17858. this._cache.orthoLeft = undefined;
  17859. this._cache.orthoRight = undefined;
  17860. this._cache.orthoBottom = undefined;
  17861. this._cache.orthoTop = undefined;
  17862. this._cache.renderWidth = undefined;
  17863. this._cache.renderHeight = undefined;
  17864. };
  17865. Camera.prototype._updateCache = function (ignoreParentClass) {
  17866. if (!ignoreParentClass) {
  17867. _super.prototype._updateCache.call(this);
  17868. }
  17869. this._cache.position.copyFrom(this.position);
  17870. this._cache.upVector.copyFrom(this.upVector);
  17871. };
  17872. // Synchronized
  17873. Camera.prototype._isSynchronized = function () {
  17874. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17875. };
  17876. Camera.prototype._isSynchronizedViewMatrix = function () {
  17877. if (!_super.prototype._isSynchronized.call(this))
  17878. return false;
  17879. return this._cache.position.equals(this.position)
  17880. && this._cache.upVector.equals(this.upVector)
  17881. && this.isSynchronizedWithParent();
  17882. };
  17883. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17884. var check = this._cache.mode === this.mode
  17885. && this._cache.minZ === this.minZ
  17886. && this._cache.maxZ === this.maxZ;
  17887. if (!check) {
  17888. return false;
  17889. }
  17890. var engine = this.getEngine();
  17891. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17892. check = this._cache.fov === this.fov
  17893. && this._cache.fovMode === this.fovMode
  17894. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17895. }
  17896. else {
  17897. check = this._cache.orthoLeft === this.orthoLeft
  17898. && this._cache.orthoRight === this.orthoRight
  17899. && this._cache.orthoBottom === this.orthoBottom
  17900. && this._cache.orthoTop === this.orthoTop
  17901. && this._cache.renderWidth === engine.getRenderWidth()
  17902. && this._cache.renderHeight === engine.getRenderHeight();
  17903. }
  17904. return check;
  17905. };
  17906. // Controls
  17907. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17908. };
  17909. Camera.prototype.detachControl = function (element) {
  17910. };
  17911. Camera.prototype.update = function () {
  17912. this._checkInputs();
  17913. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17914. this._updateRigCameras();
  17915. }
  17916. };
  17917. Camera.prototype._checkInputs = function () {
  17918. this.onAfterCheckInputsObservable.notifyObservers(this);
  17919. };
  17920. Object.defineProperty(Camera.prototype, "rigCameras", {
  17921. get: function () {
  17922. return this._rigCameras;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17928. get: function () {
  17929. return this._rigPostProcess;
  17930. },
  17931. enumerable: true,
  17932. configurable: true
  17933. });
  17934. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17935. // invalidate framebuffer
  17936. if (this._postProcesses.length > 0) {
  17937. this._postProcesses[0].markTextureDirty();
  17938. }
  17939. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17940. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17941. var cam = this._rigCameras[i];
  17942. var rigPostProcess = cam._rigPostProcess;
  17943. // for VR rig, there does not have to be a post process
  17944. if (rigPostProcess) {
  17945. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17946. if (isPass) {
  17947. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17948. cam.isIntermediate = this._postProcesses.length === 0;
  17949. }
  17950. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17951. rigPostProcess.markTextureDirty();
  17952. }
  17953. else {
  17954. cam._postProcesses = this._postProcesses.slice(0);
  17955. }
  17956. }
  17957. };
  17958. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17959. if (insertAt === void 0) { insertAt = null; }
  17960. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17961. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17962. return 0;
  17963. }
  17964. if (insertAt == null || insertAt < 0) {
  17965. this._postProcesses.push(postProcess);
  17966. }
  17967. else {
  17968. this._postProcesses.splice(insertAt, 0, postProcess);
  17969. }
  17970. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17971. return this._postProcesses.indexOf(postProcess);
  17972. };
  17973. Camera.prototype.detachPostProcess = function (postProcess) {
  17974. var idx = this._postProcesses.indexOf(postProcess);
  17975. if (idx !== -1) {
  17976. this._postProcesses.splice(idx, 1);
  17977. }
  17978. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17979. };
  17980. Camera.prototype.getWorldMatrix = function () {
  17981. if (!this._worldMatrix) {
  17982. this._worldMatrix = BABYLON.Matrix.Identity();
  17983. }
  17984. var viewMatrix = this.getViewMatrix();
  17985. viewMatrix.invertToRef(this._worldMatrix);
  17986. return this._worldMatrix;
  17987. };
  17988. Camera.prototype._getViewMatrix = function () {
  17989. return BABYLON.Matrix.Identity();
  17990. };
  17991. Camera.prototype.getViewMatrix = function (force) {
  17992. if (!force && this._isSynchronizedViewMatrix()) {
  17993. return this._computedViewMatrix;
  17994. }
  17995. this.updateCache();
  17996. this._computedViewMatrix = this._getViewMatrix();
  17997. this._currentRenderId = this.getScene().getRenderId();
  17998. this._refreshFrustumPlanes = true;
  17999. if (!this.parent || !this.parent.getWorldMatrix) {
  18000. this._globalPosition.copyFrom(this.position);
  18001. }
  18002. else {
  18003. if (!this._worldMatrix) {
  18004. this._worldMatrix = BABYLON.Matrix.Identity();
  18005. }
  18006. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18007. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18008. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18009. this._computedViewMatrix.invert();
  18010. this._markSyncedWithParent();
  18011. }
  18012. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18013. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18014. }
  18015. this.onViewMatrixChangedObservable.notifyObservers(this);
  18016. return this._computedViewMatrix;
  18017. };
  18018. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18019. this._doNotComputeProjectionMatrix = true;
  18020. if (projection !== undefined) {
  18021. this._projectionMatrix = projection;
  18022. }
  18023. };
  18024. ;
  18025. Camera.prototype.unfreezeProjectionMatrix = function () {
  18026. this._doNotComputeProjectionMatrix = false;
  18027. };
  18028. ;
  18029. Camera.prototype.getProjectionMatrix = function (force) {
  18030. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18031. return this._projectionMatrix;
  18032. }
  18033. // Cache
  18034. this._cache.mode = this.mode;
  18035. this._cache.minZ = this.minZ;
  18036. this._cache.maxZ = this.maxZ;
  18037. // Matrix
  18038. this._refreshFrustumPlanes = true;
  18039. var engine = this.getEngine();
  18040. var scene = this.getScene();
  18041. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18042. this._cache.fov = this.fov;
  18043. this._cache.fovMode = this.fovMode;
  18044. this._cache.aspectRatio = engine.getAspectRatio(this);
  18045. if (this.minZ <= 0) {
  18046. this.minZ = 0.1;
  18047. }
  18048. if (scene.useRightHandedSystem) {
  18049. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18050. }
  18051. else {
  18052. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18053. }
  18054. }
  18055. else {
  18056. var halfWidth = engine.getRenderWidth() / 2.0;
  18057. var halfHeight = engine.getRenderHeight() / 2.0;
  18058. if (scene.useRightHandedSystem) {
  18059. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18060. }
  18061. else {
  18062. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18063. }
  18064. this._cache.orthoLeft = this.orthoLeft;
  18065. this._cache.orthoRight = this.orthoRight;
  18066. this._cache.orthoBottom = this.orthoBottom;
  18067. this._cache.orthoTop = this.orthoTop;
  18068. this._cache.renderWidth = engine.getRenderWidth();
  18069. this._cache.renderHeight = engine.getRenderHeight();
  18070. }
  18071. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18072. return this._projectionMatrix;
  18073. };
  18074. Camera.prototype.getTranformationMatrix = function () {
  18075. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18076. return this._transformMatrix;
  18077. };
  18078. Camera.prototype.updateFrustumPlanes = function () {
  18079. if (!this._refreshFrustumPlanes) {
  18080. return;
  18081. }
  18082. this.getTranformationMatrix();
  18083. if (!this._frustumPlanes) {
  18084. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18085. }
  18086. else {
  18087. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18088. }
  18089. this._refreshFrustumPlanes = false;
  18090. };
  18091. Camera.prototype.isInFrustum = function (target) {
  18092. this.updateFrustumPlanes();
  18093. return target.isInFrustum(this._frustumPlanes);
  18094. };
  18095. Camera.prototype.isCompletelyInFrustum = function (target) {
  18096. this.updateFrustumPlanes();
  18097. return target.isCompletelyInFrustum(this._frustumPlanes);
  18098. };
  18099. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18100. if (length === void 0) { length = 100; }
  18101. if (!transform) {
  18102. transform = this.getWorldMatrix();
  18103. }
  18104. if (!origin) {
  18105. origin = this.position;
  18106. }
  18107. var forward = new BABYLON.Vector3(0, 0, 1);
  18108. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18109. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18110. return new BABYLON.Ray(origin, direction, length);
  18111. };
  18112. Camera.prototype.dispose = function () {
  18113. // Observables
  18114. this.onViewMatrixChangedObservable.clear();
  18115. this.onProjectionMatrixChangedObservable.clear();
  18116. this.onAfterCheckInputsObservable.clear();
  18117. this.onRestoreStateObservable.clear();
  18118. // Inputs
  18119. if (this.inputs) {
  18120. this.inputs.clear();
  18121. }
  18122. // Animations
  18123. this.getScene().stopAnimation(this);
  18124. // Remove from scene
  18125. this.getScene().removeCamera(this);
  18126. while (this._rigCameras.length > 0) {
  18127. var camera = this._rigCameras.pop();
  18128. if (camera) {
  18129. camera.dispose();
  18130. }
  18131. }
  18132. // Postprocesses
  18133. if (this._rigPostProcess) {
  18134. this._rigPostProcess.dispose(this);
  18135. this._rigPostProcess = null;
  18136. this._postProcesses = [];
  18137. }
  18138. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18139. this._rigPostProcess = null;
  18140. this._postProcesses = [];
  18141. }
  18142. else {
  18143. var i = this._postProcesses.length;
  18144. while (--i >= 0) {
  18145. this._postProcesses[i].dispose(this);
  18146. }
  18147. }
  18148. // Render targets
  18149. var i = this.customRenderTargets.length;
  18150. while (--i >= 0) {
  18151. this.customRenderTargets[i].dispose();
  18152. }
  18153. this.customRenderTargets = [];
  18154. // Active Meshes
  18155. this._activeMeshes.dispose();
  18156. _super.prototype.dispose.call(this);
  18157. };
  18158. Object.defineProperty(Camera.prototype, "leftCamera", {
  18159. // ---- Camera rigs section ----
  18160. get: function () {
  18161. if (this._rigCameras.length < 1) {
  18162. return null;
  18163. }
  18164. return this._rigCameras[0];
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. Object.defineProperty(Camera.prototype, "rightCamera", {
  18170. get: function () {
  18171. if (this._rigCameras.length < 2) {
  18172. return null;
  18173. }
  18174. return this._rigCameras[1];
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. Camera.prototype.getLeftTarget = function () {
  18180. if (this._rigCameras.length < 1) {
  18181. return null;
  18182. }
  18183. return this._rigCameras[0].getTarget();
  18184. };
  18185. Camera.prototype.getRightTarget = function () {
  18186. if (this._rigCameras.length < 2) {
  18187. return null;
  18188. }
  18189. return this._rigCameras[1].getTarget();
  18190. };
  18191. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18192. if (this.cameraRigMode === mode) {
  18193. return;
  18194. }
  18195. while (this._rigCameras.length > 0) {
  18196. var camera = this._rigCameras.pop();
  18197. if (camera) {
  18198. camera.dispose();
  18199. }
  18200. }
  18201. this.cameraRigMode = mode;
  18202. this._cameraRigParams = {};
  18203. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18204. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18205. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18206. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18207. // create the rig cameras, unless none
  18208. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18209. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18210. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18211. if (leftCamera && rightCamera) {
  18212. this._rigCameras.push(leftCamera);
  18213. this._rigCameras.push(rightCamera);
  18214. }
  18215. }
  18216. switch (this.cameraRigMode) {
  18217. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18218. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18219. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18220. break;
  18221. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18222. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18223. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18224. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18225. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18226. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18227. break;
  18228. case Camera.RIG_MODE_VR:
  18229. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18230. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18231. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18232. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18233. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18234. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18235. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18236. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18237. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18238. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18239. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18240. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18241. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18242. if (metrics.compensateDistortion) {
  18243. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18244. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18245. }
  18246. break;
  18247. case Camera.RIG_MODE_WEBVR:
  18248. if (rigParams.vrDisplay) {
  18249. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18250. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18251. //Left eye
  18252. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18253. this._rigCameras[0].setCameraRigParameter("left", true);
  18254. //leaving this for future reference
  18255. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18256. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18257. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18258. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18259. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18260. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18261. this._rigCameras[0].parent = this;
  18262. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18263. //Right eye
  18264. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18265. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18266. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18267. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18268. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18269. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18270. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18271. this._rigCameras[1].parent = this;
  18272. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18273. if (Camera.UseAlternateWebVRRendering) {
  18274. this._rigCameras[1]._skipRendering = true;
  18275. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18276. }
  18277. }
  18278. break;
  18279. }
  18280. this._cascadePostProcessesToRigCams();
  18281. this.update();
  18282. };
  18283. Camera.prototype._getVRProjectionMatrix = function () {
  18284. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18285. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18286. return this._projectionMatrix;
  18287. };
  18288. Camera.prototype._updateCameraRotationMatrix = function () {
  18289. //Here for WebVR
  18290. };
  18291. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18292. //Here for WebVR
  18293. };
  18294. /**
  18295. * This function MUST be overwritten by the different WebVR cameras available.
  18296. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18297. */
  18298. Camera.prototype._getWebVRProjectionMatrix = function () {
  18299. return BABYLON.Matrix.Identity();
  18300. };
  18301. /**
  18302. * This function MUST be overwritten by the different WebVR cameras available.
  18303. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18304. */
  18305. Camera.prototype._getWebVRViewMatrix = function () {
  18306. return BABYLON.Matrix.Identity();
  18307. };
  18308. Camera.prototype.setCameraRigParameter = function (name, value) {
  18309. if (!this._cameraRigParams) {
  18310. this._cameraRigParams = {};
  18311. }
  18312. this._cameraRigParams[name] = value;
  18313. //provisionnally:
  18314. if (name === "interaxialDistance") {
  18315. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18316. }
  18317. };
  18318. /**
  18319. * needs to be overridden by children so sub has required properties to be copied
  18320. */
  18321. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18322. return null;
  18323. };
  18324. /**
  18325. * May need to be overridden by children
  18326. */
  18327. Camera.prototype._updateRigCameras = function () {
  18328. for (var i = 0; i < this._rigCameras.length; i++) {
  18329. this._rigCameras[i].minZ = this.minZ;
  18330. this._rigCameras[i].maxZ = this.maxZ;
  18331. this._rigCameras[i].fov = this.fov;
  18332. }
  18333. // only update viewport when ANAGLYPH
  18334. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18335. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18336. }
  18337. };
  18338. Camera.prototype._setupInputs = function () {
  18339. };
  18340. Camera.prototype.serialize = function () {
  18341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18342. // Type
  18343. serializationObject.type = this.getClassName();
  18344. // Parent
  18345. if (this.parent) {
  18346. serializationObject.parentId = this.parent.id;
  18347. }
  18348. if (this.inputs) {
  18349. this.inputs.serialize(serializationObject);
  18350. }
  18351. // Animations
  18352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18353. serializationObject.ranges = this.serializeAnimationRanges();
  18354. return serializationObject;
  18355. };
  18356. Camera.prototype.clone = function (name) {
  18357. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18358. };
  18359. Camera.prototype.getDirection = function (localAxis) {
  18360. var result = BABYLON.Vector3.Zero();
  18361. this.getDirectionToRef(localAxis, result);
  18362. return result;
  18363. };
  18364. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18365. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18366. };
  18367. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18368. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18369. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18370. switch (type) {
  18371. case "ArcRotateCamera":
  18372. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18373. case "DeviceOrientationCamera":
  18374. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18375. case "FollowCamera":
  18376. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18377. case "ArcFollowCamera":
  18378. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18379. case "GamepadCamera":
  18380. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18381. case "TouchCamera":
  18382. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18383. case "VirtualJoysticksCamera":
  18384. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18385. case "WebVRFreeCamera":
  18386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18387. case "WebVRGamepadCamera":
  18388. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18389. case "VRDeviceOrientationFreeCamera":
  18390. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18391. case "VRDeviceOrientationGamepadCamera":
  18392. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18393. case "AnaglyphArcRotateCamera":
  18394. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18395. case "AnaglyphFreeCamera":
  18396. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18397. case "AnaglyphGamepadCamera":
  18398. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18399. case "AnaglyphUniversalCamera":
  18400. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18401. case "StereoscopicArcRotateCamera":
  18402. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18403. case "StereoscopicFreeCamera":
  18404. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18405. case "StereoscopicGamepadCamera":
  18406. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18407. case "StereoscopicUniversalCamera":
  18408. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18409. case "FreeCamera":// Forcing Universal here
  18410. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. default:// Universal Camera is the default value
  18412. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18413. }
  18414. };
  18415. Camera.prototype.computeWorldMatrix = function () {
  18416. return this.getWorldMatrix();
  18417. };
  18418. Camera.Parse = function (parsedCamera, scene) {
  18419. var type = parsedCamera.type;
  18420. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18421. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18422. // Parent
  18423. if (parsedCamera.parentId) {
  18424. camera._waitingParentId = parsedCamera.parentId;
  18425. }
  18426. //If camera has an input manager, let it parse inputs settings
  18427. if (camera.inputs) {
  18428. camera.inputs.parse(parsedCamera);
  18429. camera._setupInputs();
  18430. }
  18431. if (camera.setPosition) {
  18432. camera.position.copyFromFloats(0, 0, 0);
  18433. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18434. }
  18435. // Target
  18436. if (parsedCamera.target) {
  18437. if (camera.setTarget) {
  18438. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18439. }
  18440. }
  18441. // Apply 3d rig, when found
  18442. if (parsedCamera.cameraRigMode) {
  18443. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18444. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18445. }
  18446. // Animations
  18447. if (parsedCamera.animations) {
  18448. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18449. var parsedAnimation = parsedCamera.animations[animationIndex];
  18450. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18451. }
  18452. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18453. }
  18454. if (parsedCamera.autoAnimate) {
  18455. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18456. }
  18457. return camera;
  18458. };
  18459. // Statics
  18460. Camera._PERSPECTIVE_CAMERA = 0;
  18461. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18462. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18463. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18464. Camera._RIG_MODE_NONE = 0;
  18465. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18466. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18467. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18468. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18469. Camera._RIG_MODE_VR = 20;
  18470. Camera._RIG_MODE_WEBVR = 21;
  18471. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18472. Camera.UseAlternateWebVRRendering = false;
  18473. __decorate([
  18474. BABYLON.serializeAsVector3()
  18475. ], Camera.prototype, "position", void 0);
  18476. __decorate([
  18477. BABYLON.serializeAsVector3()
  18478. ], Camera.prototype, "upVector", void 0);
  18479. __decorate([
  18480. BABYLON.serialize()
  18481. ], Camera.prototype, "orthoLeft", void 0);
  18482. __decorate([
  18483. BABYLON.serialize()
  18484. ], Camera.prototype, "orthoRight", void 0);
  18485. __decorate([
  18486. BABYLON.serialize()
  18487. ], Camera.prototype, "orthoBottom", void 0);
  18488. __decorate([
  18489. BABYLON.serialize()
  18490. ], Camera.prototype, "orthoTop", void 0);
  18491. __decorate([
  18492. BABYLON.serialize()
  18493. ], Camera.prototype, "fov", void 0);
  18494. __decorate([
  18495. BABYLON.serialize()
  18496. ], Camera.prototype, "minZ", void 0);
  18497. __decorate([
  18498. BABYLON.serialize()
  18499. ], Camera.prototype, "maxZ", void 0);
  18500. __decorate([
  18501. BABYLON.serialize()
  18502. ], Camera.prototype, "inertia", void 0);
  18503. __decorate([
  18504. BABYLON.serialize()
  18505. ], Camera.prototype, "mode", void 0);
  18506. __decorate([
  18507. BABYLON.serialize()
  18508. ], Camera.prototype, "layerMask", void 0);
  18509. __decorate([
  18510. BABYLON.serialize()
  18511. ], Camera.prototype, "fovMode", void 0);
  18512. __decorate([
  18513. BABYLON.serialize()
  18514. ], Camera.prototype, "cameraRigMode", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], Camera.prototype, "interaxialDistance", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18521. return Camera;
  18522. }(BABYLON.Node));
  18523. BABYLON.Camera = Camera;
  18524. })(BABYLON || (BABYLON = {}));
  18525. //# sourceMappingURL=babylon.camera.js.map
  18526. var BABYLON;
  18527. (function (BABYLON) {
  18528. var RenderingManager = /** @class */ (function () {
  18529. function RenderingManager(scene) {
  18530. this._renderingGroups = new Array();
  18531. this._autoClearDepthStencil = {};
  18532. this._customOpaqueSortCompareFn = {};
  18533. this._customAlphaTestSortCompareFn = {};
  18534. this._customTransparentSortCompareFn = {};
  18535. this._renderinGroupInfo = null;
  18536. this._scene = scene;
  18537. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18538. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18539. }
  18540. }
  18541. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18542. if (depth === void 0) { depth = true; }
  18543. if (stencil === void 0) { stencil = true; }
  18544. if (this._depthStencilBufferAlreadyCleaned) {
  18545. return;
  18546. }
  18547. this._scene.getEngine().clear(null, false, depth, stencil);
  18548. this._depthStencilBufferAlreadyCleaned = true;
  18549. };
  18550. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18551. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18552. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18553. var info = null;
  18554. if (observable) {
  18555. if (!this._renderinGroupInfo) {
  18556. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18557. }
  18558. info = this._renderinGroupInfo;
  18559. info.scene = this._scene;
  18560. info.camera = this._scene.activeCamera;
  18561. }
  18562. // Dispatch sprites
  18563. if (renderSprites) {
  18564. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18565. var manager = this._scene.spriteManagers[index];
  18566. this.dispatchSprites(manager);
  18567. }
  18568. }
  18569. // Render
  18570. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18571. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18572. var renderingGroup = this._renderingGroups[index];
  18573. if (!renderingGroup && !observable)
  18574. continue;
  18575. var renderingGroupMask = 0;
  18576. // Fire PRECLEAR stage
  18577. if (observable && info) {
  18578. renderingGroupMask = Math.pow(2, index);
  18579. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18580. info.renderingGroupId = index;
  18581. observable.notifyObservers(info, renderingGroupMask);
  18582. }
  18583. // Clear depth/stencil if needed
  18584. if (RenderingManager.AUTOCLEAR) {
  18585. var autoClear = this._autoClearDepthStencil[index];
  18586. if (autoClear && autoClear.autoClear) {
  18587. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18588. }
  18589. }
  18590. if (observable && info) {
  18591. // Fire PREOPAQUE stage
  18592. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18593. observable.notifyObservers(info, renderingGroupMask);
  18594. // Fire PRETRANSPARENT stage
  18595. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18596. observable.notifyObservers(info, renderingGroupMask);
  18597. }
  18598. if (renderingGroup)
  18599. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18600. // Fire POSTTRANSPARENT stage
  18601. if (observable && info) {
  18602. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18603. observable.notifyObservers(info, renderingGroupMask);
  18604. }
  18605. }
  18606. };
  18607. RenderingManager.prototype.reset = function () {
  18608. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18609. var renderingGroup = this._renderingGroups[index];
  18610. if (renderingGroup) {
  18611. renderingGroup.prepare();
  18612. }
  18613. }
  18614. };
  18615. RenderingManager.prototype.dispose = function () {
  18616. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18617. var renderingGroup = this._renderingGroups[index];
  18618. if (renderingGroup) {
  18619. renderingGroup.dispose();
  18620. }
  18621. }
  18622. this._renderingGroups.length = 0;
  18623. };
  18624. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18625. if (this._renderingGroups[renderingGroupId] === undefined) {
  18626. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18627. }
  18628. };
  18629. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18630. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18631. this._prepareRenderingGroup(renderingGroupId);
  18632. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18633. };
  18634. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18635. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18636. this._prepareRenderingGroup(renderingGroupId);
  18637. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18638. };
  18639. /**
  18640. * @param subMesh The submesh to dispatch
  18641. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18642. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18643. */
  18644. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18645. if (mesh === undefined) {
  18646. mesh = subMesh.getMesh();
  18647. }
  18648. var renderingGroupId = mesh.renderingGroupId || 0;
  18649. this._prepareRenderingGroup(renderingGroupId);
  18650. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18651. };
  18652. /**
  18653. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18654. * This allowed control for front to back rendering or reversly depending of the special needs.
  18655. *
  18656. * @param renderingGroupId The rendering group id corresponding to its index
  18657. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18658. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18659. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18660. */
  18661. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18662. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18663. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18664. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18665. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18666. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18667. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18668. if (this._renderingGroups[renderingGroupId]) {
  18669. var group = this._renderingGroups[renderingGroupId];
  18670. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18671. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18672. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18673. }
  18674. };
  18675. /**
  18676. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18677. *
  18678. * @param renderingGroupId The rendering group id corresponding to its index
  18679. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18680. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18681. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18682. */
  18683. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18684. if (depth === void 0) { depth = true; }
  18685. if (stencil === void 0) { stencil = true; }
  18686. this._autoClearDepthStencil[renderingGroupId] = {
  18687. autoClear: autoClearDepthStencil,
  18688. depth: depth,
  18689. stencil: stencil
  18690. };
  18691. };
  18692. /**
  18693. * The max id used for rendering groups (not included)
  18694. */
  18695. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18696. /**
  18697. * The min id used for rendering groups (included)
  18698. */
  18699. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18700. /**
  18701. * Used to globally prevent autoclearing scenes.
  18702. */
  18703. RenderingManager.AUTOCLEAR = true;
  18704. return RenderingManager;
  18705. }());
  18706. BABYLON.RenderingManager = RenderingManager;
  18707. })(BABYLON || (BABYLON = {}));
  18708. //# sourceMappingURL=babylon.renderingManager.js.map
  18709. var BABYLON;
  18710. (function (BABYLON) {
  18711. var RenderingGroup = /** @class */ (function () {
  18712. /**
  18713. * Creates a new rendering group.
  18714. * @param index The rendering group index
  18715. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18716. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18717. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18718. */
  18719. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18720. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18721. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18722. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18723. this.index = index;
  18724. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18725. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18726. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18727. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18728. this._particleSystems = new BABYLON.SmartArray(256);
  18729. this._spriteManagers = new BABYLON.SmartArray(256);
  18730. this._edgesRenderers = new BABYLON.SmartArray(16);
  18731. this._scene = scene;
  18732. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18733. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18734. this.transparentSortCompareFn = transparentSortCompareFn;
  18735. }
  18736. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18737. /**
  18738. * Set the opaque sort comparison function.
  18739. * If null the sub meshes will be render in the order they were created
  18740. */
  18741. set: function (value) {
  18742. this._opaqueSortCompareFn = value;
  18743. if (value) {
  18744. this._renderOpaque = this.renderOpaqueSorted;
  18745. }
  18746. else {
  18747. this._renderOpaque = RenderingGroup.renderUnsorted;
  18748. }
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18754. /**
  18755. * Set the alpha test sort comparison function.
  18756. * If null the sub meshes will be render in the order they were created
  18757. */
  18758. set: function (value) {
  18759. this._alphaTestSortCompareFn = value;
  18760. if (value) {
  18761. this._renderAlphaTest = this.renderAlphaTestSorted;
  18762. }
  18763. else {
  18764. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18765. }
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18771. /**
  18772. * Set the transparent sort comparison function.
  18773. * If null the sub meshes will be render in the order they were created
  18774. */
  18775. set: function (value) {
  18776. if (value) {
  18777. this._transparentSortCompareFn = value;
  18778. }
  18779. else {
  18780. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18781. }
  18782. this._renderTransparent = this.renderTransparentSorted;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. /**
  18788. * Render all the sub meshes contained in the group.
  18789. * @param customRenderFunction Used to override the default render behaviour of the group.
  18790. * @returns true if rendered some submeshes.
  18791. */
  18792. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18793. if (customRenderFunction) {
  18794. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18795. return;
  18796. }
  18797. var engine = this._scene.getEngine();
  18798. // Depth only
  18799. if (this._depthOnlySubMeshes.length !== 0) {
  18800. engine.setAlphaTesting(true);
  18801. engine.setColorWrite(false);
  18802. this._renderAlphaTest(this._depthOnlySubMeshes);
  18803. engine.setAlphaTesting(false);
  18804. engine.setColorWrite(true);
  18805. }
  18806. // Opaque
  18807. if (this._opaqueSubMeshes.length !== 0) {
  18808. this._renderOpaque(this._opaqueSubMeshes);
  18809. }
  18810. // Alpha test
  18811. if (this._alphaTestSubMeshes.length !== 0) {
  18812. engine.setAlphaTesting(true);
  18813. this._renderAlphaTest(this._alphaTestSubMeshes);
  18814. engine.setAlphaTesting(false);
  18815. }
  18816. var stencilState = engine.getStencilBuffer();
  18817. engine.setStencilBuffer(false);
  18818. // Sprites
  18819. if (renderSprites) {
  18820. this._renderSprites();
  18821. }
  18822. // Particles
  18823. if (renderParticles) {
  18824. this._renderParticles(activeMeshes);
  18825. }
  18826. if (this.onBeforeTransparentRendering) {
  18827. this.onBeforeTransparentRendering();
  18828. }
  18829. // Transparent
  18830. if (this._transparentSubMeshes.length !== 0) {
  18831. this._renderTransparent(this._transparentSubMeshes);
  18832. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18833. }
  18834. // Set back stencil to false in case it changes before the edge renderer.
  18835. engine.setStencilBuffer(false);
  18836. // Edges
  18837. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18838. this._edgesRenderers.data[edgesRendererIndex].render();
  18839. }
  18840. // Restore Stencil state.
  18841. engine.setStencilBuffer(stencilState);
  18842. };
  18843. /**
  18844. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18845. * @param subMeshes The submeshes to render
  18846. */
  18847. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18848. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18849. };
  18850. /**
  18851. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18852. * @param subMeshes The submeshes to render
  18853. */
  18854. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18855. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18856. };
  18857. /**
  18858. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18859. * @param subMeshes The submeshes to render
  18860. */
  18861. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18862. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18863. };
  18864. /**
  18865. * Renders the submeshes in a specified order.
  18866. * @param subMeshes The submeshes to sort before render
  18867. * @param sortCompareFn The comparison function use to sort
  18868. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18869. * @param transparent Specifies to activate blending if true
  18870. */
  18871. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18872. var subIndex = 0;
  18873. var subMesh;
  18874. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18875. for (; subIndex < subMeshes.length; subIndex++) {
  18876. subMesh = subMeshes.data[subIndex];
  18877. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18878. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18879. }
  18880. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18881. if (sortCompareFn) {
  18882. sortedArray.sort(sortCompareFn);
  18883. }
  18884. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18885. subMesh = sortedArray[subIndex];
  18886. if (transparent) {
  18887. var material = subMesh.getMaterial();
  18888. if (material && material.needDepthPrePass) {
  18889. var engine = material.getScene().getEngine();
  18890. engine.setColorWrite(false);
  18891. engine.setAlphaTesting(true);
  18892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18893. subMesh.render(false);
  18894. engine.setAlphaTesting(false);
  18895. engine.setColorWrite(true);
  18896. }
  18897. }
  18898. subMesh.render(transparent);
  18899. }
  18900. };
  18901. /**
  18902. * Renders the submeshes in the order they were dispatched (no sort applied).
  18903. * @param subMeshes The submeshes to render
  18904. */
  18905. RenderingGroup.renderUnsorted = function (subMeshes) {
  18906. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18907. var submesh = subMeshes.data[subIndex];
  18908. submesh.render(false);
  18909. }
  18910. };
  18911. /**
  18912. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18913. * are rendered back to front if in the same alpha index.
  18914. *
  18915. * @param a The first submesh
  18916. * @param b The second submesh
  18917. * @returns The result of the comparison
  18918. */
  18919. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18920. // Alpha index first
  18921. if (a._alphaIndex > b._alphaIndex) {
  18922. return 1;
  18923. }
  18924. if (a._alphaIndex < b._alphaIndex) {
  18925. return -1;
  18926. }
  18927. // Then distance to camera
  18928. return RenderingGroup.backToFrontSortCompare(a, b);
  18929. };
  18930. /**
  18931. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18932. * are rendered back to front.
  18933. *
  18934. * @param a The first submesh
  18935. * @param b The second submesh
  18936. * @returns The result of the comparison
  18937. */
  18938. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18939. // Then distance to camera
  18940. if (a._distanceToCamera < b._distanceToCamera) {
  18941. return 1;
  18942. }
  18943. if (a._distanceToCamera > b._distanceToCamera) {
  18944. return -1;
  18945. }
  18946. return 0;
  18947. };
  18948. /**
  18949. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18950. * are rendered front to back (prevent overdraw).
  18951. *
  18952. * @param a The first submesh
  18953. * @param b The second submesh
  18954. * @returns The result of the comparison
  18955. */
  18956. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18957. // Then distance to camera
  18958. if (a._distanceToCamera < b._distanceToCamera) {
  18959. return -1;
  18960. }
  18961. if (a._distanceToCamera > b._distanceToCamera) {
  18962. return 1;
  18963. }
  18964. return 0;
  18965. };
  18966. /**
  18967. * Resets the different lists of submeshes to prepare a new frame.
  18968. */
  18969. RenderingGroup.prototype.prepare = function () {
  18970. this._opaqueSubMeshes.reset();
  18971. this._transparentSubMeshes.reset();
  18972. this._alphaTestSubMeshes.reset();
  18973. this._depthOnlySubMeshes.reset();
  18974. this._particleSystems.reset();
  18975. this._spriteManagers.reset();
  18976. this._edgesRenderers.reset();
  18977. };
  18978. RenderingGroup.prototype.dispose = function () {
  18979. this._opaqueSubMeshes.dispose();
  18980. this._transparentSubMeshes.dispose();
  18981. this._alphaTestSubMeshes.dispose();
  18982. this._depthOnlySubMeshes.dispose();
  18983. this._particleSystems.dispose();
  18984. this._spriteManagers.dispose();
  18985. this._edgesRenderers.dispose();
  18986. };
  18987. /**
  18988. * Inserts the submesh in its correct queue depending on its material.
  18989. * @param subMesh The submesh to dispatch
  18990. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18991. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18992. */
  18993. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18994. // Get mesh and materials if not provided
  18995. if (mesh === undefined) {
  18996. mesh = subMesh.getMesh();
  18997. }
  18998. if (material === undefined) {
  18999. material = subMesh.getMaterial();
  19000. }
  19001. if (material === null || material === undefined) {
  19002. return;
  19003. }
  19004. if (material.needAlphaBlendingForMesh(mesh)) {
  19005. this._transparentSubMeshes.push(subMesh);
  19006. }
  19007. else if (material.needAlphaTesting()) {
  19008. if (material.needDepthPrePass) {
  19009. this._depthOnlySubMeshes.push(subMesh);
  19010. }
  19011. this._alphaTestSubMeshes.push(subMesh);
  19012. }
  19013. else {
  19014. if (material.needDepthPrePass) {
  19015. this._depthOnlySubMeshes.push(subMesh);
  19016. }
  19017. this._opaqueSubMeshes.push(subMesh); // Opaque
  19018. }
  19019. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19020. this._edgesRenderers.push(mesh._edgesRenderer);
  19021. }
  19022. };
  19023. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19024. this._spriteManagers.push(spriteManager);
  19025. };
  19026. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19027. this._particleSystems.push(particleSystem);
  19028. };
  19029. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19030. if (this._particleSystems.length === 0) {
  19031. return;
  19032. }
  19033. // Particles
  19034. var activeCamera = this._scene.activeCamera;
  19035. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19036. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19037. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19038. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19039. continue;
  19040. }
  19041. var emitter = particleSystem.emitter;
  19042. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19043. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19044. }
  19045. }
  19046. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19047. };
  19048. RenderingGroup.prototype._renderSprites = function () {
  19049. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19050. return;
  19051. }
  19052. // Sprites
  19053. var activeCamera = this._scene.activeCamera;
  19054. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19055. for (var id = 0; id < this._spriteManagers.length; id++) {
  19056. var spriteManager = this._spriteManagers.data[id];
  19057. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19058. spriteManager.render();
  19059. }
  19060. }
  19061. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19062. };
  19063. return RenderingGroup;
  19064. }());
  19065. BABYLON.RenderingGroup = RenderingGroup;
  19066. })(BABYLON || (BABYLON = {}));
  19067. //# sourceMappingURL=babylon.renderingGroup.js.map
  19068. var BABYLON;
  19069. (function (BABYLON) {
  19070. var ClickInfo = /** @class */ (function () {
  19071. function ClickInfo() {
  19072. this._singleClick = false;
  19073. this._doubleClick = false;
  19074. this._hasSwiped = false;
  19075. this._ignore = false;
  19076. }
  19077. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19078. get: function () {
  19079. return this._singleClick;
  19080. },
  19081. set: function (b) {
  19082. this._singleClick = b;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19088. get: function () {
  19089. return this._doubleClick;
  19090. },
  19091. set: function (b) {
  19092. this._doubleClick = b;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19098. get: function () {
  19099. return this._hasSwiped;
  19100. },
  19101. set: function (b) {
  19102. this._hasSwiped = b;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19108. get: function () {
  19109. return this._ignore;
  19110. },
  19111. set: function (b) {
  19112. this._ignore = b;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. return ClickInfo;
  19118. }());
  19119. /**
  19120. * This class is used by the onRenderingGroupObservable
  19121. */
  19122. var RenderingGroupInfo = /** @class */ (function () {
  19123. function RenderingGroupInfo() {
  19124. }
  19125. /**
  19126. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19127. * This stage will be fired no matter what
  19128. */
  19129. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19130. /**
  19131. * Called before opaque object are rendered.
  19132. * This stage will be fired only if there's 3D Opaque content to render
  19133. */
  19134. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19135. /**
  19136. * Called after the opaque objects are rendered and before the transparent ones
  19137. * This stage will be fired only if there's 3D transparent content to render
  19138. */
  19139. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19140. /**
  19141. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19142. * This stage will be fired no matter what
  19143. */
  19144. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19145. return RenderingGroupInfo;
  19146. }());
  19147. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19148. /**
  19149. * Represents a scene to be rendered by the engine.
  19150. * @see http://doc.babylonjs.com/page.php?p=21911
  19151. */
  19152. var Scene = /** @class */ (function () {
  19153. /**
  19154. * @constructor
  19155. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19156. */
  19157. function Scene(engine) {
  19158. // Members
  19159. this.autoClear = true;
  19160. this.autoClearDepthAndStencil = true;
  19161. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19162. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19163. this.forceWireframe = false;
  19164. this._forcePointsCloud = false;
  19165. this.forceShowBoundingBoxes = false;
  19166. this.animationsEnabled = true;
  19167. this.useConstantAnimationDeltaTime = false;
  19168. this.constantlyUpdateMeshUnderPointer = false;
  19169. this.hoverCursor = "pointer";
  19170. this.defaultCursor = "";
  19171. /**
  19172. * This is used to call preventDefault() on pointer down
  19173. * in order to block unwanted artifacts like system double clicks
  19174. */
  19175. this.preventDefaultOnPointerDown = true;
  19176. // Metadata
  19177. this.metadata = null;
  19178. /**
  19179. * An event triggered when the scene is disposed.
  19180. * @type {BABYLON.Observable}
  19181. */
  19182. this.onDisposeObservable = new BABYLON.Observable();
  19183. /**
  19184. * An event triggered before rendering the scene (right after animations and physics)
  19185. * @type {BABYLON.Observable}
  19186. */
  19187. this.onBeforeRenderObservable = new BABYLON.Observable();
  19188. /**
  19189. * An event triggered after rendering the scene
  19190. * @type {BABYLON.Observable}
  19191. */
  19192. this.onAfterRenderObservable = new BABYLON.Observable();
  19193. /**
  19194. * An event triggered before animating the scene
  19195. * @type {BABYLON.Observable}
  19196. */
  19197. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19198. /**
  19199. * An event triggered after animations processing
  19200. * @type {BABYLON.Observable}
  19201. */
  19202. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19203. /**
  19204. * An event triggered before draw calls are ready to be sent
  19205. * @type {BABYLON.Observable}
  19206. */
  19207. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19208. /**
  19209. * An event triggered after draw calls have been sent
  19210. * @type {BABYLON.Observable}
  19211. */
  19212. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19213. /**
  19214. * An event triggered when physic simulation is about to be run
  19215. * @type {BABYLON.Observable}
  19216. */
  19217. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19218. /**
  19219. * An event triggered when physic simulation has been done
  19220. * @type {BABYLON.Observable}
  19221. */
  19222. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19223. /**
  19224. * An event triggered when the scene is ready
  19225. * @type {BABYLON.Observable}
  19226. */
  19227. this.onReadyObservable = new BABYLON.Observable();
  19228. /**
  19229. * An event triggered before rendering a camera
  19230. * @type {BABYLON.Observable}
  19231. */
  19232. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19233. /**
  19234. * An event triggered after rendering a camera
  19235. * @type {BABYLON.Observable}
  19236. */
  19237. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19238. /**
  19239. * An event triggered when active meshes evaluation is about to start
  19240. * @type {BABYLON.Observable}
  19241. */
  19242. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when active meshes evaluation is done
  19245. * @type {BABYLON.Observable}
  19246. */
  19247. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19248. /**
  19249. * An event triggered when particles rendering is about to start
  19250. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19251. * @type {BABYLON.Observable}
  19252. */
  19253. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19254. /**
  19255. * An event triggered when particles rendering is done
  19256. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19257. * @type {BABYLON.Observable}
  19258. */
  19259. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19260. /**
  19261. * An event triggered when sprites rendering is about to start
  19262. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19263. * @type {BABYLON.Observable}
  19264. */
  19265. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19266. /**
  19267. * An event triggered when sprites rendering is done
  19268. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19269. * @type {BABYLON.Observable}
  19270. */
  19271. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19272. /**
  19273. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19274. * @type {BABYLON.Observable}
  19275. */
  19276. this.onDataLoadedObservable = new BABYLON.Observable();
  19277. /**
  19278. * An event triggered when a camera is created
  19279. * @type {BABYLON.Observable}
  19280. */
  19281. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when a camera is removed
  19284. * @type {BABYLON.Observable}
  19285. */
  19286. this.onCameraRemovedObservable = new BABYLON.Observable();
  19287. /**
  19288. * An event triggered when a light is created
  19289. * @type {BABYLON.Observable}
  19290. */
  19291. this.onNewLightAddedObservable = new BABYLON.Observable();
  19292. /**
  19293. * An event triggered when a light is removed
  19294. * @type {BABYLON.Observable}
  19295. */
  19296. this.onLightRemovedObservable = new BABYLON.Observable();
  19297. /**
  19298. * An event triggered when a geometry is created
  19299. * @type {BABYLON.Observable}
  19300. */
  19301. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19302. /**
  19303. * An event triggered when a geometry is removed
  19304. * @type {BABYLON.Observable}
  19305. */
  19306. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19307. /**
  19308. * An event triggered when a transform node is created
  19309. * @type {BABYLON.Observable}
  19310. */
  19311. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19312. /**
  19313. * An event triggered when a transform node is removed
  19314. * @type {BABYLON.Observable}
  19315. */
  19316. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19317. /**
  19318. * An event triggered when a mesh is created
  19319. * @type {BABYLON.Observable}
  19320. */
  19321. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19322. /**
  19323. * An event triggered when a mesh is removed
  19324. * @type {BABYLON.Observable}
  19325. */
  19326. this.onMeshRemovedObservable = new BABYLON.Observable();
  19327. /**
  19328. * An event triggered when render targets are about to be rendered
  19329. * Can happen multiple times per frame.
  19330. * @type {BABYLON.Observable}
  19331. */
  19332. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19333. /**
  19334. * An event triggered when render targets were rendered.
  19335. * Can happen multiple times per frame.
  19336. * @type {BABYLON.Observable}
  19337. */
  19338. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19339. /**
  19340. * An event triggered before calculating deterministic simulation step
  19341. * @type {BABYLON.Observable}
  19342. */
  19343. this.onBeforeStepObservable = new BABYLON.Observable();
  19344. /**
  19345. * An event triggered after calculating deterministic simulation step
  19346. * @type {BABYLON.Observable}
  19347. */
  19348. this.onAfterStepObservable = new BABYLON.Observable();
  19349. /**
  19350. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19351. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19352. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  19353. */
  19354. this.onRenderingGroupObservable = new BABYLON.Observable();
  19355. // Animations
  19356. this.animations = [];
  19357. /**
  19358. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  19359. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19360. */
  19361. this.onPrePointerObservable = new BABYLON.Observable();
  19362. /**
  19363. * Observable event triggered each time an input event is received from the rendering canvas
  19364. */
  19365. this.onPointerObservable = new BABYLON.Observable();
  19366. this._meshPickProceed = false;
  19367. this._currentPickResult = null;
  19368. this._previousPickResult = null;
  19369. this._totalPointersPressed = 0;
  19370. this._doubleClickOccured = false;
  19371. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19372. this.cameraToUseForPointers = null;
  19373. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19374. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19375. this._startingPointerTime = 0;
  19376. this._previousStartingPointerTime = 0;
  19377. // Deterministic lockstep
  19378. this._timeAccumulator = 0;
  19379. this._currentStepId = 0;
  19380. this._currentInternalStep = 0;
  19381. // Keyboard
  19382. /**
  19383. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19384. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19385. */
  19386. this.onPreKeyboardObservable = new BABYLON.Observable();
  19387. /**
  19388. * Observable event triggered each time an keyboard event is received from the hosting window
  19389. */
  19390. this.onKeyboardObservable = new BABYLON.Observable();
  19391. // Coordinate system
  19392. /**
  19393. * use right-handed coordinate system on this scene.
  19394. * @type {boolean}
  19395. */
  19396. this._useRightHandedSystem = false;
  19397. // Fog
  19398. this._fogEnabled = true;
  19399. this._fogMode = Scene.FOGMODE_NONE;
  19400. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19401. this.fogDensity = 0.1;
  19402. this.fogStart = 0;
  19403. this.fogEnd = 1000.0;
  19404. // Lights
  19405. /**
  19406. * is shadow enabled on this scene.
  19407. * @type {boolean}
  19408. */
  19409. this._shadowsEnabled = true;
  19410. /**
  19411. * is light enabled on this scene.
  19412. * @type {boolean}
  19413. */
  19414. this._lightsEnabled = true;
  19415. /**
  19416. * All of the lights added to this scene.
  19417. * @see BABYLON.Light
  19418. * @type {BABYLON.Light[]}
  19419. */
  19420. this.lights = new Array();
  19421. // Cameras
  19422. /** All of the cameras added to this scene. */
  19423. this.cameras = new Array();
  19424. /** All of the active cameras added to this scene. */
  19425. this.activeCameras = new Array();
  19426. // Meshes
  19427. /**
  19428. * All of the tranform nodes added to this scene.
  19429. * @see BABYLON.TransformNode
  19430. * @type {BABYLON.TransformNode[]}
  19431. */
  19432. this.transformNodes = new Array();
  19433. /**
  19434. * All of the (abstract) meshes added to this scene.
  19435. * @see BABYLON.AbstractMesh
  19436. * @type {BABYLON.AbstractMesh[]}
  19437. */
  19438. this.meshes = new Array();
  19439. /**
  19440. * All of the animation groups added to this scene.
  19441. * @see BABYLON.AnimationGroup
  19442. * @type {BABYLON.AnimationGroup[]}
  19443. */
  19444. this.animationGroups = new Array();
  19445. // Geometries
  19446. this._geometries = new Array();
  19447. this.materials = new Array();
  19448. this.multiMaterials = new Array();
  19449. // Textures
  19450. this._texturesEnabled = true;
  19451. this.textures = new Array();
  19452. // Particles
  19453. this.particlesEnabled = true;
  19454. this.particleSystems = new Array();
  19455. // Sprites
  19456. this.spritesEnabled = true;
  19457. this.spriteManagers = new Array();
  19458. // Layers
  19459. this.layers = new Array();
  19460. this.highlightLayers = new Array();
  19461. // Skeletons
  19462. this._skeletonsEnabled = true;
  19463. this.skeletons = new Array();
  19464. // Morph targets
  19465. this.morphTargetManagers = new Array();
  19466. // Lens flares
  19467. this.lensFlaresEnabled = true;
  19468. this.lensFlareSystems = new Array();
  19469. // Collisions
  19470. this.collisionsEnabled = true;
  19471. /** Defines the gravity applied to this scene */
  19472. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19473. // Postprocesses
  19474. this.postProcesses = new Array();
  19475. this.postProcessesEnabled = true;
  19476. // Customs render targets
  19477. this.renderTargetsEnabled = true;
  19478. this.dumpNextRenderTargets = false;
  19479. this.customRenderTargets = new Array();
  19480. // Imported meshes
  19481. this.importedMeshesFiles = new Array();
  19482. // Probes
  19483. this.probesEnabled = true;
  19484. this.reflectionProbes = new Array();
  19485. this._actionManagers = new Array();
  19486. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19487. // Procedural textures
  19488. this.proceduralTexturesEnabled = true;
  19489. this._proceduralTextures = new Array();
  19490. this.soundTracks = new Array();
  19491. this._audioEnabled = true;
  19492. this._headphone = false;
  19493. // Performance counters
  19494. this._totalVertices = new BABYLON.PerfCounter();
  19495. this._activeIndices = new BABYLON.PerfCounter();
  19496. this._activeParticles = new BABYLON.PerfCounter();
  19497. this._activeBones = new BABYLON.PerfCounter();
  19498. this._animationTime = 0;
  19499. this.animationTimeScale = 1;
  19500. this._renderId = 0;
  19501. this._executeWhenReadyTimeoutId = -1;
  19502. this._intermediateRendering = false;
  19503. this._viewUpdateFlag = -1;
  19504. this._projectionUpdateFlag = -1;
  19505. this._alternateViewUpdateFlag = -1;
  19506. this._alternateProjectionUpdateFlag = -1;
  19507. this._toBeDisposed = new BABYLON.SmartArray(256);
  19508. this._activeRequests = new Array();
  19509. this._pendingData = new Array();
  19510. this._isDisposed = false;
  19511. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19512. this._activeMeshes = new BABYLON.SmartArray(256);
  19513. this._processedMaterials = new BABYLON.SmartArray(256);
  19514. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19515. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19516. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19517. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19518. this._activeAnimatables = new Array();
  19519. this._transformMatrix = BABYLON.Matrix.Zero();
  19520. this._useAlternateCameraConfiguration = false;
  19521. this._alternateRendering = false;
  19522. this.requireLightSorting = false;
  19523. this._activeMeshesFrozen = false;
  19524. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19525. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19526. this._engine.scenes.push(this);
  19527. this._uid = null;
  19528. this._renderingManager = new BABYLON.RenderingManager(this);
  19529. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19530. if (BABYLON.OutlineRenderer) {
  19531. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19532. }
  19533. if (BABYLON.Tools.IsWindowObjectExist()) {
  19534. this.attachControl();
  19535. }
  19536. //simplification queue
  19537. if (BABYLON.SimplificationQueue) {
  19538. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19539. }
  19540. //collision coordinator initialization. For now legacy per default.
  19541. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19542. // Uniform Buffer
  19543. this._createUbo();
  19544. // Default Image processing definition.
  19545. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19546. }
  19547. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19548. /** The fog is deactivated */
  19549. get: function () {
  19550. return Scene._FOGMODE_NONE;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19556. /** The fog density is following an exponential function */
  19557. get: function () {
  19558. return Scene._FOGMODE_EXP;
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19564. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19565. get: function () {
  19566. return Scene._FOGMODE_EXP2;
  19567. },
  19568. enumerable: true,
  19569. configurable: true
  19570. });
  19571. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19572. /** The fog density is following a linear function. */
  19573. get: function () {
  19574. return Scene._FOGMODE_LINEAR;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19580. /**
  19581. * Texture used in all pbr material as the reflection texture.
  19582. * As in the majority of the scene they are the same (exception for multi room and so on),
  19583. * this is easier to reference from here than from all the materials.
  19584. */
  19585. get: function () {
  19586. return this._environmentTexture;
  19587. },
  19588. /**
  19589. * Texture used in all pbr material as the reflection texture.
  19590. * As in the majority of the scene they are the same (exception for multi room and so on),
  19591. * this is easier to set here than in all the materials.
  19592. */
  19593. set: function (value) {
  19594. if (this._environmentTexture === value) {
  19595. return;
  19596. }
  19597. this._environmentTexture = value;
  19598. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19599. },
  19600. enumerable: true,
  19601. configurable: true
  19602. });
  19603. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19604. /**
  19605. * Default image processing configuration used either in the rendering
  19606. * Forward main pass or through the imageProcessingPostProcess if present.
  19607. * As in the majority of the scene they are the same (exception for multi camera),
  19608. * this is easier to reference from here than from all the materials and post process.
  19609. *
  19610. * No setter as we it is a shared configuration, you can set the values instead.
  19611. */
  19612. get: function () {
  19613. return this._imageProcessingConfiguration;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19619. get: function () {
  19620. return this._forcePointsCloud;
  19621. },
  19622. set: function (value) {
  19623. if (this._forcePointsCloud === value) {
  19624. return;
  19625. }
  19626. this._forcePointsCloud = value;
  19627. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(Scene.prototype, "onDispose", {
  19633. /** A function to be executed when this scene is disposed. */
  19634. set: function (callback) {
  19635. if (this._onDisposeObserver) {
  19636. this.onDisposeObservable.remove(this._onDisposeObserver);
  19637. }
  19638. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19639. },
  19640. enumerable: true,
  19641. configurable: true
  19642. });
  19643. Object.defineProperty(Scene.prototype, "beforeRender", {
  19644. /** A function to be executed before rendering this scene */
  19645. set: function (callback) {
  19646. if (this._onBeforeRenderObserver) {
  19647. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19648. }
  19649. if (callback) {
  19650. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19651. }
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(Scene.prototype, "afterRender", {
  19657. /** A function to be executed after rendering this scene */
  19658. set: function (callback) {
  19659. if (this._onAfterRenderObserver) {
  19660. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19661. }
  19662. if (callback) {
  19663. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19664. }
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19670. set: function (callback) {
  19671. if (this._onBeforeCameraRenderObserver) {
  19672. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19673. }
  19674. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19680. set: function (callback) {
  19681. if (this._onAfterCameraRenderObserver) {
  19682. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19683. }
  19684. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19690. get: function () {
  19691. if (!this._gamepadManager) {
  19692. this._gamepadManager = new BABYLON.GamepadManager(this);
  19693. }
  19694. return this._gamepadManager;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19700. get: function () {
  19701. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19707. get: function () {
  19708. return this._useRightHandedSystem;
  19709. },
  19710. set: function (value) {
  19711. if (this._useRightHandedSystem === value) {
  19712. return;
  19713. }
  19714. this._useRightHandedSystem = value;
  19715. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Scene.prototype.setStepId = function (newStepId) {
  19721. this._currentStepId = newStepId;
  19722. };
  19723. ;
  19724. Scene.prototype.getStepId = function () {
  19725. return this._currentStepId;
  19726. };
  19727. ;
  19728. Scene.prototype.getInternalStep = function () {
  19729. return this._currentInternalStep;
  19730. };
  19731. ;
  19732. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19733. get: function () {
  19734. return this._fogEnabled;
  19735. },
  19736. /**
  19737. * is fog enabled on this scene.
  19738. */
  19739. set: function (value) {
  19740. if (this._fogEnabled === value) {
  19741. return;
  19742. }
  19743. this._fogEnabled = value;
  19744. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Scene.prototype, "fogMode", {
  19750. get: function () {
  19751. return this._fogMode;
  19752. },
  19753. set: function (value) {
  19754. if (this._fogMode === value) {
  19755. return;
  19756. }
  19757. this._fogMode = value;
  19758. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19764. get: function () {
  19765. return this._shadowsEnabled;
  19766. },
  19767. set: function (value) {
  19768. if (this._shadowsEnabled === value) {
  19769. return;
  19770. }
  19771. this._shadowsEnabled = value;
  19772. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19778. get: function () {
  19779. return this._lightsEnabled;
  19780. },
  19781. set: function (value) {
  19782. if (this._lightsEnabled === value) {
  19783. return;
  19784. }
  19785. this._lightsEnabled = value;
  19786. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19792. /** The default material used on meshes when no material is affected */
  19793. get: function () {
  19794. if (!this._defaultMaterial) {
  19795. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19796. }
  19797. return this._defaultMaterial;
  19798. },
  19799. /** The default material used on meshes when no material is affected */
  19800. set: function (value) {
  19801. this._defaultMaterial = value;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19807. get: function () {
  19808. return this._texturesEnabled;
  19809. },
  19810. set: function (value) {
  19811. if (this._texturesEnabled === value) {
  19812. return;
  19813. }
  19814. this._texturesEnabled = value;
  19815. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19821. get: function () {
  19822. return this._skeletonsEnabled;
  19823. },
  19824. set: function (value) {
  19825. if (this._skeletonsEnabled === value) {
  19826. return;
  19827. }
  19828. this._skeletonsEnabled = value;
  19829. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19835. get: function () {
  19836. if (!this._postProcessRenderPipelineManager) {
  19837. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19838. }
  19839. return this._postProcessRenderPipelineManager;
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19845. get: function () {
  19846. if (!this._mainSoundTrack) {
  19847. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19848. }
  19849. return this._mainSoundTrack;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19855. get: function () {
  19856. return this._alternateRendering;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19862. get: function () {
  19863. return this._frustumPlanes;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Scene.prototype, "debugLayer", {
  19869. // Properties
  19870. get: function () {
  19871. if (!this._debugLayer) {
  19872. this._debugLayer = new BABYLON.DebugLayer(this);
  19873. }
  19874. return this._debugLayer;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19880. get: function () {
  19881. return this._workerCollisions;
  19882. },
  19883. set: function (enabled) {
  19884. if (!BABYLON.CollisionCoordinatorLegacy) {
  19885. return;
  19886. }
  19887. enabled = (enabled && !!Worker);
  19888. this._workerCollisions = enabled;
  19889. if (this.collisionCoordinator) {
  19890. this.collisionCoordinator.destroy();
  19891. }
  19892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19893. this.collisionCoordinator.init(this);
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19899. get: function () {
  19900. return this._selectionOctree;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19906. /**
  19907. * The mesh that is currently under the pointer.
  19908. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19909. */
  19910. get: function () {
  19911. return this._pointerOverMesh;
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(Scene.prototype, "pointerX", {
  19917. /**
  19918. * Current on-screen X position of the pointer
  19919. * @return {number} X position of the pointer
  19920. */
  19921. get: function () {
  19922. return this._pointerX;
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(Scene.prototype, "pointerY", {
  19928. /**
  19929. * Current on-screen Y position of the pointer
  19930. * @return {number} Y position of the pointer
  19931. */
  19932. get: function () {
  19933. return this._pointerY;
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Scene.prototype.getCachedMaterial = function () {
  19939. return this._cachedMaterial;
  19940. };
  19941. Scene.prototype.getCachedEffect = function () {
  19942. return this._cachedEffect;
  19943. };
  19944. Scene.prototype.getCachedVisibility = function () {
  19945. return this._cachedVisibility;
  19946. };
  19947. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19948. if (visibility === void 0) { visibility = 1; }
  19949. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19950. };
  19951. Scene.prototype.getBoundingBoxRenderer = function () {
  19952. if (!this._boundingBoxRenderer) {
  19953. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19954. }
  19955. return this._boundingBoxRenderer;
  19956. };
  19957. Scene.prototype.getOutlineRenderer = function () {
  19958. return this._outlineRenderer;
  19959. };
  19960. Scene.prototype.getEngine = function () {
  19961. return this._engine;
  19962. };
  19963. Scene.prototype.getTotalVertices = function () {
  19964. return this._totalVertices.current;
  19965. };
  19966. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19967. get: function () {
  19968. return this._totalVertices;
  19969. },
  19970. enumerable: true,
  19971. configurable: true
  19972. });
  19973. Scene.prototype.getActiveIndices = function () {
  19974. return this._activeIndices.current;
  19975. };
  19976. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19977. get: function () {
  19978. return this._activeIndices;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Scene.prototype.getActiveParticles = function () {
  19984. return this._activeParticles.current;
  19985. };
  19986. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19987. get: function () {
  19988. return this._activeParticles;
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Scene.prototype.getActiveBones = function () {
  19994. return this._activeBones.current;
  19995. };
  19996. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19997. get: function () {
  19998. return this._activeBones;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. // Stats
  20004. Scene.prototype.getInterFramePerfCounter = function () {
  20005. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20006. return 0;
  20007. };
  20008. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20009. get: function () {
  20010. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20011. return null;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Scene.prototype.getLastFrameDuration = function () {
  20017. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20018. return 0;
  20019. };
  20020. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20021. get: function () {
  20022. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20023. return null;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20029. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20030. return 0;
  20031. };
  20032. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20033. get: function () {
  20034. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20035. return null;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Scene.prototype.getActiveMeshes = function () {
  20041. return this._activeMeshes;
  20042. };
  20043. Scene.prototype.getRenderTargetsDuration = function () {
  20044. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20045. return 0;
  20046. };
  20047. Scene.prototype.getRenderDuration = function () {
  20048. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20049. return 0;
  20050. };
  20051. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20052. get: function () {
  20053. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20054. return null;
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Scene.prototype.getParticlesDuration = function () {
  20060. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20061. return 0;
  20062. };
  20063. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20064. get: function () {
  20065. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20066. return null;
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Scene.prototype.getSpritesDuration = function () {
  20072. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20073. return 0;
  20074. };
  20075. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20076. get: function () {
  20077. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20078. return null;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Scene.prototype.getAnimationRatio = function () {
  20084. return this._animationRatio;
  20085. };
  20086. Scene.prototype.getRenderId = function () {
  20087. return this._renderId;
  20088. };
  20089. Scene.prototype.incrementRenderId = function () {
  20090. this._renderId++;
  20091. };
  20092. Scene.prototype._updatePointerPosition = function (evt) {
  20093. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20094. if (!canvasRect) {
  20095. return;
  20096. }
  20097. this._pointerX = evt.clientX - canvasRect.left;
  20098. this._pointerY = evt.clientY - canvasRect.top;
  20099. this._unTranslatedPointerX = this._pointerX;
  20100. this._unTranslatedPointerY = this._pointerY;
  20101. };
  20102. Scene.prototype._createUbo = function () {
  20103. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20104. this._sceneUbo.addUniform("viewProjection", 16);
  20105. this._sceneUbo.addUniform("view", 16);
  20106. };
  20107. Scene.prototype._createAlternateUbo = function () {
  20108. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20109. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20110. this._alternateSceneUbo.addUniform("view", 16);
  20111. };
  20112. // Pointers handling
  20113. /**
  20114. * Use this method to simulate a pointer move on a mesh
  20115. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20116. */
  20117. Scene.prototype.simulatePointerMove = function (pickResult) {
  20118. var evt = new PointerEvent("pointermove");
  20119. return this._processPointerMove(pickResult, evt);
  20120. };
  20121. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20122. var canvas = this._engine.getRenderingCanvas();
  20123. if (!canvas) {
  20124. return this;
  20125. }
  20126. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20127. this.setPointerOverSprite(null);
  20128. this.setPointerOverMesh(pickResult.pickedMesh);
  20129. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20130. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20131. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20132. }
  20133. else {
  20134. canvas.style.cursor = this.hoverCursor;
  20135. }
  20136. }
  20137. else {
  20138. canvas.style.cursor = this.defaultCursor;
  20139. }
  20140. }
  20141. else {
  20142. this.setPointerOverMesh(null);
  20143. // Sprites
  20144. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20145. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20146. this.setPointerOverSprite(pickResult.pickedSprite);
  20147. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20148. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20149. }
  20150. else {
  20151. canvas.style.cursor = this.hoverCursor;
  20152. }
  20153. }
  20154. else {
  20155. this.setPointerOverSprite(null);
  20156. // Restore pointer
  20157. canvas.style.cursor = this.defaultCursor;
  20158. }
  20159. }
  20160. if (pickResult) {
  20161. if (this.onPointerMove) {
  20162. this.onPointerMove(evt, pickResult);
  20163. }
  20164. if (this.onPointerObservable.hasObservers()) {
  20165. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20166. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20167. this.onPointerObservable.notifyObservers(pi, type);
  20168. }
  20169. }
  20170. return this;
  20171. };
  20172. /**
  20173. * Use this method to simulate a pointer down on a mesh
  20174. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20175. */
  20176. Scene.prototype.simulatePointerDown = function (pickResult) {
  20177. var evt = new PointerEvent("pointerdown");
  20178. return this._processPointerDown(pickResult, evt);
  20179. };
  20180. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20181. var _this = this;
  20182. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20183. this._pickedDownMesh = pickResult.pickedMesh;
  20184. var actionManager = pickResult.pickedMesh.actionManager;
  20185. if (actionManager) {
  20186. if (actionManager.hasPickTriggers) {
  20187. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20188. switch (evt.button) {
  20189. case 0:
  20190. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20191. break;
  20192. case 1:
  20193. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20194. break;
  20195. case 2:
  20196. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20197. break;
  20198. }
  20199. }
  20200. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20201. window.setTimeout(function () {
  20202. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  20203. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20204. if (_this._totalPointersPressed !== 0 &&
  20205. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20206. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20207. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20208. _this._startingPointerTime = 0;
  20209. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20210. }
  20211. }
  20212. }, Scene.LongPressDelay);
  20213. }
  20214. }
  20215. }
  20216. if (pickResult) {
  20217. if (this.onPointerDown) {
  20218. this.onPointerDown(evt, pickResult);
  20219. }
  20220. if (this.onPointerObservable.hasObservers()) {
  20221. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20222. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20223. this.onPointerObservable.notifyObservers(pi, type);
  20224. }
  20225. }
  20226. return this;
  20227. };
  20228. /**
  20229. * Use this method to simulate a pointer up on a mesh
  20230. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20231. */
  20232. Scene.prototype.simulatePointerUp = function (pickResult) {
  20233. var evt = new PointerEvent("pointerup");
  20234. var clickInfo = new ClickInfo();
  20235. clickInfo.singleClick = true;
  20236. clickInfo.ignore = true;
  20237. return this._processPointerUp(pickResult, evt, clickInfo);
  20238. };
  20239. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20240. if (pickResult && pickResult && pickResult.pickedMesh) {
  20241. this._pickedUpMesh = pickResult.pickedMesh;
  20242. if (this._pickedDownMesh === this._pickedUpMesh) {
  20243. if (this.onPointerPick) {
  20244. this.onPointerPick(evt, pickResult);
  20245. }
  20246. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20247. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20248. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20249. this.onPointerObservable.notifyObservers(pi, type);
  20250. }
  20251. }
  20252. if (pickResult.pickedMesh.actionManager) {
  20253. if (clickInfo.ignore) {
  20254. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20255. }
  20256. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20257. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20258. }
  20259. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20261. }
  20262. }
  20263. }
  20264. if (this._pickedDownMesh &&
  20265. this._pickedDownMesh.actionManager &&
  20266. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20267. this._pickedDownMesh !== this._pickedUpMesh) {
  20268. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20269. }
  20270. if (this.onPointerUp) {
  20271. this.onPointerUp(evt, pickResult);
  20272. }
  20273. if (this.onPointerObservable.hasObservers()) {
  20274. if (!clickInfo.ignore) {
  20275. if (!clickInfo.hasSwiped) {
  20276. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20277. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20278. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20279. this.onPointerObservable.notifyObservers(pi, type);
  20280. }
  20281. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20282. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20283. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20284. this.onPointerObservable.notifyObservers(pi, type);
  20285. }
  20286. }
  20287. }
  20288. else {
  20289. var type = BABYLON.PointerEventTypes.POINTERUP;
  20290. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20291. this.onPointerObservable.notifyObservers(pi, type);
  20292. }
  20293. }
  20294. return this;
  20295. };
  20296. /**
  20297. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20298. * @param attachUp defines if you want to attach events to pointerup
  20299. * @param attachDown defines if you want to attach events to pointerdown
  20300. * @param attachMove defines if you want to attach events to pointermove
  20301. */
  20302. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20303. var _this = this;
  20304. if (attachUp === void 0) { attachUp = true; }
  20305. if (attachDown === void 0) { attachDown = true; }
  20306. if (attachMove === void 0) { attachMove = true; }
  20307. this._initActionManager = function (act, clickInfo) {
  20308. if (!_this._meshPickProceed) {
  20309. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20310. _this._currentPickResult = pickResult;
  20311. if (pickResult) {
  20312. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20313. }
  20314. _this._meshPickProceed = true;
  20315. }
  20316. return act;
  20317. };
  20318. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20319. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20320. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20321. btn !== _this._previousButtonPressed) {
  20322. _this._doubleClickOccured = false;
  20323. clickInfo.singleClick = true;
  20324. clickInfo.ignore = false;
  20325. cb(clickInfo, _this._currentPickResult);
  20326. }
  20327. };
  20328. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20329. var clickInfo = new ClickInfo();
  20330. _this._currentPickResult = null;
  20331. var act = null;
  20332. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20333. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20334. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20335. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20336. act = _this._initActionManager(act, clickInfo);
  20337. if (act)
  20338. checkPicking = act.hasPickTriggers;
  20339. }
  20340. if (checkPicking) {
  20341. var btn = evt.button;
  20342. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20343. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20344. if (!clickInfo.hasSwiped) {
  20345. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20346. if (!checkSingleClickImmediately) {
  20347. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20348. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20349. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20350. act = _this._initActionManager(act, clickInfo);
  20351. if (act)
  20352. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20353. }
  20354. }
  20355. if (checkSingleClickImmediately) {
  20356. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20357. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20358. btn !== _this._previousButtonPressed) {
  20359. clickInfo.singleClick = true;
  20360. cb(clickInfo, _this._currentPickResult);
  20361. }
  20362. }
  20363. else {
  20364. // wait that no double click has been raised during the double click delay
  20365. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20366. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20367. }
  20368. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20369. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20370. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20371. act = _this._initActionManager(act, clickInfo);
  20372. if (act)
  20373. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20374. }
  20375. if (checkDoubleClick) {
  20376. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20377. if (btn === _this._previousButtonPressed &&
  20378. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20379. !_this._doubleClickOccured) {
  20380. // pointer has not moved for 2 clicks, it's a double click
  20381. if (!clickInfo.hasSwiped &&
  20382. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20383. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20384. _this._previousStartingPointerTime = 0;
  20385. _this._doubleClickOccured = true;
  20386. clickInfo.doubleClick = true;
  20387. clickInfo.ignore = false;
  20388. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20389. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20390. }
  20391. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20392. cb(clickInfo, _this._currentPickResult);
  20393. }
  20394. else {
  20395. _this._doubleClickOccured = false;
  20396. _this._previousStartingPointerTime = _this._startingPointerTime;
  20397. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20398. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20399. _this._previousButtonPressed = btn;
  20400. if (Scene.ExclusiveDoubleClickMode) {
  20401. if (_this._previousDelayedSimpleClickTimeout) {
  20402. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20403. }
  20404. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20405. cb(clickInfo, _this._previousPickResult);
  20406. }
  20407. else {
  20408. cb(clickInfo, _this._currentPickResult);
  20409. }
  20410. }
  20411. }
  20412. else {
  20413. _this._doubleClickOccured = false;
  20414. _this._previousStartingPointerTime = _this._startingPointerTime;
  20415. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20416. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20417. _this._previousButtonPressed = btn;
  20418. }
  20419. }
  20420. }
  20421. }
  20422. clickInfo.ignore = true;
  20423. cb(clickInfo, _this._currentPickResult);
  20424. };
  20425. this._spritePredicate = function (sprite) {
  20426. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20427. };
  20428. this._onPointerMove = function (evt) {
  20429. _this._updatePointerPosition(evt);
  20430. // PreObservable support
  20431. if (_this.onPrePointerObservable.hasObservers()) {
  20432. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20433. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20434. _this.onPrePointerObservable.notifyObservers(pi, type);
  20435. if (pi.skipOnPointerObservable) {
  20436. return;
  20437. }
  20438. }
  20439. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20440. return;
  20441. }
  20442. if (!_this.pointerMovePredicate) {
  20443. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20444. }
  20445. // Meshes
  20446. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20447. _this._processPointerMove(pickResult, evt);
  20448. };
  20449. this._onPointerDown = function (evt) {
  20450. _this._totalPointersPressed++;
  20451. _this._pickedDownMesh = null;
  20452. _this._meshPickProceed = false;
  20453. _this._updatePointerPosition(evt);
  20454. if (_this.preventDefaultOnPointerDown && canvas) {
  20455. evt.preventDefault();
  20456. canvas.focus();
  20457. }
  20458. // PreObservable support
  20459. if (_this.onPrePointerObservable.hasObservers()) {
  20460. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20461. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20462. _this.onPrePointerObservable.notifyObservers(pi, type);
  20463. if (pi.skipOnPointerObservable) {
  20464. return;
  20465. }
  20466. }
  20467. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20468. return;
  20469. }
  20470. _this._startingPointerPosition.x = _this._pointerX;
  20471. _this._startingPointerPosition.y = _this._pointerY;
  20472. _this._startingPointerTime = new Date().getTime();
  20473. if (!_this.pointerDownPredicate) {
  20474. _this.pointerDownPredicate = function (mesh) {
  20475. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20476. };
  20477. }
  20478. // Meshes
  20479. _this._pickedDownMesh = null;
  20480. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20481. _this._processPointerDown(pickResult, evt);
  20482. // Sprites
  20483. _this._pickedDownSprite = null;
  20484. if (_this.spriteManagers.length > 0) {
  20485. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20486. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20487. if (pickResult.pickedSprite.actionManager) {
  20488. _this._pickedDownSprite = pickResult.pickedSprite;
  20489. switch (evt.button) {
  20490. case 0:
  20491. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20492. break;
  20493. case 1:
  20494. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20495. break;
  20496. case 2:
  20497. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20498. break;
  20499. }
  20500. if (pickResult.pickedSprite.actionManager) {
  20501. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20502. }
  20503. }
  20504. }
  20505. }
  20506. };
  20507. this._onPointerUp = function (evt) {
  20508. if (_this._totalPointersPressed === 0) {
  20509. return; // So we need to test it the pointer down was pressed before.
  20510. }
  20511. _this._totalPointersPressed--;
  20512. _this._pickedUpMesh = null;
  20513. _this._meshPickProceed = false;
  20514. _this._updatePointerPosition(evt);
  20515. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20516. // PreObservable support
  20517. if (_this.onPrePointerObservable.hasObservers()) {
  20518. if (!clickInfo.ignore) {
  20519. if (!clickInfo.hasSwiped) {
  20520. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20521. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20522. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20523. _this.onPrePointerObservable.notifyObservers(pi, type);
  20524. if (pi.skipOnPointerObservable) {
  20525. return;
  20526. }
  20527. }
  20528. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20529. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20530. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20531. _this.onPrePointerObservable.notifyObservers(pi, type);
  20532. if (pi.skipOnPointerObservable) {
  20533. return;
  20534. }
  20535. }
  20536. }
  20537. }
  20538. else {
  20539. var type = BABYLON.PointerEventTypes.POINTERUP;
  20540. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20541. _this.onPrePointerObservable.notifyObservers(pi, type);
  20542. if (pi.skipOnPointerObservable) {
  20543. return;
  20544. }
  20545. }
  20546. }
  20547. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20548. return;
  20549. }
  20550. if (!_this.pointerUpPredicate) {
  20551. _this.pointerUpPredicate = function (mesh) {
  20552. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20553. };
  20554. }
  20555. // Meshes
  20556. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20557. _this._initActionManager(null, clickInfo);
  20558. }
  20559. if (!pickResult) {
  20560. pickResult = _this._currentPickResult;
  20561. }
  20562. _this._processPointerUp(pickResult, evt, clickInfo);
  20563. // Sprites
  20564. if (_this.spriteManagers.length > 0) {
  20565. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20566. if (spritePickResult) {
  20567. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20568. if (spritePickResult.pickedSprite.actionManager) {
  20569. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20570. if (spritePickResult.pickedSprite.actionManager) {
  20571. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20572. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20573. }
  20574. }
  20575. }
  20576. }
  20577. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20578. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20579. }
  20580. }
  20581. }
  20582. _this._previousPickResult = _this._currentPickResult;
  20583. });
  20584. };
  20585. this._onKeyDown = function (evt) {
  20586. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20587. if (_this.onPreKeyboardObservable.hasObservers()) {
  20588. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20589. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20590. if (pi.skipOnPointerObservable) {
  20591. return;
  20592. }
  20593. }
  20594. if (_this.onKeyboardObservable.hasObservers()) {
  20595. var pi = new BABYLON.KeyboardInfo(type, evt);
  20596. _this.onKeyboardObservable.notifyObservers(pi, type);
  20597. }
  20598. if (_this.actionManager) {
  20599. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20600. }
  20601. };
  20602. this._onKeyUp = function (evt) {
  20603. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20604. if (_this.onPreKeyboardObservable.hasObservers()) {
  20605. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20606. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20607. if (pi.skipOnPointerObservable) {
  20608. return;
  20609. }
  20610. }
  20611. if (_this.onKeyboardObservable.hasObservers()) {
  20612. var pi = new BABYLON.KeyboardInfo(type, evt);
  20613. _this.onKeyboardObservable.notifyObservers(pi, type);
  20614. }
  20615. if (_this.actionManager) {
  20616. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20617. }
  20618. };
  20619. var engine = this.getEngine();
  20620. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20621. if (!canvas) {
  20622. return;
  20623. }
  20624. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20625. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20626. });
  20627. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20628. if (!canvas) {
  20629. return;
  20630. }
  20631. canvas.removeEventListener("keydown", _this._onKeyDown);
  20632. canvas.removeEventListener("keyup", _this._onKeyUp);
  20633. });
  20634. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20635. var canvas = this._engine.getRenderingCanvas();
  20636. if (!canvas) {
  20637. return;
  20638. }
  20639. if (attachMove) {
  20640. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20641. // Wheel
  20642. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20643. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20644. }
  20645. if (attachDown) {
  20646. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20647. }
  20648. if (attachUp) {
  20649. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20650. }
  20651. canvas.tabIndex = 1;
  20652. };
  20653. Scene.prototype.detachControl = function () {
  20654. var engine = this.getEngine();
  20655. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20656. var canvas = engine.getRenderingCanvas();
  20657. if (!canvas) {
  20658. return;
  20659. }
  20660. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20661. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20662. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20663. if (this._onCanvasBlurObserver) {
  20664. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20665. }
  20666. if (this._onCanvasFocusObserver) {
  20667. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20668. }
  20669. // Wheel
  20670. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20671. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20672. // Keyboard
  20673. canvas.removeEventListener("keydown", this._onKeyDown);
  20674. canvas.removeEventListener("keyup", this._onKeyUp);
  20675. // Observables
  20676. this.onKeyboardObservable.clear();
  20677. this.onPreKeyboardObservable.clear();
  20678. this.onPointerObservable.clear();
  20679. this.onPrePointerObservable.clear();
  20680. };
  20681. // Ready
  20682. Scene.prototype.isReady = function () {
  20683. if (this._isDisposed) {
  20684. return false;
  20685. }
  20686. if (this._pendingData.length > 0) {
  20687. return false;
  20688. }
  20689. var index;
  20690. // Geometries
  20691. for (index = 0; index < this._geometries.length; index++) {
  20692. var geometry = this._geometries[index];
  20693. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20694. return false;
  20695. }
  20696. }
  20697. // Meshes
  20698. for (index = 0; index < this.meshes.length; index++) {
  20699. var mesh = this.meshes[index];
  20700. if (!mesh.isEnabled()) {
  20701. continue;
  20702. }
  20703. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20704. continue;
  20705. }
  20706. if (!mesh.isReady()) {
  20707. return false;
  20708. }
  20709. var mat = mesh.material;
  20710. if (mat) {
  20711. if (!mat.isReady(mesh)) {
  20712. return false;
  20713. }
  20714. }
  20715. }
  20716. return true;
  20717. };
  20718. Scene.prototype.resetCachedMaterial = function () {
  20719. this._cachedMaterial = null;
  20720. this._cachedEffect = null;
  20721. this._cachedVisibility = null;
  20722. };
  20723. Scene.prototype.registerBeforeRender = function (func) {
  20724. this.onBeforeRenderObservable.add(func);
  20725. };
  20726. Scene.prototype.unregisterBeforeRender = function (func) {
  20727. this.onBeforeRenderObservable.removeCallback(func);
  20728. };
  20729. Scene.prototype.registerAfterRender = function (func) {
  20730. this.onAfterRenderObservable.add(func);
  20731. };
  20732. Scene.prototype.unregisterAfterRender = function (func) {
  20733. this.onAfterRenderObservable.removeCallback(func);
  20734. };
  20735. Scene.prototype._executeOnceBeforeRender = function (func) {
  20736. var _this = this;
  20737. var execFunc = function () {
  20738. func();
  20739. setTimeout(function () {
  20740. _this.unregisterBeforeRender(execFunc);
  20741. });
  20742. };
  20743. this.registerBeforeRender(execFunc);
  20744. };
  20745. /**
  20746. * The provided function will run before render once and will be disposed afterwards.
  20747. * A timeout delay can be provided so that the function will be executed in N ms.
  20748. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20749. * @param func The function to be executed.
  20750. * @param timeout optional delay in ms
  20751. */
  20752. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20753. var _this = this;
  20754. if (timeout !== undefined) {
  20755. setTimeout(function () {
  20756. _this._executeOnceBeforeRender(func);
  20757. }, timeout);
  20758. }
  20759. else {
  20760. this._executeOnceBeforeRender(func);
  20761. }
  20762. };
  20763. Scene.prototype._addPendingData = function (data) {
  20764. this._pendingData.push(data);
  20765. };
  20766. Scene.prototype._removePendingData = function (data) {
  20767. var wasLoading = this.isLoading;
  20768. var index = this._pendingData.indexOf(data);
  20769. if (index !== -1) {
  20770. this._pendingData.splice(index, 1);
  20771. }
  20772. if (wasLoading && !this.isLoading) {
  20773. this.onDataLoadedObservable.notifyObservers(this);
  20774. }
  20775. };
  20776. Scene.prototype.getWaitingItemsCount = function () {
  20777. return this._pendingData.length;
  20778. };
  20779. Object.defineProperty(Scene.prototype, "isLoading", {
  20780. get: function () {
  20781. return this._pendingData.length > 0;
  20782. },
  20783. enumerable: true,
  20784. configurable: true
  20785. });
  20786. /**
  20787. * Registers a function to be executed when the scene is ready.
  20788. * @param {Function} func - the function to be executed.
  20789. */
  20790. Scene.prototype.executeWhenReady = function (func) {
  20791. var _this = this;
  20792. this.onReadyObservable.add(func);
  20793. if (this._executeWhenReadyTimeoutId !== -1) {
  20794. return;
  20795. }
  20796. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20797. _this._checkIsReady();
  20798. }, 150);
  20799. };
  20800. Scene.prototype._checkIsReady = function () {
  20801. var _this = this;
  20802. if (this.isReady()) {
  20803. this.onReadyObservable.notifyObservers(this);
  20804. this.onReadyObservable.clear();
  20805. this._executeWhenReadyTimeoutId = -1;
  20806. return;
  20807. }
  20808. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20809. _this._checkIsReady();
  20810. }, 150);
  20811. };
  20812. // Animations
  20813. /**
  20814. * Will start the animation sequence of a given target
  20815. * @param target - the target
  20816. * @param {number} from - from which frame should animation start
  20817. * @param {number} to - till which frame should animation run.
  20818. * @param {boolean} [loop] - should the animation loop
  20819. * @param {number} [speedRatio] - the speed in which to run the animation
  20820. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20821. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20822. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20823. * See BABYLON.Animatable
  20824. */
  20825. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20826. if (speedRatio === void 0) { speedRatio = 1.0; }
  20827. if (from > to && speedRatio > 0) {
  20828. speedRatio *= -1;
  20829. }
  20830. this.stopAnimation(target);
  20831. if (!animatable) {
  20832. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20833. }
  20834. // Local animations
  20835. if (target.animations) {
  20836. animatable.appendAnimations(target, target.animations);
  20837. }
  20838. // Children animations
  20839. if (target.getAnimatables) {
  20840. var animatables = target.getAnimatables();
  20841. for (var index = 0; index < animatables.length; index++) {
  20842. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20843. }
  20844. }
  20845. animatable.reset();
  20846. return animatable;
  20847. };
  20848. /**
  20849. * Begin a new animation on a given node
  20850. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20851. * @param {BABYLON.Animation[]} defines the list of animations to start
  20852. * @param {number} from defines the initial value
  20853. * @param {number} to defines the final value
  20854. * @param {boolean} loop defines if you want animation to loop (off by default)
  20855. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20856. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20857. * @returns the list of created animatables
  20858. */
  20859. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20860. if (speedRatio === undefined) {
  20861. speedRatio = 1.0;
  20862. }
  20863. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20864. return animatable;
  20865. };
  20866. /**
  20867. * Begin a new animation on a given node and its hierarchy
  20868. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20869. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  20870. * @param {BABYLON.Animation[]} defines the list of animations to start
  20871. * @param {number} from defines the initial value
  20872. * @param {number} to defines the final value
  20873. * @param {boolean} loop defines if you want animation to loop (off by default)
  20874. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20875. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20876. * @returns the list of animatables created for all nodes
  20877. */
  20878. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20879. var children = target.getDescendants(directDescendantsOnly);
  20880. var result = [];
  20881. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20882. var child = children_1[_i];
  20883. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20884. }
  20885. return result;
  20886. };
  20887. Scene.prototype.getAnimatableByTarget = function (target) {
  20888. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20889. if (this._activeAnimatables[index].target === target) {
  20890. return this._activeAnimatables[index];
  20891. }
  20892. }
  20893. return null;
  20894. };
  20895. Object.defineProperty(Scene.prototype, "animatables", {
  20896. get: function () {
  20897. return this._activeAnimatables;
  20898. },
  20899. enumerable: true,
  20900. configurable: true
  20901. });
  20902. /**
  20903. * Will stop the animation of the given target
  20904. * @param target - the target
  20905. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20906. * @see beginAnimation
  20907. */
  20908. Scene.prototype.stopAnimation = function (target, animationName) {
  20909. var animatable = this.getAnimatableByTarget(target);
  20910. if (animatable) {
  20911. animatable.stop(animationName);
  20912. }
  20913. };
  20914. /**
  20915. * Stops and removes all animations that have been applied to the scene
  20916. */
  20917. Scene.prototype.stopAllAnimations = function () {
  20918. if (this._activeAnimatables) {
  20919. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20920. this._activeAnimatables[i].stop();
  20921. }
  20922. this._activeAnimatables = [];
  20923. }
  20924. };
  20925. Scene.prototype._animate = function () {
  20926. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20927. return;
  20928. }
  20929. // Getting time
  20930. var now = BABYLON.Tools.Now;
  20931. if (!this._animationTimeLast) {
  20932. if (this._pendingData.length > 0) {
  20933. return;
  20934. }
  20935. this._animationTimeLast = now;
  20936. }
  20937. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20938. this._animationTime += deltaTime;
  20939. this._animationTimeLast = now;
  20940. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20941. this._activeAnimatables[index]._animate(this._animationTime);
  20942. }
  20943. };
  20944. // Matrix
  20945. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20946. this._useAlternateCameraConfiguration = active;
  20947. };
  20948. Scene.prototype.getViewMatrix = function () {
  20949. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20950. };
  20951. Scene.prototype.getProjectionMatrix = function () {
  20952. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20953. };
  20954. Scene.prototype.getTransformMatrix = function () {
  20955. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20956. };
  20957. Scene.prototype.setTransformMatrix = function (view, projection) {
  20958. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20959. return;
  20960. }
  20961. this._viewUpdateFlag = view.updateFlag;
  20962. this._projectionUpdateFlag = projection.updateFlag;
  20963. this._viewMatrix = view;
  20964. this._projectionMatrix = projection;
  20965. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20966. // Update frustum
  20967. if (!this._frustumPlanes) {
  20968. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20969. }
  20970. else {
  20971. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20972. }
  20973. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20974. var otherCamera = this.activeCamera._alternateCamera;
  20975. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20976. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20977. }
  20978. if (this._sceneUbo.useUbo) {
  20979. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20980. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20981. this._sceneUbo.update();
  20982. }
  20983. };
  20984. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20985. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20986. return;
  20987. }
  20988. this._alternateViewUpdateFlag = view.updateFlag;
  20989. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20990. this._alternateViewMatrix = view;
  20991. this._alternateProjectionMatrix = projection;
  20992. if (!this._alternateTransformMatrix) {
  20993. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20994. }
  20995. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20996. if (!this._alternateSceneUbo) {
  20997. this._createAlternateUbo();
  20998. }
  20999. if (this._alternateSceneUbo.useUbo) {
  21000. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21001. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21002. this._alternateSceneUbo.update();
  21003. }
  21004. };
  21005. Scene.prototype.getSceneUniformBuffer = function () {
  21006. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21007. };
  21008. // Methods
  21009. Scene.prototype.getUniqueId = function () {
  21010. var result = Scene._uniqueIdCounter;
  21011. Scene._uniqueIdCounter++;
  21012. return result;
  21013. };
  21014. Scene.prototype.addMesh = function (newMesh) {
  21015. this.meshes.push(newMesh);
  21016. //notify the collision coordinator
  21017. if (this.collisionCoordinator) {
  21018. this.collisionCoordinator.onMeshAdded(newMesh);
  21019. }
  21020. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21021. };
  21022. Scene.prototype.removeMesh = function (toRemove) {
  21023. var index = this.meshes.indexOf(toRemove);
  21024. if (index !== -1) {
  21025. // Remove from the scene if mesh found
  21026. this.meshes.splice(index, 1);
  21027. }
  21028. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21029. return index;
  21030. };
  21031. Scene.prototype.addTransformNode = function (newTransformNode) {
  21032. this.transformNodes.push(newTransformNode);
  21033. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21034. };
  21035. Scene.prototype.removeTransformNode = function (toRemove) {
  21036. var index = this.transformNodes.indexOf(toRemove);
  21037. if (index !== -1) {
  21038. // Remove from the scene if found
  21039. this.transformNodes.splice(index, 1);
  21040. }
  21041. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21042. return index;
  21043. };
  21044. Scene.prototype.removeSkeleton = function (toRemove) {
  21045. var index = this.skeletons.indexOf(toRemove);
  21046. if (index !== -1) {
  21047. // Remove from the scene if found
  21048. this.skeletons.splice(index, 1);
  21049. }
  21050. return index;
  21051. };
  21052. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21053. var index = this.morphTargetManagers.indexOf(toRemove);
  21054. if (index !== -1) {
  21055. // Remove from the scene if found
  21056. this.morphTargetManagers.splice(index, 1);
  21057. }
  21058. return index;
  21059. };
  21060. Scene.prototype.removeLight = function (toRemove) {
  21061. var index = this.lights.indexOf(toRemove);
  21062. if (index !== -1) {
  21063. // Remove from meshes
  21064. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21065. var mesh = _a[_i];
  21066. mesh._removeLightSource(toRemove);
  21067. }
  21068. // Remove from the scene if mesh found
  21069. this.lights.splice(index, 1);
  21070. this.sortLightsByPriority();
  21071. }
  21072. this.onLightRemovedObservable.notifyObservers(toRemove);
  21073. return index;
  21074. };
  21075. Scene.prototype.removeCamera = function (toRemove) {
  21076. var index = this.cameras.indexOf(toRemove);
  21077. if (index !== -1) {
  21078. // Remove from the scene if mesh found
  21079. this.cameras.splice(index, 1);
  21080. }
  21081. // Remove from activeCameras
  21082. var index2 = this.activeCameras.indexOf(toRemove);
  21083. if (index2 !== -1) {
  21084. // Remove from the scene if mesh found
  21085. this.activeCameras.splice(index2, 1);
  21086. }
  21087. // Reset the activeCamera
  21088. if (this.activeCamera === toRemove) {
  21089. if (this.cameras.length > 0) {
  21090. this.activeCamera = this.cameras[0];
  21091. }
  21092. else {
  21093. this.activeCamera = null;
  21094. }
  21095. }
  21096. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21097. return index;
  21098. };
  21099. Scene.prototype.addLight = function (newLight) {
  21100. this.lights.push(newLight);
  21101. this.sortLightsByPriority();
  21102. // Add light to all meshes (To support if the light is removed and then readded)
  21103. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21104. var mesh = _a[_i];
  21105. if (mesh._lightSources.indexOf(newLight) === -1) {
  21106. mesh._lightSources.push(newLight);
  21107. mesh._resyncLightSources();
  21108. }
  21109. }
  21110. this.onNewLightAddedObservable.notifyObservers(newLight);
  21111. };
  21112. Scene.prototype.sortLightsByPriority = function () {
  21113. if (this.requireLightSorting) {
  21114. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21115. }
  21116. };
  21117. Scene.prototype.addCamera = function (newCamera) {
  21118. this.cameras.push(newCamera);
  21119. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21120. };
  21121. /**
  21122. * Switch active camera
  21123. * @param {Camera} newCamera - new active camera
  21124. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21125. */
  21126. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21127. if (attachControl === void 0) { attachControl = true; }
  21128. var canvas = this._engine.getRenderingCanvas();
  21129. if (!canvas) {
  21130. return;
  21131. }
  21132. if (this.activeCamera) {
  21133. this.activeCamera.detachControl(canvas);
  21134. }
  21135. this.activeCamera = newCamera;
  21136. if (attachControl) {
  21137. newCamera.attachControl(canvas);
  21138. }
  21139. };
  21140. /**
  21141. * sets the active camera of the scene using its ID
  21142. * @param {string} id - the camera's ID
  21143. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21144. * @see activeCamera
  21145. */
  21146. Scene.prototype.setActiveCameraByID = function (id) {
  21147. var camera = this.getCameraByID(id);
  21148. if (camera) {
  21149. this.activeCamera = camera;
  21150. return camera;
  21151. }
  21152. return null;
  21153. };
  21154. /**
  21155. * sets the active camera of the scene using its name
  21156. * @param {string} name - the camera's name
  21157. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21158. * @see activeCamera
  21159. */
  21160. Scene.prototype.setActiveCameraByName = function (name) {
  21161. var camera = this.getCameraByName(name);
  21162. if (camera) {
  21163. this.activeCamera = camera;
  21164. return camera;
  21165. }
  21166. return null;
  21167. };
  21168. /**
  21169. * get an animation group using its name
  21170. * @param {string} the material's name
  21171. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21172. */
  21173. Scene.prototype.getAnimationGroupByName = function (name) {
  21174. for (var index = 0; index < this.animationGroups.length; index++) {
  21175. if (this.animationGroups[index].name === name) {
  21176. return this.animationGroups[index];
  21177. }
  21178. }
  21179. return null;
  21180. };
  21181. /**
  21182. * get a material using its id
  21183. * @param {string} the material's ID
  21184. * @return {BABYLON.Material|null} the material or null if none found.
  21185. */
  21186. Scene.prototype.getMaterialByID = function (id) {
  21187. for (var index = 0; index < this.materials.length; index++) {
  21188. if (this.materials[index].id === id) {
  21189. return this.materials[index];
  21190. }
  21191. }
  21192. return null;
  21193. };
  21194. /**
  21195. * get a material using its name
  21196. * @param {string} the material's name
  21197. * @return {BABYLON.Material|null} the material or null if none found.
  21198. */
  21199. Scene.prototype.getMaterialByName = function (name) {
  21200. for (var index = 0; index < this.materials.length; index++) {
  21201. if (this.materials[index].name === name) {
  21202. return this.materials[index];
  21203. }
  21204. }
  21205. return null;
  21206. };
  21207. Scene.prototype.getLensFlareSystemByName = function (name) {
  21208. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21209. if (this.lensFlareSystems[index].name === name) {
  21210. return this.lensFlareSystems[index];
  21211. }
  21212. }
  21213. return null;
  21214. };
  21215. Scene.prototype.getLensFlareSystemByID = function (id) {
  21216. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21217. if (this.lensFlareSystems[index].id === id) {
  21218. return this.lensFlareSystems[index];
  21219. }
  21220. }
  21221. return null;
  21222. };
  21223. Scene.prototype.getCameraByID = function (id) {
  21224. for (var index = 0; index < this.cameras.length; index++) {
  21225. if (this.cameras[index].id === id) {
  21226. return this.cameras[index];
  21227. }
  21228. }
  21229. return null;
  21230. };
  21231. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21232. for (var index = 0; index < this.cameras.length; index++) {
  21233. if (this.cameras[index].uniqueId === uniqueId) {
  21234. return this.cameras[index];
  21235. }
  21236. }
  21237. return null;
  21238. };
  21239. /**
  21240. * get a camera using its name
  21241. * @param {string} the camera's name
  21242. * @return {BABYLON.Camera|null} the camera or null if none found.
  21243. */
  21244. Scene.prototype.getCameraByName = function (name) {
  21245. for (var index = 0; index < this.cameras.length; index++) {
  21246. if (this.cameras[index].name === name) {
  21247. return this.cameras[index];
  21248. }
  21249. }
  21250. return null;
  21251. };
  21252. /**
  21253. * get a bone using its id
  21254. * @param {string} the bone's id
  21255. * @return {BABYLON.Bone|null} the bone or null if not found
  21256. */
  21257. Scene.prototype.getBoneByID = function (id) {
  21258. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21259. var skeleton = this.skeletons[skeletonIndex];
  21260. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21261. if (skeleton.bones[boneIndex].id === id) {
  21262. return skeleton.bones[boneIndex];
  21263. }
  21264. }
  21265. }
  21266. return null;
  21267. };
  21268. /**
  21269. * get a bone using its id
  21270. * @param {string} the bone's name
  21271. * @return {BABYLON.Bone|null} the bone or null if not found
  21272. */
  21273. Scene.prototype.getBoneByName = function (name) {
  21274. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21275. var skeleton = this.skeletons[skeletonIndex];
  21276. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21277. if (skeleton.bones[boneIndex].name === name) {
  21278. return skeleton.bones[boneIndex];
  21279. }
  21280. }
  21281. }
  21282. return null;
  21283. };
  21284. /**
  21285. * get a light node using its name
  21286. * @param {string} the light's name
  21287. * @return {BABYLON.Light|null} the light or null if none found.
  21288. */
  21289. Scene.prototype.getLightByName = function (name) {
  21290. for (var index = 0; index < this.lights.length; index++) {
  21291. if (this.lights[index].name === name) {
  21292. return this.lights[index];
  21293. }
  21294. }
  21295. return null;
  21296. };
  21297. /**
  21298. * get a light node using its ID
  21299. * @param {string} the light's id
  21300. * @return {BABYLON.Light|null} the light or null if none found.
  21301. */
  21302. Scene.prototype.getLightByID = function (id) {
  21303. for (var index = 0; index < this.lights.length; index++) {
  21304. if (this.lights[index].id === id) {
  21305. return this.lights[index];
  21306. }
  21307. }
  21308. return null;
  21309. };
  21310. /**
  21311. * get a light node using its scene-generated unique ID
  21312. * @param {number} the light's unique id
  21313. * @return {BABYLON.Light|null} the light or null if none found.
  21314. */
  21315. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21316. for (var index = 0; index < this.lights.length; index++) {
  21317. if (this.lights[index].uniqueId === uniqueId) {
  21318. return this.lights[index];
  21319. }
  21320. }
  21321. return null;
  21322. };
  21323. /**
  21324. * get a particle system by id
  21325. * @param id {number} the particle system id
  21326. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21327. */
  21328. Scene.prototype.getParticleSystemByID = function (id) {
  21329. for (var index = 0; index < this.particleSystems.length; index++) {
  21330. if (this.particleSystems[index].id === id) {
  21331. return this.particleSystems[index];
  21332. }
  21333. }
  21334. return null;
  21335. };
  21336. /**
  21337. * get a geometry using its ID
  21338. * @param {string} the geometry's id
  21339. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21340. */
  21341. Scene.prototype.getGeometryByID = function (id) {
  21342. for (var index = 0; index < this._geometries.length; index++) {
  21343. if (this._geometries[index].id === id) {
  21344. return this._geometries[index];
  21345. }
  21346. }
  21347. return null;
  21348. };
  21349. /**
  21350. * add a new geometry to this scene.
  21351. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21352. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21353. * @return {boolean} was the geometry added or not
  21354. */
  21355. Scene.prototype.pushGeometry = function (geometry, force) {
  21356. if (!force && this.getGeometryByID(geometry.id)) {
  21357. return false;
  21358. }
  21359. this._geometries.push(geometry);
  21360. //notify the collision coordinator
  21361. if (this.collisionCoordinator) {
  21362. this.collisionCoordinator.onGeometryAdded(geometry);
  21363. }
  21364. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21365. return true;
  21366. };
  21367. /**
  21368. * Removes an existing geometry
  21369. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21370. * @return {boolean} was the geometry removed or not
  21371. */
  21372. Scene.prototype.removeGeometry = function (geometry) {
  21373. var index = this._geometries.indexOf(geometry);
  21374. if (index > -1) {
  21375. this._geometries.splice(index, 1);
  21376. //notify the collision coordinator
  21377. if (this.collisionCoordinator) {
  21378. this.collisionCoordinator.onGeometryDeleted(geometry);
  21379. }
  21380. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21381. return true;
  21382. }
  21383. return false;
  21384. };
  21385. Scene.prototype.getGeometries = function () {
  21386. return this._geometries;
  21387. };
  21388. /**
  21389. * Get the first added mesh found of a given ID
  21390. * @param {string} id - the id to search for
  21391. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21392. */
  21393. Scene.prototype.getMeshByID = function (id) {
  21394. for (var index = 0; index < this.meshes.length; index++) {
  21395. if (this.meshes[index].id === id) {
  21396. return this.meshes[index];
  21397. }
  21398. }
  21399. return null;
  21400. };
  21401. Scene.prototype.getMeshesByID = function (id) {
  21402. return this.meshes.filter(function (m) {
  21403. return m.id === id;
  21404. });
  21405. };
  21406. /**
  21407. * Get the first added transform node found of a given ID
  21408. * @param {string} id - the id to search for
  21409. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21410. */
  21411. Scene.prototype.getTransformNodeByID = function (id) {
  21412. for (var index = 0; index < this.transformNodes.length; index++) {
  21413. if (this.transformNodes[index].id === id) {
  21414. return this.transformNodes[index];
  21415. }
  21416. }
  21417. return null;
  21418. };
  21419. Scene.prototype.getTransformNodesByID = function (id) {
  21420. return this.transformNodes.filter(function (m) {
  21421. return m.id === id;
  21422. });
  21423. };
  21424. /**
  21425. * Get a mesh with its auto-generated unique id
  21426. * @param {number} uniqueId - the unique id to search for
  21427. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21428. */
  21429. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21430. for (var index = 0; index < this.meshes.length; index++) {
  21431. if (this.meshes[index].uniqueId === uniqueId) {
  21432. return this.meshes[index];
  21433. }
  21434. }
  21435. return null;
  21436. };
  21437. /**
  21438. * Get a the last added mesh found of a given ID
  21439. * @param {string} id - the id to search for
  21440. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21441. */
  21442. Scene.prototype.getLastMeshByID = function (id) {
  21443. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21444. if (this.meshes[index].id === id) {
  21445. return this.meshes[index];
  21446. }
  21447. }
  21448. return null;
  21449. };
  21450. /**
  21451. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21452. * @param {string} id - the id to search for
  21453. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21454. */
  21455. Scene.prototype.getLastEntryByID = function (id) {
  21456. var index;
  21457. for (index = this.meshes.length - 1; index >= 0; index--) {
  21458. if (this.meshes[index].id === id) {
  21459. return this.meshes[index];
  21460. }
  21461. }
  21462. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21463. if (this.transformNodes[index].id === id) {
  21464. return this.transformNodes[index];
  21465. }
  21466. }
  21467. for (index = this.cameras.length - 1; index >= 0; index--) {
  21468. if (this.cameras[index].id === id) {
  21469. return this.cameras[index];
  21470. }
  21471. }
  21472. for (index = this.lights.length - 1; index >= 0; index--) {
  21473. if (this.lights[index].id === id) {
  21474. return this.lights[index];
  21475. }
  21476. }
  21477. return null;
  21478. };
  21479. Scene.prototype.getNodeByID = function (id) {
  21480. var mesh = this.getMeshByID(id);
  21481. if (mesh) {
  21482. return mesh;
  21483. }
  21484. var light = this.getLightByID(id);
  21485. if (light) {
  21486. return light;
  21487. }
  21488. var camera = this.getCameraByID(id);
  21489. if (camera) {
  21490. return camera;
  21491. }
  21492. var bone = this.getBoneByID(id);
  21493. return bone;
  21494. };
  21495. Scene.prototype.getNodeByName = function (name) {
  21496. var mesh = this.getMeshByName(name);
  21497. if (mesh) {
  21498. return mesh;
  21499. }
  21500. var light = this.getLightByName(name);
  21501. if (light) {
  21502. return light;
  21503. }
  21504. var camera = this.getCameraByName(name);
  21505. if (camera) {
  21506. return camera;
  21507. }
  21508. var bone = this.getBoneByName(name);
  21509. return bone;
  21510. };
  21511. Scene.prototype.getMeshByName = function (name) {
  21512. for (var index = 0; index < this.meshes.length; index++) {
  21513. if (this.meshes[index].name === name) {
  21514. return this.meshes[index];
  21515. }
  21516. }
  21517. return null;
  21518. };
  21519. Scene.prototype.getTransformNodeByName = function (name) {
  21520. for (var index = 0; index < this.transformNodes.length; index++) {
  21521. if (this.transformNodes[index].name === name) {
  21522. return this.transformNodes[index];
  21523. }
  21524. }
  21525. return null;
  21526. };
  21527. Scene.prototype.getSoundByName = function (name) {
  21528. var index;
  21529. if (BABYLON.AudioEngine) {
  21530. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21531. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21532. return this.mainSoundTrack.soundCollection[index];
  21533. }
  21534. }
  21535. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21536. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21537. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21538. return this.soundTracks[sdIndex].soundCollection[index];
  21539. }
  21540. }
  21541. }
  21542. }
  21543. return null;
  21544. };
  21545. Scene.prototype.getLastSkeletonByID = function (id) {
  21546. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21547. if (this.skeletons[index].id === id) {
  21548. return this.skeletons[index];
  21549. }
  21550. }
  21551. return null;
  21552. };
  21553. Scene.prototype.getSkeletonById = function (id) {
  21554. for (var index = 0; index < this.skeletons.length; index++) {
  21555. if (this.skeletons[index].id === id) {
  21556. return this.skeletons[index];
  21557. }
  21558. }
  21559. return null;
  21560. };
  21561. Scene.prototype.getSkeletonByName = function (name) {
  21562. for (var index = 0; index < this.skeletons.length; index++) {
  21563. if (this.skeletons[index].name === name) {
  21564. return this.skeletons[index];
  21565. }
  21566. }
  21567. return null;
  21568. };
  21569. Scene.prototype.getMorphTargetManagerById = function (id) {
  21570. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21571. if (this.morphTargetManagers[index].uniqueId === id) {
  21572. return this.morphTargetManagers[index];
  21573. }
  21574. }
  21575. return null;
  21576. };
  21577. Scene.prototype.isActiveMesh = function (mesh) {
  21578. return (this._activeMeshes.indexOf(mesh) !== -1);
  21579. };
  21580. /**
  21581. * Return a the first highlight layer of the scene with a given name.
  21582. * @param name The name of the highlight layer to look for.
  21583. * @return The highlight layer if found otherwise null.
  21584. */
  21585. Scene.prototype.getHighlightLayerByName = function (name) {
  21586. for (var index = 0; index < this.highlightLayers.length; index++) {
  21587. if (this.highlightLayers[index].name === name) {
  21588. return this.highlightLayers[index];
  21589. }
  21590. }
  21591. return null;
  21592. };
  21593. Object.defineProperty(Scene.prototype, "uid", {
  21594. /**
  21595. * Return a unique id as a string which can serve as an identifier for the scene
  21596. */
  21597. get: function () {
  21598. if (!this._uid) {
  21599. this._uid = BABYLON.Tools.RandomId();
  21600. }
  21601. return this._uid;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. /**
  21607. * Add an externaly attached data from its key.
  21608. * This method call will fail and return false, if such key already exists.
  21609. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21610. * @param key the unique key that identifies the data
  21611. * @param data the data object to associate to the key for this Engine instance
  21612. * @return true if no such key were already present and the data was added successfully, false otherwise
  21613. */
  21614. Scene.prototype.addExternalData = function (key, data) {
  21615. if (!this._externalData) {
  21616. this._externalData = new BABYLON.StringDictionary();
  21617. }
  21618. return this._externalData.add(key, data);
  21619. };
  21620. /**
  21621. * Get an externaly attached data from its key
  21622. * @param key the unique key that identifies the data
  21623. * @return the associated data, if present (can be null), or undefined if not present
  21624. */
  21625. Scene.prototype.getExternalData = function (key) {
  21626. if (!this._externalData) {
  21627. return null;
  21628. }
  21629. return this._externalData.get(key);
  21630. };
  21631. /**
  21632. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21633. * @param key the unique key that identifies the data
  21634. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21635. * @return the associated data, can be null if the factory returned null.
  21636. */
  21637. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21638. if (!this._externalData) {
  21639. this._externalData = new BABYLON.StringDictionary();
  21640. }
  21641. return this._externalData.getOrAddWithFactory(key, factory);
  21642. };
  21643. /**
  21644. * Remove an externaly attached data from the Engine instance
  21645. * @param key the unique key that identifies the data
  21646. * @return true if the data was successfully removed, false if it doesn't exist
  21647. */
  21648. Scene.prototype.removeExternalData = function (key) {
  21649. return this._externalData.remove(key);
  21650. };
  21651. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21652. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21653. if (mesh.showSubMeshesBoundingBox) {
  21654. var boundingInfo = subMesh.getBoundingInfo();
  21655. if (boundingInfo !== null && boundingInfo !== undefined) {
  21656. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21657. }
  21658. }
  21659. var material = subMesh.getMaterial();
  21660. if (material !== null && material !== undefined) {
  21661. // Render targets
  21662. if (material.getRenderTargetTextures !== undefined) {
  21663. if (this._processedMaterials.indexOf(material) === -1) {
  21664. this._processedMaterials.push(material);
  21665. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21666. }
  21667. }
  21668. // Dispatch
  21669. this._activeIndices.addCount(subMesh.indexCount, false);
  21670. this._renderingManager.dispatch(subMesh, mesh, material);
  21671. }
  21672. }
  21673. };
  21674. Scene.prototype._isInIntermediateRendering = function () {
  21675. return this._intermediateRendering;
  21676. };
  21677. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21678. this._activeMeshCandidateProvider = provider;
  21679. };
  21680. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21681. return this._activeMeshCandidateProvider;
  21682. };
  21683. /**
  21684. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21685. */
  21686. Scene.prototype.freezeActiveMeshes = function () {
  21687. this._evaluateActiveMeshes();
  21688. this._activeMeshesFrozen = true;
  21689. return this;
  21690. };
  21691. /**
  21692. * Use this function to restart evaluating active meshes on every frame
  21693. */
  21694. Scene.prototype.unfreezeActiveMeshes = function () {
  21695. this._activeMeshesFrozen = false;
  21696. return this;
  21697. };
  21698. Scene.prototype._evaluateActiveMeshes = function () {
  21699. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21700. return;
  21701. }
  21702. if (!this.activeCamera) {
  21703. return;
  21704. }
  21705. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21706. this.activeCamera._activeMeshes.reset();
  21707. this._activeMeshes.reset();
  21708. this._renderingManager.reset();
  21709. this._processedMaterials.reset();
  21710. this._activeParticleSystems.reset();
  21711. this._activeSkeletons.reset();
  21712. this._softwareSkinnedMeshes.reset();
  21713. if (this._boundingBoxRenderer) {
  21714. this._boundingBoxRenderer.reset();
  21715. }
  21716. // Meshes
  21717. var meshes;
  21718. var len;
  21719. var checkIsEnabled = true;
  21720. // Determine mesh candidates
  21721. if (this._activeMeshCandidateProvider !== undefined) {
  21722. // Use _activeMeshCandidateProvider
  21723. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21724. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21725. if (meshes !== undefined) {
  21726. len = meshes.length;
  21727. }
  21728. else {
  21729. len = 0;
  21730. }
  21731. }
  21732. else if (this._selectionOctree !== undefined) {
  21733. // Octree
  21734. var selection = this._selectionOctree.select(this._frustumPlanes);
  21735. meshes = selection.data;
  21736. len = selection.length;
  21737. }
  21738. else {
  21739. // Full scene traversal
  21740. len = this.meshes.length;
  21741. meshes = this.meshes;
  21742. }
  21743. // Check each mesh
  21744. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21745. mesh = meshes[meshIndex];
  21746. if (mesh.isBlocked) {
  21747. continue;
  21748. }
  21749. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21750. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21751. continue;
  21752. }
  21753. mesh.computeWorldMatrix();
  21754. // Intersections
  21755. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21756. this._meshesForIntersections.pushNoDuplicate(mesh);
  21757. }
  21758. // Switch to current LOD
  21759. meshLOD = mesh.getLOD(this.activeCamera);
  21760. if (meshLOD === undefined || meshLOD === null) {
  21761. continue;
  21762. }
  21763. mesh._preActivate();
  21764. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21765. this._activeMeshes.push(mesh);
  21766. this.activeCamera._activeMeshes.push(mesh);
  21767. mesh._activate(this._renderId);
  21768. if (meshLOD !== mesh) {
  21769. meshLOD._activate(this._renderId);
  21770. }
  21771. this._activeMesh(mesh, meshLOD);
  21772. }
  21773. }
  21774. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21775. // Particle systems
  21776. if (this.particlesEnabled) {
  21777. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21778. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21779. var particleSystem = this.particleSystems[particleIndex];
  21780. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21781. continue;
  21782. }
  21783. var emitter = particleSystem.emitter;
  21784. if (!emitter.position || emitter.isEnabled()) {
  21785. this._activeParticleSystems.push(particleSystem);
  21786. particleSystem.animate();
  21787. this._renderingManager.dispatchParticles(particleSystem);
  21788. }
  21789. }
  21790. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21791. }
  21792. };
  21793. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21794. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21795. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21796. mesh.skeleton.prepare();
  21797. }
  21798. if (!mesh.computeBonesUsingShaders) {
  21799. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21800. }
  21801. }
  21802. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21803. var boundingInfo = sourceMesh.getBoundingInfo();
  21804. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21805. }
  21806. if (mesh !== undefined && mesh !== null
  21807. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21808. // Submeshes Octrees
  21809. var len;
  21810. var subMeshes;
  21811. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21812. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21813. len = intersections.length;
  21814. subMeshes = intersections.data;
  21815. }
  21816. else {
  21817. subMeshes = mesh.subMeshes;
  21818. len = subMeshes.length;
  21819. }
  21820. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21821. subMesh = subMeshes[subIndex];
  21822. this._evaluateSubMesh(subMesh, mesh);
  21823. }
  21824. }
  21825. };
  21826. Scene.prototype.updateTransformMatrix = function (force) {
  21827. if (!this.activeCamera) {
  21828. return;
  21829. }
  21830. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21831. };
  21832. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21833. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21834. };
  21835. Scene.prototype._renderForCamera = function (camera) {
  21836. if (camera && camera._skipRendering) {
  21837. return;
  21838. }
  21839. var engine = this._engine;
  21840. this.activeCamera = camera;
  21841. if (!this.activeCamera)
  21842. throw new Error("Active camera not set");
  21843. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21844. // Viewport
  21845. engine.setViewport(this.activeCamera.viewport);
  21846. // Camera
  21847. this.resetCachedMaterial();
  21848. this._renderId++;
  21849. this.activeCamera.update();
  21850. this.updateTransformMatrix();
  21851. if (camera._alternateCamera) {
  21852. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21853. this._alternateRendering = true;
  21854. }
  21855. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21856. // Meshes
  21857. this._evaluateActiveMeshes();
  21858. // Software skinning
  21859. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21860. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21861. mesh.applySkeleton(mesh.skeleton);
  21862. }
  21863. // Render targets
  21864. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21865. var needsRestoreFrameBuffer = false;
  21866. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21867. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21868. }
  21869. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21870. this._intermediateRendering = true;
  21871. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21872. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21873. var renderTarget = this._renderTargets.data[renderIndex];
  21874. if (renderTarget._shouldRender()) {
  21875. this._renderId++;
  21876. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21877. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21878. }
  21879. }
  21880. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21881. this._intermediateRendering = false;
  21882. this._renderId++;
  21883. needsRestoreFrameBuffer = true; // Restore back buffer
  21884. }
  21885. // Render HighlightLayer Texture
  21886. var stencilState = this._engine.getStencilBuffer();
  21887. var renderhighlights = false;
  21888. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21889. this._intermediateRendering = true;
  21890. for (var i = 0; i < this.highlightLayers.length; i++) {
  21891. var highlightLayer = this.highlightLayers[i];
  21892. if (highlightLayer.shouldRender() &&
  21893. (!highlightLayer.camera ||
  21894. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21895. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21896. renderhighlights = true;
  21897. var renderTarget = highlightLayer._mainTexture;
  21898. if (renderTarget._shouldRender()) {
  21899. this._renderId++;
  21900. renderTarget.render(false, false);
  21901. needsRestoreFrameBuffer = true;
  21902. }
  21903. }
  21904. }
  21905. this._intermediateRendering = false;
  21906. this._renderId++;
  21907. }
  21908. if (needsRestoreFrameBuffer) {
  21909. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21910. }
  21911. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21912. // Prepare Frame
  21913. this.postProcessManager._prepareFrame();
  21914. // Backgrounds
  21915. var layerIndex;
  21916. var layer;
  21917. if (this.layers.length) {
  21918. engine.setDepthBuffer(false);
  21919. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21920. layer = this.layers[layerIndex];
  21921. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21922. layer.render();
  21923. }
  21924. }
  21925. engine.setDepthBuffer(true);
  21926. }
  21927. // Activate HighlightLayer stencil
  21928. if (renderhighlights) {
  21929. this._engine.setStencilBuffer(true);
  21930. }
  21931. // Render
  21932. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21933. this._renderingManager.render(null, null, true, true);
  21934. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21935. // Restore HighlightLayer stencil
  21936. if (renderhighlights) {
  21937. this._engine.setStencilBuffer(stencilState);
  21938. }
  21939. // Bounding boxes
  21940. if (this._boundingBoxRenderer) {
  21941. this._boundingBoxRenderer.render();
  21942. }
  21943. // Lens flares
  21944. if (this.lensFlaresEnabled) {
  21945. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21946. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21947. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21948. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21949. lensFlareSystem.render();
  21950. }
  21951. }
  21952. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21953. }
  21954. // Foregrounds
  21955. if (this.layers.length) {
  21956. engine.setDepthBuffer(false);
  21957. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21958. layer = this.layers[layerIndex];
  21959. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21960. layer.render();
  21961. }
  21962. }
  21963. engine.setDepthBuffer(true);
  21964. }
  21965. // Highlight Layer
  21966. if (renderhighlights) {
  21967. engine.setDepthBuffer(false);
  21968. for (var i = 0; i < this.highlightLayers.length; i++) {
  21969. if (this.highlightLayers[i].shouldRender()) {
  21970. this.highlightLayers[i].render();
  21971. }
  21972. }
  21973. engine.setDepthBuffer(true);
  21974. }
  21975. // Finalize frame
  21976. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21977. // Reset some special arrays
  21978. this._renderTargets.reset();
  21979. this._alternateRendering = false;
  21980. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21981. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21982. };
  21983. Scene.prototype._processSubCameras = function (camera) {
  21984. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21985. this._renderForCamera(camera);
  21986. return;
  21987. }
  21988. // Update camera
  21989. if (this.activeCamera) {
  21990. this.activeCamera.update();
  21991. }
  21992. // rig cameras
  21993. for (var index = 0; index < camera._rigCameras.length; index++) {
  21994. this._renderForCamera(camera._rigCameras[index]);
  21995. }
  21996. this.activeCamera = camera;
  21997. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21998. };
  21999. Scene.prototype._checkIntersections = function () {
  22000. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22001. var sourceMesh = this._meshesForIntersections.data[index];
  22002. if (!sourceMesh.actionManager) {
  22003. continue;
  22004. }
  22005. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22006. var action = sourceMesh.actionManager.actions[actionIndex];
  22007. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22008. var parameters = action.getTriggerParameter();
  22009. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22010. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22011. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22012. if (areIntersecting && currentIntersectionInProgress === -1) {
  22013. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22014. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22015. sourceMesh._intersectionsInProgress.push(otherMesh);
  22016. }
  22017. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22018. sourceMesh._intersectionsInProgress.push(otherMesh);
  22019. }
  22020. }
  22021. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22022. //They intersected, and now they don't.
  22023. //is this trigger an exit trigger? execute an event.
  22024. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22025. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22026. }
  22027. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22028. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22029. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22030. }
  22031. }
  22032. }
  22033. }
  22034. }
  22035. };
  22036. Scene.prototype.render = function () {
  22037. if (this.isDisposed) {
  22038. return;
  22039. }
  22040. this._activeParticles.fetchNewFrame();
  22041. this._totalVertices.fetchNewFrame();
  22042. this._activeIndices.fetchNewFrame();
  22043. this._activeBones.fetchNewFrame();
  22044. this._meshesForIntersections.reset();
  22045. this.resetCachedMaterial();
  22046. this.onBeforeAnimationsObservable.notifyObservers(this);
  22047. // Actions
  22048. if (this.actionManager) {
  22049. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22050. }
  22051. //Simplification Queue
  22052. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22053. this.simplificationQueue.executeNext();
  22054. }
  22055. if (this._engine.isDeterministicLockStep()) {
  22056. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22057. var defaultFPS = (60.0 / 1000.0);
  22058. var defaultFrameTime = 1000 / 60; // frame time in MS
  22059. if (this._physicsEngine) {
  22060. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22061. }
  22062. var stepsTaken = 0;
  22063. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22064. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22065. internalSteps = Math.min(internalSteps, maxSubSteps);
  22066. do {
  22067. this.onBeforeStepObservable.notifyObservers(this);
  22068. // Animations
  22069. this._animationRatio = defaultFrameTime * defaultFPS;
  22070. this._animate();
  22071. this.onAfterAnimationsObservable.notifyObservers(this);
  22072. // Physics
  22073. if (this._physicsEngine) {
  22074. this.onBeforePhysicsObservable.notifyObservers(this);
  22075. this._physicsEngine._step(defaultFrameTime / 1000);
  22076. this.onAfterPhysicsObservable.notifyObservers(this);
  22077. }
  22078. this.onAfterStepObservable.notifyObservers(this);
  22079. this._currentStepId++;
  22080. stepsTaken++;
  22081. deltaTime -= defaultFrameTime;
  22082. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22083. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22084. }
  22085. else {
  22086. // Animations
  22087. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22088. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22089. this._animate();
  22090. this.onAfterAnimationsObservable.notifyObservers(this);
  22091. // Physics
  22092. if (this._physicsEngine) {
  22093. this.onBeforePhysicsObservable.notifyObservers(this);
  22094. this._physicsEngine._step(deltaTime / 1000.0);
  22095. this.onAfterPhysicsObservable.notifyObservers(this);
  22096. }
  22097. }
  22098. // update gamepad manager
  22099. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22100. this._gamepadManager._checkGamepadsStatus();
  22101. }
  22102. // Before render
  22103. this.onBeforeRenderObservable.notifyObservers(this);
  22104. // Customs render targets
  22105. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22106. var engine = this.getEngine();
  22107. var currentActiveCamera = this.activeCamera;
  22108. if (this.renderTargetsEnabled) {
  22109. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22110. this._intermediateRendering = true;
  22111. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22112. var renderTarget = this.customRenderTargets[customIndex];
  22113. if (renderTarget._shouldRender()) {
  22114. this._renderId++;
  22115. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22116. if (!this.activeCamera)
  22117. throw new Error("Active camera not set");
  22118. // Viewport
  22119. engine.setViewport(this.activeCamera.viewport);
  22120. // Camera
  22121. this.updateTransformMatrix();
  22122. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22123. }
  22124. }
  22125. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22126. this._intermediateRendering = false;
  22127. this._renderId++;
  22128. }
  22129. // Restore back buffer
  22130. if (this.customRenderTargets.length > 0) {
  22131. engine.restoreDefaultFramebuffer();
  22132. }
  22133. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22134. this.activeCamera = currentActiveCamera;
  22135. // Procedural textures
  22136. if (this.proceduralTexturesEnabled) {
  22137. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22138. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22139. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22140. if (proceduralTexture._shouldRender()) {
  22141. proceduralTexture.render();
  22142. }
  22143. }
  22144. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22145. }
  22146. // Clear
  22147. if (this.autoClearDepthAndStencil || this.autoClear) {
  22148. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22149. }
  22150. // Shadows
  22151. if (this.shadowsEnabled) {
  22152. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22153. var light = this.lights[lightIndex];
  22154. var shadowGenerator = light.getShadowGenerator();
  22155. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22156. var shadowMap = (shadowGenerator.getShadowMap());
  22157. if (this.textures.indexOf(shadowMap) !== -1) {
  22158. this._renderTargets.push(shadowMap);
  22159. }
  22160. }
  22161. }
  22162. }
  22163. // Depth renderer
  22164. if (this._depthRenderer) {
  22165. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22166. }
  22167. // Geometry renderer
  22168. if (this._geometryBufferRenderer) {
  22169. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22170. }
  22171. // RenderPipeline
  22172. if (this._postProcessRenderPipelineManager) {
  22173. this._postProcessRenderPipelineManager.update();
  22174. }
  22175. // Multi-cameras?
  22176. if (this.activeCameras.length > 0) {
  22177. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22178. if (cameraIndex > 0) {
  22179. this._engine.clear(null, false, true, true);
  22180. }
  22181. this._processSubCameras(this.activeCameras[cameraIndex]);
  22182. }
  22183. }
  22184. else {
  22185. if (!this.activeCamera) {
  22186. throw new Error("No camera defined");
  22187. }
  22188. this._processSubCameras(this.activeCamera);
  22189. }
  22190. // Intersection checks
  22191. this._checkIntersections();
  22192. // Update the audio listener attached to the camera
  22193. if (BABYLON.AudioEngine) {
  22194. this._updateAudioParameters();
  22195. }
  22196. // After render
  22197. if (this.afterRender) {
  22198. this.afterRender();
  22199. }
  22200. this.onAfterRenderObservable.notifyObservers(this);
  22201. // Cleaning
  22202. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22203. var data = this._toBeDisposed.data[index];
  22204. if (data) {
  22205. data.dispose();
  22206. }
  22207. this._toBeDisposed[index] = null;
  22208. }
  22209. this._toBeDisposed.reset();
  22210. if (this.dumpNextRenderTargets) {
  22211. this.dumpNextRenderTargets = false;
  22212. }
  22213. this._activeBones.addCount(0, true);
  22214. this._activeIndices.addCount(0, true);
  22215. this._activeParticles.addCount(0, true);
  22216. };
  22217. Scene.prototype._updateAudioParameters = function () {
  22218. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22219. return;
  22220. }
  22221. var listeningCamera;
  22222. var audioEngine = BABYLON.Engine.audioEngine;
  22223. if (this.activeCameras.length > 0) {
  22224. listeningCamera = this.activeCameras[0];
  22225. }
  22226. else {
  22227. listeningCamera = this.activeCamera;
  22228. }
  22229. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22230. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22231. // for VR cameras
  22232. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22233. listeningCamera = listeningCamera.rigCameras[0];
  22234. }
  22235. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22236. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22237. cameraDirection.normalize();
  22238. // To avoid some errors on GearVR
  22239. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22240. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22241. }
  22242. var i;
  22243. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22244. var sound = this.mainSoundTrack.soundCollection[i];
  22245. if (sound.useCustomAttenuation) {
  22246. sound.updateDistanceFromListener();
  22247. }
  22248. }
  22249. for (i = 0; i < this.soundTracks.length; i++) {
  22250. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22251. sound = this.soundTracks[i].soundCollection[j];
  22252. if (sound.useCustomAttenuation) {
  22253. sound.updateDistanceFromListener();
  22254. }
  22255. }
  22256. }
  22257. }
  22258. };
  22259. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22260. // Audio
  22261. get: function () {
  22262. return this._audioEnabled;
  22263. },
  22264. set: function (value) {
  22265. this._audioEnabled = value;
  22266. if (BABYLON.AudioEngine) {
  22267. if (this._audioEnabled) {
  22268. this._enableAudio();
  22269. }
  22270. else {
  22271. this._disableAudio();
  22272. }
  22273. }
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Scene.prototype._disableAudio = function () {
  22279. var i;
  22280. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22281. this.mainSoundTrack.soundCollection[i].pause();
  22282. }
  22283. for (i = 0; i < this.soundTracks.length; i++) {
  22284. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22285. this.soundTracks[i].soundCollection[j].pause();
  22286. }
  22287. }
  22288. };
  22289. Scene.prototype._enableAudio = function () {
  22290. var i;
  22291. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22292. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22293. this.mainSoundTrack.soundCollection[i].play();
  22294. }
  22295. }
  22296. for (i = 0; i < this.soundTracks.length; i++) {
  22297. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22298. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22299. this.soundTracks[i].soundCollection[j].play();
  22300. }
  22301. }
  22302. }
  22303. };
  22304. Object.defineProperty(Scene.prototype, "headphone", {
  22305. get: function () {
  22306. return this._headphone;
  22307. },
  22308. set: function (value) {
  22309. this._headphone = value;
  22310. if (BABYLON.AudioEngine) {
  22311. if (this._headphone) {
  22312. this._switchAudioModeForHeadphones();
  22313. }
  22314. else {
  22315. this._switchAudioModeForNormalSpeakers();
  22316. }
  22317. }
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Scene.prototype._switchAudioModeForHeadphones = function () {
  22323. this.mainSoundTrack.switchPanningModelToHRTF();
  22324. for (var i = 0; i < this.soundTracks.length; i++) {
  22325. this.soundTracks[i].switchPanningModelToHRTF();
  22326. }
  22327. };
  22328. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22329. this.mainSoundTrack.switchPanningModelToEqualPower();
  22330. for (var i = 0; i < this.soundTracks.length; i++) {
  22331. this.soundTracks[i].switchPanningModelToEqualPower();
  22332. }
  22333. };
  22334. Scene.prototype.enableDepthRenderer = function () {
  22335. if (this._depthRenderer) {
  22336. return this._depthRenderer;
  22337. }
  22338. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22339. return this._depthRenderer;
  22340. };
  22341. Scene.prototype.disableDepthRenderer = function () {
  22342. if (!this._depthRenderer) {
  22343. return;
  22344. }
  22345. this._depthRenderer.dispose();
  22346. this._depthRenderer = null;
  22347. };
  22348. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22349. if (ratio === void 0) { ratio = 1; }
  22350. if (this._geometryBufferRenderer) {
  22351. return this._geometryBufferRenderer;
  22352. }
  22353. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22354. if (!this._geometryBufferRenderer.isSupported) {
  22355. this._geometryBufferRenderer = null;
  22356. }
  22357. return this._geometryBufferRenderer;
  22358. };
  22359. Scene.prototype.disableGeometryBufferRenderer = function () {
  22360. if (!this._geometryBufferRenderer) {
  22361. return;
  22362. }
  22363. this._geometryBufferRenderer.dispose();
  22364. this._geometryBufferRenderer = null;
  22365. };
  22366. Scene.prototype.freezeMaterials = function () {
  22367. for (var i = 0; i < this.materials.length; i++) {
  22368. this.materials[i].freeze();
  22369. }
  22370. };
  22371. Scene.prototype.unfreezeMaterials = function () {
  22372. for (var i = 0; i < this.materials.length; i++) {
  22373. this.materials[i].unfreeze();
  22374. }
  22375. };
  22376. Scene.prototype.dispose = function () {
  22377. this.beforeRender = null;
  22378. this.afterRender = null;
  22379. this.skeletons = [];
  22380. this.morphTargetManagers = [];
  22381. this.importedMeshesFiles = new Array();
  22382. this.stopAllAnimations();
  22383. this.resetCachedMaterial();
  22384. if (this._depthRenderer) {
  22385. this._depthRenderer.dispose();
  22386. }
  22387. if (this._gamepadManager) {
  22388. this._gamepadManager.dispose();
  22389. this._gamepadManager = null;
  22390. }
  22391. // Smart arrays
  22392. if (this.activeCamera) {
  22393. this.activeCamera._activeMeshes.dispose();
  22394. this.activeCamera = null;
  22395. }
  22396. this._activeMeshes.dispose();
  22397. this._renderingManager.dispose();
  22398. this._processedMaterials.dispose();
  22399. this._activeParticleSystems.dispose();
  22400. this._activeSkeletons.dispose();
  22401. this._softwareSkinnedMeshes.dispose();
  22402. this._renderTargets.dispose();
  22403. if (this._boundingBoxRenderer) {
  22404. this._boundingBoxRenderer.dispose();
  22405. }
  22406. this._meshesForIntersections.dispose();
  22407. this._toBeDisposed.dispose();
  22408. // Abort active requests
  22409. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22410. var request = _a[_i];
  22411. request.abort();
  22412. }
  22413. // Debug layer
  22414. if (this._debugLayer) {
  22415. this._debugLayer.hide();
  22416. }
  22417. // Events
  22418. this.onDisposeObservable.notifyObservers(this);
  22419. this.onDisposeObservable.clear();
  22420. this.onBeforeRenderObservable.clear();
  22421. this.onAfterRenderObservable.clear();
  22422. this.OnBeforeRenderTargetsRenderObservable.clear();
  22423. this.OnAfterRenderTargetsRenderObservable.clear();
  22424. this.onAfterStepObservable.clear();
  22425. this.onBeforeStepObservable.clear();
  22426. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22427. this.onAfterActiveMeshesEvaluationObservable.clear();
  22428. this.onBeforeParticlesRenderingObservable.clear();
  22429. this.onAfterParticlesRenderingObservable.clear();
  22430. this.onBeforeSpritesRenderingObservable.clear();
  22431. this.onAfterSpritesRenderingObservable.clear();
  22432. this.onBeforeDrawPhaseObservable.clear();
  22433. this.onAfterDrawPhaseObservable.clear();
  22434. this.onBeforePhysicsObservable.clear();
  22435. this.onAfterPhysicsObservable.clear();
  22436. this.onBeforeAnimationsObservable.clear();
  22437. this.onAfterAnimationsObservable.clear();
  22438. this.onDataLoadedObservable.clear();
  22439. this.detachControl();
  22440. // Release sounds & sounds tracks
  22441. if (BABYLON.AudioEngine) {
  22442. this.disposeSounds();
  22443. }
  22444. // VR Helper
  22445. if (this.VRHelper) {
  22446. this.VRHelper.dispose();
  22447. }
  22448. // Detach cameras
  22449. var canvas = this._engine.getRenderingCanvas();
  22450. if (canvas) {
  22451. var index;
  22452. for (index = 0; index < this.cameras.length; index++) {
  22453. this.cameras[index].detachControl(canvas);
  22454. }
  22455. }
  22456. // Release animation groups
  22457. while (this.animationGroups.length) {
  22458. this.animationGroups[0].dispose();
  22459. }
  22460. // Release lights
  22461. while (this.lights.length) {
  22462. this.lights[0].dispose();
  22463. }
  22464. // Release meshes
  22465. while (this.meshes.length) {
  22466. this.meshes[0].dispose(true);
  22467. }
  22468. while (this.transformNodes.length) {
  22469. this.removeTransformNode(this.transformNodes[0]);
  22470. }
  22471. // Release cameras
  22472. while (this.cameras.length) {
  22473. this.cameras[0].dispose();
  22474. }
  22475. // Release materials
  22476. if (this.defaultMaterial) {
  22477. this.defaultMaterial.dispose();
  22478. }
  22479. while (this.multiMaterials.length) {
  22480. this.multiMaterials[0].dispose();
  22481. }
  22482. while (this.materials.length) {
  22483. this.materials[0].dispose();
  22484. }
  22485. // Release particles
  22486. while (this.particleSystems.length) {
  22487. this.particleSystems[0].dispose();
  22488. }
  22489. // Release sprites
  22490. while (this.spriteManagers.length) {
  22491. this.spriteManagers[0].dispose();
  22492. }
  22493. // Release postProcesses
  22494. while (this.postProcesses.length) {
  22495. this.postProcesses[0].dispose();
  22496. }
  22497. // Release layers
  22498. while (this.layers.length) {
  22499. this.layers[0].dispose();
  22500. }
  22501. while (this.highlightLayers.length) {
  22502. this.highlightLayers[0].dispose();
  22503. }
  22504. // Release textures
  22505. while (this.textures.length) {
  22506. this.textures[0].dispose();
  22507. }
  22508. // Release UBO
  22509. this._sceneUbo.dispose();
  22510. if (this._alternateSceneUbo) {
  22511. this._alternateSceneUbo.dispose();
  22512. }
  22513. // Post-processes
  22514. this.postProcessManager.dispose();
  22515. if (this._postProcessRenderPipelineManager) {
  22516. this._postProcessRenderPipelineManager.dispose();
  22517. }
  22518. // Physics
  22519. if (this._physicsEngine) {
  22520. this.disablePhysicsEngine();
  22521. }
  22522. // Remove from engine
  22523. index = this._engine.scenes.indexOf(this);
  22524. if (index > -1) {
  22525. this._engine.scenes.splice(index, 1);
  22526. }
  22527. this._engine.wipeCaches(true);
  22528. this._isDisposed = true;
  22529. };
  22530. Object.defineProperty(Scene.prototype, "isDisposed", {
  22531. get: function () {
  22532. return this._isDisposed;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. // Release sounds & sounds tracks
  22538. Scene.prototype.disposeSounds = function () {
  22539. if (!this._mainSoundTrack) {
  22540. return;
  22541. }
  22542. this.mainSoundTrack.dispose();
  22543. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22544. this.soundTracks[scIndex].dispose();
  22545. }
  22546. };
  22547. // Octrees
  22548. Scene.prototype.getWorldExtends = function () {
  22549. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22550. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22551. for (var index = 0; index < this.meshes.length; index++) {
  22552. var mesh = this.meshes[index];
  22553. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22554. continue;
  22555. }
  22556. mesh.computeWorldMatrix(true);
  22557. var boundingInfo = mesh.getBoundingInfo();
  22558. var minBox = boundingInfo.boundingBox.minimumWorld;
  22559. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22560. BABYLON.Tools.CheckExtends(minBox, min, max);
  22561. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22562. }
  22563. return {
  22564. min: min,
  22565. max: max
  22566. };
  22567. };
  22568. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22569. if (maxCapacity === void 0) { maxCapacity = 64; }
  22570. if (maxDepth === void 0) { maxDepth = 2; }
  22571. if (!this._selectionOctree) {
  22572. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22573. }
  22574. var worldExtends = this.getWorldExtends();
  22575. // Update octree
  22576. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22577. return this._selectionOctree;
  22578. };
  22579. // Picking
  22580. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22581. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22582. var result = BABYLON.Ray.Zero();
  22583. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22584. return result;
  22585. };
  22586. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22587. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22588. var engine = this._engine;
  22589. if (!camera) {
  22590. if (!this.activeCamera)
  22591. throw new Error("Active camera not set");
  22592. camera = this.activeCamera;
  22593. }
  22594. var cameraViewport = camera.viewport;
  22595. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22596. // Moving coordinates to local viewport world
  22597. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22598. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22599. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22600. return this;
  22601. };
  22602. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22603. var result = BABYLON.Ray.Zero();
  22604. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22605. return result;
  22606. };
  22607. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22608. if (!BABYLON.PickingInfo) {
  22609. return this;
  22610. }
  22611. var engine = this._engine;
  22612. if (!camera) {
  22613. if (!this.activeCamera)
  22614. throw new Error("Active camera not set");
  22615. camera = this.activeCamera;
  22616. }
  22617. var cameraViewport = camera.viewport;
  22618. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22619. var identity = BABYLON.Matrix.Identity();
  22620. // Moving coordinates to local viewport world
  22621. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22622. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22623. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22624. return this;
  22625. };
  22626. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22627. if (!BABYLON.PickingInfo) {
  22628. return null;
  22629. }
  22630. var pickingInfo = null;
  22631. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22632. var mesh = this.meshes[meshIndex];
  22633. if (predicate) {
  22634. if (!predicate(mesh)) {
  22635. continue;
  22636. }
  22637. }
  22638. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22639. continue;
  22640. }
  22641. var world = mesh.getWorldMatrix();
  22642. var ray = rayFunction(world);
  22643. var result = mesh.intersects(ray, fastCheck);
  22644. if (!result || !result.hit)
  22645. continue;
  22646. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22647. continue;
  22648. pickingInfo = result;
  22649. if (fastCheck) {
  22650. break;
  22651. }
  22652. }
  22653. return pickingInfo || new BABYLON.PickingInfo();
  22654. };
  22655. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22656. if (!BABYLON.PickingInfo) {
  22657. return null;
  22658. }
  22659. var pickingInfos = new Array();
  22660. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22661. var mesh = this.meshes[meshIndex];
  22662. if (predicate) {
  22663. if (!predicate(mesh)) {
  22664. continue;
  22665. }
  22666. }
  22667. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22668. continue;
  22669. }
  22670. var world = mesh.getWorldMatrix();
  22671. var ray = rayFunction(world);
  22672. var result = mesh.intersects(ray, false);
  22673. if (!result || !result.hit)
  22674. continue;
  22675. pickingInfos.push(result);
  22676. }
  22677. return pickingInfos;
  22678. };
  22679. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22680. if (!BABYLON.PickingInfo) {
  22681. return null;
  22682. }
  22683. var pickingInfo = null;
  22684. if (!camera) {
  22685. if (!this.activeCamera) {
  22686. return null;
  22687. }
  22688. camera = this.activeCamera;
  22689. }
  22690. if (this.spriteManagers.length > 0) {
  22691. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22692. var spriteManager = this.spriteManagers[spriteIndex];
  22693. if (!spriteManager.isPickable) {
  22694. continue;
  22695. }
  22696. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22697. if (!result || !result.hit)
  22698. continue;
  22699. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22700. continue;
  22701. pickingInfo = result;
  22702. if (fastCheck) {
  22703. break;
  22704. }
  22705. }
  22706. }
  22707. return pickingInfo || new BABYLON.PickingInfo();
  22708. };
  22709. /** Launch a ray to try to pick a mesh in the scene
  22710. * @param x position on screen
  22711. * @param y position on screen
  22712. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  22713. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22714. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22715. */
  22716. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22717. var _this = this;
  22718. if (!BABYLON.PickingInfo) {
  22719. return null;
  22720. }
  22721. return this._internalPick(function (world) {
  22722. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22723. return _this._tempPickingRay;
  22724. }, predicate, fastCheck);
  22725. };
  22726. /** Launch a ray to try to pick a sprite in the scene
  22727. * @param x position on screen
  22728. * @param y position on screen
  22729. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  22730. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22731. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22732. */
  22733. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22734. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22735. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22736. };
  22737. /** Use the given ray to pick a mesh in the scene
  22738. * @param ray The ray to use to pick meshes
  22739. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  22740. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22741. */
  22742. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22743. var _this = this;
  22744. return this._internalPick(function (world) {
  22745. if (!_this._pickWithRayInverseMatrix) {
  22746. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22747. }
  22748. world.invertToRef(_this._pickWithRayInverseMatrix);
  22749. if (!_this._cachedRayForTransform) {
  22750. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22751. }
  22752. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22753. return _this._cachedRayForTransform;
  22754. }, predicate, fastCheck);
  22755. };
  22756. /**
  22757. * Launch a ray to try to pick a mesh in the scene
  22758. * @param x X position on screen
  22759. * @param y Y position on screen
  22760. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  22761. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22762. */
  22763. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22764. var _this = this;
  22765. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22766. };
  22767. /**
  22768. * Launch a ray to try to pick a mesh in the scene
  22769. * @param ray Ray to use
  22770. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  22771. */
  22772. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22773. var _this = this;
  22774. return this._internalMultiPick(function (world) {
  22775. if (!_this._pickWithRayInverseMatrix) {
  22776. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22777. }
  22778. world.invertToRef(_this._pickWithRayInverseMatrix);
  22779. if (!_this._cachedRayForTransform) {
  22780. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22781. }
  22782. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22783. return _this._cachedRayForTransform;
  22784. }, predicate);
  22785. };
  22786. Scene.prototype.setPointerOverMesh = function (mesh) {
  22787. if (this._pointerOverMesh === mesh) {
  22788. return;
  22789. }
  22790. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22791. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22792. }
  22793. this._pointerOverMesh = mesh;
  22794. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22795. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22796. }
  22797. };
  22798. Scene.prototype.getPointerOverMesh = function () {
  22799. return this._pointerOverMesh;
  22800. };
  22801. Scene.prototype.setPointerOverSprite = function (sprite) {
  22802. if (this._pointerOverSprite === sprite) {
  22803. return;
  22804. }
  22805. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22806. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22807. }
  22808. this._pointerOverSprite = sprite;
  22809. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22810. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22811. }
  22812. };
  22813. Scene.prototype.getPointerOverSprite = function () {
  22814. return this._pointerOverSprite;
  22815. };
  22816. // Physics
  22817. Scene.prototype.getPhysicsEngine = function () {
  22818. return this._physicsEngine;
  22819. };
  22820. /**
  22821. * Enables physics to the current scene
  22822. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22823. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22824. * @return {boolean} was the physics engine initialized
  22825. */
  22826. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22827. if (gravity === void 0) { gravity = null; }
  22828. if (this._physicsEngine) {
  22829. return true;
  22830. }
  22831. try {
  22832. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22833. return true;
  22834. }
  22835. catch (e) {
  22836. BABYLON.Tools.Error(e.message);
  22837. return false;
  22838. }
  22839. };
  22840. Scene.prototype.disablePhysicsEngine = function () {
  22841. if (!this._physicsEngine) {
  22842. return;
  22843. }
  22844. this._physicsEngine.dispose();
  22845. this._physicsEngine = null;
  22846. };
  22847. Scene.prototype.isPhysicsEnabled = function () {
  22848. return this._physicsEngine !== undefined;
  22849. };
  22850. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22851. var mesh = compound.parts[0].mesh;
  22852. if (mesh.physicsImpostor) {
  22853. mesh.physicsImpostor.dispose();
  22854. mesh.physicsImpostor = null;
  22855. }
  22856. };
  22857. // Misc.
  22858. Scene.prototype._rebuildGeometries = function () {
  22859. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22860. var geometry = _a[_i];
  22861. geometry._rebuild();
  22862. }
  22863. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22864. var mesh = _c[_b];
  22865. mesh._rebuild();
  22866. }
  22867. if (this.postProcessManager) {
  22868. this.postProcessManager._rebuild();
  22869. }
  22870. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22871. var layer = _e[_d];
  22872. layer._rebuild();
  22873. }
  22874. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22875. var highlightLayer = _g[_f];
  22876. highlightLayer._rebuild();
  22877. }
  22878. if (this._boundingBoxRenderer) {
  22879. this._boundingBoxRenderer._rebuild();
  22880. }
  22881. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22882. var system = _j[_h];
  22883. system.rebuild();
  22884. }
  22885. if (this._postProcessRenderPipelineManager) {
  22886. this._postProcessRenderPipelineManager._rebuild();
  22887. }
  22888. };
  22889. Scene.prototype._rebuildTextures = function () {
  22890. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22891. var texture = _a[_i];
  22892. texture._rebuild();
  22893. }
  22894. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22895. };
  22896. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22897. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22898. if (replace === void 0) { replace = false; }
  22899. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22900. // Dispose existing camera or light in replace mode.
  22901. if (replace) {
  22902. if (this.activeCamera) {
  22903. this.activeCamera.dispose();
  22904. this.activeCamera = null;
  22905. }
  22906. if (this.lights) {
  22907. for (var i = 0; i < this.lights.length; i++) {
  22908. this.lights[i].dispose();
  22909. }
  22910. }
  22911. }
  22912. // Light
  22913. if (this.lights.length === 0) {
  22914. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22915. }
  22916. // Camera
  22917. if (!this.activeCamera) {
  22918. var worldExtends = this.getWorldExtends();
  22919. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22920. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22921. var camera;
  22922. var radius = worldSize.length() * 1.5;
  22923. if (createArcRotateCamera) {
  22924. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22925. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22926. arcRotateCamera.wheelPrecision = 100 / radius;
  22927. camera = arcRotateCamera;
  22928. }
  22929. else {
  22930. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22931. freeCamera.setTarget(worldCenter);
  22932. camera = freeCamera;
  22933. }
  22934. camera.minZ = radius * 0.01;
  22935. camera.maxZ = radius * 1000;
  22936. camera.speed = radius * 0.2;
  22937. this.activeCamera = camera;
  22938. var canvas = this.getEngine().getRenderingCanvas();
  22939. if (attachCameraControls && canvas) {
  22940. camera.attachControl(canvas);
  22941. }
  22942. }
  22943. };
  22944. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22945. if (pbr === void 0) { pbr = false; }
  22946. if (scale === void 0) { scale = 1000; }
  22947. if (blur === void 0) { blur = 0; }
  22948. if (environmentTexture) {
  22949. this.environmentTexture = environmentTexture;
  22950. }
  22951. if (!this.environmentTexture) {
  22952. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22953. return null;
  22954. }
  22955. // Skybox
  22956. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22957. if (pbr) {
  22958. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22959. hdrSkyboxMaterial.backFaceCulling = false;
  22960. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22961. if (hdrSkyboxMaterial.reflectionTexture) {
  22962. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22963. }
  22964. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22965. hdrSkyboxMaterial.disableLighting = true;
  22966. hdrSkyboxMaterial.twoSidedLighting = true;
  22967. hdrSkybox.infiniteDistance = true;
  22968. hdrSkybox.material = hdrSkyboxMaterial;
  22969. }
  22970. else {
  22971. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22972. skyboxMaterial.backFaceCulling = false;
  22973. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22974. if (skyboxMaterial.reflectionTexture) {
  22975. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22976. }
  22977. skyboxMaterial.disableLighting = true;
  22978. hdrSkybox.infiniteDistance = true;
  22979. hdrSkybox.material = skyboxMaterial;
  22980. }
  22981. return hdrSkybox;
  22982. };
  22983. Scene.prototype.createDefaultEnvironment = function (options) {
  22984. if (BABYLON.EnvironmentHelper) {
  22985. return new BABYLON.EnvironmentHelper(options, this);
  22986. }
  22987. return null;
  22988. };
  22989. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22990. if (webVROptions === void 0) { webVROptions = {}; }
  22991. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22992. };
  22993. // Tags
  22994. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22995. if (tagsQuery === undefined) {
  22996. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22997. return list;
  22998. }
  22999. var listByTags = [];
  23000. forEach = forEach || (function (item) { return; });
  23001. for (var i in list) {
  23002. var item = list[i];
  23003. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23004. listByTags.push(item);
  23005. forEach(item);
  23006. }
  23007. }
  23008. return listByTags;
  23009. };
  23010. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23011. return this._getByTags(this.meshes, tagsQuery, forEach);
  23012. };
  23013. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23014. return this._getByTags(this.cameras, tagsQuery, forEach);
  23015. };
  23016. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23017. return this._getByTags(this.lights, tagsQuery, forEach);
  23018. };
  23019. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23020. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23021. };
  23022. /**
  23023. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23024. * This allowed control for front to back rendering or reversly depending of the special needs.
  23025. *
  23026. * @param renderingGroupId The rendering group id corresponding to its index
  23027. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23028. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23029. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23030. */
  23031. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23032. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23033. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23034. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23035. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23036. };
  23037. /**
  23038. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23039. *
  23040. * @param renderingGroupId The rendering group id corresponding to its index
  23041. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23042. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23043. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23044. */
  23045. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23046. if (depth === void 0) { depth = true; }
  23047. if (stencil === void 0) { stencil = true; }
  23048. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23049. };
  23050. /**
  23051. * Will flag all materials as dirty to trigger new shader compilation
  23052. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23053. */
  23054. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23055. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23056. var material = _a[_i];
  23057. if (predicate && !predicate(material)) {
  23058. continue;
  23059. }
  23060. material.markAsDirty(flag);
  23061. }
  23062. };
  23063. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23064. var _this = this;
  23065. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23066. this._activeRequests.push(request);
  23067. request.onCompleteObservable.add(function (request) {
  23068. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23069. });
  23070. return request;
  23071. };
  23072. // Statics
  23073. Scene._FOGMODE_NONE = 0;
  23074. Scene._FOGMODE_EXP = 1;
  23075. Scene._FOGMODE_EXP2 = 2;
  23076. Scene._FOGMODE_LINEAR = 3;
  23077. Scene._uniqueIdCounter = 0;
  23078. Scene.MinDeltaTime = 1.0;
  23079. Scene.MaxDeltaTime = 1000.0;
  23080. /** The distance in pixel that you have to move to prevent some events */
  23081. Scene.DragMovementThreshold = 10; // in pixels
  23082. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23083. Scene.LongPressDelay = 500; // in milliseconds
  23084. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23085. Scene.DoubleClickDelay = 300; // in milliseconds
  23086. /** If you need to check double click without raising a single click at first click, enable this flag */
  23087. Scene.ExclusiveDoubleClickMode = false;
  23088. return Scene;
  23089. }());
  23090. BABYLON.Scene = Scene;
  23091. })(BABYLON || (BABYLON = {}));
  23092. //# sourceMappingURL=babylon.scene.js.map
  23093. var BABYLON;
  23094. (function (BABYLON) {
  23095. var Buffer = /** @class */ (function () {
  23096. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23097. if (instanced === void 0) { instanced = false; }
  23098. if (engine instanceof BABYLON.Mesh) {
  23099. this._engine = engine.getScene().getEngine();
  23100. }
  23101. else {
  23102. this._engine = engine;
  23103. }
  23104. this._updatable = updatable;
  23105. this._data = data;
  23106. this._strideSize = stride;
  23107. if (!postponeInternalCreation) {
  23108. this.create();
  23109. }
  23110. this._instanced = instanced;
  23111. this._instanceDivisor = instanced ? 1 : 0;
  23112. }
  23113. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23114. // a lot of these parameters are ignored as they are overriden by the buffer
  23115. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23116. };
  23117. // Properties
  23118. Buffer.prototype.isUpdatable = function () {
  23119. return this._updatable;
  23120. };
  23121. Buffer.prototype.getData = function () {
  23122. return this._data;
  23123. };
  23124. Buffer.prototype.getBuffer = function () {
  23125. return this._buffer;
  23126. };
  23127. Buffer.prototype.getStrideSize = function () {
  23128. return this._strideSize;
  23129. };
  23130. Buffer.prototype.getIsInstanced = function () {
  23131. return this._instanced;
  23132. };
  23133. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23134. get: function () {
  23135. return this._instanceDivisor;
  23136. },
  23137. set: function (value) {
  23138. this._instanceDivisor = value;
  23139. if (value == 0) {
  23140. this._instanced = false;
  23141. }
  23142. else {
  23143. this._instanced = true;
  23144. }
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. // Methods
  23150. Buffer.prototype.create = function (data) {
  23151. if (data === void 0) { data = null; }
  23152. if (!data && this._buffer) {
  23153. return; // nothing to do
  23154. }
  23155. data = data || this._data;
  23156. if (!data) {
  23157. return;
  23158. }
  23159. if (!this._buffer) {
  23160. if (this._updatable) {
  23161. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23162. this._data = data;
  23163. }
  23164. else {
  23165. this._buffer = this._engine.createVertexBuffer(data);
  23166. }
  23167. }
  23168. else if (this._updatable) {
  23169. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23170. this._data = data;
  23171. }
  23172. };
  23173. Buffer.prototype._rebuild = function () {
  23174. this._buffer = null;
  23175. this.create(this._data);
  23176. };
  23177. Buffer.prototype.update = function (data) {
  23178. this.create(data);
  23179. };
  23180. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23181. if (!this._buffer) {
  23182. return;
  23183. }
  23184. if (this._updatable) {
  23185. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23186. this._data = null;
  23187. }
  23188. };
  23189. Buffer.prototype.dispose = function () {
  23190. if (!this._buffer) {
  23191. return;
  23192. }
  23193. if (this._engine._releaseBuffer(this._buffer)) {
  23194. this._buffer = null;
  23195. }
  23196. };
  23197. return Buffer;
  23198. }());
  23199. BABYLON.Buffer = Buffer;
  23200. })(BABYLON || (BABYLON = {}));
  23201. //# sourceMappingURL=babylon.buffer.js.map
  23202. var BABYLON;
  23203. (function (BABYLON) {
  23204. var VertexBuffer = /** @class */ (function () {
  23205. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23206. if (!stride) {
  23207. // Deduce stride from kind
  23208. switch (kind) {
  23209. case VertexBuffer.PositionKind:
  23210. stride = 3;
  23211. break;
  23212. case VertexBuffer.NormalKind:
  23213. stride = 3;
  23214. break;
  23215. case VertexBuffer.UVKind:
  23216. case VertexBuffer.UV2Kind:
  23217. case VertexBuffer.UV3Kind:
  23218. case VertexBuffer.UV4Kind:
  23219. case VertexBuffer.UV5Kind:
  23220. case VertexBuffer.UV6Kind:
  23221. stride = 2;
  23222. break;
  23223. case VertexBuffer.TangentKind:
  23224. case VertexBuffer.ColorKind:
  23225. stride = 4;
  23226. break;
  23227. case VertexBuffer.MatricesIndicesKind:
  23228. case VertexBuffer.MatricesIndicesExtraKind:
  23229. stride = 4;
  23230. break;
  23231. case VertexBuffer.MatricesWeightsKind:
  23232. case VertexBuffer.MatricesWeightsExtraKind:
  23233. default:
  23234. stride = 4;
  23235. break;
  23236. }
  23237. }
  23238. if (data instanceof BABYLON.Buffer) {
  23239. if (!stride) {
  23240. stride = data.getStrideSize();
  23241. }
  23242. this._buffer = data;
  23243. this._ownsBuffer = false;
  23244. }
  23245. else {
  23246. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23247. this._ownsBuffer = true;
  23248. }
  23249. this._stride = stride;
  23250. this._offset = offset ? offset : 0;
  23251. this._size = size ? size : stride;
  23252. this._kind = kind;
  23253. }
  23254. VertexBuffer.prototype._rebuild = function () {
  23255. if (!this._buffer) {
  23256. return;
  23257. }
  23258. this._buffer._rebuild();
  23259. };
  23260. /**
  23261. * Returns the kind of the VertexBuffer (string).
  23262. */
  23263. VertexBuffer.prototype.getKind = function () {
  23264. return this._kind;
  23265. };
  23266. // Properties
  23267. /**
  23268. * Boolean : is the VertexBuffer updatable ?
  23269. */
  23270. VertexBuffer.prototype.isUpdatable = function () {
  23271. return this._buffer.isUpdatable();
  23272. };
  23273. /**
  23274. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23275. */
  23276. VertexBuffer.prototype.getData = function () {
  23277. return this._buffer.getData();
  23278. };
  23279. /**
  23280. * Returns the WebGLBuffer associated to the VertexBuffer.
  23281. */
  23282. VertexBuffer.prototype.getBuffer = function () {
  23283. return this._buffer.getBuffer();
  23284. };
  23285. /**
  23286. * Returns the stride of the VertexBuffer (integer).
  23287. */
  23288. VertexBuffer.prototype.getStrideSize = function () {
  23289. return this._stride;
  23290. };
  23291. /**
  23292. * Returns the offset (integer).
  23293. */
  23294. VertexBuffer.prototype.getOffset = function () {
  23295. return this._offset;
  23296. };
  23297. /**
  23298. * Returns the VertexBuffer total size (integer).
  23299. */
  23300. VertexBuffer.prototype.getSize = function () {
  23301. return this._size;
  23302. };
  23303. /**
  23304. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23305. */
  23306. VertexBuffer.prototype.getIsInstanced = function () {
  23307. return this._buffer.getIsInstanced();
  23308. };
  23309. /**
  23310. * Returns the instancing divisor, zero for non-instanced (integer).
  23311. */
  23312. VertexBuffer.prototype.getInstanceDivisor = function () {
  23313. return this._buffer.instanceDivisor;
  23314. };
  23315. // Methods
  23316. /**
  23317. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23318. * Returns the created WebGLBuffer.
  23319. */
  23320. VertexBuffer.prototype.create = function (data) {
  23321. return this._buffer.create(data);
  23322. };
  23323. /**
  23324. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23325. * Returns the updated WebGLBuffer.
  23326. */
  23327. VertexBuffer.prototype.update = function (data) {
  23328. return this._buffer.update(data);
  23329. };
  23330. /**
  23331. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23332. * Returns the directly updated WebGLBuffer.
  23333. */
  23334. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23335. return this._buffer.updateDirectly(data, offset);
  23336. };
  23337. /**
  23338. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23339. */
  23340. VertexBuffer.prototype.dispose = function () {
  23341. if (this._ownsBuffer) {
  23342. this._buffer.dispose();
  23343. }
  23344. };
  23345. Object.defineProperty(VertexBuffer, "PositionKind", {
  23346. get: function () {
  23347. return VertexBuffer._PositionKind;
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(VertexBuffer, "NormalKind", {
  23353. get: function () {
  23354. return VertexBuffer._NormalKind;
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. Object.defineProperty(VertexBuffer, "TangentKind", {
  23360. get: function () {
  23361. return VertexBuffer._TangentKind;
  23362. },
  23363. enumerable: true,
  23364. configurable: true
  23365. });
  23366. Object.defineProperty(VertexBuffer, "UVKind", {
  23367. get: function () {
  23368. return VertexBuffer._UVKind;
  23369. },
  23370. enumerable: true,
  23371. configurable: true
  23372. });
  23373. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23374. get: function () {
  23375. return VertexBuffer._UV2Kind;
  23376. },
  23377. enumerable: true,
  23378. configurable: true
  23379. });
  23380. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23381. get: function () {
  23382. return VertexBuffer._UV3Kind;
  23383. },
  23384. enumerable: true,
  23385. configurable: true
  23386. });
  23387. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23388. get: function () {
  23389. return VertexBuffer._UV4Kind;
  23390. },
  23391. enumerable: true,
  23392. configurable: true
  23393. });
  23394. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23395. get: function () {
  23396. return VertexBuffer._UV5Kind;
  23397. },
  23398. enumerable: true,
  23399. configurable: true
  23400. });
  23401. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23402. get: function () {
  23403. return VertexBuffer._UV6Kind;
  23404. },
  23405. enumerable: true,
  23406. configurable: true
  23407. });
  23408. Object.defineProperty(VertexBuffer, "ColorKind", {
  23409. get: function () {
  23410. return VertexBuffer._ColorKind;
  23411. },
  23412. enumerable: true,
  23413. configurable: true
  23414. });
  23415. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23416. get: function () {
  23417. return VertexBuffer._MatricesIndicesKind;
  23418. },
  23419. enumerable: true,
  23420. configurable: true
  23421. });
  23422. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23423. get: function () {
  23424. return VertexBuffer._MatricesWeightsKind;
  23425. },
  23426. enumerable: true,
  23427. configurable: true
  23428. });
  23429. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23430. get: function () {
  23431. return VertexBuffer._MatricesIndicesExtraKind;
  23432. },
  23433. enumerable: true,
  23434. configurable: true
  23435. });
  23436. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23437. get: function () {
  23438. return VertexBuffer._MatricesWeightsExtraKind;
  23439. },
  23440. enumerable: true,
  23441. configurable: true
  23442. });
  23443. // Enums
  23444. VertexBuffer._PositionKind = "position";
  23445. VertexBuffer._NormalKind = "normal";
  23446. VertexBuffer._TangentKind = "tangent";
  23447. VertexBuffer._UVKind = "uv";
  23448. VertexBuffer._UV2Kind = "uv2";
  23449. VertexBuffer._UV3Kind = "uv3";
  23450. VertexBuffer._UV4Kind = "uv4";
  23451. VertexBuffer._UV5Kind = "uv5";
  23452. VertexBuffer._UV6Kind = "uv6";
  23453. VertexBuffer._ColorKind = "color";
  23454. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23455. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23456. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23457. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23458. return VertexBuffer;
  23459. }());
  23460. BABYLON.VertexBuffer = VertexBuffer;
  23461. })(BABYLON || (BABYLON = {}));
  23462. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23463. var BABYLON;
  23464. (function (BABYLON) {
  23465. var InternalTexture = /** @class */ (function () {
  23466. function InternalTexture(engine, dataSource) {
  23467. this.onLoadedObservable = new BABYLON.Observable();
  23468. // Private
  23469. this._initialSlot = -1;
  23470. this._designatedSlot = -1;
  23471. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23472. this._references = 1;
  23473. this._engine = engine;
  23474. this._dataSource = dataSource;
  23475. this._webGLTexture = engine._createTexture();
  23476. }
  23477. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23478. get: function () {
  23479. return this._dataSource;
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. InternalTexture.prototype.incrementReferences = function () {
  23485. this._references++;
  23486. };
  23487. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23488. if (depth === void 0) { depth = 1; }
  23489. this.width = width;
  23490. this.height = height;
  23491. this.depth = depth;
  23492. this.baseWidth = width;
  23493. this.baseHeight = height;
  23494. this.baseDepth = depth;
  23495. this._size = width * height * depth;
  23496. };
  23497. InternalTexture.prototype._rebuild = function () {
  23498. var _this = this;
  23499. var proxy;
  23500. this.isReady = false;
  23501. this._cachedCoordinatesMode = null;
  23502. this._cachedWrapU = null;
  23503. this._cachedWrapV = null;
  23504. this._cachedAnisotropicFilteringLevel = null;
  23505. switch (this._dataSource) {
  23506. case InternalTexture.DATASOURCE_TEMP:
  23507. return;
  23508. case InternalTexture.DATASOURCE_URL:
  23509. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23510. _this.isReady = true;
  23511. }, null, this._buffer, undefined, this.format);
  23512. proxy._swapAndDie(this);
  23513. return;
  23514. case InternalTexture.DATASOURCE_RAW:
  23515. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23516. proxy._swapAndDie(this);
  23517. this.isReady = true;
  23518. return;
  23519. case InternalTexture.DATASOURCE_RAW3D:
  23520. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23521. proxy._swapAndDie(this);
  23522. this.isReady = true;
  23523. return;
  23524. case InternalTexture.DATASOURCE_DYNAMIC:
  23525. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23526. proxy._swapAndDie(this);
  23527. // The engine will make sure to update content so no need to flag it as isReady = true
  23528. return;
  23529. case InternalTexture.DATASOURCE_RENDERTARGET:
  23530. var options = new BABYLON.RenderTargetCreationOptions();
  23531. options.generateDepthBuffer = this._generateDepthBuffer;
  23532. options.generateMipMaps = this.generateMipMaps;
  23533. options.generateStencilBuffer = this._generateStencilBuffer;
  23534. options.samplingMode = this.samplingMode;
  23535. options.type = this.type;
  23536. if (this.isCube) {
  23537. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23538. }
  23539. else {
  23540. var size = {
  23541. width: this.width,
  23542. height: this.height
  23543. };
  23544. proxy = this._engine.createRenderTargetTexture(size, options);
  23545. }
  23546. proxy._swapAndDie(this);
  23547. this.isReady = true;
  23548. return;
  23549. case InternalTexture.DATASOURCE_CUBE:
  23550. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23551. _this.isReady = true;
  23552. }, null, this.format, this._extension);
  23553. proxy._swapAndDie(this);
  23554. return;
  23555. case InternalTexture.DATASOURCE_CUBERAW:
  23556. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23557. proxy._swapAndDie(this);
  23558. this.isReady = true;
  23559. return;
  23560. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23561. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23562. if (proxy) {
  23563. proxy._swapAndDie(_this);
  23564. }
  23565. _this.isReady = true;
  23566. }, null, this.format, this._extension);
  23567. return;
  23568. }
  23569. };
  23570. InternalTexture.prototype._swapAndDie = function (target) {
  23571. target._webGLTexture = this._webGLTexture;
  23572. if (this._framebuffer) {
  23573. target._framebuffer = this._framebuffer;
  23574. }
  23575. if (this._depthStencilBuffer) {
  23576. target._depthStencilBuffer = this._depthStencilBuffer;
  23577. }
  23578. if (this._lodTextureHigh) {
  23579. if (target._lodTextureHigh) {
  23580. target._lodTextureHigh.dispose();
  23581. }
  23582. target._lodTextureHigh = this._lodTextureHigh;
  23583. }
  23584. if (this._lodTextureMid) {
  23585. if (target._lodTextureMid) {
  23586. target._lodTextureMid.dispose();
  23587. }
  23588. target._lodTextureMid = this._lodTextureMid;
  23589. }
  23590. if (this._lodTextureLow) {
  23591. if (target._lodTextureLow) {
  23592. target._lodTextureLow.dispose();
  23593. }
  23594. target._lodTextureLow = this._lodTextureLow;
  23595. }
  23596. var cache = this._engine.getLoadedTexturesCache();
  23597. var index = cache.indexOf(this);
  23598. if (index !== -1) {
  23599. cache.splice(index, 1);
  23600. }
  23601. };
  23602. InternalTexture.prototype.dispose = function () {
  23603. if (!this._webGLTexture) {
  23604. return;
  23605. }
  23606. this._references--;
  23607. if (this._references === 0) {
  23608. this._engine._releaseTexture(this);
  23609. this._webGLTexture = null;
  23610. }
  23611. };
  23612. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23613. InternalTexture.DATASOURCE_URL = 1;
  23614. InternalTexture.DATASOURCE_TEMP = 2;
  23615. InternalTexture.DATASOURCE_RAW = 3;
  23616. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23617. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23618. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23619. InternalTexture.DATASOURCE_CUBE = 7;
  23620. InternalTexture.DATASOURCE_CUBERAW = 8;
  23621. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23622. InternalTexture.DATASOURCE_RAW3D = 10;
  23623. return InternalTexture;
  23624. }());
  23625. BABYLON.InternalTexture = InternalTexture;
  23626. })(BABYLON || (BABYLON = {}));
  23627. //# sourceMappingURL=babylon.internalTexture.js.map
  23628. var BABYLON;
  23629. (function (BABYLON) {
  23630. var BaseTexture = /** @class */ (function () {
  23631. function BaseTexture(scene) {
  23632. this._hasAlpha = false;
  23633. this.getAlphaFromRGB = false;
  23634. this.level = 1;
  23635. this.coordinatesIndex = 0;
  23636. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23637. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23638. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23639. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23640. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23641. this.isCube = false;
  23642. this.is3D = false;
  23643. this.gammaSpace = true;
  23644. this.invertZ = false;
  23645. this.lodLevelInAlpha = false;
  23646. this.lodGenerationOffset = 0.0;
  23647. this.lodGenerationScale = 0.8;
  23648. this.isRenderTarget = false;
  23649. this.animations = new Array();
  23650. /**
  23651. * An event triggered when the texture is disposed.
  23652. * @type {BABYLON.Observable}
  23653. */
  23654. this.onDisposeObservable = new BABYLON.Observable();
  23655. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23656. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23657. if (this._scene) {
  23658. this._scene.textures.push(this);
  23659. }
  23660. this._uid = null;
  23661. }
  23662. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23663. get: function () {
  23664. return this._hasAlpha;
  23665. },
  23666. set: function (value) {
  23667. if (this._hasAlpha === value) {
  23668. return;
  23669. }
  23670. this._hasAlpha = value;
  23671. if (this._scene) {
  23672. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23673. }
  23674. },
  23675. enumerable: true,
  23676. configurable: true
  23677. });
  23678. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23679. get: function () {
  23680. return this._coordinatesMode;
  23681. },
  23682. set: function (value) {
  23683. if (this._coordinatesMode === value) {
  23684. return;
  23685. }
  23686. this._coordinatesMode = value;
  23687. if (this._scene) {
  23688. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23689. }
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. Object.defineProperty(BaseTexture.prototype, "uid", {
  23695. get: function () {
  23696. if (!this._uid) {
  23697. this._uid = BABYLON.Tools.RandomId();
  23698. }
  23699. return this._uid;
  23700. },
  23701. enumerable: true,
  23702. configurable: true
  23703. });
  23704. BaseTexture.prototype.toString = function () {
  23705. return this.name;
  23706. };
  23707. BaseTexture.prototype.getClassName = function () {
  23708. return "BaseTexture";
  23709. };
  23710. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23711. set: function (callback) {
  23712. if (this._onDisposeObserver) {
  23713. this.onDisposeObservable.remove(this._onDisposeObserver);
  23714. }
  23715. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23716. },
  23717. enumerable: true,
  23718. configurable: true
  23719. });
  23720. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23721. get: function () {
  23722. return true;
  23723. },
  23724. enumerable: true,
  23725. configurable: true
  23726. });
  23727. BaseTexture.prototype.getScene = function () {
  23728. return this._scene;
  23729. };
  23730. BaseTexture.prototype.getTextureMatrix = function () {
  23731. return BABYLON.Matrix.IdentityReadOnly;
  23732. };
  23733. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23734. return BABYLON.Matrix.IdentityReadOnly;
  23735. };
  23736. BaseTexture.prototype.getInternalTexture = function () {
  23737. return this._texture;
  23738. };
  23739. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23740. return !this.isBlocking || this.isReady();
  23741. };
  23742. BaseTexture.prototype.isReady = function () {
  23743. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23744. this.delayLoad();
  23745. return false;
  23746. }
  23747. if (this._texture) {
  23748. return this._texture.isReady;
  23749. }
  23750. return false;
  23751. };
  23752. BaseTexture.prototype.getSize = function () {
  23753. if (this._texture && this._texture.width) {
  23754. return new BABYLON.Size(this._texture.width, this._texture.height);
  23755. }
  23756. if (this._texture && this._texture._size) {
  23757. return new BABYLON.Size(this._texture._size, this._texture._size);
  23758. }
  23759. return BABYLON.Size.Zero();
  23760. };
  23761. BaseTexture.prototype.getBaseSize = function () {
  23762. if (!this.isReady() || !this._texture)
  23763. return BABYLON.Size.Zero();
  23764. if (this._texture._size) {
  23765. return new BABYLON.Size(this._texture._size, this._texture._size);
  23766. }
  23767. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23768. };
  23769. BaseTexture.prototype.scale = function (ratio) {
  23770. };
  23771. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23772. get: function () {
  23773. return false;
  23774. },
  23775. enumerable: true,
  23776. configurable: true
  23777. });
  23778. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23779. if (!this._scene) {
  23780. return null;
  23781. }
  23782. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23783. for (var index = 0; index < texturesCache.length; index++) {
  23784. var texturesCacheEntry = texturesCache[index];
  23785. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23786. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23787. texturesCacheEntry.incrementReferences();
  23788. return texturesCacheEntry;
  23789. }
  23790. }
  23791. }
  23792. return null;
  23793. };
  23794. BaseTexture.prototype._rebuild = function () {
  23795. };
  23796. BaseTexture.prototype.delayLoad = function () {
  23797. };
  23798. BaseTexture.prototype.clone = function () {
  23799. return null;
  23800. };
  23801. Object.defineProperty(BaseTexture.prototype, "textureType", {
  23802. get: function () {
  23803. if (!this._texture) {
  23804. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23805. }
  23806. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23807. },
  23808. enumerable: true,
  23809. configurable: true
  23810. });
  23811. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  23812. get: function () {
  23813. if (!this._texture) {
  23814. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23815. }
  23816. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23817. },
  23818. enumerable: true,
  23819. configurable: true
  23820. });
  23821. BaseTexture.prototype.readPixels = function (faceIndex) {
  23822. if (faceIndex === void 0) { faceIndex = 0; }
  23823. if (!this._texture) {
  23824. return null;
  23825. }
  23826. var size = this.getSize();
  23827. var scene = this.getScene();
  23828. if (!scene) {
  23829. return null;
  23830. }
  23831. var engine = scene.getEngine();
  23832. if (this._texture.isCube) {
  23833. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  23834. }
  23835. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  23836. };
  23837. BaseTexture.prototype.releaseInternalTexture = function () {
  23838. if (this._texture) {
  23839. this._texture.dispose();
  23840. this._texture = null;
  23841. }
  23842. };
  23843. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  23844. get: function () {
  23845. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  23846. return null;
  23847. }
  23848. if (!this._texture._sphericalPolynomial) {
  23849. this._texture._sphericalPolynomial =
  23850. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  23851. }
  23852. return this._texture._sphericalPolynomial;
  23853. },
  23854. set: function (value) {
  23855. if (this._texture) {
  23856. this._texture._sphericalPolynomial = value;
  23857. }
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  23863. get: function () {
  23864. if (this._texture) {
  23865. return this._texture._lodTextureHigh;
  23866. }
  23867. return null;
  23868. },
  23869. enumerable: true,
  23870. configurable: true
  23871. });
  23872. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  23873. get: function () {
  23874. if (this._texture) {
  23875. return this._texture._lodTextureMid;
  23876. }
  23877. return null;
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  23883. get: function () {
  23884. if (this._texture) {
  23885. return this._texture._lodTextureLow;
  23886. }
  23887. return null;
  23888. },
  23889. enumerable: true,
  23890. configurable: true
  23891. });
  23892. BaseTexture.prototype.dispose = function () {
  23893. if (!this._scene) {
  23894. return;
  23895. }
  23896. // Animations
  23897. this._scene.stopAnimation(this);
  23898. // Remove from scene
  23899. this._scene._removePendingData(this);
  23900. var index = this._scene.textures.indexOf(this);
  23901. if (index >= 0) {
  23902. this._scene.textures.splice(index, 1);
  23903. }
  23904. if (this._texture === undefined) {
  23905. return;
  23906. }
  23907. // Release
  23908. this.releaseInternalTexture();
  23909. // Callback
  23910. this.onDisposeObservable.notifyObservers(this);
  23911. this.onDisposeObservable.clear();
  23912. };
  23913. BaseTexture.prototype.serialize = function () {
  23914. if (!this.name) {
  23915. return null;
  23916. }
  23917. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23918. // Animations
  23919. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23920. return serializationObject;
  23921. };
  23922. BaseTexture.WhenAllReady = function (textures, callback) {
  23923. var numRemaining = textures.length;
  23924. if (numRemaining === 0) {
  23925. callback();
  23926. return;
  23927. }
  23928. var _loop_1 = function () {
  23929. texture = textures[i];
  23930. if (texture.isReady()) {
  23931. if (--numRemaining === 0) {
  23932. callback();
  23933. }
  23934. }
  23935. else {
  23936. onLoadObservable = texture.onLoadObservable;
  23937. var onLoadCallback_1 = function () {
  23938. onLoadObservable.removeCallback(onLoadCallback_1);
  23939. if (--numRemaining === 0) {
  23940. callback();
  23941. }
  23942. };
  23943. onLoadObservable.add(onLoadCallback_1);
  23944. }
  23945. };
  23946. var texture, onLoadObservable;
  23947. for (var i = 0; i < textures.length; i++) {
  23948. _loop_1();
  23949. }
  23950. };
  23951. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23952. __decorate([
  23953. BABYLON.serialize()
  23954. ], BaseTexture.prototype, "name", void 0);
  23955. __decorate([
  23956. BABYLON.serialize("hasAlpha")
  23957. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23958. __decorate([
  23959. BABYLON.serialize()
  23960. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23961. __decorate([
  23962. BABYLON.serialize()
  23963. ], BaseTexture.prototype, "level", void 0);
  23964. __decorate([
  23965. BABYLON.serialize()
  23966. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23967. __decorate([
  23968. BABYLON.serialize("coordinatesMode")
  23969. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23970. __decorate([
  23971. BABYLON.serialize()
  23972. ], BaseTexture.prototype, "wrapU", void 0);
  23973. __decorate([
  23974. BABYLON.serialize()
  23975. ], BaseTexture.prototype, "wrapV", void 0);
  23976. __decorate([
  23977. BABYLON.serialize()
  23978. ], BaseTexture.prototype, "wrapR", void 0);
  23979. __decorate([
  23980. BABYLON.serialize()
  23981. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23982. __decorate([
  23983. BABYLON.serialize()
  23984. ], BaseTexture.prototype, "isCube", void 0);
  23985. __decorate([
  23986. BABYLON.serialize()
  23987. ], BaseTexture.prototype, "is3D", void 0);
  23988. __decorate([
  23989. BABYLON.serialize()
  23990. ], BaseTexture.prototype, "gammaSpace", void 0);
  23991. __decorate([
  23992. BABYLON.serialize()
  23993. ], BaseTexture.prototype, "invertZ", void 0);
  23994. __decorate([
  23995. BABYLON.serialize()
  23996. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23997. __decorate([
  23998. BABYLON.serialize()
  23999. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24000. __decorate([
  24001. BABYLON.serialize()
  24002. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24003. __decorate([
  24004. BABYLON.serialize()
  24005. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24006. return BaseTexture;
  24007. }());
  24008. BABYLON.BaseTexture = BaseTexture;
  24009. })(BABYLON || (BABYLON = {}));
  24010. //# sourceMappingURL=babylon.baseTexture.js.map
  24011. var BABYLON;
  24012. (function (BABYLON) {
  24013. var Texture = /** @class */ (function (_super) {
  24014. __extends(Texture, _super);
  24015. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24016. if (noMipmap === void 0) { noMipmap = false; }
  24017. if (invertY === void 0) { invertY = true; }
  24018. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24019. if (onLoad === void 0) { onLoad = null; }
  24020. if (onError === void 0) { onError = null; }
  24021. if (buffer === void 0) { buffer = null; }
  24022. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24023. var _this = _super.call(this, scene) || this;
  24024. _this.uOffset = 0;
  24025. _this.vOffset = 0;
  24026. _this.uScale = 1.0;
  24027. _this.vScale = 1.0;
  24028. _this.uAng = 0;
  24029. _this.vAng = 0;
  24030. _this.wAng = 0;
  24031. _this._isBlocking = true;
  24032. _this.name = url || "";
  24033. _this.url = url;
  24034. _this._noMipmap = noMipmap;
  24035. _this._invertY = invertY;
  24036. _this._samplingMode = samplingMode;
  24037. _this._buffer = buffer;
  24038. _this._deleteBuffer = deleteBuffer;
  24039. if (format) {
  24040. _this._format = format;
  24041. }
  24042. scene = _this.getScene();
  24043. if (!scene) {
  24044. return _this;
  24045. }
  24046. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24047. var load = function () {
  24048. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24049. _this.onLoadObservable.notifyObservers(_this);
  24050. }
  24051. if (onLoad) {
  24052. onLoad();
  24053. }
  24054. if (!_this.isBlocking && scene) {
  24055. scene.resetCachedMaterial();
  24056. }
  24057. };
  24058. if (!_this.url) {
  24059. _this._delayedOnLoad = load;
  24060. _this._delayedOnError = onError;
  24061. return _this;
  24062. }
  24063. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24064. if (!_this._texture) {
  24065. if (!scene.useDelayedTextureLoading) {
  24066. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24067. if (deleteBuffer) {
  24068. delete _this._buffer;
  24069. }
  24070. }
  24071. else {
  24072. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24073. _this._delayedOnLoad = load;
  24074. _this._delayedOnError = onError;
  24075. }
  24076. }
  24077. else {
  24078. if (_this._texture.isReady) {
  24079. BABYLON.Tools.SetImmediate(function () { return load(); });
  24080. }
  24081. else {
  24082. _this._texture.onLoadedObservable.add(load);
  24083. }
  24084. }
  24085. return _this;
  24086. }
  24087. Object.defineProperty(Texture.prototype, "noMipmap", {
  24088. get: function () {
  24089. return this._noMipmap;
  24090. },
  24091. enumerable: true,
  24092. configurable: true
  24093. });
  24094. Object.defineProperty(Texture.prototype, "isBlocking", {
  24095. get: function () {
  24096. return this._isBlocking;
  24097. },
  24098. set: function (value) {
  24099. this._isBlocking = value;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Object.defineProperty(Texture.prototype, "samplingMode", {
  24105. get: function () {
  24106. return this._samplingMode;
  24107. },
  24108. enumerable: true,
  24109. configurable: true
  24110. });
  24111. Texture.prototype.updateURL = function (url) {
  24112. this.url = url;
  24113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24114. this.delayLoad();
  24115. };
  24116. Texture.prototype.delayLoad = function () {
  24117. var _this = this;
  24118. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24119. return;
  24120. }
  24121. var scene = this.getScene();
  24122. if (!scene) {
  24123. return;
  24124. }
  24125. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24126. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24127. if (!this._texture) {
  24128. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24129. if (this._deleteBuffer) {
  24130. delete this._buffer;
  24131. }
  24132. }
  24133. else {
  24134. if (this._texture.isReady) {
  24135. BABYLON.Tools.SetImmediate(function () {
  24136. if (!_this._delayedOnLoad) {
  24137. return;
  24138. }
  24139. _this._delayedOnLoad();
  24140. });
  24141. }
  24142. else {
  24143. if (this._delayedOnLoad) {
  24144. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24145. }
  24146. }
  24147. }
  24148. };
  24149. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24150. if (!this._texture) {
  24151. return;
  24152. }
  24153. var scene = this.getScene();
  24154. if (!scene) {
  24155. return;
  24156. }
  24157. this._samplingMode = samplingMode;
  24158. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24159. };
  24160. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24161. x *= this.uScale;
  24162. y *= this.vScale;
  24163. x -= 0.5 * this.uScale;
  24164. y -= 0.5 * this.vScale;
  24165. z -= 0.5;
  24166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24167. t.x += 0.5 * this.uScale + this.uOffset;
  24168. t.y += 0.5 * this.vScale + this.vOffset;
  24169. t.z += 0.5;
  24170. };
  24171. Texture.prototype.getTextureMatrix = function () {
  24172. var _this = this;
  24173. if (this.uOffset === this._cachedUOffset &&
  24174. this.vOffset === this._cachedVOffset &&
  24175. this.uScale === this._cachedUScale &&
  24176. this.vScale === this._cachedVScale &&
  24177. this.uAng === this._cachedUAng &&
  24178. this.vAng === this._cachedVAng &&
  24179. this.wAng === this._cachedWAng) {
  24180. return this._cachedTextureMatrix;
  24181. }
  24182. this._cachedUOffset = this.uOffset;
  24183. this._cachedVOffset = this.vOffset;
  24184. this._cachedUScale = this.uScale;
  24185. this._cachedVScale = this.vScale;
  24186. this._cachedUAng = this.uAng;
  24187. this._cachedVAng = this.vAng;
  24188. this._cachedWAng = this.wAng;
  24189. if (!this._cachedTextureMatrix) {
  24190. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24191. this._rowGenerationMatrix = new BABYLON.Matrix();
  24192. this._t0 = BABYLON.Vector3.Zero();
  24193. this._t1 = BABYLON.Vector3.Zero();
  24194. this._t2 = BABYLON.Vector3.Zero();
  24195. }
  24196. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24197. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24198. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24199. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24200. this._t1.subtractInPlace(this._t0);
  24201. this._t2.subtractInPlace(this._t0);
  24202. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24203. this._cachedTextureMatrix.m[0] = this._t1.x;
  24204. this._cachedTextureMatrix.m[1] = this._t1.y;
  24205. this._cachedTextureMatrix.m[2] = this._t1.z;
  24206. this._cachedTextureMatrix.m[4] = this._t2.x;
  24207. this._cachedTextureMatrix.m[5] = this._t2.y;
  24208. this._cachedTextureMatrix.m[6] = this._t2.z;
  24209. this._cachedTextureMatrix.m[8] = this._t0.x;
  24210. this._cachedTextureMatrix.m[9] = this._t0.y;
  24211. this._cachedTextureMatrix.m[10] = this._t0.z;
  24212. var scene = this.getScene();
  24213. if (!scene) {
  24214. return this._cachedTextureMatrix;
  24215. }
  24216. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24217. return mat.hasTexture(_this);
  24218. });
  24219. return this._cachedTextureMatrix;
  24220. };
  24221. Texture.prototype.getReflectionTextureMatrix = function () {
  24222. var _this = this;
  24223. var scene = this.getScene();
  24224. if (!scene) {
  24225. return this._cachedTextureMatrix;
  24226. }
  24227. if (this.uOffset === this._cachedUOffset &&
  24228. this.vOffset === this._cachedVOffset &&
  24229. this.uScale === this._cachedUScale &&
  24230. this.vScale === this._cachedVScale &&
  24231. this.coordinatesMode === this._cachedCoordinatesMode) {
  24232. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24233. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24234. return this._cachedTextureMatrix;
  24235. }
  24236. }
  24237. else {
  24238. return this._cachedTextureMatrix;
  24239. }
  24240. }
  24241. if (!this._cachedTextureMatrix) {
  24242. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24243. }
  24244. if (!this._projectionModeMatrix) {
  24245. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24246. }
  24247. this._cachedUOffset = this.uOffset;
  24248. this._cachedVOffset = this.vOffset;
  24249. this._cachedUScale = this.uScale;
  24250. this._cachedVScale = this.vScale;
  24251. this._cachedCoordinatesMode = this.coordinatesMode;
  24252. switch (this.coordinatesMode) {
  24253. case Texture.PLANAR_MODE:
  24254. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24255. this._cachedTextureMatrix[0] = this.uScale;
  24256. this._cachedTextureMatrix[5] = this.vScale;
  24257. this._cachedTextureMatrix[12] = this.uOffset;
  24258. this._cachedTextureMatrix[13] = this.vOffset;
  24259. break;
  24260. case Texture.PROJECTION_MODE:
  24261. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24262. this._projectionModeMatrix.m[0] = 0.5;
  24263. this._projectionModeMatrix.m[5] = -0.5;
  24264. this._projectionModeMatrix.m[10] = 0.0;
  24265. this._projectionModeMatrix.m[12] = 0.5;
  24266. this._projectionModeMatrix.m[13] = 0.5;
  24267. this._projectionModeMatrix.m[14] = 1.0;
  24268. this._projectionModeMatrix.m[15] = 1.0;
  24269. var projectionMatrix = scene.getProjectionMatrix();
  24270. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24271. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24272. break;
  24273. default:
  24274. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24275. break;
  24276. }
  24277. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24278. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24279. });
  24280. return this._cachedTextureMatrix;
  24281. };
  24282. Texture.prototype.clone = function () {
  24283. var _this = this;
  24284. return BABYLON.SerializationHelper.Clone(function () {
  24285. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24286. }, this);
  24287. };
  24288. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24289. get: function () {
  24290. if (!this._onLoadObservable) {
  24291. this._onLoadObservable = new BABYLON.Observable();
  24292. }
  24293. return this._onLoadObservable;
  24294. },
  24295. enumerable: true,
  24296. configurable: true
  24297. });
  24298. Texture.prototype.serialize = function () {
  24299. var serializationObject = _super.prototype.serialize.call(this);
  24300. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24301. serializationObject.base64String = this._buffer;
  24302. serializationObject.name = serializationObject.name.replace("data:", "");
  24303. }
  24304. return serializationObject;
  24305. };
  24306. Texture.prototype.getClassName = function () {
  24307. return "Texture";
  24308. };
  24309. Texture.prototype.dispose = function () {
  24310. _super.prototype.dispose.call(this);
  24311. if (this.onLoadObservable) {
  24312. this.onLoadObservable.clear();
  24313. this._onLoadObservable = null;
  24314. }
  24315. this._delayedOnLoad = null;
  24316. this._delayedOnError = null;
  24317. };
  24318. // Statics
  24319. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24320. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24321. if (onLoad === void 0) { onLoad = null; }
  24322. if (onError === void 0) { onError = null; }
  24323. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24324. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24325. };
  24326. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24327. if (parsedTexture.customType) {
  24328. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24329. // Update Sampling Mode
  24330. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24331. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24332. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24333. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24334. }
  24335. }
  24336. return parsedCustomTexture;
  24337. }
  24338. if (parsedTexture.isCube) {
  24339. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24340. }
  24341. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24342. return null;
  24343. }
  24344. var texture = BABYLON.SerializationHelper.Parse(function () {
  24345. var generateMipMaps = true;
  24346. if (parsedTexture.noMipmap) {
  24347. generateMipMaps = false;
  24348. }
  24349. if (parsedTexture.mirrorPlane) {
  24350. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24351. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24352. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24353. return mirrorTexture;
  24354. }
  24355. else if (parsedTexture.isRenderTarget) {
  24356. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24357. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24358. return renderTargetTexture;
  24359. }
  24360. else {
  24361. var texture;
  24362. if (parsedTexture.base64String) {
  24363. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24364. }
  24365. else {
  24366. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24367. }
  24368. return texture;
  24369. }
  24370. }, parsedTexture, scene);
  24371. // Update Sampling Mode
  24372. if (parsedTexture.samplingMode) {
  24373. var sampling = parsedTexture.samplingMode;
  24374. if (texture._samplingMode !== sampling) {
  24375. texture.updateSamplingMode(sampling);
  24376. }
  24377. }
  24378. // Animations
  24379. if (parsedTexture.animations) {
  24380. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24381. var parsedAnimation = parsedTexture.animations[animationIndex];
  24382. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24383. }
  24384. }
  24385. return texture;
  24386. };
  24387. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24388. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24389. if (noMipmap === void 0) { noMipmap = false; }
  24390. if (invertY === void 0) { invertY = true; }
  24391. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24392. if (onLoad === void 0) { onLoad = null; }
  24393. if (onError === void 0) { onError = null; }
  24394. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24395. if (name.substr(0, 5) !== "data:") {
  24396. name = "data:" + name;
  24397. }
  24398. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24399. };
  24400. // Constants
  24401. Texture.NEAREST_SAMPLINGMODE = 1;
  24402. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24403. Texture.BILINEAR_SAMPLINGMODE = 2;
  24404. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24405. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24406. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24407. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24408. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24409. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24410. Texture.NEAREST_LINEAR = 7;
  24411. Texture.NEAREST_NEAREST = 8;
  24412. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24413. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24414. Texture.LINEAR_LINEAR = 11;
  24415. Texture.LINEAR_NEAREST = 12;
  24416. Texture.EXPLICIT_MODE = 0;
  24417. Texture.SPHERICAL_MODE = 1;
  24418. Texture.PLANAR_MODE = 2;
  24419. Texture.CUBIC_MODE = 3;
  24420. Texture.PROJECTION_MODE = 4;
  24421. Texture.SKYBOX_MODE = 5;
  24422. Texture.INVCUBIC_MODE = 6;
  24423. Texture.EQUIRECTANGULAR_MODE = 7;
  24424. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24425. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24426. Texture.CLAMP_ADDRESSMODE = 0;
  24427. Texture.WRAP_ADDRESSMODE = 1;
  24428. Texture.MIRROR_ADDRESSMODE = 2;
  24429. __decorate([
  24430. BABYLON.serialize()
  24431. ], Texture.prototype, "url", void 0);
  24432. __decorate([
  24433. BABYLON.serialize()
  24434. ], Texture.prototype, "uOffset", void 0);
  24435. __decorate([
  24436. BABYLON.serialize()
  24437. ], Texture.prototype, "vOffset", void 0);
  24438. __decorate([
  24439. BABYLON.serialize()
  24440. ], Texture.prototype, "uScale", void 0);
  24441. __decorate([
  24442. BABYLON.serialize()
  24443. ], Texture.prototype, "vScale", void 0);
  24444. __decorate([
  24445. BABYLON.serialize()
  24446. ], Texture.prototype, "uAng", void 0);
  24447. __decorate([
  24448. BABYLON.serialize()
  24449. ], Texture.prototype, "vAng", void 0);
  24450. __decorate([
  24451. BABYLON.serialize()
  24452. ], Texture.prototype, "wAng", void 0);
  24453. __decorate([
  24454. BABYLON.serialize()
  24455. ], Texture.prototype, "isBlocking", null);
  24456. return Texture;
  24457. }(BABYLON.BaseTexture));
  24458. BABYLON.Texture = Texture;
  24459. })(BABYLON || (BABYLON = {}));
  24460. //# sourceMappingURL=babylon.texture.js.map
  24461. var BABYLON;
  24462. (function (BABYLON) {
  24463. var _InstancesBatch = /** @class */ (function () {
  24464. function _InstancesBatch() {
  24465. this.mustReturn = false;
  24466. this.visibleInstances = new Array();
  24467. this.renderSelf = new Array();
  24468. }
  24469. return _InstancesBatch;
  24470. }());
  24471. BABYLON._InstancesBatch = _InstancesBatch;
  24472. var Mesh = /** @class */ (function (_super) {
  24473. __extends(Mesh, _super);
  24474. /**
  24475. * @constructor
  24476. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24477. * @param {Scene} scene The scene to add this mesh to.
  24478. * @param {Node} parent The parent of this mesh, if it has one
  24479. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24480. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24481. * When false, achieved by calling a clone(), also passing False.
  24482. * This will make creation of children, recursive.
  24483. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24484. */
  24485. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24486. if (scene === void 0) { scene = null; }
  24487. if (parent === void 0) { parent = null; }
  24488. if (source === void 0) { source = null; }
  24489. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24490. var _this = _super.call(this, name, scene) || this;
  24491. // Events
  24492. /**
  24493. * An event triggered before rendering the mesh
  24494. * @type {BABYLON.Observable}
  24495. */
  24496. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24497. /**
  24498. * An event triggered after rendering the mesh
  24499. * @type {BABYLON.Observable}
  24500. */
  24501. _this.onAfterRenderObservable = new BABYLON.Observable();
  24502. /**
  24503. * An event triggered before drawing the mesh
  24504. * @type {BABYLON.Observable}
  24505. */
  24506. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24507. // Members
  24508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24509. _this.instances = new Array();
  24510. _this._LODLevels = new Array();
  24511. _this._visibleInstances = {};
  24512. _this._renderIdForInstances = new Array();
  24513. _this._batchCache = new _InstancesBatch();
  24514. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24515. // Use by builder only to know what orientation were the mesh build in.
  24516. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24517. _this.overrideMaterialSideOrientation = null;
  24518. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24519. // Will be used to save a source mesh reference, If any
  24520. _this._source = null;
  24521. scene = _this.getScene();
  24522. if (source) {
  24523. // Source mesh
  24524. _this._source = source;
  24525. // Geometry
  24526. if (source._geometry) {
  24527. source._geometry.applyToMesh(_this);
  24528. }
  24529. // Deep copy
  24530. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24531. // Metadata
  24532. if (source.metadata && source.metadata.clone) {
  24533. _this.metadata = source.metadata.clone();
  24534. }
  24535. else {
  24536. _this.metadata = source.metadata;
  24537. }
  24538. // Tags
  24539. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24540. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24541. }
  24542. // Parent
  24543. _this.parent = source.parent;
  24544. // Pivot
  24545. _this.setPivotMatrix(source.getPivotMatrix());
  24546. _this.id = name + "." + source.id;
  24547. // Material
  24548. _this.material = source.material;
  24549. var index;
  24550. if (!doNotCloneChildren) {
  24551. // Children
  24552. var directDescendants = source.getDescendants(true);
  24553. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24554. var child = directDescendants[index_1];
  24555. if (child.clone) {
  24556. child.clone(name + "." + child.name, _this);
  24557. }
  24558. }
  24559. }
  24560. // Physics clone
  24561. var physicsEngine = _this.getScene().getPhysicsEngine();
  24562. if (clonePhysicsImpostor && physicsEngine) {
  24563. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24564. if (impostor) {
  24565. _this.physicsImpostor = impostor.clone(_this);
  24566. }
  24567. }
  24568. // Particles
  24569. for (index = 0; index < scene.particleSystems.length; index++) {
  24570. var system = scene.particleSystems[index];
  24571. if (system.emitter === source) {
  24572. system.clone(system.name, _this);
  24573. }
  24574. }
  24575. _this.computeWorldMatrix(true);
  24576. }
  24577. // Parent
  24578. if (parent !== null) {
  24579. _this.parent = parent;
  24580. }
  24581. return _this;
  24582. }
  24583. Object.defineProperty(Mesh, "FRONTSIDE", {
  24584. /**
  24585. * Mesh side orientation : usually the external or front surface
  24586. */
  24587. get: function () {
  24588. return Mesh._FRONTSIDE;
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Mesh, "BACKSIDE", {
  24594. /**
  24595. * Mesh side orientation : usually the internal or back surface
  24596. */
  24597. get: function () {
  24598. return Mesh._BACKSIDE;
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24604. /**
  24605. * Mesh side orientation : both internal and external or front and back surfaces
  24606. */
  24607. get: function () {
  24608. return Mesh._DOUBLESIDE;
  24609. },
  24610. enumerable: true,
  24611. configurable: true
  24612. });
  24613. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24614. /**
  24615. * Mesh side orientation : by default, `FRONTSIDE`
  24616. */
  24617. get: function () {
  24618. return Mesh._DEFAULTSIDE;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Mesh, "NO_CAP", {
  24624. /**
  24625. * Mesh cap setting : no cap
  24626. */
  24627. get: function () {
  24628. return Mesh._NO_CAP;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Mesh, "CAP_START", {
  24634. /**
  24635. * Mesh cap setting : one cap at the beginning of the mesh
  24636. */
  24637. get: function () {
  24638. return Mesh._CAP_START;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Mesh, "CAP_END", {
  24644. /**
  24645. * Mesh cap setting : one cap at the end of the mesh
  24646. */
  24647. get: function () {
  24648. return Mesh._CAP_END;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. Object.defineProperty(Mesh, "CAP_ALL", {
  24654. /**
  24655. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24656. */
  24657. get: function () {
  24658. return Mesh._CAP_ALL;
  24659. },
  24660. enumerable: true,
  24661. configurable: true
  24662. });
  24663. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24664. set: function (callback) {
  24665. if (this._onBeforeDrawObserver) {
  24666. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24667. }
  24668. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24674. get: function () {
  24675. return this._morphTargetManager;
  24676. },
  24677. set: function (value) {
  24678. if (this._morphTargetManager === value) {
  24679. return;
  24680. }
  24681. this._morphTargetManager = value;
  24682. this._syncGeometryWithMorphTargetManager();
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. Object.defineProperty(Mesh.prototype, "source", {
  24688. get: function () {
  24689. return this._source;
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24695. get: function () {
  24696. return this._unIndexed;
  24697. },
  24698. set: function (value) {
  24699. if (this._unIndexed !== value) {
  24700. this._unIndexed = value;
  24701. this._markSubMeshesAsAttributesDirty();
  24702. }
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. // Methods
  24708. /**
  24709. * Returns the string "Mesh".
  24710. */
  24711. Mesh.prototype.getClassName = function () {
  24712. return "Mesh";
  24713. };
  24714. /**
  24715. * Returns a string.
  24716. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24717. */
  24718. Mesh.prototype.toString = function (fullDetails) {
  24719. var ret = _super.prototype.toString.call(this, fullDetails);
  24720. ret += ", n vertices: " + this.getTotalVertices();
  24721. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24722. if (this.animations) {
  24723. for (var i = 0; i < this.animations.length; i++) {
  24724. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24725. }
  24726. }
  24727. if (fullDetails) {
  24728. if (this._geometry) {
  24729. var ib = this.getIndices();
  24730. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24731. if (vb && ib) {
  24732. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24733. }
  24734. }
  24735. else {
  24736. ret += ", flat shading: UNKNOWN";
  24737. }
  24738. }
  24739. return ret;
  24740. };
  24741. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24742. /**
  24743. * True if the mesh has some Levels Of Details (LOD).
  24744. * Returns a boolean.
  24745. */
  24746. get: function () {
  24747. return this._LODLevels.length > 0;
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. Mesh.prototype._sortLODLevels = function () {
  24753. this._LODLevels.sort(function (a, b) {
  24754. if (a.distance < b.distance) {
  24755. return 1;
  24756. }
  24757. if (a.distance > b.distance) {
  24758. return -1;
  24759. }
  24760. return 0;
  24761. });
  24762. };
  24763. /**
  24764. * Add a mesh as LOD level triggered at the given distance.
  24765. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24766. * @param {number} distance The distance from the center of the object to show this level
  24767. * @param {Mesh} mesh The mesh to be added as LOD level
  24768. * @return {Mesh} This mesh (for chaining)
  24769. */
  24770. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24771. if (mesh && mesh._masterMesh) {
  24772. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24773. return this;
  24774. }
  24775. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24776. this._LODLevels.push(level);
  24777. if (mesh) {
  24778. mesh._masterMesh = this;
  24779. }
  24780. this._sortLODLevels();
  24781. return this;
  24782. };
  24783. /**
  24784. * Returns the LOD level mesh at the passed distance or null if not found.
  24785. * It is related to the method `addLODLevel(distance, mesh)`.
  24786. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24787. * Returns an object Mesh or `null`.
  24788. */
  24789. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24790. for (var index = 0; index < this._LODLevels.length; index++) {
  24791. var level = this._LODLevels[index];
  24792. if (level.distance === distance) {
  24793. return level.mesh;
  24794. }
  24795. }
  24796. return null;
  24797. };
  24798. /**
  24799. * Remove a mesh from the LOD array
  24800. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24801. * @param {Mesh} mesh The mesh to be removed.
  24802. * @return {Mesh} This mesh (for chaining)
  24803. */
  24804. Mesh.prototype.removeLODLevel = function (mesh) {
  24805. for (var index = 0; index < this._LODLevels.length; index++) {
  24806. if (this._LODLevels[index].mesh === mesh) {
  24807. this._LODLevels.splice(index, 1);
  24808. if (mesh) {
  24809. mesh._masterMesh = null;
  24810. }
  24811. }
  24812. }
  24813. this._sortLODLevels();
  24814. return this;
  24815. };
  24816. /**
  24817. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24818. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24819. */
  24820. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24821. if (!this._LODLevels || this._LODLevels.length === 0) {
  24822. return this;
  24823. }
  24824. var bSphere;
  24825. if (boundingSphere) {
  24826. bSphere = boundingSphere;
  24827. }
  24828. else {
  24829. var boundingInfo = this.getBoundingInfo();
  24830. bSphere = boundingInfo.boundingSphere;
  24831. }
  24832. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  24833. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24834. if (this.onLODLevelSelection) {
  24835. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24836. }
  24837. return this;
  24838. }
  24839. for (var index = 0; index < this._LODLevels.length; index++) {
  24840. var level = this._LODLevels[index];
  24841. if (level.distance < distanceToCamera) {
  24842. if (level.mesh) {
  24843. level.mesh._preActivate();
  24844. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24845. }
  24846. if (this.onLODLevelSelection) {
  24847. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24848. }
  24849. return level.mesh;
  24850. }
  24851. }
  24852. if (this.onLODLevelSelection) {
  24853. this.onLODLevelSelection(distanceToCamera, this, this);
  24854. }
  24855. return this;
  24856. };
  24857. Object.defineProperty(Mesh.prototype, "geometry", {
  24858. /**
  24859. * Returns the mesh internal Geometry object.
  24860. */
  24861. get: function () {
  24862. return this._geometry;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24869. */
  24870. Mesh.prototype.getTotalVertices = function () {
  24871. if (this._geometry === null || this._geometry === undefined) {
  24872. return 0;
  24873. }
  24874. return this._geometry.getTotalVertices();
  24875. };
  24876. /**
  24877. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24878. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  24879. * You can force the copy with forceCopy === true
  24880. * Returns null if the mesh has no geometry or no vertex buffer.
  24881. * Possible `kind` values :
  24882. * - BABYLON.VertexBuffer.PositionKind
  24883. * - BABYLON.VertexBuffer.UVKind
  24884. * - BABYLON.VertexBuffer.UV2Kind
  24885. * - BABYLON.VertexBuffer.UV3Kind
  24886. * - BABYLON.VertexBuffer.UV4Kind
  24887. * - BABYLON.VertexBuffer.UV5Kind
  24888. * - BABYLON.VertexBuffer.UV6Kind
  24889. * - BABYLON.VertexBuffer.ColorKind
  24890. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24891. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24892. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24893. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24894. */
  24895. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24896. if (!this._geometry) {
  24897. return null;
  24898. }
  24899. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24900. };
  24901. /**
  24902. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24903. * Returns `null` if the mesh has no geometry.
  24904. * Possible `kind` values :
  24905. * - BABYLON.VertexBuffer.PositionKind
  24906. * - BABYLON.VertexBuffer.UVKind
  24907. * - BABYLON.VertexBuffer.UV2Kind
  24908. * - BABYLON.VertexBuffer.UV3Kind
  24909. * - BABYLON.VertexBuffer.UV4Kind
  24910. * - BABYLON.VertexBuffer.UV5Kind
  24911. * - BABYLON.VertexBuffer.UV6Kind
  24912. * - BABYLON.VertexBuffer.ColorKind
  24913. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24914. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24915. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24916. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24917. */
  24918. Mesh.prototype.getVertexBuffer = function (kind) {
  24919. if (!this._geometry) {
  24920. return null;
  24921. }
  24922. return this._geometry.getVertexBuffer(kind);
  24923. };
  24924. /**
  24925. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24926. * Possible `kind` values :
  24927. * - BABYLON.VertexBuffer.PositionKind
  24928. * - BABYLON.VertexBuffer.UVKind
  24929. * - BABYLON.VertexBuffer.UV2Kind
  24930. * - BABYLON.VertexBuffer.UV3Kind
  24931. * - BABYLON.VertexBuffer.UV4Kind
  24932. * - BABYLON.VertexBuffer.UV5Kind
  24933. * - BABYLON.VertexBuffer.UV6Kind
  24934. * - BABYLON.VertexBuffer.ColorKind
  24935. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24936. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24937. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24938. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24939. */
  24940. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24941. if (!this._geometry) {
  24942. if (this._delayInfo) {
  24943. return this._delayInfo.indexOf(kind) !== -1;
  24944. }
  24945. return false;
  24946. }
  24947. return this._geometry.isVerticesDataPresent(kind);
  24948. };
  24949. /**
  24950. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24951. * Possible `kind` values :
  24952. * - BABYLON.VertexBuffer.PositionKind
  24953. * - BABYLON.VertexBuffer.UVKind
  24954. * - BABYLON.VertexBuffer.UV2Kind
  24955. * - BABYLON.VertexBuffer.UV3Kind
  24956. * - BABYLON.VertexBuffer.UV4Kind
  24957. * - BABYLON.VertexBuffer.UV5Kind
  24958. * - BABYLON.VertexBuffer.UV6Kind
  24959. * - BABYLON.VertexBuffer.ColorKind
  24960. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24961. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24962. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24963. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24964. */
  24965. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24966. if (!this._geometry) {
  24967. if (this._delayInfo) {
  24968. return this._delayInfo.indexOf(kind) !== -1;
  24969. }
  24970. return false;
  24971. }
  24972. return this._geometry.isVertexBufferUpdatable(kind);
  24973. };
  24974. /**
  24975. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24976. * Possible `kind` values :
  24977. * - BABYLON.VertexBuffer.PositionKind
  24978. * - BABYLON.VertexBuffer.UVKind
  24979. * - BABYLON.VertexBuffer.UV2Kind
  24980. * - BABYLON.VertexBuffer.UV3Kind
  24981. * - BABYLON.VertexBuffer.UV4Kind
  24982. * - BABYLON.VertexBuffer.UV5Kind
  24983. * - BABYLON.VertexBuffer.UV6Kind
  24984. * - BABYLON.VertexBuffer.ColorKind
  24985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24989. */
  24990. Mesh.prototype.getVerticesDataKinds = function () {
  24991. if (!this._geometry) {
  24992. var result = new Array();
  24993. if (this._delayInfo) {
  24994. this._delayInfo.forEach(function (kind, index, array) {
  24995. result.push(kind);
  24996. });
  24997. }
  24998. return result;
  24999. }
  25000. return this._geometry.getVerticesDataKinds();
  25001. };
  25002. /**
  25003. * Returns a positive integer : the total number of indices in this mesh geometry.
  25004. * Returns zero if the mesh has no geometry.
  25005. */
  25006. Mesh.prototype.getTotalIndices = function () {
  25007. if (!this._geometry) {
  25008. return 0;
  25009. }
  25010. return this._geometry.getTotalIndices();
  25011. };
  25012. /**
  25013. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25014. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  25015. * Returns an empty array if the mesh has no geometry.
  25016. */
  25017. Mesh.prototype.getIndices = function (copyWhenShared) {
  25018. if (!this._geometry) {
  25019. return [];
  25020. }
  25021. return this._geometry.getIndices(copyWhenShared);
  25022. };
  25023. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25024. get: function () {
  25025. return this._masterMesh !== null && this._masterMesh !== undefined;
  25026. },
  25027. enumerable: true,
  25028. configurable: true
  25029. });
  25030. /**
  25031. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  25032. */
  25033. Mesh.prototype.isReady = function () {
  25034. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25035. return false;
  25036. }
  25037. return _super.prototype.isReady.call(this);
  25038. };
  25039. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25040. /**
  25041. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25042. * This property is pertinent only for updatable parametric shapes.
  25043. */
  25044. get: function () {
  25045. return this._areNormalsFrozen;
  25046. },
  25047. enumerable: true,
  25048. configurable: true
  25049. });
  25050. /**
  25051. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25052. * It has no effect at all on other shapes.
  25053. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25054. * Returns the Mesh.
  25055. */
  25056. Mesh.prototype.freezeNormals = function () {
  25057. this._areNormalsFrozen = true;
  25058. return this;
  25059. };
  25060. /**
  25061. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25062. * It has no effect at all on other shapes.
  25063. * It reactivates the mesh normals computation if it was previously frozen.
  25064. * Returns the Mesh.
  25065. */
  25066. Mesh.prototype.unfreezeNormals = function () {
  25067. this._areNormalsFrozen = false;
  25068. return this;
  25069. };
  25070. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25071. /**
  25072. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25073. */
  25074. set: function (count) {
  25075. this._overridenInstanceCount = count;
  25076. },
  25077. enumerable: true,
  25078. configurable: true
  25079. });
  25080. // Methods
  25081. Mesh.prototype._preActivate = function () {
  25082. var sceneRenderId = this.getScene().getRenderId();
  25083. if (this._preActivateId === sceneRenderId) {
  25084. return this;
  25085. }
  25086. this._preActivateId = sceneRenderId;
  25087. this._visibleInstances = null;
  25088. return this;
  25089. };
  25090. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25091. if (this._visibleInstances) {
  25092. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25093. }
  25094. return this;
  25095. };
  25096. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25097. if (!this._visibleInstances) {
  25098. this._visibleInstances = {};
  25099. this._visibleInstances.defaultRenderId = renderId;
  25100. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25101. }
  25102. if (!this._visibleInstances[renderId]) {
  25103. this._visibleInstances[renderId] = new Array();
  25104. }
  25105. this._visibleInstances[renderId].push(instance);
  25106. return this;
  25107. };
  25108. /**
  25109. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25110. * This means the mesh underlying bounding box and sphere are recomputed.
  25111. * Returns the Mesh.
  25112. */
  25113. Mesh.prototype.refreshBoundingInfo = function () {
  25114. return this._refreshBoundingInfo(false);
  25115. };
  25116. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25117. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25118. return this;
  25119. }
  25120. var data = this._getPositionData(applySkeleton);
  25121. if (data) {
  25122. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25123. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25124. }
  25125. if (this.subMeshes) {
  25126. for (var index = 0; index < this.subMeshes.length; index++) {
  25127. this.subMeshes[index].refreshBoundingInfo();
  25128. }
  25129. }
  25130. this._updateBoundingInfo();
  25131. return this;
  25132. };
  25133. Mesh.prototype._getPositionData = function (applySkeleton) {
  25134. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25135. if (data && applySkeleton && this.skeleton) {
  25136. data = data.slice();
  25137. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25138. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25139. if (matricesWeightsData && matricesIndicesData) {
  25140. var needExtras = this.numBoneInfluencers > 4;
  25141. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25142. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25143. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25144. var tempVector = BABYLON.Tmp.Vector3[0];
  25145. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25146. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25147. var matWeightIdx = 0;
  25148. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25149. finalMatrix.reset();
  25150. var inf;
  25151. var weight;
  25152. for (inf = 0; inf < 4; inf++) {
  25153. weight = matricesWeightsData[matWeightIdx + inf];
  25154. if (weight <= 0)
  25155. break;
  25156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25157. finalMatrix.addToSelf(tempMatrix);
  25158. }
  25159. if (needExtras) {
  25160. for (inf = 0; inf < 4; inf++) {
  25161. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25162. if (weight <= 0)
  25163. break;
  25164. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25165. finalMatrix.addToSelf(tempMatrix);
  25166. }
  25167. }
  25168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25169. tempVector.toArray(data, index);
  25170. }
  25171. }
  25172. }
  25173. return data;
  25174. };
  25175. Mesh.prototype._createGlobalSubMesh = function (force) {
  25176. var totalVertices = this.getTotalVertices();
  25177. if (!totalVertices || !this.getIndices()) {
  25178. return null;
  25179. }
  25180. // Check if we need to recreate the submeshes
  25181. if (this.subMeshes && this.subMeshes.length > 0) {
  25182. var ib = this.getIndices();
  25183. if (!ib) {
  25184. return null;
  25185. }
  25186. var totalIndices = ib.length;
  25187. var needToRecreate = false;
  25188. if (force) {
  25189. needToRecreate = true;
  25190. }
  25191. else {
  25192. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25193. var submesh = _a[_i];
  25194. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25195. needToRecreate = true;
  25196. break;
  25197. }
  25198. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25199. needToRecreate = true;
  25200. break;
  25201. }
  25202. }
  25203. }
  25204. if (!needToRecreate) {
  25205. return this.subMeshes[0];
  25206. }
  25207. }
  25208. this.releaseSubMeshes();
  25209. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25210. };
  25211. Mesh.prototype.subdivide = function (count) {
  25212. if (count < 1) {
  25213. return;
  25214. }
  25215. var totalIndices = this.getTotalIndices();
  25216. var subdivisionSize = (totalIndices / count) | 0;
  25217. var offset = 0;
  25218. // Ensure that subdivisionSize is a multiple of 3
  25219. while (subdivisionSize % 3 !== 0) {
  25220. subdivisionSize++;
  25221. }
  25222. this.releaseSubMeshes();
  25223. for (var index = 0; index < count; index++) {
  25224. if (offset >= totalIndices) {
  25225. break;
  25226. }
  25227. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25228. offset += subdivisionSize;
  25229. }
  25230. this.synchronizeInstances();
  25231. };
  25232. /**
  25233. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25234. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25235. * The `data` are either a numeric array either a Float32Array.
  25236. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25237. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  25238. * Note that a new underlying VertexBuffer object is created each call.
  25239. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25240. *
  25241. * Possible `kind` values :
  25242. * - BABYLON.VertexBuffer.PositionKind
  25243. * - BABYLON.VertexBuffer.UVKind
  25244. * - BABYLON.VertexBuffer.UV2Kind
  25245. * - BABYLON.VertexBuffer.UV3Kind
  25246. * - BABYLON.VertexBuffer.UV4Kind
  25247. * - BABYLON.VertexBuffer.UV5Kind
  25248. * - BABYLON.VertexBuffer.UV6Kind
  25249. * - BABYLON.VertexBuffer.ColorKind
  25250. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25251. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25252. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25253. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25254. *
  25255. * Returns the Mesh.
  25256. */
  25257. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25258. if (updatable === void 0) { updatable = false; }
  25259. if (!this._geometry) {
  25260. var vertexData = new BABYLON.VertexData();
  25261. vertexData.set(data, kind);
  25262. var scene = this.getScene();
  25263. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25264. }
  25265. else {
  25266. this._geometry.setVerticesData(kind, data, updatable, stride);
  25267. }
  25268. return this;
  25269. };
  25270. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25271. if (updatable === void 0) { updatable = true; }
  25272. var vb = this.getVertexBuffer(kind);
  25273. if (!vb || vb.isUpdatable() === updatable) {
  25274. return;
  25275. }
  25276. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25277. };
  25278. /**
  25279. * Sets the mesh VertexBuffer.
  25280. * Returns the Mesh.
  25281. */
  25282. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25283. if (!this._geometry) {
  25284. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25285. }
  25286. this._geometry.setVerticesBuffer(buffer);
  25287. return this;
  25288. };
  25289. /**
  25290. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25291. * If the mesh has no geometry, it is simply returned as it is.
  25292. * The `data` are either a numeric array either a Float32Array.
  25293. * No new underlying VertexBuffer object is created.
  25294. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25295. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25296. *
  25297. * Possible `kind` values :
  25298. * - BABYLON.VertexBuffer.PositionKind
  25299. * - BABYLON.VertexBuffer.UVKind
  25300. * - BABYLON.VertexBuffer.UV2Kind
  25301. * - BABYLON.VertexBuffer.UV3Kind
  25302. * - BABYLON.VertexBuffer.UV4Kind
  25303. * - BABYLON.VertexBuffer.UV5Kind
  25304. * - BABYLON.VertexBuffer.UV6Kind
  25305. * - BABYLON.VertexBuffer.ColorKind
  25306. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25307. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25308. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25309. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25310. *
  25311. * Returns the Mesh.
  25312. */
  25313. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25314. if (!this._geometry) {
  25315. return this;
  25316. }
  25317. if (!makeItUnique) {
  25318. this._geometry.updateVerticesData(kind, data, updateExtends);
  25319. }
  25320. else {
  25321. this.makeGeometryUnique();
  25322. this.updateVerticesData(kind, data, updateExtends, false);
  25323. }
  25324. return this;
  25325. };
  25326. /**
  25327. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25328. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25329. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25330. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25331. * Returns the Mesh.
  25332. */
  25333. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25334. if (computeNormals === void 0) { computeNormals = true; }
  25335. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25336. if (!positions) {
  25337. return this;
  25338. }
  25339. positionFunction(positions);
  25340. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25341. if (computeNormals) {
  25342. var indices = this.getIndices();
  25343. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25344. if (!normals) {
  25345. return this;
  25346. }
  25347. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25348. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25349. }
  25350. return this;
  25351. };
  25352. /**
  25353. * Creates a un-shared specific occurence of the geometry for the mesh.
  25354. * Returns the Mesh.
  25355. */
  25356. Mesh.prototype.makeGeometryUnique = function () {
  25357. if (!this._geometry) {
  25358. return this;
  25359. }
  25360. var oldGeometry = this._geometry;
  25361. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25362. oldGeometry.releaseForMesh(this, true);
  25363. geometry.applyToMesh(this);
  25364. return this;
  25365. };
  25366. /**
  25367. * Sets the mesh indices.
  25368. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25369. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25370. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25371. * This method creates a new index buffer each call.
  25372. * Returns the Mesh.
  25373. */
  25374. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25375. if (totalVertices === void 0) { totalVertices = null; }
  25376. if (updatable === void 0) { updatable = false; }
  25377. if (!this._geometry) {
  25378. var vertexData = new BABYLON.VertexData();
  25379. vertexData.indices = indices;
  25380. var scene = this.getScene();
  25381. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25382. }
  25383. else {
  25384. this._geometry.setIndices(indices, totalVertices, updatable);
  25385. }
  25386. return this;
  25387. };
  25388. /**
  25389. * Update the current index buffer
  25390. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25391. * Returns the Mesh.
  25392. */
  25393. Mesh.prototype.updateIndices = function (indices, offset) {
  25394. if (!this._geometry) {
  25395. return this;
  25396. }
  25397. this._geometry.updateIndices(indices, offset);
  25398. return this;
  25399. };
  25400. /**
  25401. * Invert the geometry to move from a right handed system to a left handed one.
  25402. * Returns the Mesh.
  25403. */
  25404. Mesh.prototype.toLeftHanded = function () {
  25405. if (!this._geometry) {
  25406. return this;
  25407. }
  25408. this._geometry.toLeftHanded();
  25409. return this;
  25410. };
  25411. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25412. if (!this._geometry) {
  25413. return this;
  25414. }
  25415. var engine = this.getScene().getEngine();
  25416. // Wireframe
  25417. var indexToBind;
  25418. if (this._unIndexed) {
  25419. indexToBind = null;
  25420. }
  25421. else {
  25422. switch (fillMode) {
  25423. case BABYLON.Material.PointFillMode:
  25424. indexToBind = null;
  25425. break;
  25426. case BABYLON.Material.WireFrameFillMode:
  25427. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25428. break;
  25429. default:
  25430. case BABYLON.Material.TriangleFillMode:
  25431. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25432. break;
  25433. }
  25434. }
  25435. // VBOs
  25436. this._geometry._bind(effect, indexToBind);
  25437. return this;
  25438. };
  25439. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25440. if (alternate === void 0) { alternate = false; }
  25441. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25442. return this;
  25443. }
  25444. this.onBeforeDrawObservable.notifyObservers(this);
  25445. var scene = this.getScene();
  25446. var engine = scene.getEngine();
  25447. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25448. // or triangles as points
  25449. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25450. }
  25451. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25452. // Triangles as wireframe
  25453. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25454. }
  25455. else {
  25456. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25457. }
  25458. if (scene._isAlternateRenderingEnabled && !alternate) {
  25459. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25460. if (!effect || !scene.activeCamera) {
  25461. return this;
  25462. }
  25463. scene._switchToAlternateCameraConfiguration(true);
  25464. this._effectiveMaterial.bindView(effect);
  25465. this._effectiveMaterial.bindViewProjection(effect);
  25466. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25467. this._draw(subMesh, fillMode, instancesCount, true);
  25468. engine.setViewport(scene.activeCamera.viewport);
  25469. scene._switchToAlternateCameraConfiguration(false);
  25470. this._effectiveMaterial.bindView(effect);
  25471. this._effectiveMaterial.bindViewProjection(effect);
  25472. }
  25473. return this;
  25474. };
  25475. /**
  25476. * Registers for this mesh a javascript function called just before the rendering process.
  25477. * This function is passed the current mesh.
  25478. * Return the Mesh.
  25479. */
  25480. Mesh.prototype.registerBeforeRender = function (func) {
  25481. this.onBeforeRenderObservable.add(func);
  25482. return this;
  25483. };
  25484. /**
  25485. * Disposes a previously registered javascript function called before the rendering.
  25486. * This function is passed the current mesh.
  25487. * Returns the Mesh.
  25488. */
  25489. Mesh.prototype.unregisterBeforeRender = function (func) {
  25490. this.onBeforeRenderObservable.removeCallback(func);
  25491. return this;
  25492. };
  25493. /**
  25494. * Registers for this mesh a javascript function called just after the rendering is complete.
  25495. * This function is passed the current mesh.
  25496. * Returns the Mesh.
  25497. */
  25498. Mesh.prototype.registerAfterRender = function (func) {
  25499. this.onAfterRenderObservable.add(func);
  25500. return this;
  25501. };
  25502. /**
  25503. * Disposes a previously registered javascript function called after the rendering.
  25504. * This function is passed the current mesh.
  25505. * Return the Mesh.
  25506. */
  25507. Mesh.prototype.unregisterAfterRender = function (func) {
  25508. this.onAfterRenderObservable.removeCallback(func);
  25509. return this;
  25510. };
  25511. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25512. var scene = this.getScene();
  25513. this._batchCache.mustReturn = false;
  25514. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25515. this._batchCache.visibleInstances[subMeshId] = null;
  25516. if (this._visibleInstances) {
  25517. var currentRenderId = scene.getRenderId();
  25518. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25519. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25520. var selfRenderId = this._renderId;
  25521. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25522. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25523. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25524. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25525. }
  25526. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25527. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25528. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25529. this._batchCache.mustReturn = true;
  25530. return this._batchCache;
  25531. }
  25532. if (currentRenderId !== selfRenderId) {
  25533. this._batchCache.renderSelf[subMeshId] = false;
  25534. }
  25535. }
  25536. this._renderIdForInstances[subMeshId] = currentRenderId;
  25537. }
  25538. return this._batchCache;
  25539. };
  25540. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25541. var visibleInstances = batch.visibleInstances[subMesh._id];
  25542. if (!visibleInstances) {
  25543. return this;
  25544. }
  25545. var matricesCount = visibleInstances.length + 1;
  25546. var bufferSize = matricesCount * 16 * 4;
  25547. var currentInstancesBufferSize = this._instancesBufferSize;
  25548. var instancesBuffer = this._instancesBuffer;
  25549. while (this._instancesBufferSize < bufferSize) {
  25550. this._instancesBufferSize *= 2;
  25551. }
  25552. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25553. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25554. }
  25555. var offset = 0;
  25556. var instancesCount = 0;
  25557. var world = this.getWorldMatrix();
  25558. if (batch.renderSelf[subMesh._id]) {
  25559. world.copyToArray(this._instancesData, offset);
  25560. offset += 16;
  25561. instancesCount++;
  25562. }
  25563. if (visibleInstances) {
  25564. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25565. var instance = visibleInstances[instanceIndex];
  25566. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25567. offset += 16;
  25568. instancesCount++;
  25569. }
  25570. }
  25571. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25572. if (instancesBuffer) {
  25573. instancesBuffer.dispose();
  25574. }
  25575. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25576. this._instancesBuffer = instancesBuffer;
  25577. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25578. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25579. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25580. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25581. }
  25582. else {
  25583. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25584. }
  25585. this._bind(subMesh, effect, fillMode);
  25586. this._draw(subMesh, fillMode, instancesCount);
  25587. engine.unbindInstanceAttributes();
  25588. return this;
  25589. };
  25590. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25591. var scene = this.getScene();
  25592. var engine = scene.getEngine();
  25593. if (hardwareInstancedRendering) {
  25594. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25595. }
  25596. else {
  25597. if (batch.renderSelf[subMesh._id]) {
  25598. // Draw
  25599. if (onBeforeDraw) {
  25600. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25601. }
  25602. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25603. }
  25604. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25605. if (visibleInstancesForSubMesh) {
  25606. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25607. var instance = visibleInstancesForSubMesh[instanceIndex];
  25608. // World
  25609. var world = instance.getWorldMatrix();
  25610. if (onBeforeDraw) {
  25611. onBeforeDraw(true, world, effectiveMaterial);
  25612. }
  25613. // Draw
  25614. this._draw(subMesh, fillMode);
  25615. }
  25616. }
  25617. }
  25618. return this;
  25619. };
  25620. /**
  25621. * Triggers the draw call for the mesh.
  25622. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25623. * Returns the Mesh.
  25624. */
  25625. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25626. this.checkOcclusionQuery();
  25627. if (this._isOccluded) {
  25628. return this;
  25629. }
  25630. var scene = this.getScene();
  25631. // Managing instances
  25632. var batch = this._getInstancesRenderList(subMesh._id);
  25633. if (batch.mustReturn) {
  25634. return this;
  25635. }
  25636. // Checking geometry state
  25637. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25638. return this;
  25639. }
  25640. this.onBeforeRenderObservable.notifyObservers(this);
  25641. var engine = scene.getEngine();
  25642. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25643. // Material
  25644. var material = subMesh.getMaterial();
  25645. if (!material) {
  25646. return this;
  25647. }
  25648. this._effectiveMaterial = material;
  25649. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25650. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25651. return this;
  25652. }
  25653. }
  25654. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25655. return this;
  25656. }
  25657. // Alpha mode
  25658. if (enableAlphaMode) {
  25659. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25660. }
  25661. // Outline - step 1
  25662. var savedDepthWrite = engine.getDepthWrite();
  25663. if (this.renderOutline) {
  25664. engine.setDepthWrite(false);
  25665. scene.getOutlineRenderer().render(subMesh, batch);
  25666. engine.setDepthWrite(savedDepthWrite);
  25667. }
  25668. var effect;
  25669. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25670. effect = subMesh.effect;
  25671. }
  25672. else {
  25673. effect = this._effectiveMaterial.getEffect();
  25674. }
  25675. if (!effect) {
  25676. return this;
  25677. }
  25678. var sideOrientation = this.overrideMaterialSideOrientation;
  25679. if (sideOrientation == null) {
  25680. sideOrientation = this._effectiveMaterial.sideOrientation;
  25681. if (this._getWorldMatrixDeterminant() < 0) {
  25682. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25683. }
  25684. }
  25685. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25686. if (this._effectiveMaterial.forceDepthWrite) {
  25687. engine.setDepthWrite(true);
  25688. }
  25689. // Bind
  25690. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25691. if (!hardwareInstancedRendering) {
  25692. this._bind(subMesh, effect, fillMode);
  25693. }
  25694. var world = this.getWorldMatrix();
  25695. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25696. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25697. }
  25698. else {
  25699. this._effectiveMaterial.bind(world, this);
  25700. }
  25701. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25702. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25703. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25704. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25705. }
  25706. // Draw
  25707. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25708. // Unbind
  25709. this._effectiveMaterial.unbind();
  25710. // Outline - step 2
  25711. if (this.renderOutline && savedDepthWrite) {
  25712. engine.setDepthWrite(true);
  25713. engine.setColorWrite(false);
  25714. scene.getOutlineRenderer().render(subMesh, batch);
  25715. engine.setColorWrite(true);
  25716. }
  25717. // Overlay
  25718. if (this.renderOverlay) {
  25719. var currentMode = engine.getAlphaMode();
  25720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25721. scene.getOutlineRenderer().render(subMesh, batch, true);
  25722. engine.setAlphaMode(currentMode);
  25723. }
  25724. this.onAfterRenderObservable.notifyObservers(this);
  25725. return this;
  25726. };
  25727. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25728. if (isInstance && effectiveMaterial) {
  25729. effectiveMaterial.bindOnlyWorldMatrix(world);
  25730. }
  25731. };
  25732. /**
  25733. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25734. */
  25735. Mesh.prototype.getEmittedParticleSystems = function () {
  25736. var results = new Array();
  25737. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25738. var particleSystem = this.getScene().particleSystems[index];
  25739. if (particleSystem.emitter === this) {
  25740. results.push(particleSystem);
  25741. }
  25742. }
  25743. return results;
  25744. };
  25745. /**
  25746. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25747. */
  25748. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25749. var results = new Array();
  25750. var descendants = this.getDescendants();
  25751. descendants.push(this);
  25752. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25753. var particleSystem = this.getScene().particleSystems[index];
  25754. var emitter = particleSystem.emitter;
  25755. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  25756. results.push(particleSystem);
  25757. }
  25758. }
  25759. return results;
  25760. };
  25761. Mesh.prototype._checkDelayState = function () {
  25762. var scene = this.getScene();
  25763. if (this._geometry) {
  25764. this._geometry.load(scene);
  25765. }
  25766. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25768. this._queueLoad(scene);
  25769. }
  25770. return this;
  25771. };
  25772. Mesh.prototype._queueLoad = function (scene) {
  25773. var _this = this;
  25774. scene._addPendingData(this);
  25775. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25776. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25777. if (data instanceof ArrayBuffer) {
  25778. _this._delayLoadingFunction(data, _this);
  25779. }
  25780. else {
  25781. _this._delayLoadingFunction(JSON.parse(data), _this);
  25782. }
  25783. _this.instances.forEach(function (instance) {
  25784. instance._syncSubMeshes();
  25785. });
  25786. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25787. scene._removePendingData(_this);
  25788. }, function () { }, scene.database, getBinaryData);
  25789. return this;
  25790. };
  25791. /**
  25792. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25793. */
  25794. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25795. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25796. return false;
  25797. }
  25798. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25799. return false;
  25800. }
  25801. this._checkDelayState();
  25802. return true;
  25803. };
  25804. /**
  25805. * Sets the mesh material by the material or multiMaterial `id` property.
  25806. * The material `id` is a string identifying the material or the multiMaterial.
  25807. * This method returns the Mesh.
  25808. */
  25809. Mesh.prototype.setMaterialByID = function (id) {
  25810. var materials = this.getScene().materials;
  25811. var index;
  25812. for (index = materials.length - 1; index > -1; index--) {
  25813. if (materials[index].id === id) {
  25814. this.material = materials[index];
  25815. return this;
  25816. }
  25817. }
  25818. // Multi
  25819. var multiMaterials = this.getScene().multiMaterials;
  25820. for (index = multiMaterials.length - 1; index > -1; index--) {
  25821. if (multiMaterials[index].id === id) {
  25822. this.material = multiMaterials[index];
  25823. return this;
  25824. }
  25825. }
  25826. return this;
  25827. };
  25828. /**
  25829. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25830. */
  25831. Mesh.prototype.getAnimatables = function () {
  25832. var results = new Array();
  25833. if (this.material) {
  25834. results.push(this.material);
  25835. }
  25836. if (this.skeleton) {
  25837. results.push(this.skeleton);
  25838. }
  25839. return results;
  25840. };
  25841. /**
  25842. * Modifies the mesh geometry according to the passed transformation matrix.
  25843. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25844. * The mesh normals are modified accordingly the same transformation.
  25845. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25846. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25847. * Returns the Mesh.
  25848. */
  25849. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25850. // Position
  25851. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25852. return this;
  25853. }
  25854. var submeshes = this.subMeshes.splice(0);
  25855. this._resetPointsArrayCache();
  25856. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25857. var temp = new Array();
  25858. var index;
  25859. for (index = 0; index < data.length; index += 3) {
  25860. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25861. }
  25862. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25863. // Normals
  25864. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25865. return this;
  25866. }
  25867. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25868. temp = [];
  25869. for (index = 0; index < data.length; index += 3) {
  25870. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25871. }
  25872. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25873. // flip faces?
  25874. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25875. this.flipFaces();
  25876. }
  25877. // Restore submeshes
  25878. this.releaseSubMeshes();
  25879. this.subMeshes = submeshes;
  25880. return this;
  25881. };
  25882. /**
  25883. * Modifies the mesh geometry according to its own current World Matrix.
  25884. * The mesh World Matrix is then reset.
  25885. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25886. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  25887. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25888. * Returns the Mesh.
  25889. */
  25890. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25891. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25892. this.scaling.copyFromFloats(1, 1, 1);
  25893. this.position.copyFromFloats(0, 0, 0);
  25894. this.rotation.copyFromFloats(0, 0, 0);
  25895. //only if quaternion is already set
  25896. if (this.rotationQuaternion) {
  25897. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25898. }
  25899. this._worldMatrix = BABYLON.Matrix.Identity();
  25900. return this;
  25901. };
  25902. Object.defineProperty(Mesh.prototype, "_positions", {
  25903. // Cache
  25904. get: function () {
  25905. if (this._geometry) {
  25906. return this._geometry._positions;
  25907. }
  25908. return null;
  25909. },
  25910. enumerable: true,
  25911. configurable: true
  25912. });
  25913. Mesh.prototype._resetPointsArrayCache = function () {
  25914. if (this._geometry) {
  25915. this._geometry._resetPointsArrayCache();
  25916. }
  25917. return this;
  25918. };
  25919. Mesh.prototype._generatePointsArray = function () {
  25920. if (this._geometry) {
  25921. return this._geometry._generatePointsArray();
  25922. }
  25923. return false;
  25924. };
  25925. /**
  25926. * Returns a new Mesh object generated from the current mesh properties.
  25927. * This method must not get confused with createInstance().
  25928. * The parameter `name` is a string, the name given to the new mesh.
  25929. * The optional parameter `newParent` can be any Node object (default `null`).
  25930. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25931. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  25932. */
  25933. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25934. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25935. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25936. };
  25937. /**
  25938. * Disposes the Mesh.
  25939. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25940. * Returns nothing.
  25941. */
  25942. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25943. var _this = this;
  25944. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25945. this.morphTargetManager = null;
  25946. if (this._geometry) {
  25947. this._geometry.releaseForMesh(this, true);
  25948. }
  25949. // Sources
  25950. var meshes = this.getScene().meshes;
  25951. meshes.forEach(function (abstractMesh) {
  25952. var mesh = abstractMesh;
  25953. if (mesh._source && mesh._source === _this) {
  25954. mesh._source = null;
  25955. }
  25956. });
  25957. this._source = null;
  25958. // Instances
  25959. if (this._instancesBuffer) {
  25960. this._instancesBuffer.dispose();
  25961. this._instancesBuffer = null;
  25962. }
  25963. while (this.instances.length) {
  25964. this.instances[0].dispose();
  25965. }
  25966. // Highlight layers.
  25967. var highlightLayers = this.getScene().highlightLayers;
  25968. for (var i = 0; i < highlightLayers.length; i++) {
  25969. var highlightLayer = highlightLayers[i];
  25970. if (highlightLayer) {
  25971. highlightLayer.removeMesh(this);
  25972. highlightLayer.removeExcludedMesh(this);
  25973. }
  25974. }
  25975. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25976. };
  25977. /**
  25978. * Modifies the mesh geometry according to a displacement map.
  25979. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  25980. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25981. * This method returns nothing.
  25982. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25983. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25984. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  25985. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25986. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25987. *
  25988. * Returns the Mesh.
  25989. */
  25990. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25991. var _this = this;
  25992. var scene = this.getScene();
  25993. var onload = function (img) {
  25994. // Getting height map data
  25995. var canvas = document.createElement("canvas");
  25996. var context = canvas.getContext("2d");
  25997. var heightMapWidth = img.width;
  25998. var heightMapHeight = img.height;
  25999. canvas.width = heightMapWidth;
  26000. canvas.height = heightMapHeight;
  26001. context.drawImage(img, 0, 0);
  26002. // Create VertexData from map data
  26003. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26004. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26005. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26006. //execute success callback, if set
  26007. if (onSuccess) {
  26008. onSuccess(_this);
  26009. }
  26010. };
  26011. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26012. return this;
  26013. };
  26014. /**
  26015. * Modifies the mesh geometry according to a displacementMap buffer.
  26016. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  26017. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26018. * This method returns nothing.
  26019. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  26020. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26021. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26022. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26023. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26024. *
  26025. * Returns the Mesh.
  26026. */
  26027. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26028. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26029. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26030. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26031. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26032. return this;
  26033. }
  26034. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26035. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26036. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26037. var position = BABYLON.Vector3.Zero();
  26038. var normal = BABYLON.Vector3.Zero();
  26039. var uv = BABYLON.Vector2.Zero();
  26040. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26041. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26042. for (var index = 0; index < positions.length; index += 3) {
  26043. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26044. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26045. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26046. // Compute height
  26047. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26048. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26049. var pos = (u + v * heightMapWidth) * 4;
  26050. var r = buffer[pos] / 255.0;
  26051. var g = buffer[pos + 1] / 255.0;
  26052. var b = buffer[pos + 2] / 255.0;
  26053. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26054. normal.normalize();
  26055. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26056. position = position.add(normal);
  26057. position.toArray(positions, index);
  26058. }
  26059. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26060. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26061. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26062. return this;
  26063. };
  26064. /**
  26065. * Modify the mesh to get a flat shading rendering.
  26066. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26067. * This method returns the Mesh.
  26068. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26069. */
  26070. Mesh.prototype.convertToFlatShadedMesh = function () {
  26071. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26072. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26073. var kinds = this.getVerticesDataKinds();
  26074. var vbs = {};
  26075. var data = {};
  26076. var newdata = {};
  26077. var updatableNormals = false;
  26078. var kindIndex;
  26079. var kind;
  26080. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26081. kind = kinds[kindIndex];
  26082. var vertexBuffer = this.getVertexBuffer(kind);
  26083. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26084. updatableNormals = vertexBuffer.isUpdatable();
  26085. kinds.splice(kindIndex, 1);
  26086. kindIndex--;
  26087. continue;
  26088. }
  26089. vbs[kind] = vertexBuffer;
  26090. data[kind] = vbs[kind].getData();
  26091. newdata[kind] = [];
  26092. }
  26093. // Save previous submeshes
  26094. var previousSubmeshes = this.subMeshes.slice(0);
  26095. var indices = this.getIndices();
  26096. var totalIndices = this.getTotalIndices();
  26097. // Generating unique vertices per face
  26098. var index;
  26099. for (index = 0; index < totalIndices; index++) {
  26100. var vertexIndex = indices[index];
  26101. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26102. kind = kinds[kindIndex];
  26103. var stride = vbs[kind].getStrideSize();
  26104. for (var offset = 0; offset < stride; offset++) {
  26105. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26106. }
  26107. }
  26108. }
  26109. // Updating faces & normal
  26110. var normals = [];
  26111. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26112. for (index = 0; index < totalIndices; index += 3) {
  26113. indices[index] = index;
  26114. indices[index + 1] = index + 1;
  26115. indices[index + 2] = index + 2;
  26116. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26117. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26118. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26119. var p1p2 = p1.subtract(p2);
  26120. var p3p2 = p3.subtract(p2);
  26121. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26122. // Store same normals for every vertex
  26123. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26124. normals.push(normal.x);
  26125. normals.push(normal.y);
  26126. normals.push(normal.z);
  26127. }
  26128. }
  26129. this.setIndices(indices);
  26130. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26131. // Updating vertex buffers
  26132. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26133. kind = kinds[kindIndex];
  26134. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26135. }
  26136. // Updating submeshes
  26137. this.releaseSubMeshes();
  26138. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26139. var previousOne = previousSubmeshes[submeshIndex];
  26140. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26141. }
  26142. this.synchronizeInstances();
  26143. return this;
  26144. };
  26145. /**
  26146. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26147. * In other words, more vertices, no more indices and a single bigger VBO.
  26148. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26149. * Returns the Mesh.
  26150. */
  26151. Mesh.prototype.convertToUnIndexedMesh = function () {
  26152. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26153. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26154. var kinds = this.getVerticesDataKinds();
  26155. var vbs = {};
  26156. var data = {};
  26157. var newdata = {};
  26158. var kindIndex;
  26159. var kind;
  26160. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26161. kind = kinds[kindIndex];
  26162. var vertexBuffer = this.getVertexBuffer(kind);
  26163. vbs[kind] = vertexBuffer;
  26164. data[kind] = vbs[kind].getData();
  26165. newdata[kind] = [];
  26166. }
  26167. // Save previous submeshes
  26168. var previousSubmeshes = this.subMeshes.slice(0);
  26169. var indices = this.getIndices();
  26170. var totalIndices = this.getTotalIndices();
  26171. // Generating unique vertices per face
  26172. var index;
  26173. for (index = 0; index < totalIndices; index++) {
  26174. var vertexIndex = indices[index];
  26175. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26176. kind = kinds[kindIndex];
  26177. var stride = vbs[kind].getStrideSize();
  26178. for (var offset = 0; offset < stride; offset++) {
  26179. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26180. }
  26181. }
  26182. }
  26183. // Updating indices
  26184. for (index = 0; index < totalIndices; index += 3) {
  26185. indices[index] = index;
  26186. indices[index + 1] = index + 1;
  26187. indices[index + 2] = index + 2;
  26188. }
  26189. this.setIndices(indices);
  26190. // Updating vertex buffers
  26191. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26192. kind = kinds[kindIndex];
  26193. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26194. }
  26195. // Updating submeshes
  26196. this.releaseSubMeshes();
  26197. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26198. var previousOne = previousSubmeshes[submeshIndex];
  26199. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26200. }
  26201. this._unIndexed = true;
  26202. this.synchronizeInstances();
  26203. return this;
  26204. };
  26205. /**
  26206. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26207. * This method returns the Mesh.
  26208. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26209. */
  26210. Mesh.prototype.flipFaces = function (flipNormals) {
  26211. if (flipNormals === void 0) { flipNormals = false; }
  26212. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26213. var i;
  26214. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26215. for (i = 0; i < vertex_data.normals.length; i++) {
  26216. vertex_data.normals[i] *= -1;
  26217. }
  26218. }
  26219. if (vertex_data.indices) {
  26220. var temp;
  26221. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26222. // reassign indices
  26223. temp = vertex_data.indices[i + 1];
  26224. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26225. vertex_data.indices[i + 2] = temp;
  26226. }
  26227. }
  26228. vertex_data.applyToMesh(this);
  26229. return this;
  26230. };
  26231. // Instances
  26232. /**
  26233. * Creates a new InstancedMesh object from the mesh model.
  26234. * An instance shares the same properties and the same material than its model.
  26235. * Only these properties of each instance can then be set individually :
  26236. * - position
  26237. * - rotation
  26238. * - rotationQuaternion
  26239. * - setPivotMatrix
  26240. * - scaling
  26241. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26242. * Warning : this method is not supported for Line mesh and LineSystem
  26243. */
  26244. Mesh.prototype.createInstance = function (name) {
  26245. return new BABYLON.InstancedMesh(name, this);
  26246. };
  26247. /**
  26248. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26249. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26250. * This method returns the Mesh.
  26251. */
  26252. Mesh.prototype.synchronizeInstances = function () {
  26253. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26254. var instance = this.instances[instanceIndex];
  26255. instance._syncSubMeshes();
  26256. }
  26257. return this;
  26258. };
  26259. /**
  26260. * Simplify the mesh according to the given array of settings.
  26261. * Function will return immediately and will simplify async. It returns the Mesh.
  26262. * @param settings a collection of simplification settings.
  26263. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26264. * @param type the type of simplification to run.
  26265. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26266. */
  26267. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26268. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26269. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26270. this.getScene().simplificationQueue.addTask({
  26271. settings: settings,
  26272. parallelProcessing: parallelProcessing,
  26273. mesh: this,
  26274. simplificationType: simplificationType,
  26275. successCallback: successCallback
  26276. });
  26277. return this;
  26278. };
  26279. /**
  26280. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26281. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26282. * This should be used together with the simplification to avoid disappearing triangles.
  26283. * Returns the Mesh.
  26284. * @param successCallback an optional success callback to be called after the optimization finished.
  26285. */
  26286. Mesh.prototype.optimizeIndices = function (successCallback) {
  26287. var _this = this;
  26288. var indices = this.getIndices();
  26289. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26290. if (!positions || !indices) {
  26291. return this;
  26292. }
  26293. var vectorPositions = new Array();
  26294. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26295. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26296. }
  26297. var dupes = new Array();
  26298. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26299. var realPos = vectorPositions.length - 1 - iteration;
  26300. var testedPosition = vectorPositions[realPos];
  26301. for (var j = 0; j < realPos; ++j) {
  26302. var againstPosition = vectorPositions[j];
  26303. if (testedPosition.equals(againstPosition)) {
  26304. dupes[realPos] = j;
  26305. break;
  26306. }
  26307. }
  26308. }, function () {
  26309. for (var i = 0; i < indices.length; ++i) {
  26310. indices[i] = dupes[indices[i]] || indices[i];
  26311. }
  26312. //indices are now reordered
  26313. var originalSubMeshes = _this.subMeshes.slice(0);
  26314. _this.setIndices(indices);
  26315. _this.subMeshes = originalSubMeshes;
  26316. if (successCallback) {
  26317. successCallback(_this);
  26318. }
  26319. });
  26320. return this;
  26321. };
  26322. Mesh.prototype.serialize = function (serializationObject) {
  26323. serializationObject.name = this.name;
  26324. serializationObject.id = this.id;
  26325. serializationObject.type = this.getClassName();
  26326. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26327. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26328. }
  26329. serializationObject.position = this.position.asArray();
  26330. if (this.rotationQuaternion) {
  26331. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26332. }
  26333. else if (this.rotation) {
  26334. serializationObject.rotation = this.rotation.asArray();
  26335. }
  26336. serializationObject.scaling = this.scaling.asArray();
  26337. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26338. serializationObject.isEnabled = this.isEnabled(false);
  26339. serializationObject.isVisible = this.isVisible;
  26340. serializationObject.infiniteDistance = this.infiniteDistance;
  26341. serializationObject.pickable = this.isPickable;
  26342. serializationObject.receiveShadows = this.receiveShadows;
  26343. serializationObject.billboardMode = this.billboardMode;
  26344. serializationObject.visibility = this.visibility;
  26345. serializationObject.checkCollisions = this.checkCollisions;
  26346. serializationObject.isBlocker = this.isBlocker;
  26347. // Parent
  26348. if (this.parent) {
  26349. serializationObject.parentId = this.parent.id;
  26350. }
  26351. // Geometry
  26352. serializationObject.isUnIndexed = this.isUnIndexed;
  26353. var geometry = this._geometry;
  26354. if (geometry) {
  26355. var geometryId = geometry.id;
  26356. serializationObject.geometryId = geometryId;
  26357. // SubMeshes
  26358. serializationObject.subMeshes = [];
  26359. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26360. var subMesh = this.subMeshes[subIndex];
  26361. serializationObject.subMeshes.push({
  26362. materialIndex: subMesh.materialIndex,
  26363. verticesStart: subMesh.verticesStart,
  26364. verticesCount: subMesh.verticesCount,
  26365. indexStart: subMesh.indexStart,
  26366. indexCount: subMesh.indexCount
  26367. });
  26368. }
  26369. }
  26370. // Material
  26371. if (this.material) {
  26372. serializationObject.materialId = this.material.id;
  26373. }
  26374. else {
  26375. this.material = null;
  26376. }
  26377. // Morph targets
  26378. if (this.morphTargetManager) {
  26379. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26380. }
  26381. // Skeleton
  26382. if (this.skeleton) {
  26383. serializationObject.skeletonId = this.skeleton.id;
  26384. }
  26385. // Physics
  26386. //TODO implement correct serialization for physics impostors.
  26387. var impostor = this.getPhysicsImpostor();
  26388. if (impostor) {
  26389. serializationObject.physicsMass = impostor.getParam("mass");
  26390. serializationObject.physicsFriction = impostor.getParam("friction");
  26391. serializationObject.physicsRestitution = impostor.getParam("mass");
  26392. serializationObject.physicsImpostor = impostor.type;
  26393. }
  26394. // Metadata
  26395. if (this.metadata) {
  26396. serializationObject.metadata = this.metadata;
  26397. }
  26398. // Instances
  26399. serializationObject.instances = [];
  26400. for (var index = 0; index < this.instances.length; index++) {
  26401. var instance = this.instances[index];
  26402. var serializationInstance = {
  26403. name: instance.name,
  26404. id: instance.id,
  26405. position: instance.position.asArray(),
  26406. scaling: instance.scaling.asArray()
  26407. };
  26408. if (instance.rotationQuaternion) {
  26409. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26410. }
  26411. else if (instance.rotation) {
  26412. serializationInstance.rotation = instance.rotation.asArray();
  26413. }
  26414. serializationObject.instances.push(serializationInstance);
  26415. // Animations
  26416. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26417. serializationInstance.ranges = instance.serializeAnimationRanges();
  26418. }
  26419. //
  26420. // Animations
  26421. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26422. serializationObject.ranges = this.serializeAnimationRanges();
  26423. // Layer mask
  26424. serializationObject.layerMask = this.layerMask;
  26425. // Alpha
  26426. serializationObject.alphaIndex = this.alphaIndex;
  26427. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26428. // Overlay
  26429. serializationObject.overlayAlpha = this.overlayAlpha;
  26430. serializationObject.overlayColor = this.overlayColor.asArray();
  26431. serializationObject.renderOverlay = this.renderOverlay;
  26432. // Fog
  26433. serializationObject.applyFog = this.applyFog;
  26434. // Action Manager
  26435. if (this.actionManager) {
  26436. serializationObject.actions = this.actionManager.serialize(this.name);
  26437. }
  26438. };
  26439. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26440. if (!this.geometry) {
  26441. return;
  26442. }
  26443. this._markSubMeshesAsAttributesDirty();
  26444. var morphTargetManager = this._morphTargetManager;
  26445. if (morphTargetManager && morphTargetManager.vertexCount) {
  26446. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26447. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26448. this.morphTargetManager = null;
  26449. return;
  26450. }
  26451. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26452. var morphTarget = morphTargetManager.getActiveTarget(index);
  26453. var positions = morphTarget.getPositions();
  26454. if (!positions) {
  26455. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26456. return;
  26457. }
  26458. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26459. var normals = morphTarget.getNormals();
  26460. if (normals) {
  26461. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26462. }
  26463. var tangents = morphTarget.getTangents();
  26464. if (tangents) {
  26465. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26466. }
  26467. }
  26468. }
  26469. else {
  26470. var index = 0;
  26471. // Positions
  26472. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26473. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26474. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26475. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26476. }
  26477. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26478. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26479. }
  26480. index++;
  26481. }
  26482. }
  26483. };
  26484. // Statics
  26485. /**
  26486. * Returns a new Mesh object parsed from the source provided.
  26487. * The parameter `parsedMesh` is the source.
  26488. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26489. */
  26490. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26491. var mesh;
  26492. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26493. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26494. }
  26495. else {
  26496. mesh = new Mesh(parsedMesh.name, scene);
  26497. }
  26498. mesh.id = parsedMesh.id;
  26499. if (BABYLON.Tags) {
  26500. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26501. }
  26502. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26503. if (parsedMesh.metadata !== undefined) {
  26504. mesh.metadata = parsedMesh.metadata;
  26505. }
  26506. if (parsedMesh.rotationQuaternion) {
  26507. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26508. }
  26509. else if (parsedMesh.rotation) {
  26510. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26511. }
  26512. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26513. if (parsedMesh.localMatrix) {
  26514. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26515. }
  26516. else if (parsedMesh.pivotMatrix) {
  26517. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26518. }
  26519. mesh.setEnabled(parsedMesh.isEnabled);
  26520. mesh.isVisible = parsedMesh.isVisible;
  26521. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26522. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26523. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26524. if (parsedMesh.applyFog !== undefined) {
  26525. mesh.applyFog = parsedMesh.applyFog;
  26526. }
  26527. if (parsedMesh.pickable !== undefined) {
  26528. mesh.isPickable = parsedMesh.pickable;
  26529. }
  26530. if (parsedMesh.alphaIndex !== undefined) {
  26531. mesh.alphaIndex = parsedMesh.alphaIndex;
  26532. }
  26533. mesh.receiveShadows = parsedMesh.receiveShadows;
  26534. mesh.billboardMode = parsedMesh.billboardMode;
  26535. if (parsedMesh.visibility !== undefined) {
  26536. mesh.visibility = parsedMesh.visibility;
  26537. }
  26538. mesh.checkCollisions = parsedMesh.checkCollisions;
  26539. if (parsedMesh.isBlocker !== undefined) {
  26540. mesh.isBlocker = parsedMesh.isBlocker;
  26541. }
  26542. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26543. // freezeWorldMatrix
  26544. if (parsedMesh.freezeWorldMatrix) {
  26545. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26546. }
  26547. // Parent
  26548. if (parsedMesh.parentId) {
  26549. mesh._waitingParentId = parsedMesh.parentId;
  26550. }
  26551. // Actions
  26552. if (parsedMesh.actions !== undefined) {
  26553. mesh._waitingActions = parsedMesh.actions;
  26554. }
  26555. // Overlay
  26556. if (parsedMesh.overlayAlpha !== undefined) {
  26557. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26558. }
  26559. if (parsedMesh.overlayColor !== undefined) {
  26560. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26561. }
  26562. if (parsedMesh.renderOverlay !== undefined) {
  26563. mesh.renderOverlay = parsedMesh.renderOverlay;
  26564. }
  26565. // Geometry
  26566. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26567. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26568. if (parsedMesh.delayLoadingFile) {
  26569. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26570. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26571. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26572. if (parsedMesh._binaryInfo) {
  26573. mesh._binaryInfo = parsedMesh._binaryInfo;
  26574. }
  26575. mesh._delayInfo = [];
  26576. if (parsedMesh.hasUVs) {
  26577. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26578. }
  26579. if (parsedMesh.hasUVs2) {
  26580. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26581. }
  26582. if (parsedMesh.hasUVs3) {
  26583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26584. }
  26585. if (parsedMesh.hasUVs4) {
  26586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26587. }
  26588. if (parsedMesh.hasUVs5) {
  26589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26590. }
  26591. if (parsedMesh.hasUVs6) {
  26592. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26593. }
  26594. if (parsedMesh.hasColors) {
  26595. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26596. }
  26597. if (parsedMesh.hasMatricesIndices) {
  26598. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26599. }
  26600. if (parsedMesh.hasMatricesWeights) {
  26601. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26602. }
  26603. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26604. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26605. mesh._checkDelayState();
  26606. }
  26607. }
  26608. else {
  26609. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26610. }
  26611. // Material
  26612. if (parsedMesh.materialId) {
  26613. mesh.setMaterialByID(parsedMesh.materialId);
  26614. }
  26615. else {
  26616. mesh.material = null;
  26617. }
  26618. // Morph targets
  26619. if (parsedMesh.morphTargetManagerId > -1) {
  26620. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26621. }
  26622. // Skeleton
  26623. if (parsedMesh.skeletonId > -1) {
  26624. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26625. if (parsedMesh.numBoneInfluencers) {
  26626. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26627. }
  26628. }
  26629. // Animations
  26630. if (parsedMesh.animations) {
  26631. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26632. var parsedAnimation = parsedMesh.animations[animationIndex];
  26633. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26634. }
  26635. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26636. }
  26637. if (parsedMesh.autoAnimate) {
  26638. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26639. }
  26640. // Layer Mask
  26641. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26642. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26643. }
  26644. else {
  26645. mesh.layerMask = 0x0FFFFFFF;
  26646. }
  26647. // Physics
  26648. if (parsedMesh.physicsImpostor) {
  26649. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26650. mass: parsedMesh.physicsMass,
  26651. friction: parsedMesh.physicsFriction,
  26652. restitution: parsedMesh.physicsRestitution
  26653. }, scene);
  26654. }
  26655. // Instances
  26656. if (parsedMesh.instances) {
  26657. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26658. var parsedInstance = parsedMesh.instances[index];
  26659. var instance = mesh.createInstance(parsedInstance.name);
  26660. if (parsedInstance.id) {
  26661. instance.id = parsedInstance.id;
  26662. }
  26663. if (BABYLON.Tags) {
  26664. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26665. }
  26666. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26667. if (parsedInstance.parentId) {
  26668. instance._waitingParentId = parsedInstance.parentId;
  26669. }
  26670. if (parsedInstance.rotationQuaternion) {
  26671. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26672. }
  26673. else if (parsedInstance.rotation) {
  26674. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26675. }
  26676. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26677. instance.checkCollisions = mesh.checkCollisions;
  26678. if (parsedMesh.animations) {
  26679. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26680. parsedAnimation = parsedMesh.animations[animationIndex];
  26681. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26682. }
  26683. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26684. }
  26685. }
  26686. }
  26687. return mesh;
  26688. };
  26689. /**
  26690. * Creates a ribbon mesh.
  26691. * Please consider using the same method from the MeshBuilder class instead.
  26692. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26693. *
  26694. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26695. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26696. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26697. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26698. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  26699. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  26700. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  26701. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26702. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26704. */
  26705. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26706. if (closeArray === void 0) { closeArray = false; }
  26707. if (updatable === void 0) { updatable = false; }
  26708. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26709. pathArray: pathArray,
  26710. closeArray: closeArray,
  26711. closePath: closePath,
  26712. offset: offset,
  26713. updatable: updatable,
  26714. sideOrientation: sideOrientation,
  26715. instance: instance
  26716. }, scene);
  26717. };
  26718. /**
  26719. * Creates a plane polygonal mesh. By default, this is a disc.
  26720. * Please consider using the same method from the MeshBuilder class instead.
  26721. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26722. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  26723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26726. */
  26727. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26728. if (scene === void 0) { scene = null; }
  26729. var options = {
  26730. radius: radius,
  26731. tessellation: tessellation,
  26732. sideOrientation: sideOrientation,
  26733. updatable: updatable
  26734. };
  26735. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26736. };
  26737. /**
  26738. * Creates a box mesh.
  26739. * Please consider using the same method from the MeshBuilder class instead.
  26740. * The parameter `size` sets the size (float) of each box side (default 1).
  26741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26744. */
  26745. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26746. if (scene === void 0) { scene = null; }
  26747. var options = {
  26748. size: size,
  26749. sideOrientation: sideOrientation,
  26750. updatable: updatable
  26751. };
  26752. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26753. };
  26754. /**
  26755. * Creates a sphere mesh.
  26756. * Please consider using the same method from the MeshBuilder class instead.
  26757. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26758. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26760. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26762. */
  26763. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26764. var options = {
  26765. segments: segments,
  26766. diameterX: diameter,
  26767. diameterY: diameter,
  26768. diameterZ: diameter,
  26769. sideOrientation: sideOrientation,
  26770. updatable: updatable
  26771. };
  26772. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26773. };
  26774. /**
  26775. * Creates a cylinder or a cone mesh.
  26776. * Please consider using the same method from the MeshBuilder class instead.
  26777. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26778. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26779. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  26780. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26781. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26785. */
  26786. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26787. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26788. if (scene !== undefined) {
  26789. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26790. updatable = scene;
  26791. }
  26792. scene = subdivisions;
  26793. subdivisions = 1;
  26794. }
  26795. var options = {
  26796. height: height,
  26797. diameterTop: diameterTop,
  26798. diameterBottom: diameterBottom,
  26799. tessellation: tessellation,
  26800. subdivisions: subdivisions,
  26801. sideOrientation: sideOrientation,
  26802. updatable: updatable
  26803. };
  26804. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26805. };
  26806. // Torus (Code from SharpDX.org)
  26807. /**
  26808. * Creates a torus mesh.
  26809. * Please consider using the same method from the MeshBuilder class instead.
  26810. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26811. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26812. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26813. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26814. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26816. */
  26817. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26818. var options = {
  26819. diameter: diameter,
  26820. thickness: thickness,
  26821. tessellation: tessellation,
  26822. sideOrientation: sideOrientation,
  26823. updatable: updatable
  26824. };
  26825. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26826. };
  26827. /**
  26828. * Creates a torus knot mesh.
  26829. * Please consider using the same method from the MeshBuilder class instead.
  26830. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26831. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26832. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26833. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26837. */
  26838. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26839. var options = {
  26840. radius: radius,
  26841. tube: tube,
  26842. radialSegments: radialSegments,
  26843. tubularSegments: tubularSegments,
  26844. p: p,
  26845. q: q,
  26846. sideOrientation: sideOrientation,
  26847. updatable: updatable
  26848. };
  26849. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26850. };
  26851. /**
  26852. * Creates a line mesh.
  26853. * Please consider using the same method from the MeshBuilder class instead.
  26854. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  26855. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26856. * The parameter `points` is an array successive Vector3.
  26857. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  26858. * When updating an instance, remember that only point positions can change, not the number of points.
  26859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26860. */
  26861. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26862. if (scene === void 0) { scene = null; }
  26863. if (updatable === void 0) { updatable = false; }
  26864. if (instance === void 0) { instance = null; }
  26865. var options = {
  26866. points: points,
  26867. updatable: updatable,
  26868. instance: instance
  26869. };
  26870. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26871. };
  26872. /**
  26873. * Creates a dashed line mesh.
  26874. * Please consider using the same method from the MeshBuilder class instead.
  26875. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  26876. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26877. * The parameter `points` is an array successive Vector3.
  26878. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26879. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26880. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26881. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  26882. * When updating an instance, remember that only point positions can change, not the number of points.
  26883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26884. */
  26885. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26886. if (scene === void 0) { scene = null; }
  26887. var options = {
  26888. points: points,
  26889. dashSize: dashSize,
  26890. gapSize: gapSize,
  26891. dashNb: dashNb,
  26892. updatable: updatable,
  26893. instance: instance
  26894. };
  26895. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26896. };
  26897. /**
  26898. * Creates a polygon mesh.
  26899. * Please consider using the same method from the MeshBuilder class instead.
  26900. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26901. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  26902. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26903. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26904. * Remember you can only change the shape positions, not their number when updating a polygon.
  26905. */
  26906. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26907. var options = {
  26908. shape: shape,
  26909. holes: holes,
  26910. updatable: updatable,
  26911. sideOrientation: sideOrientation
  26912. };
  26913. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26914. };
  26915. /**
  26916. * Creates an extruded polygon mesh, with depth in the Y direction.
  26917. * Please consider using the same method from the MeshBuilder class instead.
  26918. */
  26919. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26920. var options = {
  26921. shape: shape,
  26922. holes: holes,
  26923. depth: depth,
  26924. updatable: updatable,
  26925. sideOrientation: sideOrientation
  26926. };
  26927. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26928. };
  26929. /**
  26930. * Creates an extruded shape mesh.
  26931. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26932. * Please consider using the same method from the MeshBuilder class instead.
  26933. *
  26934. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26935. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  26936. * extruded along the Z axis.
  26937. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26938. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  26939. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26940. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  26941. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  26942. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26943. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26944. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26945. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26946. */
  26947. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26948. if (scene === void 0) { scene = null; }
  26949. var options = {
  26950. shape: shape,
  26951. path: path,
  26952. scale: scale,
  26953. rotation: rotation,
  26954. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26955. sideOrientation: sideOrientation,
  26956. instance: instance,
  26957. updatable: updatable
  26958. };
  26959. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26960. };
  26961. /**
  26962. * Creates an custom extruded shape mesh.
  26963. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26964. * Please consider using the same method from the MeshBuilder class instead.
  26965. *
  26966. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26967. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  26968. * extruded along the Z axis.
  26969. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26970. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  26971. * and the distance of this point from the begining of the path :
  26972. * ```javascript
  26973. * var rotationFunction = function(i, distance) {
  26974. * // do things
  26975. * return rotationValue; }
  26976. * ```
  26977. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26978. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  26979. * and the distance of this point from the begining of the path :
  26980. * ```javascript
  26981. * var scaleFunction = function(i, distance) {
  26982. * // do things
  26983. * return scaleValue;}
  26984. * ```
  26985. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26986. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26987. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26988. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  26989. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  26990. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26992. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26994. */
  26995. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26996. var options = {
  26997. shape: shape,
  26998. path: path,
  26999. scaleFunction: scaleFunction,
  27000. rotationFunction: rotationFunction,
  27001. ribbonCloseArray: ribbonCloseArray,
  27002. ribbonClosePath: ribbonClosePath,
  27003. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27004. sideOrientation: sideOrientation,
  27005. instance: instance,
  27006. updatable: updatable
  27007. };
  27008. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27009. };
  27010. /**
  27011. * Creates lathe mesh.
  27012. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27013. * Please consider using the same method from the MeshBuilder class instead.
  27014. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  27015. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27016. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27017. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27021. */
  27022. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27023. var options = {
  27024. shape: shape,
  27025. radius: radius,
  27026. tessellation: tessellation,
  27027. sideOrientation: sideOrientation,
  27028. updatable: updatable
  27029. };
  27030. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27031. };
  27032. /**
  27033. * Creates a plane mesh.
  27034. * Please consider using the same method from the MeshBuilder class instead.
  27035. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27036. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27039. */
  27040. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27041. var options = {
  27042. size: size,
  27043. width: size,
  27044. height: size,
  27045. sideOrientation: sideOrientation,
  27046. updatable: updatable
  27047. };
  27048. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27049. };
  27050. /**
  27051. * Creates a ground mesh.
  27052. * Please consider using the same method from the MeshBuilder class instead.
  27053. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27054. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27056. */
  27057. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27058. var options = {
  27059. width: width,
  27060. height: height,
  27061. subdivisions: subdivisions,
  27062. updatable: updatable
  27063. };
  27064. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27065. };
  27066. /**
  27067. * Creates a tiled ground mesh.
  27068. * Please consider using the same method from the MeshBuilder class instead.
  27069. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27070. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27071. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27072. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27073. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27074. * numbers of subdivisions on the ground width and height of each tile.
  27075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27076. */
  27077. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27078. var options = {
  27079. xmin: xmin,
  27080. zmin: zmin,
  27081. xmax: xmax,
  27082. zmax: zmax,
  27083. subdivisions: subdivisions,
  27084. precision: precision,
  27085. updatable: updatable
  27086. };
  27087. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27088. };
  27089. /**
  27090. * Creates a ground mesh from a height map.
  27091. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27092. * Please consider using the same method from the MeshBuilder class instead.
  27093. * The parameter `url` sets the URL of the height map image resource.
  27094. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27095. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27096. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27097. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27098. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  27099. * This function is passed the newly built mesh :
  27100. * ```javascript
  27101. * function(mesh) { // do things
  27102. * return; }
  27103. * ```
  27104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27105. */
  27106. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27107. var options = {
  27108. width: width,
  27109. height: height,
  27110. subdivisions: subdivisions,
  27111. minHeight: minHeight,
  27112. maxHeight: maxHeight,
  27113. updatable: updatable,
  27114. onReady: onReady
  27115. };
  27116. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27117. };
  27118. /**
  27119. * Creates a tube mesh.
  27120. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27121. * Please consider using the same method from the MeshBuilder class instead.
  27122. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27123. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27124. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27125. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27126. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  27127. * It must return a radius value (positive float) :
  27128. * ```javascript
  27129. * var radiusFunction = function(i, distance) {
  27130. * // do things
  27131. * return radius; }
  27132. * ```
  27133. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  27134. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  27135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27138. */
  27139. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27140. var options = {
  27141. path: path,
  27142. radius: radius,
  27143. tessellation: tessellation,
  27144. radiusFunction: radiusFunction,
  27145. arc: 1,
  27146. cap: cap,
  27147. updatable: updatable,
  27148. sideOrientation: sideOrientation,
  27149. instance: instance
  27150. };
  27151. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27152. };
  27153. /**
  27154. * Creates a polyhedron mesh.
  27155. * Please consider using the same method from the MeshBuilder class instead.
  27156. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  27157. * to choose the wanted type.
  27158. * The parameter `size` (positive float, default 1) sets the polygon size.
  27159. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27160. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  27161. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  27162. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  27163. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  27164. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  27165. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27166. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27168. */
  27169. Mesh.CreatePolyhedron = function (name, options, scene) {
  27170. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27171. };
  27172. /**
  27173. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27174. * Please consider using the same method from the MeshBuilder class instead.
  27175. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27176. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  27177. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27178. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  27179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27182. */
  27183. Mesh.CreateIcoSphere = function (name, options, scene) {
  27184. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27185. };
  27186. /**
  27187. * Creates a decal mesh.
  27188. * Please consider using the same method from the MeshBuilder class instead.
  27189. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  27190. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27191. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27192. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27193. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27194. */
  27195. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27196. var options = {
  27197. position: position,
  27198. normal: normal,
  27199. size: size,
  27200. angle: angle
  27201. };
  27202. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27203. };
  27204. // Skeletons
  27205. /**
  27206. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27207. */
  27208. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27209. if (!this._sourcePositions) {
  27210. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27211. if (!source) {
  27212. return this._sourcePositions;
  27213. }
  27214. this._sourcePositions = new Float32Array(source);
  27215. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27216. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27217. }
  27218. }
  27219. return this._sourcePositions;
  27220. };
  27221. /**
  27222. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27223. */
  27224. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27225. if (!this._sourceNormals) {
  27226. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27227. if (!source) {
  27228. return this._sourceNormals;
  27229. }
  27230. this._sourceNormals = new Float32Array(source);
  27231. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27232. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27233. }
  27234. }
  27235. return this._sourceNormals;
  27236. };
  27237. /**
  27238. * Updates the vertex buffer by applying transformation from the bones.
  27239. * Returns the Mesh.
  27240. *
  27241. * @param {skeleton} skeleton to apply
  27242. */
  27243. Mesh.prototype.applySkeleton = function (skeleton) {
  27244. if (!this.geometry) {
  27245. return this;
  27246. }
  27247. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27248. return this;
  27249. }
  27250. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27252. return this;
  27253. }
  27254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27255. return this;
  27256. }
  27257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27258. return this;
  27259. }
  27260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27261. return this;
  27262. }
  27263. if (!this._sourcePositions) {
  27264. var submeshes = this.subMeshes.slice();
  27265. this.setPositionsForCPUSkinning();
  27266. this.subMeshes = submeshes;
  27267. }
  27268. if (!this._sourceNormals) {
  27269. this.setNormalsForCPUSkinning();
  27270. }
  27271. // positionsData checks for not being Float32Array will only pass at most once
  27272. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27273. if (!positionsData) {
  27274. return this;
  27275. }
  27276. if (!(positionsData instanceof Float32Array)) {
  27277. positionsData = new Float32Array(positionsData);
  27278. }
  27279. // normalsData checks for not being Float32Array will only pass at most once
  27280. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27281. if (!normalsData) {
  27282. return this;
  27283. }
  27284. if (!(normalsData instanceof Float32Array)) {
  27285. normalsData = new Float32Array(normalsData);
  27286. }
  27287. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27288. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27289. if (!matricesWeightsData || !matricesIndicesData) {
  27290. return this;
  27291. }
  27292. var needExtras = this.numBoneInfluencers > 4;
  27293. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27294. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27295. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27296. var tempVector3 = BABYLON.Vector3.Zero();
  27297. var finalMatrix = new BABYLON.Matrix();
  27298. var tempMatrix = new BABYLON.Matrix();
  27299. var matWeightIdx = 0;
  27300. var inf;
  27301. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27302. var weight;
  27303. for (inf = 0; inf < 4; inf++) {
  27304. weight = matricesWeightsData[matWeightIdx + inf];
  27305. if (weight > 0) {
  27306. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27307. finalMatrix.addToSelf(tempMatrix);
  27308. }
  27309. else
  27310. break;
  27311. }
  27312. if (needExtras) {
  27313. for (inf = 0; inf < 4; inf++) {
  27314. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27315. if (weight > 0) {
  27316. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27317. finalMatrix.addToSelf(tempMatrix);
  27318. }
  27319. else
  27320. break;
  27321. }
  27322. }
  27323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27324. tempVector3.toArray(positionsData, index);
  27325. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27326. tempVector3.toArray(normalsData, index);
  27327. finalMatrix.reset();
  27328. }
  27329. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27330. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27331. return this;
  27332. };
  27333. // Tools
  27334. /**
  27335. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27336. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27337. */
  27338. Mesh.MinMax = function (meshes) {
  27339. var minVector = null;
  27340. var maxVector = null;
  27341. meshes.forEach(function (mesh, index, array) {
  27342. var boundingInfo = mesh.getBoundingInfo();
  27343. var boundingBox = boundingInfo.boundingBox;
  27344. if (!minVector || !maxVector) {
  27345. minVector = boundingBox.minimumWorld;
  27346. maxVector = boundingBox.maximumWorld;
  27347. }
  27348. else {
  27349. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27350. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27351. }
  27352. });
  27353. if (!minVector || !maxVector) {
  27354. return {
  27355. min: BABYLON.Vector3.Zero(),
  27356. max: BABYLON.Vector3.Zero()
  27357. };
  27358. }
  27359. return {
  27360. min: minVector,
  27361. max: maxVector
  27362. };
  27363. };
  27364. /**
  27365. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27366. */
  27367. Mesh.Center = function (meshesOrMinMaxVector) {
  27368. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27369. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27370. };
  27371. /**
  27372. * Merge the array of meshes into a single mesh for performance reasons.
  27373. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27374. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27375. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27376. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27377. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27378. */
  27379. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27380. if (disposeSource === void 0) { disposeSource = true; }
  27381. var index;
  27382. if (!allow32BitsIndices) {
  27383. var totalVertices = 0;
  27384. // Counting vertices
  27385. for (index = 0; index < meshes.length; index++) {
  27386. if (meshes[index]) {
  27387. totalVertices += meshes[index].getTotalVertices();
  27388. if (totalVertices > 65536) {
  27389. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27390. return null;
  27391. }
  27392. }
  27393. }
  27394. }
  27395. // Merge
  27396. var vertexData = null;
  27397. var otherVertexData;
  27398. var indiceArray = new Array();
  27399. var source = null;
  27400. for (index = 0; index < meshes.length; index++) {
  27401. if (meshes[index]) {
  27402. meshes[index].computeWorldMatrix(true);
  27403. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27404. otherVertexData.transform(meshes[index].getWorldMatrix());
  27405. if (vertexData) {
  27406. vertexData.merge(otherVertexData);
  27407. }
  27408. else {
  27409. vertexData = otherVertexData;
  27410. source = meshes[index];
  27411. }
  27412. if (subdivideWithSubMeshes) {
  27413. indiceArray.push(meshes[index].getTotalIndices());
  27414. }
  27415. }
  27416. }
  27417. source = source;
  27418. if (!meshSubclass) {
  27419. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27420. }
  27421. vertexData.applyToMesh(meshSubclass);
  27422. // Setting properties
  27423. meshSubclass.material = source.material;
  27424. meshSubclass.checkCollisions = source.checkCollisions;
  27425. // Cleaning
  27426. if (disposeSource) {
  27427. for (index = 0; index < meshes.length; index++) {
  27428. if (meshes[index]) {
  27429. meshes[index].dispose();
  27430. }
  27431. }
  27432. }
  27433. // Subdivide
  27434. if (subdivideWithSubMeshes) {
  27435. //-- Suppresions du submesh global
  27436. meshSubclass.releaseSubMeshes();
  27437. index = 0;
  27438. var offset = 0;
  27439. //-- aplique la subdivision en fonction du tableau d'indices
  27440. while (index < indiceArray.length) {
  27441. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27442. offset += indiceArray[index];
  27443. index++;
  27444. }
  27445. }
  27446. return meshSubclass;
  27447. };
  27448. // Consts
  27449. Mesh._FRONTSIDE = 0;
  27450. Mesh._BACKSIDE = 1;
  27451. Mesh._DOUBLESIDE = 2;
  27452. Mesh._DEFAULTSIDE = 0;
  27453. Mesh._NO_CAP = 0;
  27454. Mesh._CAP_START = 1;
  27455. Mesh._CAP_END = 2;
  27456. Mesh._CAP_ALL = 3;
  27457. return Mesh;
  27458. }(BABYLON.AbstractMesh));
  27459. BABYLON.Mesh = Mesh;
  27460. })(BABYLON || (BABYLON = {}));
  27461. //# sourceMappingURL=babylon.mesh.js.map
  27462. var BABYLON;
  27463. (function (BABYLON) {
  27464. var BaseSubMesh = /** @class */ (function () {
  27465. function BaseSubMesh() {
  27466. }
  27467. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27468. get: function () {
  27469. return this._materialEffect;
  27470. },
  27471. enumerable: true,
  27472. configurable: true
  27473. });
  27474. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27475. if (defines === void 0) { defines = null; }
  27476. if (this._materialEffect === effect) {
  27477. if (!effect) {
  27478. this._materialDefines = null;
  27479. }
  27480. return;
  27481. }
  27482. this._materialDefines = defines;
  27483. this._materialEffect = effect;
  27484. };
  27485. return BaseSubMesh;
  27486. }());
  27487. BABYLON.BaseSubMesh = BaseSubMesh;
  27488. var SubMesh = /** @class */ (function (_super) {
  27489. __extends(SubMesh, _super);
  27490. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27491. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27492. var _this = _super.call(this) || this;
  27493. _this.materialIndex = materialIndex;
  27494. _this.verticesStart = verticesStart;
  27495. _this.verticesCount = verticesCount;
  27496. _this.indexStart = indexStart;
  27497. _this.indexCount = indexCount;
  27498. _this._renderId = 0;
  27499. _this._mesh = mesh;
  27500. _this._renderingMesh = renderingMesh || mesh;
  27501. mesh.subMeshes.push(_this);
  27502. _this._trianglePlanes = [];
  27503. _this._id = mesh.subMeshes.length - 1;
  27504. if (createBoundingBox) {
  27505. _this.refreshBoundingInfo();
  27506. mesh.computeWorldMatrix(true);
  27507. }
  27508. return _this;
  27509. }
  27510. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27511. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27512. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27513. };
  27514. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27515. get: function () {
  27516. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. /**
  27522. * Returns the submesh BoudingInfo object.
  27523. */
  27524. SubMesh.prototype.getBoundingInfo = function () {
  27525. if (this.IsGlobal) {
  27526. return this._mesh.getBoundingInfo();
  27527. }
  27528. return this._boundingInfo;
  27529. };
  27530. /**
  27531. * Sets the submesh BoundingInfo.
  27532. * Return the SubMesh.
  27533. */
  27534. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27535. this._boundingInfo = boundingInfo;
  27536. return this;
  27537. };
  27538. /**
  27539. * Returns the mesh of the current submesh.
  27540. */
  27541. SubMesh.prototype.getMesh = function () {
  27542. return this._mesh;
  27543. };
  27544. /**
  27545. * Returns the rendering mesh of the submesh.
  27546. */
  27547. SubMesh.prototype.getRenderingMesh = function () {
  27548. return this._renderingMesh;
  27549. };
  27550. /**
  27551. * Returns the submesh material.
  27552. */
  27553. SubMesh.prototype.getMaterial = function () {
  27554. var rootMaterial = this._renderingMesh.material;
  27555. if (rootMaterial === null || rootMaterial === undefined) {
  27556. return this._mesh.getScene().defaultMaterial;
  27557. }
  27558. else if (rootMaterial.getSubMaterial) {
  27559. var multiMaterial = rootMaterial;
  27560. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27561. if (this._currentMaterial !== effectiveMaterial) {
  27562. this._currentMaterial = effectiveMaterial;
  27563. this._materialDefines = null;
  27564. }
  27565. return effectiveMaterial;
  27566. }
  27567. return rootMaterial;
  27568. };
  27569. // Methods
  27570. /**
  27571. * Sets a new updated BoundingInfo object to the submesh.
  27572. * Returns the SubMesh.
  27573. */
  27574. SubMesh.prototype.refreshBoundingInfo = function () {
  27575. this._lastColliderWorldVertices = null;
  27576. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27577. return this;
  27578. }
  27579. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27580. if (!data) {
  27581. this._boundingInfo = this._mesh.getBoundingInfo();
  27582. return this;
  27583. }
  27584. var indices = this._renderingMesh.getIndices();
  27585. var extend;
  27586. //is this the only submesh?
  27587. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27588. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27589. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27590. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27591. }
  27592. else {
  27593. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27594. }
  27595. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27596. return this;
  27597. };
  27598. SubMesh.prototype._checkCollision = function (collider) {
  27599. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27600. return boundingInfo._checkCollision(collider);
  27601. };
  27602. /**
  27603. * Updates the submesh BoundingInfo.
  27604. * Returns the Submesh.
  27605. */
  27606. SubMesh.prototype.updateBoundingInfo = function (world) {
  27607. var boundingInfo = this.getBoundingInfo();
  27608. if (!boundingInfo) {
  27609. this.refreshBoundingInfo();
  27610. boundingInfo = this.getBoundingInfo();
  27611. }
  27612. boundingInfo.update(world);
  27613. return this;
  27614. };
  27615. /**
  27616. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27617. * Boolean returned.
  27618. */
  27619. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27620. var boundingInfo = this.getBoundingInfo();
  27621. if (!boundingInfo) {
  27622. return false;
  27623. }
  27624. return boundingInfo.isInFrustum(frustumPlanes);
  27625. };
  27626. /**
  27627. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27628. * Boolean returned.
  27629. */
  27630. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27631. var boundingInfo = this.getBoundingInfo();
  27632. if (!boundingInfo) {
  27633. return false;
  27634. }
  27635. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27636. };
  27637. /**
  27638. * Renders the submesh.
  27639. * Returns it.
  27640. */
  27641. SubMesh.prototype.render = function (enableAlphaMode) {
  27642. this._renderingMesh.render(this, enableAlphaMode);
  27643. return this;
  27644. };
  27645. /**
  27646. * Returns a new Index Buffer.
  27647. * Type returned : WebGLBuffer.
  27648. */
  27649. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27650. if (!this._linesIndexBuffer) {
  27651. var linesIndices = [];
  27652. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27653. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27654. }
  27655. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27656. this.linesIndexCount = linesIndices.length;
  27657. }
  27658. return this._linesIndexBuffer;
  27659. };
  27660. /**
  27661. * True is the passed Ray intersects the submesh bounding box.
  27662. * Boolean returned.
  27663. */
  27664. SubMesh.prototype.canIntersects = function (ray) {
  27665. var boundingInfo = this.getBoundingInfo();
  27666. if (!boundingInfo) {
  27667. return false;
  27668. }
  27669. return ray.intersectsBox(boundingInfo.boundingBox);
  27670. };
  27671. /**
  27672. * Returns an object IntersectionInfo.
  27673. */
  27674. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27675. var intersectInfo = null;
  27676. // LineMesh first as it's also a Mesh...
  27677. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27678. var lineMesh = this._mesh;
  27679. // Line test
  27680. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27681. var p0 = positions[indices[index]];
  27682. var p1 = positions[indices[index + 1]];
  27683. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27684. if (length < 0) {
  27685. continue;
  27686. }
  27687. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27688. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27689. if (fastCheck) {
  27690. break;
  27691. }
  27692. }
  27693. }
  27694. }
  27695. else {
  27696. // Triangles test
  27697. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27698. var p0 = positions[indices[index]];
  27699. var p1 = positions[indices[index + 1]];
  27700. var p2 = positions[indices[index + 2]];
  27701. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27702. if (currentIntersectInfo) {
  27703. if (currentIntersectInfo.distance < 0) {
  27704. continue;
  27705. }
  27706. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27707. intersectInfo = currentIntersectInfo;
  27708. intersectInfo.faceId = index / 3;
  27709. if (fastCheck) {
  27710. break;
  27711. }
  27712. }
  27713. }
  27714. }
  27715. }
  27716. return intersectInfo;
  27717. };
  27718. SubMesh.prototype._rebuild = function () {
  27719. if (this._linesIndexBuffer) {
  27720. this._linesIndexBuffer = null;
  27721. }
  27722. };
  27723. // Clone
  27724. /**
  27725. * Creates a new Submesh from the passed Mesh.
  27726. */
  27727. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27728. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27729. if (!this.IsGlobal) {
  27730. var boundingInfo = this.getBoundingInfo();
  27731. if (!boundingInfo) {
  27732. return result;
  27733. }
  27734. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27735. }
  27736. return result;
  27737. };
  27738. // Dispose
  27739. /**
  27740. * Disposes the Submesh.
  27741. * Returns nothing.
  27742. */
  27743. SubMesh.prototype.dispose = function () {
  27744. if (this._linesIndexBuffer) {
  27745. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  27746. this._linesIndexBuffer = null;
  27747. }
  27748. // Remove from mesh
  27749. var index = this._mesh.subMeshes.indexOf(this);
  27750. this._mesh.subMeshes.splice(index, 1);
  27751. };
  27752. // Statics
  27753. /**
  27754. * Creates a new Submesh from the passed parameters :
  27755. * - materialIndex (integer) : the index of the main mesh material.
  27756. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  27757. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  27758. * - mesh (Mesh) : the main mesh to create the submesh from.
  27759. * - renderingMesh (optional Mesh) : rendering mesh.
  27760. */
  27761. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  27762. var minVertexIndex = Number.MAX_VALUE;
  27763. var maxVertexIndex = -Number.MAX_VALUE;
  27764. renderingMesh = (renderingMesh || mesh);
  27765. var indices = renderingMesh.getIndices();
  27766. for (var index = startIndex; index < startIndex + indexCount; index++) {
  27767. var vertexIndex = indices[index];
  27768. if (vertexIndex < minVertexIndex)
  27769. minVertexIndex = vertexIndex;
  27770. if (vertexIndex > maxVertexIndex)
  27771. maxVertexIndex = vertexIndex;
  27772. }
  27773. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  27774. };
  27775. return SubMesh;
  27776. }(BaseSubMesh));
  27777. BABYLON.SubMesh = SubMesh;
  27778. })(BABYLON || (BABYLON = {}));
  27779. //# sourceMappingURL=babylon.subMesh.js.map
  27780. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27781. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27782. s = arguments[i];
  27783. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27784. t[p] = s[p];
  27785. }
  27786. return t;
  27787. };
  27788. var BABYLON;
  27789. (function (BABYLON) {
  27790. var MaterialDefines = /** @class */ (function () {
  27791. function MaterialDefines() {
  27792. this._isDirty = true;
  27793. this._areLightsDirty = true;
  27794. this._areAttributesDirty = true;
  27795. this._areTexturesDirty = true;
  27796. this._areFresnelDirty = true;
  27797. this._areMiscDirty = true;
  27798. this._areImageProcessingDirty = true;
  27799. this._normals = false;
  27800. this._uvs = false;
  27801. this._needNormals = false;
  27802. this._needUVs = false;
  27803. }
  27804. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27805. get: function () {
  27806. return this._isDirty;
  27807. },
  27808. enumerable: true,
  27809. configurable: true
  27810. });
  27811. MaterialDefines.prototype.markAsProcessed = function () {
  27812. this._isDirty = false;
  27813. this._areAttributesDirty = false;
  27814. this._areTexturesDirty = false;
  27815. this._areFresnelDirty = false;
  27816. this._areLightsDirty = false;
  27817. this._areMiscDirty = false;
  27818. this._areImageProcessingDirty = false;
  27819. };
  27820. MaterialDefines.prototype.markAsUnprocessed = function () {
  27821. this._isDirty = true;
  27822. };
  27823. MaterialDefines.prototype.markAllAsDirty = function () {
  27824. this._areTexturesDirty = true;
  27825. this._areAttributesDirty = true;
  27826. this._areLightsDirty = true;
  27827. this._areFresnelDirty = true;
  27828. this._areMiscDirty = true;
  27829. this._areImageProcessingDirty = true;
  27830. this._isDirty = true;
  27831. };
  27832. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27833. this._areImageProcessingDirty = true;
  27834. this._isDirty = true;
  27835. };
  27836. MaterialDefines.prototype.markAsLightDirty = function () {
  27837. this._areLightsDirty = true;
  27838. this._isDirty = true;
  27839. };
  27840. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27841. this._areAttributesDirty = true;
  27842. this._isDirty = true;
  27843. };
  27844. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27845. this._areTexturesDirty = true;
  27846. this._isDirty = true;
  27847. };
  27848. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27849. this._areFresnelDirty = true;
  27850. this._isDirty = true;
  27851. };
  27852. MaterialDefines.prototype.markAsMiscDirty = function () {
  27853. this._areMiscDirty = true;
  27854. this._isDirty = true;
  27855. };
  27856. MaterialDefines.prototype.rebuild = function () {
  27857. if (this._keys) {
  27858. delete this._keys;
  27859. }
  27860. this._keys = [];
  27861. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27862. var key = _a[_i];
  27863. if (key[0] === "_") {
  27864. continue;
  27865. }
  27866. this._keys.push(key);
  27867. }
  27868. };
  27869. MaterialDefines.prototype.isEqual = function (other) {
  27870. if (this._keys.length !== other._keys.length) {
  27871. return false;
  27872. }
  27873. for (var index = 0; index < this._keys.length; index++) {
  27874. var prop = this._keys[index];
  27875. if (this[prop] !== other[prop]) {
  27876. return false;
  27877. }
  27878. }
  27879. return true;
  27880. };
  27881. MaterialDefines.prototype.cloneTo = function (other) {
  27882. if (this._keys.length !== other._keys.length) {
  27883. other._keys = this._keys.slice(0);
  27884. }
  27885. for (var index = 0; index < this._keys.length; index++) {
  27886. var prop = this._keys[index];
  27887. other[prop] = this[prop];
  27888. }
  27889. };
  27890. MaterialDefines.prototype.reset = function () {
  27891. for (var index = 0; index < this._keys.length; index++) {
  27892. var prop = this._keys[index];
  27893. if (typeof (this[prop]) === "number") {
  27894. this[prop] = 0;
  27895. }
  27896. else {
  27897. this[prop] = false;
  27898. }
  27899. }
  27900. };
  27901. MaterialDefines.prototype.toString = function () {
  27902. var result = "";
  27903. for (var index = 0; index < this._keys.length; index++) {
  27904. var prop = this._keys[index];
  27905. var value = this[prop];
  27906. if (typeof (value) === "number") {
  27907. result += "#define " + prop + " " + this[prop] + "\n";
  27908. }
  27909. else if (value) {
  27910. result += "#define " + prop + "\n";
  27911. }
  27912. }
  27913. return result;
  27914. };
  27915. return MaterialDefines;
  27916. }());
  27917. BABYLON.MaterialDefines = MaterialDefines;
  27918. var Material = /** @class */ (function () {
  27919. function Material(name, scene, doNotAdd) {
  27920. this.checkReadyOnEveryCall = false;
  27921. this.checkReadyOnlyOnce = false;
  27922. this.state = "";
  27923. this.alpha = 1.0;
  27924. this._backFaceCulling = true;
  27925. this.doNotSerialize = false;
  27926. this.storeEffectOnSubMeshes = false;
  27927. /**
  27928. * An event triggered when the material is disposed.
  27929. * @type {BABYLON.Observable}
  27930. */
  27931. this.onDisposeObservable = new BABYLON.Observable();
  27932. /**
  27933. * An event triggered when the material is bound.
  27934. * @type {BABYLON.Observable}
  27935. */
  27936. this.onBindObservable = new BABYLON.Observable();
  27937. /**
  27938. * An event triggered when the material is unbound.
  27939. * @type {BABYLON.Observable}
  27940. */
  27941. this.onUnBindObservable = new BABYLON.Observable();
  27942. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27943. this._needDepthPrePass = false;
  27944. this.disableDepthWrite = false;
  27945. this.forceDepthWrite = false;
  27946. this.separateCullingPass = false;
  27947. this._fogEnabled = true;
  27948. this.pointSize = 1.0;
  27949. this.zOffset = 0;
  27950. this._wasPreviouslyReady = false;
  27951. this._fillMode = Material.TriangleFillMode;
  27952. this.name = name;
  27953. this.id = name || BABYLON.Tools.RandomId();
  27954. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27955. if (this._scene.useRightHandedSystem) {
  27956. this.sideOrientation = Material.ClockWiseSideOrientation;
  27957. }
  27958. else {
  27959. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27960. }
  27961. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27962. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27963. if (!doNotAdd) {
  27964. this._scene.materials.push(this);
  27965. }
  27966. }
  27967. Object.defineProperty(Material, "TriangleFillMode", {
  27968. get: function () {
  27969. return Material._TriangleFillMode;
  27970. },
  27971. enumerable: true,
  27972. configurable: true
  27973. });
  27974. Object.defineProperty(Material, "WireFrameFillMode", {
  27975. get: function () {
  27976. return Material._WireFrameFillMode;
  27977. },
  27978. enumerable: true,
  27979. configurable: true
  27980. });
  27981. Object.defineProperty(Material, "PointFillMode", {
  27982. get: function () {
  27983. return Material._PointFillMode;
  27984. },
  27985. enumerable: true,
  27986. configurable: true
  27987. });
  27988. Object.defineProperty(Material, "PointListDrawMode", {
  27989. get: function () {
  27990. return Material._PointListDrawMode;
  27991. },
  27992. enumerable: true,
  27993. configurable: true
  27994. });
  27995. Object.defineProperty(Material, "LineListDrawMode", {
  27996. get: function () {
  27997. return Material._LineListDrawMode;
  27998. },
  27999. enumerable: true,
  28000. configurable: true
  28001. });
  28002. Object.defineProperty(Material, "LineLoopDrawMode", {
  28003. get: function () {
  28004. return Material._LineLoopDrawMode;
  28005. },
  28006. enumerable: true,
  28007. configurable: true
  28008. });
  28009. Object.defineProperty(Material, "LineStripDrawMode", {
  28010. get: function () {
  28011. return Material._LineStripDrawMode;
  28012. },
  28013. enumerable: true,
  28014. configurable: true
  28015. });
  28016. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28017. get: function () {
  28018. return Material._TriangleStripDrawMode;
  28019. },
  28020. enumerable: true,
  28021. configurable: true
  28022. });
  28023. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28024. get: function () {
  28025. return Material._TriangleFanDrawMode;
  28026. },
  28027. enumerable: true,
  28028. configurable: true
  28029. });
  28030. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28031. get: function () {
  28032. return Material._ClockWiseSideOrientation;
  28033. },
  28034. enumerable: true,
  28035. configurable: true
  28036. });
  28037. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28038. get: function () {
  28039. return Material._CounterClockWiseSideOrientation;
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. Object.defineProperty(Material, "TextureDirtyFlag", {
  28045. get: function () {
  28046. return Material._TextureDirtyFlag;
  28047. },
  28048. enumerable: true,
  28049. configurable: true
  28050. });
  28051. Object.defineProperty(Material, "LightDirtyFlag", {
  28052. get: function () {
  28053. return Material._LightDirtyFlag;
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28059. get: function () {
  28060. return Material._FresnelDirtyFlag;
  28061. },
  28062. enumerable: true,
  28063. configurable: true
  28064. });
  28065. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28066. get: function () {
  28067. return Material._AttributesDirtyFlag;
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. Object.defineProperty(Material, "MiscDirtyFlag", {
  28073. get: function () {
  28074. return Material._MiscDirtyFlag;
  28075. },
  28076. enumerable: true,
  28077. configurable: true
  28078. });
  28079. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28080. get: function () {
  28081. return this._backFaceCulling;
  28082. },
  28083. set: function (value) {
  28084. if (this._backFaceCulling === value) {
  28085. return;
  28086. }
  28087. this._backFaceCulling = value;
  28088. this.markAsDirty(Material.TextureDirtyFlag);
  28089. },
  28090. enumerable: true,
  28091. configurable: true
  28092. });
  28093. Object.defineProperty(Material.prototype, "onDispose", {
  28094. set: function (callback) {
  28095. if (this._onDisposeObserver) {
  28096. this.onDisposeObservable.remove(this._onDisposeObserver);
  28097. }
  28098. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. Object.defineProperty(Material.prototype, "onBind", {
  28104. set: function (callback) {
  28105. if (this._onBindObserver) {
  28106. this.onBindObservable.remove(this._onBindObserver);
  28107. }
  28108. this._onBindObserver = this.onBindObservable.add(callback);
  28109. },
  28110. enumerable: true,
  28111. configurable: true
  28112. });
  28113. Object.defineProperty(Material.prototype, "alphaMode", {
  28114. get: function () {
  28115. return this._alphaMode;
  28116. },
  28117. set: function (value) {
  28118. if (this._alphaMode === value) {
  28119. return;
  28120. }
  28121. this._alphaMode = value;
  28122. this.markAsDirty(Material.TextureDirtyFlag);
  28123. },
  28124. enumerable: true,
  28125. configurable: true
  28126. });
  28127. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28128. get: function () {
  28129. return this._needDepthPrePass;
  28130. },
  28131. set: function (value) {
  28132. if (this._needDepthPrePass === value) {
  28133. return;
  28134. }
  28135. this._needDepthPrePass = value;
  28136. if (this._needDepthPrePass) {
  28137. this.checkReadyOnEveryCall = true;
  28138. }
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Object.defineProperty(Material.prototype, "fogEnabled", {
  28144. get: function () {
  28145. return this._fogEnabled;
  28146. },
  28147. set: function (value) {
  28148. if (this._fogEnabled === value) {
  28149. return;
  28150. }
  28151. this._fogEnabled = value;
  28152. this.markAsDirty(Material.MiscDirtyFlag);
  28153. },
  28154. enumerable: true,
  28155. configurable: true
  28156. });
  28157. Object.defineProperty(Material.prototype, "wireframe", {
  28158. get: function () {
  28159. return this._fillMode === Material.WireFrameFillMode;
  28160. },
  28161. set: function (value) {
  28162. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28163. },
  28164. enumerable: true,
  28165. configurable: true
  28166. });
  28167. Object.defineProperty(Material.prototype, "pointsCloud", {
  28168. get: function () {
  28169. return this._fillMode === Material.PointFillMode;
  28170. },
  28171. set: function (value) {
  28172. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28173. },
  28174. enumerable: true,
  28175. configurable: true
  28176. });
  28177. Object.defineProperty(Material.prototype, "fillMode", {
  28178. get: function () {
  28179. return this._fillMode;
  28180. },
  28181. set: function (value) {
  28182. if (this._fillMode === value) {
  28183. return;
  28184. }
  28185. this._fillMode = value;
  28186. this.markAsDirty(Material.MiscDirtyFlag);
  28187. },
  28188. enumerable: true,
  28189. configurable: true
  28190. });
  28191. /**
  28192. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28193. * subclasses should override adding information pertainent to themselves
  28194. */
  28195. Material.prototype.toString = function (fullDetails) {
  28196. var ret = "Name: " + this.name;
  28197. if (fullDetails) {
  28198. }
  28199. return ret;
  28200. };
  28201. /**
  28202. * Child classes can use it to update shaders
  28203. */
  28204. Material.prototype.getClassName = function () {
  28205. return "Material";
  28206. };
  28207. Object.defineProperty(Material.prototype, "isFrozen", {
  28208. get: function () {
  28209. return this.checkReadyOnlyOnce;
  28210. },
  28211. enumerable: true,
  28212. configurable: true
  28213. });
  28214. Material.prototype.freeze = function () {
  28215. this.checkReadyOnlyOnce = true;
  28216. };
  28217. Material.prototype.unfreeze = function () {
  28218. this.checkReadyOnlyOnce = false;
  28219. };
  28220. Material.prototype.isReady = function (mesh, useInstances) {
  28221. return true;
  28222. };
  28223. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28224. return false;
  28225. };
  28226. Material.prototype.getEffect = function () {
  28227. return this._effect;
  28228. };
  28229. Material.prototype.getScene = function () {
  28230. return this._scene;
  28231. };
  28232. Material.prototype.needAlphaBlending = function () {
  28233. return (this.alpha < 1.0);
  28234. };
  28235. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28236. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28237. };
  28238. Material.prototype.needAlphaTesting = function () {
  28239. return false;
  28240. };
  28241. Material.prototype.getAlphaTestTexture = function () {
  28242. return null;
  28243. };
  28244. Material.prototype.markDirty = function () {
  28245. this._wasPreviouslyReady = false;
  28246. };
  28247. Material.prototype._preBind = function (effect, overrideOrientation) {
  28248. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28249. var engine = this._scene.getEngine();
  28250. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28251. var reverse = orientation === Material.ClockWiseSideOrientation;
  28252. engine.enableEffect(effect ? effect : this._effect);
  28253. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28254. return reverse;
  28255. };
  28256. Material.prototype.bind = function (world, mesh) {
  28257. };
  28258. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28259. };
  28260. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28261. };
  28262. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28263. sceneUbo.bindToEffect(effect, "Scene");
  28264. };
  28265. Material.prototype.bindView = function (effect) {
  28266. if (!this._useUBO) {
  28267. effect.setMatrix("view", this.getScene().getViewMatrix());
  28268. }
  28269. else {
  28270. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28271. }
  28272. };
  28273. Material.prototype.bindViewProjection = function (effect) {
  28274. if (!this._useUBO) {
  28275. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28276. }
  28277. else {
  28278. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28279. }
  28280. };
  28281. Material.prototype._afterBind = function (mesh) {
  28282. this._scene._cachedMaterial = this;
  28283. if (mesh) {
  28284. this._scene._cachedVisibility = mesh.visibility;
  28285. }
  28286. else {
  28287. this._scene._cachedVisibility = 1;
  28288. }
  28289. if (mesh) {
  28290. this.onBindObservable.notifyObservers(mesh);
  28291. }
  28292. if (this.disableDepthWrite) {
  28293. var engine = this._scene.getEngine();
  28294. this._cachedDepthWriteState = engine.getDepthWrite();
  28295. engine.setDepthWrite(false);
  28296. }
  28297. };
  28298. Material.prototype.unbind = function () {
  28299. this.onUnBindObservable.notifyObservers(this);
  28300. if (this.disableDepthWrite) {
  28301. var engine = this._scene.getEngine();
  28302. engine.setDepthWrite(this._cachedDepthWriteState);
  28303. }
  28304. };
  28305. Material.prototype.getActiveTextures = function () {
  28306. return [];
  28307. };
  28308. Material.prototype.hasTexture = function (texture) {
  28309. return false;
  28310. };
  28311. Material.prototype.clone = function (name) {
  28312. return null;
  28313. };
  28314. Material.prototype.getBindedMeshes = function () {
  28315. var result = new Array();
  28316. for (var index = 0; index < this._scene.meshes.length; index++) {
  28317. var mesh = this._scene.meshes[index];
  28318. if (mesh.material === this) {
  28319. result.push(mesh);
  28320. }
  28321. }
  28322. return result;
  28323. };
  28324. /**
  28325. * Force shader compilation including textures ready check
  28326. */
  28327. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28328. var _this = this;
  28329. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28330. var subMesh = new BABYLON.BaseSubMesh();
  28331. var scene = this.getScene();
  28332. var engine = scene.getEngine();
  28333. var checkReady = function () {
  28334. if (!_this._scene || !_this._scene.getEngine()) {
  28335. return;
  28336. }
  28337. if (subMesh._materialDefines) {
  28338. subMesh._materialDefines._renderId = -1;
  28339. }
  28340. var alphaTestState = engine.getAlphaTesting();
  28341. var clipPlaneState = scene.clipPlane;
  28342. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28343. if (localOptions.clipPlane) {
  28344. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28345. }
  28346. if (_this.storeEffectOnSubMeshes) {
  28347. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28348. if (onCompiled) {
  28349. onCompiled(_this);
  28350. }
  28351. }
  28352. else {
  28353. setTimeout(checkReady, 16);
  28354. }
  28355. }
  28356. else {
  28357. if (_this.isReady(mesh)) {
  28358. if (onCompiled) {
  28359. onCompiled(_this);
  28360. }
  28361. }
  28362. else {
  28363. setTimeout(checkReady, 16);
  28364. }
  28365. }
  28366. engine.setAlphaTesting(alphaTestState);
  28367. if (options && options.clipPlane) {
  28368. scene.clipPlane = clipPlaneState;
  28369. }
  28370. };
  28371. checkReady();
  28372. };
  28373. Material.prototype.markAsDirty = function (flag) {
  28374. if (flag & Material.TextureDirtyFlag) {
  28375. this._markAllSubMeshesAsTexturesDirty();
  28376. }
  28377. if (flag & Material.LightDirtyFlag) {
  28378. this._markAllSubMeshesAsLightsDirty();
  28379. }
  28380. if (flag & Material.FresnelDirtyFlag) {
  28381. this._markAllSubMeshesAsFresnelDirty();
  28382. }
  28383. if (flag & Material.AttributesDirtyFlag) {
  28384. this._markAllSubMeshesAsAttributesDirty();
  28385. }
  28386. if (flag & Material.MiscDirtyFlag) {
  28387. this._markAllSubMeshesAsMiscDirty();
  28388. }
  28389. this.getScene().resetCachedMaterial();
  28390. };
  28391. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28392. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28393. var mesh = _a[_i];
  28394. if (!mesh.subMeshes) {
  28395. continue;
  28396. }
  28397. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28398. var subMesh = _c[_b];
  28399. if (subMesh.getMaterial() !== this) {
  28400. continue;
  28401. }
  28402. if (!subMesh._materialDefines) {
  28403. continue;
  28404. }
  28405. func(subMesh._materialDefines);
  28406. }
  28407. }
  28408. };
  28409. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28410. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28411. };
  28412. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28413. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28414. };
  28415. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28416. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28417. };
  28418. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28420. };
  28421. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28422. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28423. };
  28424. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28426. };
  28427. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28428. // Animations
  28429. this.getScene().stopAnimation(this);
  28430. // Remove from scene
  28431. var index = this._scene.materials.indexOf(this);
  28432. if (index >= 0) {
  28433. this._scene.materials.splice(index, 1);
  28434. }
  28435. // Remove from meshes
  28436. for (index = 0; index < this._scene.meshes.length; index++) {
  28437. var mesh = this._scene.meshes[index];
  28438. if (mesh.material === this) {
  28439. mesh.material = null;
  28440. if (mesh.geometry) {
  28441. var geometry = (mesh.geometry);
  28442. if (this.storeEffectOnSubMeshes) {
  28443. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28444. var subMesh = _a[_i];
  28445. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28446. if (forceDisposeEffect && subMesh._materialEffect) {
  28447. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28448. }
  28449. }
  28450. }
  28451. else {
  28452. geometry._releaseVertexArrayObject(this._effect);
  28453. }
  28454. }
  28455. }
  28456. }
  28457. this._uniformBuffer.dispose();
  28458. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28459. if (forceDisposeEffect && this._effect) {
  28460. if (!this.storeEffectOnSubMeshes) {
  28461. this._scene.getEngine()._releaseEffect(this._effect);
  28462. }
  28463. this._effect = null;
  28464. }
  28465. // Callback
  28466. this.onDisposeObservable.notifyObservers(this);
  28467. this.onDisposeObservable.clear();
  28468. this.onBindObservable.clear();
  28469. this.onUnBindObservable.clear();
  28470. };
  28471. Material.prototype.serialize = function () {
  28472. return BABYLON.SerializationHelper.Serialize(this);
  28473. };
  28474. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28475. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28476. multiMaterial.id = parsedMultiMaterial.id;
  28477. if (BABYLON.Tags) {
  28478. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28479. }
  28480. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28481. var subMatId = parsedMultiMaterial.materials[matIndex];
  28482. if (subMatId) {
  28483. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28484. }
  28485. else {
  28486. multiMaterial.subMaterials.push(null);
  28487. }
  28488. }
  28489. return multiMaterial;
  28490. };
  28491. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28492. if (!parsedMaterial.customType) {
  28493. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28494. }
  28495. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28496. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28497. if (!BABYLON.LegacyPBRMaterial) {
  28498. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28499. return;
  28500. }
  28501. }
  28502. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28503. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28504. ;
  28505. };
  28506. // Triangle views
  28507. Material._TriangleFillMode = 0;
  28508. Material._WireFrameFillMode = 1;
  28509. Material._PointFillMode = 2;
  28510. // Draw modes
  28511. Material._PointListDrawMode = 3;
  28512. Material._LineListDrawMode = 4;
  28513. Material._LineLoopDrawMode = 5;
  28514. Material._LineStripDrawMode = 6;
  28515. Material._TriangleStripDrawMode = 7;
  28516. Material._TriangleFanDrawMode = 8;
  28517. Material._ClockWiseSideOrientation = 0;
  28518. Material._CounterClockWiseSideOrientation = 1;
  28519. Material._TextureDirtyFlag = 1;
  28520. Material._LightDirtyFlag = 2;
  28521. Material._FresnelDirtyFlag = 4;
  28522. Material._AttributesDirtyFlag = 8;
  28523. Material._MiscDirtyFlag = 16;
  28524. __decorate([
  28525. BABYLON.serialize()
  28526. ], Material.prototype, "id", void 0);
  28527. __decorate([
  28528. BABYLON.serialize()
  28529. ], Material.prototype, "name", void 0);
  28530. __decorate([
  28531. BABYLON.serialize()
  28532. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28533. __decorate([
  28534. BABYLON.serialize()
  28535. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28536. __decorate([
  28537. BABYLON.serialize()
  28538. ], Material.prototype, "state", void 0);
  28539. __decorate([
  28540. BABYLON.serialize()
  28541. ], Material.prototype, "alpha", void 0);
  28542. __decorate([
  28543. BABYLON.serialize("backFaceCulling")
  28544. ], Material.prototype, "_backFaceCulling", void 0);
  28545. __decorate([
  28546. BABYLON.serialize()
  28547. ], Material.prototype, "sideOrientation", void 0);
  28548. __decorate([
  28549. BABYLON.serialize("alphaMode")
  28550. ], Material.prototype, "_alphaMode", void 0);
  28551. __decorate([
  28552. BABYLON.serialize()
  28553. ], Material.prototype, "_needDepthPrePass", void 0);
  28554. __decorate([
  28555. BABYLON.serialize()
  28556. ], Material.prototype, "disableDepthWrite", void 0);
  28557. __decorate([
  28558. BABYLON.serialize()
  28559. ], Material.prototype, "forceDepthWrite", void 0);
  28560. __decorate([
  28561. BABYLON.serialize()
  28562. ], Material.prototype, "separateCullingPass", void 0);
  28563. __decorate([
  28564. BABYLON.serialize("fogEnabled")
  28565. ], Material.prototype, "_fogEnabled", void 0);
  28566. __decorate([
  28567. BABYLON.serialize()
  28568. ], Material.prototype, "pointSize", void 0);
  28569. __decorate([
  28570. BABYLON.serialize()
  28571. ], Material.prototype, "zOffset", void 0);
  28572. __decorate([
  28573. BABYLON.serialize()
  28574. ], Material.prototype, "wireframe", null);
  28575. __decorate([
  28576. BABYLON.serialize()
  28577. ], Material.prototype, "pointsCloud", null);
  28578. __decorate([
  28579. BABYLON.serialize()
  28580. ], Material.prototype, "fillMode", null);
  28581. return Material;
  28582. }());
  28583. BABYLON.Material = Material;
  28584. })(BABYLON || (BABYLON = {}));
  28585. //# sourceMappingURL=babylon.material.js.map
  28586. var BABYLON;
  28587. (function (BABYLON) {
  28588. var UniformBuffer = /** @class */ (function () {
  28589. /**
  28590. * Uniform buffer objects.
  28591. *
  28592. * Handles blocks of uniform on the GPU.
  28593. *
  28594. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28595. *
  28596. * For more information, please refer to :
  28597. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28598. */
  28599. function UniformBuffer(engine, data, dynamic) {
  28600. this._engine = engine;
  28601. this._noUBO = !engine.supportsUniformBuffers;
  28602. this._dynamic = dynamic;
  28603. this._data = data || [];
  28604. this._uniformLocations = {};
  28605. this._uniformSizes = {};
  28606. this._uniformLocationPointer = 0;
  28607. this._needSync = false;
  28608. if (this._noUBO) {
  28609. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28610. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28611. this.updateFloat = this._updateFloatForEffect;
  28612. this.updateFloat2 = this._updateFloat2ForEffect;
  28613. this.updateFloat3 = this._updateFloat3ForEffect;
  28614. this.updateFloat4 = this._updateFloat4ForEffect;
  28615. this.updateMatrix = this._updateMatrixForEffect;
  28616. this.updateVector3 = this._updateVector3ForEffect;
  28617. this.updateVector4 = this._updateVector4ForEffect;
  28618. this.updateColor3 = this._updateColor3ForEffect;
  28619. this.updateColor4 = this._updateColor4ForEffect;
  28620. }
  28621. else {
  28622. this._engine._uniformBuffers.push(this);
  28623. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28624. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28625. this.updateFloat = this._updateFloatForUniform;
  28626. this.updateFloat2 = this._updateFloat2ForUniform;
  28627. this.updateFloat3 = this._updateFloat3ForUniform;
  28628. this.updateFloat4 = this._updateFloat4ForUniform;
  28629. this.updateMatrix = this._updateMatrixForUniform;
  28630. this.updateVector3 = this._updateVector3ForUniform;
  28631. this.updateVector4 = this._updateVector4ForUniform;
  28632. this.updateColor3 = this._updateColor3ForUniform;
  28633. this.updateColor4 = this._updateColor4ForUniform;
  28634. }
  28635. }
  28636. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28637. // Properties
  28638. /**
  28639. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28640. * or just falling back on setUniformXXX calls.
  28641. */
  28642. get: function () {
  28643. return !this._noUBO;
  28644. },
  28645. enumerable: true,
  28646. configurable: true
  28647. });
  28648. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28649. /**
  28650. * Indicates if the WebGL underlying uniform buffer is in sync
  28651. * with the javascript cache data.
  28652. */
  28653. get: function () {
  28654. return !this._needSync;
  28655. },
  28656. enumerable: true,
  28657. configurable: true
  28658. });
  28659. /**
  28660. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28661. * Also, a dynamic UniformBuffer will disable cache verification and always
  28662. * update the underlying WebGL uniform buffer to the GPU.
  28663. */
  28664. UniformBuffer.prototype.isDynamic = function () {
  28665. return this._dynamic !== undefined;
  28666. };
  28667. /**
  28668. * The data cache on JS side.
  28669. */
  28670. UniformBuffer.prototype.getData = function () {
  28671. return this._bufferData;
  28672. };
  28673. /**
  28674. * The underlying WebGL Uniform buffer.
  28675. */
  28676. UniformBuffer.prototype.getBuffer = function () {
  28677. return this._buffer;
  28678. };
  28679. /**
  28680. * std140 layout specifies how to align data within an UBO structure.
  28681. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28682. * for specs.
  28683. */
  28684. UniformBuffer.prototype._fillAlignment = function (size) {
  28685. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28686. // and 4x4 matrices
  28687. // TODO : change if other types are used
  28688. var alignment;
  28689. if (size <= 2) {
  28690. alignment = size;
  28691. }
  28692. else {
  28693. alignment = 4;
  28694. }
  28695. if ((this._uniformLocationPointer % alignment) !== 0) {
  28696. var oldPointer = this._uniformLocationPointer;
  28697. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28698. var diff = this._uniformLocationPointer - oldPointer;
  28699. for (var i = 0; i < diff; i++) {
  28700. this._data.push(0);
  28701. }
  28702. }
  28703. };
  28704. /**
  28705. * Adds an uniform in the buffer.
  28706. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28707. * for the layout to be correct !
  28708. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28709. * @param {number|number[]} size Data size, or data directly.
  28710. */
  28711. UniformBuffer.prototype.addUniform = function (name, size) {
  28712. if (this._noUBO) {
  28713. return;
  28714. }
  28715. if (this._uniformLocations[name] !== undefined) {
  28716. // Already existing uniform
  28717. return;
  28718. }
  28719. // This function must be called in the order of the shader layout !
  28720. // size can be the size of the uniform, or data directly
  28721. var data;
  28722. if (size instanceof Array) {
  28723. data = size;
  28724. size = data.length;
  28725. }
  28726. else {
  28727. size = size;
  28728. data = [];
  28729. // Fill with zeros
  28730. for (var i = 0; i < size; i++) {
  28731. data.push(0);
  28732. }
  28733. }
  28734. this._fillAlignment(size);
  28735. this._uniformSizes[name] = size;
  28736. this._uniformLocations[name] = this._uniformLocationPointer;
  28737. this._uniformLocationPointer += size;
  28738. for (var i = 0; i < size; i++) {
  28739. this._data.push(data[i]);
  28740. }
  28741. this._needSync = true;
  28742. };
  28743. /**
  28744. * Wrapper for addUniform.
  28745. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28746. * @param {Matrix} mat A 4x4 matrix.
  28747. */
  28748. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28749. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28750. };
  28751. /**
  28752. * Wrapper for addUniform.
  28753. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28754. * @param {number} x
  28755. * @param {number} y
  28756. */
  28757. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28758. var temp = [x, y];
  28759. this.addUniform(name, temp);
  28760. };
  28761. /**
  28762. * Wrapper for addUniform.
  28763. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28764. * @param {number} x
  28765. * @param {number} y
  28766. * @param {number} z
  28767. */
  28768. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28769. var temp = [x, y, z];
  28770. this.addUniform(name, temp);
  28771. };
  28772. /**
  28773. * Wrapper for addUniform.
  28774. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28775. * @param {Color3} color
  28776. */
  28777. UniformBuffer.prototype.addColor3 = function (name, color) {
  28778. var temp = new Array();
  28779. color.toArray(temp);
  28780. this.addUniform(name, temp);
  28781. };
  28782. /**
  28783. * Wrapper for addUniform.
  28784. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28785. * @param {Color3} color
  28786. * @param {number} alpha
  28787. */
  28788. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28789. var temp = new Array();
  28790. color.toArray(temp);
  28791. temp.push(alpha);
  28792. this.addUniform(name, temp);
  28793. };
  28794. /**
  28795. * Wrapper for addUniform.
  28796. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28797. * @param {Vector3} vector
  28798. */
  28799. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28800. var temp = new Array();
  28801. vector.toArray(temp);
  28802. this.addUniform(name, temp);
  28803. };
  28804. /**
  28805. * Wrapper for addUniform.
  28806. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28807. */
  28808. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28809. this.addUniform(name, 12);
  28810. };
  28811. /**
  28812. * Wrapper for addUniform.
  28813. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28814. */
  28815. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28816. this.addUniform(name, 8);
  28817. };
  28818. /**
  28819. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28820. */
  28821. UniformBuffer.prototype.create = function () {
  28822. if (this._noUBO) {
  28823. return;
  28824. }
  28825. if (this._buffer) {
  28826. return; // nothing to do
  28827. }
  28828. // See spec, alignment must be filled as a vec4
  28829. this._fillAlignment(4);
  28830. this._bufferData = new Float32Array(this._data);
  28831. this._rebuild();
  28832. this._needSync = true;
  28833. };
  28834. UniformBuffer.prototype._rebuild = function () {
  28835. if (this._noUBO) {
  28836. return;
  28837. }
  28838. if (this._dynamic) {
  28839. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28840. }
  28841. else {
  28842. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28843. }
  28844. };
  28845. /**
  28846. * Updates the WebGL Uniform Buffer on the GPU.
  28847. * If the `dynamic` flag is set to true, no cache comparison is done.
  28848. * Otherwise, the buffer will be updated only if the cache differs.
  28849. */
  28850. UniformBuffer.prototype.update = function () {
  28851. if (!this._buffer) {
  28852. this.create();
  28853. return;
  28854. }
  28855. if (!this._dynamic && !this._needSync) {
  28856. return;
  28857. }
  28858. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28859. this._needSync = false;
  28860. };
  28861. /**
  28862. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28863. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28864. * @param {number[]|Float32Array} data Flattened data
  28865. * @param {number} size Size of the data.
  28866. */
  28867. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28868. var location = this._uniformLocations[uniformName];
  28869. if (location === undefined) {
  28870. if (this._buffer) {
  28871. // Cannot add an uniform if the buffer is already created
  28872. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28873. return;
  28874. }
  28875. this.addUniform(uniformName, size);
  28876. location = this._uniformLocations[uniformName];
  28877. }
  28878. if (!this._buffer) {
  28879. this.create();
  28880. }
  28881. if (!this._dynamic) {
  28882. // Cache for static uniform buffers
  28883. var changed = false;
  28884. for (var i = 0; i < size; i++) {
  28885. if (this._bufferData[location + i] !== data[i]) {
  28886. changed = true;
  28887. this._bufferData[location + i] = data[i];
  28888. }
  28889. }
  28890. this._needSync = this._needSync || changed;
  28891. }
  28892. else {
  28893. // No cache for dynamic
  28894. for (var i = 0; i < size; i++) {
  28895. this._bufferData[location + i] = data[i];
  28896. }
  28897. }
  28898. };
  28899. // Update methods
  28900. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28901. // To match std140, matrix must be realigned
  28902. for (var i = 0; i < 3; i++) {
  28903. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28904. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28905. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28906. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28907. }
  28908. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28909. };
  28910. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28911. this._currentEffect.setMatrix3x3(name, matrix);
  28912. };
  28913. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28914. this._currentEffect.setMatrix2x2(name, matrix);
  28915. };
  28916. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28917. // To match std140, matrix must be realigned
  28918. for (var i = 0; i < 2; i++) {
  28919. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28920. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28921. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28922. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28923. }
  28924. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28925. };
  28926. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28927. this._currentEffect.setFloat(name, x);
  28928. };
  28929. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28930. UniformBuffer._tempBuffer[0] = x;
  28931. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28932. };
  28933. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28934. if (suffix === void 0) { suffix = ""; }
  28935. this._currentEffect.setFloat2(name + suffix, x, y);
  28936. };
  28937. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28938. if (suffix === void 0) { suffix = ""; }
  28939. UniformBuffer._tempBuffer[0] = x;
  28940. UniformBuffer._tempBuffer[1] = y;
  28941. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28942. };
  28943. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28944. if (suffix === void 0) { suffix = ""; }
  28945. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28946. };
  28947. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28948. if (suffix === void 0) { suffix = ""; }
  28949. UniformBuffer._tempBuffer[0] = x;
  28950. UniformBuffer._tempBuffer[1] = y;
  28951. UniformBuffer._tempBuffer[2] = z;
  28952. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28953. };
  28954. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28955. if (suffix === void 0) { suffix = ""; }
  28956. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28957. };
  28958. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28959. if (suffix === void 0) { suffix = ""; }
  28960. UniformBuffer._tempBuffer[0] = x;
  28961. UniformBuffer._tempBuffer[1] = y;
  28962. UniformBuffer._tempBuffer[2] = z;
  28963. UniformBuffer._tempBuffer[3] = w;
  28964. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28965. };
  28966. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28967. this._currentEffect.setMatrix(name, mat);
  28968. };
  28969. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28970. this.updateUniform(name, mat.toArray(), 16);
  28971. };
  28972. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28973. this._currentEffect.setVector3(name, vector);
  28974. };
  28975. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28976. vector.toArray(UniformBuffer._tempBuffer);
  28977. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28978. };
  28979. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28980. this._currentEffect.setVector4(name, vector);
  28981. };
  28982. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28983. vector.toArray(UniformBuffer._tempBuffer);
  28984. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28985. };
  28986. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28987. if (suffix === void 0) { suffix = ""; }
  28988. this._currentEffect.setColor3(name + suffix, color);
  28989. };
  28990. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28991. if (suffix === void 0) { suffix = ""; }
  28992. color.toArray(UniformBuffer._tempBuffer);
  28993. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28994. };
  28995. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28996. if (suffix === void 0) { suffix = ""; }
  28997. this._currentEffect.setColor4(name + suffix, color, alpha);
  28998. };
  28999. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29000. if (suffix === void 0) { suffix = ""; }
  29001. color.toArray(UniformBuffer._tempBuffer);
  29002. UniformBuffer._tempBuffer[3] = alpha;
  29003. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29004. };
  29005. /**
  29006. * Sets a sampler uniform on the effect.
  29007. * @param {string} name Name of the sampler.
  29008. * @param {Texture} texture
  29009. */
  29010. UniformBuffer.prototype.setTexture = function (name, texture) {
  29011. this._currentEffect.setTexture(name, texture);
  29012. };
  29013. /**
  29014. * Directly updates the value of the uniform in the cache AND on the GPU.
  29015. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29016. * @param {number[]|Float32Array} data Flattened data
  29017. */
  29018. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29019. this.updateUniform(uniformName, data, data.length);
  29020. this.update();
  29021. };
  29022. /**
  29023. * Binds this uniform buffer to an effect.
  29024. * @param {Effect} effect
  29025. * @param {string} name Name of the uniform block in the shader.
  29026. */
  29027. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29028. this._currentEffect = effect;
  29029. if (this._noUBO || !this._buffer) {
  29030. return;
  29031. }
  29032. effect.bindUniformBuffer(this._buffer, name);
  29033. };
  29034. /**
  29035. * Disposes the uniform buffer.
  29036. */
  29037. UniformBuffer.prototype.dispose = function () {
  29038. if (this._noUBO) {
  29039. return;
  29040. }
  29041. var index = this._engine._uniformBuffers.indexOf(this);
  29042. if (index !== -1) {
  29043. this._engine._uniformBuffers.splice(index, 1);
  29044. }
  29045. if (!this._buffer) {
  29046. return;
  29047. }
  29048. if (this._engine._releaseBuffer(this._buffer)) {
  29049. this._buffer = null;
  29050. }
  29051. };
  29052. // Pool for avoiding memory leaks
  29053. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29054. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29055. return UniformBuffer;
  29056. }());
  29057. BABYLON.UniformBuffer = UniformBuffer;
  29058. })(BABYLON || (BABYLON = {}));
  29059. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29060. var BABYLON;
  29061. (function (BABYLON) {
  29062. var VertexData = /** @class */ (function () {
  29063. function VertexData() {
  29064. }
  29065. VertexData.prototype.set = function (data, kind) {
  29066. switch (kind) {
  29067. case BABYLON.VertexBuffer.PositionKind:
  29068. this.positions = data;
  29069. break;
  29070. case BABYLON.VertexBuffer.NormalKind:
  29071. this.normals = data;
  29072. break;
  29073. case BABYLON.VertexBuffer.TangentKind:
  29074. this.tangents = data;
  29075. break;
  29076. case BABYLON.VertexBuffer.UVKind:
  29077. this.uvs = data;
  29078. break;
  29079. case BABYLON.VertexBuffer.UV2Kind:
  29080. this.uvs2 = data;
  29081. break;
  29082. case BABYLON.VertexBuffer.UV3Kind:
  29083. this.uvs3 = data;
  29084. break;
  29085. case BABYLON.VertexBuffer.UV4Kind:
  29086. this.uvs4 = data;
  29087. break;
  29088. case BABYLON.VertexBuffer.UV5Kind:
  29089. this.uvs5 = data;
  29090. break;
  29091. case BABYLON.VertexBuffer.UV6Kind:
  29092. this.uvs6 = data;
  29093. break;
  29094. case BABYLON.VertexBuffer.ColorKind:
  29095. this.colors = data;
  29096. break;
  29097. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29098. this.matricesIndices = data;
  29099. break;
  29100. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29101. this.matricesWeights = data;
  29102. break;
  29103. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29104. this.matricesIndicesExtra = data;
  29105. break;
  29106. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29107. this.matricesWeightsExtra = data;
  29108. break;
  29109. }
  29110. };
  29111. /**
  29112. * Associates the vertexData to the passed Mesh.
  29113. * Sets it as updatable or not (default `false`).
  29114. * Returns the VertexData.
  29115. */
  29116. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29117. this._applyTo(mesh, updatable);
  29118. return this;
  29119. };
  29120. /**
  29121. * Associates the vertexData to the passed Geometry.
  29122. * Sets it as updatable or not (default `false`).
  29123. * Returns the VertexData.
  29124. */
  29125. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29126. this._applyTo(geometry, updatable);
  29127. return this;
  29128. };
  29129. /**
  29130. * Updates the associated mesh.
  29131. * Returns the VertexData.
  29132. */
  29133. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29134. this._update(mesh);
  29135. return this;
  29136. };
  29137. /**
  29138. * Updates the associated geometry.
  29139. * Returns the VertexData.
  29140. */
  29141. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29142. this._update(geometry);
  29143. return this;
  29144. };
  29145. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29146. if (updatable === void 0) { updatable = false; }
  29147. if (this.positions) {
  29148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29149. }
  29150. if (this.normals) {
  29151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29152. }
  29153. if (this.tangents) {
  29154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29155. }
  29156. if (this.uvs) {
  29157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29158. }
  29159. if (this.uvs2) {
  29160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29161. }
  29162. if (this.uvs3) {
  29163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29164. }
  29165. if (this.uvs4) {
  29166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29167. }
  29168. if (this.uvs5) {
  29169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29170. }
  29171. if (this.uvs6) {
  29172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29173. }
  29174. if (this.colors) {
  29175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29176. }
  29177. if (this.matricesIndices) {
  29178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29179. }
  29180. if (this.matricesWeights) {
  29181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29182. }
  29183. if (this.matricesIndicesExtra) {
  29184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29185. }
  29186. if (this.matricesWeightsExtra) {
  29187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29188. }
  29189. if (this.indices) {
  29190. meshOrGeometry.setIndices(this.indices, null, updatable);
  29191. }
  29192. return this;
  29193. };
  29194. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29195. if (this.positions) {
  29196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29197. }
  29198. if (this.normals) {
  29199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29200. }
  29201. if (this.tangents) {
  29202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29203. }
  29204. if (this.uvs) {
  29205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29206. }
  29207. if (this.uvs2) {
  29208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29209. }
  29210. if (this.uvs3) {
  29211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29212. }
  29213. if (this.uvs4) {
  29214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29215. }
  29216. if (this.uvs5) {
  29217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29218. }
  29219. if (this.uvs6) {
  29220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29221. }
  29222. if (this.colors) {
  29223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29224. }
  29225. if (this.matricesIndices) {
  29226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29227. }
  29228. if (this.matricesWeights) {
  29229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29230. }
  29231. if (this.matricesIndicesExtra) {
  29232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29233. }
  29234. if (this.matricesWeightsExtra) {
  29235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29236. }
  29237. if (this.indices) {
  29238. meshOrGeometry.setIndices(this.indices, null);
  29239. }
  29240. return this;
  29241. };
  29242. /**
  29243. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29244. * Returns the VertexData.
  29245. */
  29246. VertexData.prototype.transform = function (matrix) {
  29247. var transformed = BABYLON.Vector3.Zero();
  29248. var index;
  29249. if (this.positions) {
  29250. var position = BABYLON.Vector3.Zero();
  29251. for (index = 0; index < this.positions.length; index += 3) {
  29252. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29253. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29254. this.positions[index] = transformed.x;
  29255. this.positions[index + 1] = transformed.y;
  29256. this.positions[index + 2] = transformed.z;
  29257. }
  29258. }
  29259. if (this.normals) {
  29260. var normal = BABYLON.Vector3.Zero();
  29261. for (index = 0; index < this.normals.length; index += 3) {
  29262. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29263. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29264. this.normals[index] = transformed.x;
  29265. this.normals[index + 1] = transformed.y;
  29266. this.normals[index + 2] = transformed.z;
  29267. }
  29268. }
  29269. if (this.tangents) {
  29270. var tangent = BABYLON.Vector4.Zero();
  29271. var tangentTransformed = BABYLON.Vector4.Zero();
  29272. for (index = 0; index < this.tangents.length; index += 4) {
  29273. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29274. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29275. this.tangents[index] = tangentTransformed.x;
  29276. this.tangents[index + 1] = tangentTransformed.y;
  29277. this.tangents[index + 2] = tangentTransformed.z;
  29278. this.tangents[index + 3] = tangentTransformed.w;
  29279. }
  29280. }
  29281. return this;
  29282. };
  29283. /**
  29284. * Merges the passed VertexData into the current one.
  29285. * Returns the modified VertexData.
  29286. */
  29287. VertexData.prototype.merge = function (other, options) {
  29288. options = options || {};
  29289. if (other.indices) {
  29290. if (!this.indices) {
  29291. this.indices = [];
  29292. }
  29293. var offset = this.positions ? this.positions.length / 3 : 0;
  29294. for (var index = 0; index < other.indices.length; index++) {
  29295. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29296. this.indices.push(other.indices[index] + offset);
  29297. }
  29298. }
  29299. this.positions = this._mergeElement(this.positions, other.positions);
  29300. if (!this.positions) {
  29301. return this;
  29302. }
  29303. var count = this.positions.length / 3;
  29304. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29305. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29306. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29307. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29308. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29309. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29310. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29311. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29312. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29313. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29314. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29315. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29316. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29317. return this;
  29318. };
  29319. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29320. if (length === void 0) { length = 0; }
  29321. if (defaultValue === void 0) { defaultValue = 0; }
  29322. if (!other && !source) {
  29323. return null;
  29324. }
  29325. if (!other) {
  29326. var padding = new Float32Array(source.length);
  29327. padding.fill(defaultValue);
  29328. return this._mergeElement(source, padding, length);
  29329. }
  29330. if (!source) {
  29331. if (length === 0 || length === other.length) {
  29332. return other;
  29333. }
  29334. var padding = new Float32Array(length - other.length);
  29335. padding.fill(defaultValue);
  29336. return this._mergeElement(padding, other, length);
  29337. }
  29338. var len = other.length + source.length;
  29339. var isSrcTypedArray = source instanceof Float32Array;
  29340. var isOthTypedArray = other instanceof Float32Array;
  29341. // use non-loop method when the source is Float32Array
  29342. if (isSrcTypedArray) {
  29343. var ret32 = new Float32Array(len);
  29344. ret32.set(source);
  29345. ret32.set(other, source.length);
  29346. return ret32;
  29347. // source is number[], when other is also use concat
  29348. }
  29349. else if (!isOthTypedArray) {
  29350. return source.concat(other);
  29351. // source is a number[], but other is a Float32Array, loop required
  29352. }
  29353. else {
  29354. var ret = source.slice(0); // copy source to a separate array
  29355. for (var i = 0, len = other.length; i < len; i++) {
  29356. ret.push(other[i]);
  29357. }
  29358. return ret;
  29359. }
  29360. };
  29361. /**
  29362. * Serializes the VertexData.
  29363. * Returns a serialized object.
  29364. */
  29365. VertexData.prototype.serialize = function () {
  29366. var serializationObject = this.serialize();
  29367. if (this.positions) {
  29368. serializationObject.positions = this.positions;
  29369. }
  29370. if (this.normals) {
  29371. serializationObject.normals = this.normals;
  29372. }
  29373. if (this.tangents) {
  29374. serializationObject.tangents = this.tangents;
  29375. }
  29376. if (this.uvs) {
  29377. serializationObject.uvs = this.uvs;
  29378. }
  29379. if (this.uvs2) {
  29380. serializationObject.uvs2 = this.uvs2;
  29381. }
  29382. if (this.uvs3) {
  29383. serializationObject.uvs3 = this.uvs3;
  29384. }
  29385. if (this.uvs4) {
  29386. serializationObject.uvs4 = this.uvs4;
  29387. }
  29388. if (this.uvs5) {
  29389. serializationObject.uvs5 = this.uvs5;
  29390. }
  29391. if (this.uvs6) {
  29392. serializationObject.uvs6 = this.uvs6;
  29393. }
  29394. if (this.colors) {
  29395. serializationObject.colors = this.colors;
  29396. }
  29397. if (this.matricesIndices) {
  29398. serializationObject.matricesIndices = this.matricesIndices;
  29399. serializationObject.matricesIndices._isExpanded = true;
  29400. }
  29401. if (this.matricesWeights) {
  29402. serializationObject.matricesWeights = this.matricesWeights;
  29403. }
  29404. if (this.matricesIndicesExtra) {
  29405. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29406. serializationObject.matricesIndicesExtra._isExpanded = true;
  29407. }
  29408. if (this.matricesWeightsExtra) {
  29409. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29410. }
  29411. serializationObject.indices = this.indices;
  29412. return serializationObject;
  29413. };
  29414. // Statics
  29415. /**
  29416. * Returns the object VertexData associated to the passed mesh.
  29417. */
  29418. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29419. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29420. };
  29421. /**
  29422. * Returns the object VertexData associated to the passed geometry.
  29423. */
  29424. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29425. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29426. };
  29427. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29428. var result = new VertexData();
  29429. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29430. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29431. }
  29432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29433. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29434. }
  29435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29436. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29437. }
  29438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29439. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29440. }
  29441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29442. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29443. }
  29444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29445. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29446. }
  29447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29448. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29449. }
  29450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29451. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29452. }
  29453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29454. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29455. }
  29456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29457. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29458. }
  29459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29460. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29461. }
  29462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29463. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29464. }
  29465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29466. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29467. }
  29468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29469. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29470. }
  29471. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29472. return result;
  29473. };
  29474. /**
  29475. * Creates the vertexData of the Ribbon.
  29476. */
  29477. VertexData.CreateRibbon = function (options) {
  29478. var pathArray = options.pathArray;
  29479. var closeArray = options.closeArray || false;
  29480. var closePath = options.closePath || false;
  29481. var invertUV = options.invertUV || false;
  29482. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29483. var offset = options.offset || defaultOffset;
  29484. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29485. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29486. var customUV = options.uvs;
  29487. var customColors = options.colors;
  29488. var positions = [];
  29489. var indices = [];
  29490. var normals = [];
  29491. var uvs = [];
  29492. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29493. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29494. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29495. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29496. var minlg; // minimal length among all paths from pathArray
  29497. var lg = []; // array of path lengths : nb of vertex per path
  29498. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29499. var p; // path iterator
  29500. var i; // point iterator
  29501. var j; // point iterator
  29502. // if single path in pathArray
  29503. if (pathArray.length < 2) {
  29504. var ar1 = [];
  29505. var ar2 = [];
  29506. for (i = 0; i < pathArray[0].length - offset; i++) {
  29507. ar1.push(pathArray[0][i]);
  29508. ar2.push(pathArray[0][i + offset]);
  29509. }
  29510. pathArray = [ar1, ar2];
  29511. }
  29512. // positions and horizontal distances (u)
  29513. var idc = 0;
  29514. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29515. var path;
  29516. var l;
  29517. minlg = pathArray[0].length;
  29518. var vectlg;
  29519. var dist;
  29520. for (p = 0; p < pathArray.length; p++) {
  29521. uTotalDistance[p] = 0;
  29522. us[p] = [0];
  29523. path = pathArray[p];
  29524. l = path.length;
  29525. minlg = (minlg < l) ? minlg : l;
  29526. j = 0;
  29527. while (j < l) {
  29528. positions.push(path[j].x, path[j].y, path[j].z);
  29529. if (j > 0) {
  29530. vectlg = path[j].subtract(path[j - 1]).length();
  29531. dist = vectlg + uTotalDistance[p];
  29532. us[p].push(dist);
  29533. uTotalDistance[p] = dist;
  29534. }
  29535. j++;
  29536. }
  29537. if (closePath) {
  29538. j--;
  29539. positions.push(path[0].x, path[0].y, path[0].z);
  29540. vectlg = path[j].subtract(path[0]).length();
  29541. dist = vectlg + uTotalDistance[p];
  29542. us[p].push(dist);
  29543. uTotalDistance[p] = dist;
  29544. }
  29545. lg[p] = l + closePathCorr;
  29546. idx[p] = idc;
  29547. idc += (l + closePathCorr);
  29548. }
  29549. // vertical distances (v)
  29550. var path1;
  29551. var path2;
  29552. var vertex1 = null;
  29553. var vertex2 = null;
  29554. for (i = 0; i < minlg + closePathCorr; i++) {
  29555. vTotalDistance[i] = 0;
  29556. vs[i] = [0];
  29557. for (p = 0; p < pathArray.length - 1; p++) {
  29558. path1 = pathArray[p];
  29559. path2 = pathArray[p + 1];
  29560. if (i === minlg) {
  29561. vertex1 = path1[0];
  29562. vertex2 = path2[0];
  29563. }
  29564. else {
  29565. vertex1 = path1[i];
  29566. vertex2 = path2[i];
  29567. }
  29568. vectlg = vertex2.subtract(vertex1).length();
  29569. dist = vectlg + vTotalDistance[i];
  29570. vs[i].push(dist);
  29571. vTotalDistance[i] = dist;
  29572. }
  29573. if (closeArray && vertex2 && vertex1) {
  29574. path1 = pathArray[p];
  29575. path2 = pathArray[0];
  29576. if (i === minlg) {
  29577. vertex2 = path2[0];
  29578. }
  29579. vectlg = vertex2.subtract(vertex1).length();
  29580. dist = vectlg + vTotalDistance[i];
  29581. vTotalDistance[i] = dist;
  29582. }
  29583. }
  29584. // uvs
  29585. var u;
  29586. var v;
  29587. if (customUV) {
  29588. for (p = 0; p < customUV.length; p++) {
  29589. uvs.push(customUV[p].x, customUV[p].y);
  29590. }
  29591. }
  29592. else {
  29593. for (p = 0; p < pathArray.length; p++) {
  29594. for (i = 0; i < minlg + closePathCorr; i++) {
  29595. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29596. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29597. if (invertUV) {
  29598. uvs.push(v, u);
  29599. }
  29600. else {
  29601. uvs.push(u, v);
  29602. }
  29603. }
  29604. }
  29605. }
  29606. // indices
  29607. p = 0; // path index
  29608. var pi = 0; // positions array index
  29609. var l1 = lg[p] - 1; // path1 length
  29610. var l2 = lg[p + 1] - 1; // path2 length
  29611. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29612. var shft = idx[1] - idx[0]; // shift
  29613. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29614. while (pi <= min && p < path1nb) {
  29615. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  29616. indices.push(pi, pi + shft, pi + 1);
  29617. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29618. pi += 1;
  29619. if (pi === min) {
  29620. p++;
  29621. if (p === lg.length - 1) {
  29622. shft = idx[0] - idx[p];
  29623. l1 = lg[p] - 1;
  29624. l2 = lg[0] - 1;
  29625. }
  29626. else {
  29627. shft = idx[p + 1] - idx[p];
  29628. l1 = lg[p] - 1;
  29629. l2 = lg[p + 1] - 1;
  29630. }
  29631. pi = idx[p];
  29632. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29633. }
  29634. }
  29635. // normals
  29636. VertexData.ComputeNormals(positions, indices, normals);
  29637. if (closePath) {
  29638. var indexFirst = 0;
  29639. var indexLast = 0;
  29640. for (p = 0; p < pathArray.length; p++) {
  29641. indexFirst = idx[p] * 3;
  29642. if (p + 1 < pathArray.length) {
  29643. indexLast = (idx[p + 1] - 1) * 3;
  29644. }
  29645. else {
  29646. indexLast = normals.length - 3;
  29647. }
  29648. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29649. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29650. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29651. normals[indexLast] = normals[indexFirst];
  29652. normals[indexLast + 1] = normals[indexFirst + 1];
  29653. normals[indexLast + 2] = normals[indexFirst + 2];
  29654. }
  29655. }
  29656. // sides
  29657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29658. // Colors
  29659. var colors = null;
  29660. if (customColors) {
  29661. colors = new Float32Array(customColors.length * 4);
  29662. for (var c = 0; c < customColors.length; c++) {
  29663. colors[c * 4] = customColors[c].r;
  29664. colors[c * 4 + 1] = customColors[c].g;
  29665. colors[c * 4 + 2] = customColors[c].b;
  29666. colors[c * 4 + 3] = customColors[c].a;
  29667. }
  29668. }
  29669. // Result
  29670. var vertexData = new VertexData();
  29671. var positions32 = new Float32Array(positions);
  29672. var normals32 = new Float32Array(normals);
  29673. var uvs32 = new Float32Array(uvs);
  29674. vertexData.indices = indices;
  29675. vertexData.positions = positions32;
  29676. vertexData.normals = normals32;
  29677. vertexData.uvs = uvs32;
  29678. if (colors) {
  29679. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29680. }
  29681. if (closePath) {
  29682. vertexData._idx = idx;
  29683. }
  29684. return vertexData;
  29685. };
  29686. /**
  29687. * Creates the VertexData of the Box.
  29688. */
  29689. VertexData.CreateBox = function (options) {
  29690. var normalsSource = [
  29691. new BABYLON.Vector3(0, 0, 1),
  29692. new BABYLON.Vector3(0, 0, -1),
  29693. new BABYLON.Vector3(1, 0, 0),
  29694. new BABYLON.Vector3(-1, 0, 0),
  29695. new BABYLON.Vector3(0, 1, 0),
  29696. new BABYLON.Vector3(0, -1, 0)
  29697. ];
  29698. var indices = [];
  29699. var positions = [];
  29700. var normals = [];
  29701. var uvs = [];
  29702. var width = options.width || options.size || 1;
  29703. var height = options.height || options.size || 1;
  29704. var depth = options.depth || options.size || 1;
  29705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29706. var faceUV = options.faceUV || new Array(6);
  29707. var faceColors = options.faceColors;
  29708. var colors = [];
  29709. // default face colors and UV if undefined
  29710. for (var f = 0; f < 6; f++) {
  29711. if (faceUV[f] === undefined) {
  29712. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29713. }
  29714. if (faceColors && faceColors[f] === undefined) {
  29715. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29716. }
  29717. }
  29718. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29719. // Create each face in turn.
  29720. for (var index = 0; index < normalsSource.length; index++) {
  29721. var normal = normalsSource[index];
  29722. // Get two vectors perpendicular to the face normal and to each other.
  29723. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29724. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29725. // Six indices (two triangles) per face.
  29726. var verticesLength = positions.length / 3;
  29727. indices.push(verticesLength);
  29728. indices.push(verticesLength + 1);
  29729. indices.push(verticesLength + 2);
  29730. indices.push(verticesLength);
  29731. indices.push(verticesLength + 2);
  29732. indices.push(verticesLength + 3);
  29733. // Four vertices per face.
  29734. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29735. positions.push(vertex.x, vertex.y, vertex.z);
  29736. normals.push(normal.x, normal.y, normal.z);
  29737. uvs.push(faceUV[index].z, faceUV[index].w);
  29738. if (faceColors) {
  29739. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29740. }
  29741. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29742. positions.push(vertex.x, vertex.y, vertex.z);
  29743. normals.push(normal.x, normal.y, normal.z);
  29744. uvs.push(faceUV[index].x, faceUV[index].w);
  29745. if (faceColors) {
  29746. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29747. }
  29748. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29749. positions.push(vertex.x, vertex.y, vertex.z);
  29750. normals.push(normal.x, normal.y, normal.z);
  29751. uvs.push(faceUV[index].x, faceUV[index].y);
  29752. if (faceColors) {
  29753. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29754. }
  29755. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29756. positions.push(vertex.x, vertex.y, vertex.z);
  29757. normals.push(normal.x, normal.y, normal.z);
  29758. uvs.push(faceUV[index].z, faceUV[index].y);
  29759. if (faceColors) {
  29760. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29761. }
  29762. }
  29763. // sides
  29764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29765. // Result
  29766. var vertexData = new VertexData();
  29767. vertexData.indices = indices;
  29768. vertexData.positions = positions;
  29769. vertexData.normals = normals;
  29770. vertexData.uvs = uvs;
  29771. if (faceColors) {
  29772. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29773. vertexData.colors = totalColors;
  29774. }
  29775. return vertexData;
  29776. };
  29777. /**
  29778. * Creates the VertexData of the Sphere.
  29779. */
  29780. VertexData.CreateSphere = function (options) {
  29781. var segments = options.segments || 32;
  29782. var diameterX = options.diameterX || options.diameter || 1;
  29783. var diameterY = options.diameterY || options.diameter || 1;
  29784. var diameterZ = options.diameterZ || options.diameter || 1;
  29785. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29786. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29787. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29788. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29789. var totalZRotationSteps = 2 + segments;
  29790. var totalYRotationSteps = 2 * totalZRotationSteps;
  29791. var indices = [];
  29792. var positions = [];
  29793. var normals = [];
  29794. var uvs = [];
  29795. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29796. var normalizedZ = zRotationStep / totalZRotationSteps;
  29797. var angleZ = normalizedZ * Math.PI * slice;
  29798. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29799. var normalizedY = yRotationStep / totalYRotationSteps;
  29800. var angleY = normalizedY * Math.PI * 2 * arc;
  29801. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29802. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29803. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29804. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29805. var vertex = complete.multiply(radius);
  29806. var normal = complete.divide(radius).normalize();
  29807. positions.push(vertex.x, vertex.y, vertex.z);
  29808. normals.push(normal.x, normal.y, normal.z);
  29809. uvs.push(normalizedY, normalizedZ);
  29810. }
  29811. if (zRotationStep > 0) {
  29812. var verticesCount = positions.length / 3;
  29813. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29814. indices.push((firstIndex));
  29815. indices.push((firstIndex + 1));
  29816. indices.push(firstIndex + totalYRotationSteps + 1);
  29817. indices.push((firstIndex + totalYRotationSteps + 1));
  29818. indices.push((firstIndex + 1));
  29819. indices.push((firstIndex + totalYRotationSteps + 2));
  29820. }
  29821. }
  29822. }
  29823. // Sides
  29824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29825. // Result
  29826. var vertexData = new VertexData();
  29827. vertexData.indices = indices;
  29828. vertexData.positions = positions;
  29829. vertexData.normals = normals;
  29830. vertexData.uvs = uvs;
  29831. return vertexData;
  29832. };
  29833. /**
  29834. * Creates the VertexData of the Cylinder or Cone.
  29835. */
  29836. VertexData.CreateCylinder = function (options) {
  29837. var height = options.height || 2;
  29838. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29839. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29840. var tessellation = options.tessellation || 24;
  29841. var subdivisions = options.subdivisions || 1;
  29842. var hasRings = options.hasRings ? true : false;
  29843. var enclose = options.enclose ? true : false;
  29844. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29845. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29846. var faceUV = options.faceUV || new Array(3);
  29847. var faceColors = options.faceColors;
  29848. // default face colors and UV if undefined
  29849. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29850. var ringNb = (hasRings) ? subdivisions : 1;
  29851. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29852. var f;
  29853. for (f = 0; f < surfaceNb; f++) {
  29854. if (faceColors && faceColors[f] === undefined) {
  29855. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29856. }
  29857. }
  29858. for (f = 0; f < surfaceNb; f++) {
  29859. if (faceUV && faceUV[f] === undefined) {
  29860. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29861. }
  29862. }
  29863. var indices = new Array();
  29864. var positions = new Array();
  29865. var normals = new Array();
  29866. var uvs = new Array();
  29867. var colors = new Array();
  29868. var angle_step = Math.PI * 2 * arc / tessellation;
  29869. var angle;
  29870. var h;
  29871. var radius;
  29872. var tan = (diameterBottom - diameterTop) / 2 / height;
  29873. var ringVertex = BABYLON.Vector3.Zero();
  29874. var ringNormal = BABYLON.Vector3.Zero();
  29875. var ringFirstVertex = BABYLON.Vector3.Zero();
  29876. var ringFirstNormal = BABYLON.Vector3.Zero();
  29877. var quadNormal = BABYLON.Vector3.Zero();
  29878. var Y = BABYLON.Axis.Y;
  29879. // positions, normals, uvs
  29880. var i;
  29881. var j;
  29882. var r;
  29883. var ringIdx = 1;
  29884. var s = 1; // surface index
  29885. var cs = 0;
  29886. var v = 0;
  29887. for (i = 0; i <= subdivisions; i++) {
  29888. h = i / subdivisions;
  29889. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29890. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29891. for (r = 0; r < ringIdx; r++) {
  29892. if (hasRings) {
  29893. s += r;
  29894. }
  29895. if (enclose) {
  29896. s += 2 * r;
  29897. }
  29898. for (j = 0; j <= tessellation; j++) {
  29899. angle = j * angle_step;
  29900. // position
  29901. ringVertex.x = Math.cos(-angle) * radius;
  29902. ringVertex.y = -height / 2 + h * height;
  29903. ringVertex.z = Math.sin(-angle) * radius;
  29904. // normal
  29905. if (diameterTop === 0 && i === subdivisions) {
  29906. // if no top cap, reuse former normals
  29907. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29908. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29909. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29910. }
  29911. else {
  29912. ringNormal.x = ringVertex.x;
  29913. ringNormal.z = ringVertex.z;
  29914. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29915. ringNormal.normalize();
  29916. }
  29917. // keep first ring vertex values for enclose
  29918. if (j === 0) {
  29919. ringFirstVertex.copyFrom(ringVertex);
  29920. ringFirstNormal.copyFrom(ringNormal);
  29921. }
  29922. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29923. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29924. if (hasRings) {
  29925. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29926. }
  29927. else {
  29928. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29929. }
  29930. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29931. if (faceColors) {
  29932. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29933. }
  29934. }
  29935. // if enclose, add four vertices and their dedicated normals
  29936. if (arc !== 1 && enclose) {
  29937. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29938. positions.push(0, ringVertex.y, 0);
  29939. positions.push(0, ringVertex.y, 0);
  29940. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29941. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29942. quadNormal.normalize();
  29943. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29944. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29945. quadNormal.normalize();
  29946. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29947. if (hasRings) {
  29948. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29949. }
  29950. else {
  29951. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29952. }
  29953. uvs.push(faceUV[s + 1].x, v);
  29954. uvs.push(faceUV[s + 1].z, v);
  29955. if (hasRings) {
  29956. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29957. }
  29958. else {
  29959. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29960. }
  29961. uvs.push(faceUV[s + 2].x, v);
  29962. uvs.push(faceUV[s + 2].z, v);
  29963. if (faceColors) {
  29964. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29965. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29966. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29967. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29968. }
  29969. }
  29970. if (cs !== s) {
  29971. cs = s;
  29972. }
  29973. }
  29974. }
  29975. // indices
  29976. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29977. var s;
  29978. i = 0;
  29979. for (s = 0; s < subdivisions; s++) {
  29980. var i0 = 0;
  29981. var i1 = 0;
  29982. var i2 = 0;
  29983. var i3 = 0;
  29984. for (j = 0; j < tessellation; j++) {
  29985. i0 = i * (e + 1) + j;
  29986. i1 = (i + 1) * (e + 1) + j;
  29987. i2 = i * (e + 1) + (j + 1);
  29988. i3 = (i + 1) * (e + 1) + (j + 1);
  29989. indices.push(i0, i1, i2);
  29990. indices.push(i3, i2, i1);
  29991. }
  29992. if (arc !== 1 && enclose) {
  29993. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29994. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29995. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29996. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29997. }
  29998. i = (hasRings) ? (i + 2) : (i + 1);
  29999. }
  30000. // Caps
  30001. var createCylinderCap = function (isTop) {
  30002. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30003. if (radius === 0) {
  30004. return;
  30005. }
  30006. // Cap positions, normals & uvs
  30007. var angle;
  30008. var circleVector;
  30009. var i;
  30010. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30011. var c = null;
  30012. if (faceColors) {
  30013. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30014. }
  30015. // cap center
  30016. var vbase = positions.length / 3;
  30017. var offset = isTop ? height / 2 : -height / 2;
  30018. var center = new BABYLON.Vector3(0, offset, 0);
  30019. positions.push(center.x, center.y, center.z);
  30020. normals.push(0, isTop ? 1 : -1, 0);
  30021. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30022. if (c) {
  30023. colors.push(c.r, c.g, c.b, c.a);
  30024. }
  30025. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30026. for (i = 0; i <= tessellation; i++) {
  30027. angle = Math.PI * 2 * i * arc / tessellation;
  30028. var cos = Math.cos(-angle);
  30029. var sin = Math.sin(-angle);
  30030. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30031. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30032. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30033. normals.push(0, isTop ? 1 : -1, 0);
  30034. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30035. if (c) {
  30036. colors.push(c.r, c.g, c.b, c.a);
  30037. }
  30038. }
  30039. // Cap indices
  30040. for (i = 0; i < tessellation; i++) {
  30041. if (!isTop) {
  30042. indices.push(vbase);
  30043. indices.push(vbase + (i + 1));
  30044. indices.push(vbase + (i + 2));
  30045. }
  30046. else {
  30047. indices.push(vbase);
  30048. indices.push(vbase + (i + 2));
  30049. indices.push(vbase + (i + 1));
  30050. }
  30051. }
  30052. };
  30053. // add caps to geometry
  30054. createCylinderCap(false);
  30055. createCylinderCap(true);
  30056. // Sides
  30057. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30058. var vertexData = new VertexData();
  30059. vertexData.indices = indices;
  30060. vertexData.positions = positions;
  30061. vertexData.normals = normals;
  30062. vertexData.uvs = uvs;
  30063. if (faceColors) {
  30064. vertexData.colors = colors;
  30065. }
  30066. return vertexData;
  30067. };
  30068. /**
  30069. * Creates the VertexData of the Torus.
  30070. */
  30071. VertexData.CreateTorus = function (options) {
  30072. var indices = [];
  30073. var positions = [];
  30074. var normals = [];
  30075. var uvs = [];
  30076. var diameter = options.diameter || 1;
  30077. var thickness = options.thickness || 0.5;
  30078. var tessellation = options.tessellation || 16;
  30079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30080. var stride = tessellation + 1;
  30081. for (var i = 0; i <= tessellation; i++) {
  30082. var u = i / tessellation;
  30083. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30084. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30085. for (var j = 0; j <= tessellation; j++) {
  30086. var v = 1 - j / tessellation;
  30087. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30088. var dx = Math.cos(innerAngle);
  30089. var dy = Math.sin(innerAngle);
  30090. // Create a vertex.
  30091. var normal = new BABYLON.Vector3(dx, dy, 0);
  30092. var position = normal.scale(thickness / 2);
  30093. var textureCoordinate = new BABYLON.Vector2(u, v);
  30094. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30095. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30096. positions.push(position.x, position.y, position.z);
  30097. normals.push(normal.x, normal.y, normal.z);
  30098. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30099. // And create indices for two triangles.
  30100. var nextI = (i + 1) % stride;
  30101. var nextJ = (j + 1) % stride;
  30102. indices.push(i * stride + j);
  30103. indices.push(i * stride + nextJ);
  30104. indices.push(nextI * stride + j);
  30105. indices.push(i * stride + nextJ);
  30106. indices.push(nextI * stride + nextJ);
  30107. indices.push(nextI * stride + j);
  30108. }
  30109. }
  30110. // Sides
  30111. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30112. // Result
  30113. var vertexData = new VertexData();
  30114. vertexData.indices = indices;
  30115. vertexData.positions = positions;
  30116. vertexData.normals = normals;
  30117. vertexData.uvs = uvs;
  30118. return vertexData;
  30119. };
  30120. /**
  30121. * Creates the VertexData of the LineSystem.
  30122. */
  30123. VertexData.CreateLineSystem = function (options) {
  30124. var indices = [];
  30125. var positions = [];
  30126. var lines = options.lines;
  30127. var colors = options.colors;
  30128. var vertexColors = [];
  30129. var idx = 0;
  30130. for (var l = 0; l < lines.length; l++) {
  30131. var points = lines[l];
  30132. for (var index = 0; index < points.length; index++) {
  30133. positions.push(points[index].x, points[index].y, points[index].z);
  30134. if (colors) {
  30135. var color = colors[l];
  30136. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30137. }
  30138. if (index > 0) {
  30139. indices.push(idx - 1);
  30140. indices.push(idx);
  30141. }
  30142. idx++;
  30143. }
  30144. }
  30145. var vertexData = new VertexData();
  30146. vertexData.indices = indices;
  30147. vertexData.positions = positions;
  30148. if (colors) {
  30149. vertexData.colors = vertexColors;
  30150. }
  30151. return vertexData;
  30152. };
  30153. /**
  30154. * Create the VertexData of the DashedLines.
  30155. */
  30156. VertexData.CreateDashedLines = function (options) {
  30157. var dashSize = options.dashSize || 3;
  30158. var gapSize = options.gapSize || 1;
  30159. var dashNb = options.dashNb || 200;
  30160. var points = options.points;
  30161. var positions = new Array();
  30162. var indices = new Array();
  30163. var curvect = BABYLON.Vector3.Zero();
  30164. var lg = 0;
  30165. var nb = 0;
  30166. var shft = 0;
  30167. var dashshft = 0;
  30168. var curshft = 0;
  30169. var idx = 0;
  30170. var i = 0;
  30171. for (i = 0; i < points.length - 1; i++) {
  30172. points[i + 1].subtractToRef(points[i], curvect);
  30173. lg += curvect.length();
  30174. }
  30175. shft = lg / dashNb;
  30176. dashshft = dashSize * shft / (dashSize + gapSize);
  30177. for (i = 0; i < points.length - 1; i++) {
  30178. points[i + 1].subtractToRef(points[i], curvect);
  30179. nb = Math.floor(curvect.length() / shft);
  30180. curvect.normalize();
  30181. for (var j = 0; j < nb; j++) {
  30182. curshft = shft * j;
  30183. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30184. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30185. indices.push(idx, idx + 1);
  30186. idx += 2;
  30187. }
  30188. }
  30189. // Result
  30190. var vertexData = new VertexData();
  30191. vertexData.positions = positions;
  30192. vertexData.indices = indices;
  30193. return vertexData;
  30194. };
  30195. /**
  30196. * Creates the VertexData of the Ground.
  30197. */
  30198. VertexData.CreateGround = function (options) {
  30199. var indices = [];
  30200. var positions = [];
  30201. var normals = [];
  30202. var uvs = [];
  30203. var row, col;
  30204. var width = options.width || 1;
  30205. var height = options.height || 1;
  30206. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30207. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30208. for (row = 0; row <= subdivisionsY; row++) {
  30209. for (col = 0; col <= subdivisionsX; col++) {
  30210. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30211. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30212. positions.push(position.x, position.y, position.z);
  30213. normals.push(normal.x, normal.y, normal.z);
  30214. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30215. }
  30216. }
  30217. for (row = 0; row < subdivisionsY; row++) {
  30218. for (col = 0; col < subdivisionsX; col++) {
  30219. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30220. indices.push(col + 1 + row * (subdivisionsX + 1));
  30221. indices.push(col + row * (subdivisionsX + 1));
  30222. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30223. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30224. indices.push(col + row * (subdivisionsX + 1));
  30225. }
  30226. }
  30227. // Result
  30228. var vertexData = new VertexData();
  30229. vertexData.indices = indices;
  30230. vertexData.positions = positions;
  30231. vertexData.normals = normals;
  30232. vertexData.uvs = uvs;
  30233. return vertexData;
  30234. };
  30235. /**
  30236. * Creates the VertexData of the TiledGround.
  30237. */
  30238. VertexData.CreateTiledGround = function (options) {
  30239. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30240. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30241. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30242. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30243. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30244. var precision = options.precision || { w: 1, h: 1 };
  30245. var indices = new Array();
  30246. var positions = new Array();
  30247. var normals = new Array();
  30248. var uvs = new Array();
  30249. var row, col, tileRow, tileCol;
  30250. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30251. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30252. precision.w = (precision.w < 1) ? 1 : precision.w;
  30253. precision.h = (precision.h < 1) ? 1 : precision.h;
  30254. var tileSize = {
  30255. 'w': (xmax - xmin) / subdivisions.w,
  30256. 'h': (zmax - zmin) / subdivisions.h
  30257. };
  30258. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30259. // Indices
  30260. var base = positions.length / 3;
  30261. var rowLength = precision.w + 1;
  30262. for (row = 0; row < precision.h; row++) {
  30263. for (col = 0; col < precision.w; col++) {
  30264. var square = [
  30265. base + col + row * rowLength,
  30266. base + (col + 1) + row * rowLength,
  30267. base + (col + 1) + (row + 1) * rowLength,
  30268. base + col + (row + 1) * rowLength
  30269. ];
  30270. indices.push(square[1]);
  30271. indices.push(square[2]);
  30272. indices.push(square[3]);
  30273. indices.push(square[0]);
  30274. indices.push(square[1]);
  30275. indices.push(square[3]);
  30276. }
  30277. }
  30278. // Position, normals and uvs
  30279. var position = BABYLON.Vector3.Zero();
  30280. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30281. for (row = 0; row <= precision.h; row++) {
  30282. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30283. for (col = 0; col <= precision.w; col++) {
  30284. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30285. position.y = 0;
  30286. positions.push(position.x, position.y, position.z);
  30287. normals.push(normal.x, normal.y, normal.z);
  30288. uvs.push(col / precision.w, row / precision.h);
  30289. }
  30290. }
  30291. }
  30292. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30293. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30294. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30295. }
  30296. }
  30297. // Result
  30298. var vertexData = new VertexData();
  30299. vertexData.indices = indices;
  30300. vertexData.positions = positions;
  30301. vertexData.normals = normals;
  30302. vertexData.uvs = uvs;
  30303. return vertexData;
  30304. };
  30305. /**
  30306. * Creates the VertexData of the Ground designed from a heightmap.
  30307. */
  30308. VertexData.CreateGroundFromHeightMap = function (options) {
  30309. var indices = [];
  30310. var positions = [];
  30311. var normals = [];
  30312. var uvs = [];
  30313. var row, col;
  30314. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30315. // Vertices
  30316. for (row = 0; row <= options.subdivisions; row++) {
  30317. for (col = 0; col <= options.subdivisions; col++) {
  30318. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  30319. // Compute height
  30320. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30321. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30322. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30323. var r = options.buffer[pos] / 255.0;
  30324. var g = options.buffer[pos + 1] / 255.0;
  30325. var b = options.buffer[pos + 2] / 255.0;
  30326. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30327. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30328. // Add vertex
  30329. positions.push(position.x, position.y, position.z);
  30330. normals.push(0, 0, 0);
  30331. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30332. }
  30333. }
  30334. // Indices
  30335. for (row = 0; row < options.subdivisions; row++) {
  30336. for (col = 0; col < options.subdivisions; col++) {
  30337. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30338. indices.push(col + 1 + row * (options.subdivisions + 1));
  30339. indices.push(col + row * (options.subdivisions + 1));
  30340. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30341. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30342. indices.push(col + row * (options.subdivisions + 1));
  30343. }
  30344. }
  30345. // Normals
  30346. VertexData.ComputeNormals(positions, indices, normals);
  30347. // Result
  30348. var vertexData = new VertexData();
  30349. vertexData.indices = indices;
  30350. vertexData.positions = positions;
  30351. vertexData.normals = normals;
  30352. vertexData.uvs = uvs;
  30353. return vertexData;
  30354. };
  30355. /**
  30356. * Creates the VertexData of the Plane.
  30357. */
  30358. VertexData.CreatePlane = function (options) {
  30359. var indices = [];
  30360. var positions = [];
  30361. var normals = [];
  30362. var uvs = [];
  30363. var width = options.width || options.size || 1;
  30364. var height = options.height || options.size || 1;
  30365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30366. // Vertices
  30367. var halfWidth = width / 2.0;
  30368. var halfHeight = height / 2.0;
  30369. positions.push(-halfWidth, -halfHeight, 0);
  30370. normals.push(0, 0, -1.0);
  30371. uvs.push(0.0, 0.0);
  30372. positions.push(halfWidth, -halfHeight, 0);
  30373. normals.push(0, 0, -1.0);
  30374. uvs.push(1.0, 0.0);
  30375. positions.push(halfWidth, halfHeight, 0);
  30376. normals.push(0, 0, -1.0);
  30377. uvs.push(1.0, 1.0);
  30378. positions.push(-halfWidth, halfHeight, 0);
  30379. normals.push(0, 0, -1.0);
  30380. uvs.push(0.0, 1.0);
  30381. // Indices
  30382. indices.push(0);
  30383. indices.push(1);
  30384. indices.push(2);
  30385. indices.push(0);
  30386. indices.push(2);
  30387. indices.push(3);
  30388. // Sides
  30389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30390. // Result
  30391. var vertexData = new VertexData();
  30392. vertexData.indices = indices;
  30393. vertexData.positions = positions;
  30394. vertexData.normals = normals;
  30395. vertexData.uvs = uvs;
  30396. return vertexData;
  30397. };
  30398. /**
  30399. * Creates the VertexData of the Disc or regular Polygon.
  30400. */
  30401. VertexData.CreateDisc = function (options) {
  30402. var positions = new Array();
  30403. var indices = new Array();
  30404. var normals = new Array();
  30405. var uvs = new Array();
  30406. var radius = options.radius || 0.5;
  30407. var tessellation = options.tessellation || 64;
  30408. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30410. // positions and uvs
  30411. positions.push(0, 0, 0); // disc center first
  30412. uvs.push(0.5, 0.5);
  30413. var theta = Math.PI * 2 * arc;
  30414. var step = theta / tessellation;
  30415. for (var a = 0; a < theta; a += step) {
  30416. var x = Math.cos(a);
  30417. var y = Math.sin(a);
  30418. var u = (x + 1) / 2;
  30419. var v = (1 - y) / 2;
  30420. positions.push(radius * x, radius * y, 0);
  30421. uvs.push(u, v);
  30422. }
  30423. if (arc === 1) {
  30424. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30425. uvs.push(uvs[2], uvs[3]);
  30426. }
  30427. //indices
  30428. var vertexNb = positions.length / 3;
  30429. for (var i = 1; i < vertexNb - 1; i++) {
  30430. indices.push(i + 1, 0, i);
  30431. }
  30432. // result
  30433. VertexData.ComputeNormals(positions, indices, normals);
  30434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30435. var vertexData = new VertexData();
  30436. vertexData.indices = indices;
  30437. vertexData.positions = positions;
  30438. vertexData.normals = normals;
  30439. vertexData.uvs = uvs;
  30440. return vertexData;
  30441. };
  30442. /**
  30443. * Re-creates the VertexData of the Polygon for sideOrientation.
  30444. */
  30445. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30446. var faceUV = fUV || new Array(3);
  30447. var faceColors = fColors;
  30448. var colors = [];
  30449. // default face colors and UV if undefined
  30450. for (var f = 0; f < 3; f++) {
  30451. if (faceUV[f] === undefined) {
  30452. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30453. }
  30454. if (faceColors && faceColors[f] === undefined) {
  30455. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30456. }
  30457. }
  30458. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30459. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30460. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30461. var indices = polygon.getIndices();
  30462. // set face colours and textures
  30463. var idx = 0;
  30464. var face = 0;
  30465. for (var index = 0; index < normals.length; index += 3) {
  30466. //Edge Face no. 1
  30467. if (Math.abs(normals[index + 1]) < 0.001) {
  30468. face = 1;
  30469. }
  30470. //Top Face no. 0
  30471. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30472. face = 0;
  30473. }
  30474. //Bottom Face no. 2
  30475. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30476. face = 2;
  30477. }
  30478. idx = index / 3;
  30479. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30480. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30481. if (faceColors) {
  30482. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30483. }
  30484. }
  30485. // sides
  30486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30487. // Result
  30488. var vertexData = new VertexData();
  30489. vertexData.indices = indices;
  30490. vertexData.positions = positions;
  30491. vertexData.normals = normals;
  30492. vertexData.uvs = uvs;
  30493. if (faceColors) {
  30494. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30495. vertexData.colors = totalColors;
  30496. }
  30497. return vertexData;
  30498. };
  30499. /**
  30500. * Creates the VertexData of the IcoSphere.
  30501. */
  30502. VertexData.CreateIcoSphere = function (options) {
  30503. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30504. var radius = options.radius || 1;
  30505. var flat = (options.flat === undefined) ? true : options.flat;
  30506. var subdivisions = options.subdivisions || 4;
  30507. var radiusX = options.radiusX || radius;
  30508. var radiusY = options.radiusY || radius;
  30509. var radiusZ = options.radiusZ || radius;
  30510. var t = (1 + Math.sqrt(5)) / 2;
  30511. // 12 vertex x,y,z
  30512. var ico_vertices = [
  30513. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30514. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30515. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30516. ];
  30517. // index of 3 vertex makes a face of icopshere
  30518. var ico_indices = [
  30519. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30520. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30521. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30522. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30523. ];
  30524. // vertex for uv have aliased position, not for UV
  30525. var vertices_unalias_id = [
  30526. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30527. // vertex alias
  30528. 0,
  30529. 2,
  30530. 3,
  30531. 3,
  30532. 3,
  30533. 4,
  30534. 7,
  30535. 8,
  30536. 9,
  30537. 9,
  30538. 10,
  30539. 11 // 23: B + 12
  30540. ];
  30541. // uv as integer step (not pixels !)
  30542. var ico_vertexuv = [
  30543. 5, 1, 3, 1, 6, 4, 0, 0,
  30544. 5, 3, 4, 2, 2, 2, 4, 0,
  30545. 2, 0, 1, 1, 6, 0, 6, 2,
  30546. // vertex alias (for same vertex on different faces)
  30547. 0, 4,
  30548. 3, 3,
  30549. 4, 4,
  30550. 3, 1,
  30551. 4, 2,
  30552. 4, 4,
  30553. 0, 2,
  30554. 1, 1,
  30555. 2, 2,
  30556. 3, 3,
  30557. 1, 3,
  30558. 2, 4 // 23: B + 12
  30559. ];
  30560. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30561. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30562. // First island of uv mapping
  30563. // v = 4h 3+ 2
  30564. // v = 3h 9+ 4
  30565. // v = 2h 9+ 5 B
  30566. // v = 1h 9 1 0
  30567. // v = 0h 3 8 7 A
  30568. // u = 0 1 2 3 4 5 6 *a
  30569. // Second island of uv mapping
  30570. // v = 4h 0+ B+ 4+
  30571. // v = 3h A+ 2+
  30572. // v = 2h 7+ 6 3+
  30573. // v = 1h 8+ 3+
  30574. // v = 0h
  30575. // u = 0 1 2 3 4 5 6 *a
  30576. // Face layout on texture UV mapping
  30577. // ============
  30578. // \ 4 /\ 16 / ======
  30579. // \ / \ / /\ 11 /
  30580. // \/ 7 \/ / \ /
  30581. // ======= / 10 \/
  30582. // /\ 17 /\ =======
  30583. // / \ / \ \ 15 /\
  30584. // / 8 \/ 12 \ \ / \
  30585. // ============ \/ 6 \
  30586. // \ 18 /\ ============
  30587. // \ / \ \ 5 /\ 0 /
  30588. // \/ 13 \ \ / \ /
  30589. // ======= \/ 1 \/
  30590. // =============
  30591. // /\ 19 /\ 2 /\
  30592. // / \ / \ / \
  30593. // / 14 \/ 9 \/ 3 \
  30594. // ===================
  30595. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30596. var ustep = 138 / 1024;
  30597. var vstep = 239 / 1024;
  30598. var uoffset = 60 / 1024;
  30599. var voffset = 26 / 1024;
  30600. // Second island should have margin, not to touch the first island
  30601. // avoid any borderline artefact in pixel rounding
  30602. var island_u_offset = -40 / 1024;
  30603. var island_v_offset = +20 / 1024;
  30604. // face is either island 0 or 1 :
  30605. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30606. var island = [
  30607. 0, 0, 0, 0, 1,
  30608. 0, 0, 1, 1, 0,
  30609. 0, 0, 1, 1, 0,
  30610. 0, 1, 1, 1, 0 // 15 - 19
  30611. ];
  30612. var indices = new Array();
  30613. var positions = new Array();
  30614. var normals = new Array();
  30615. var uvs = new Array();
  30616. var current_indice = 0;
  30617. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30618. var face_vertex_pos = new Array(3);
  30619. var face_vertex_uv = new Array(3);
  30620. var v012;
  30621. for (v012 = 0; v012 < 3; v012++) {
  30622. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30623. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30624. }
  30625. // create all with normals
  30626. for (var face = 0; face < 20; face++) {
  30627. // 3 vertex per face
  30628. for (v012 = 0; v012 < 3; v012++) {
  30629. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30630. var v_id = ico_indices[3 * face + v012];
  30631. // vertex have 3D position (x,y,z)
  30632. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  30633. // Normalize to get normal, then scale to radius
  30634. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30635. // uv Coordinates from vertex ID
  30636. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  30637. }
  30638. // Subdivide the face (interpolate pos, norm, uv)
  30639. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30640. // - norm is linear interpolation of vertex corner normal
  30641. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30642. // - uv is linear interpolation
  30643. //
  30644. // Topology is as below for sub-divide by 2
  30645. // vertex shown as v0,v1,v2
  30646. // interp index is i1 to progress in range [v0,v1[
  30647. // interp index is i2 to progress in range [v0,v2[
  30648. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30649. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30650. //
  30651. //
  30652. // i2 v2
  30653. // ^ ^
  30654. // / / \
  30655. // / / \
  30656. // / / \
  30657. // / / (0,1) \
  30658. // / #---------\
  30659. // / / \ (0,0)'/ \
  30660. // / / \ / \
  30661. // / / \ / \
  30662. // / / (0,0) \ / (1,0) \
  30663. // / #---------#---------\
  30664. // v0 v1
  30665. //
  30666. // --------------------> i1
  30667. //
  30668. // interp of (i1,i2):
  30669. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30670. // along i1 : lerp(x0,x1, i1/(S-i2))
  30671. //
  30672. // centroid of triangle is needed to get help normal computation
  30673. // (c1,c2) are used for centroid location
  30674. var interp_vertex = function (i1, i2, c1, c2) {
  30675. // vertex is interpolated from
  30676. // - face_vertex_pos[0..2]
  30677. // - face_vertex_uv[0..2]
  30678. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30679. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30680. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30681. pos_interp.normalize();
  30682. var vertex_normal;
  30683. if (flat) {
  30684. // in flat mode, recalculate normal as face centroid normal
  30685. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30686. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30687. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30688. }
  30689. else {
  30690. // in smooth mode, recalculate normal from each single vertex position
  30691. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30692. }
  30693. // Vertex normal need correction due to X,Y,Z radius scaling
  30694. vertex_normal.x /= radiusX;
  30695. vertex_normal.y /= radiusY;
  30696. vertex_normal.z /= radiusZ;
  30697. vertex_normal.normalize();
  30698. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30699. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30700. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30701. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30702. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30703. uvs.push(uv_interp.x, uv_interp.y);
  30704. // push each vertex has member of a face
  30705. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30706. indices.push(current_indice);
  30707. current_indice++;
  30708. };
  30709. for (var i2 = 0; i2 < subdivisions; i2++) {
  30710. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30711. // face : (i1,i2) for /\ :
  30712. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30713. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30714. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30715. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30716. if (i1 + i2 + 1 < subdivisions) {
  30717. // face : (i1,i2)' for \/ :
  30718. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30719. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30720. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30721. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30722. }
  30723. }
  30724. }
  30725. }
  30726. // Sides
  30727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30728. // Result
  30729. var vertexData = new VertexData();
  30730. vertexData.indices = indices;
  30731. vertexData.positions = positions;
  30732. vertexData.normals = normals;
  30733. vertexData.uvs = uvs;
  30734. return vertexData;
  30735. };
  30736. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30737. /**
  30738. * Creates the VertexData of the Polyhedron.
  30739. */
  30740. VertexData.CreatePolyhedron = function (options) {
  30741. // provided polyhedron types :
  30742. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30743. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  30744. var polyhedra = [];
  30745. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  30746. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  30747. polyhedra[2] = {
  30748. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  30749. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  30750. };
  30751. polyhedra[3] = {
  30752. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  30753. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  30754. };
  30755. polyhedra[4] = {
  30756. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  30757. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  30758. };
  30759. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  30760. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  30761. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  30762. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  30763. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  30764. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  30765. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  30766. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  30767. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  30768. polyhedra[14] = {
  30769. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  30770. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  30771. };
  30772. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30773. var size = options.size;
  30774. var sizeX = options.sizeX || size || 1;
  30775. var sizeY = options.sizeY || size || 1;
  30776. var sizeZ = options.sizeZ || size || 1;
  30777. var data = options.custom || polyhedra[type];
  30778. var nbfaces = data.face.length;
  30779. var faceUV = options.faceUV || new Array(nbfaces);
  30780. var faceColors = options.faceColors;
  30781. var flat = (options.flat === undefined) ? true : options.flat;
  30782. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30783. var positions = new Array();
  30784. var indices = new Array();
  30785. var normals = new Array();
  30786. var uvs = new Array();
  30787. var colors = new Array();
  30788. var index = 0;
  30789. var faceIdx = 0; // face cursor in the array "indexes"
  30790. var indexes = new Array();
  30791. var i = 0;
  30792. var f = 0;
  30793. var u, v, ang, x, y, tmp;
  30794. // default face colors and UV if undefined
  30795. if (flat) {
  30796. for (f = 0; f < nbfaces; f++) {
  30797. if (faceColors && faceColors[f] === undefined) {
  30798. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30799. }
  30800. if (faceUV && faceUV[f] === undefined) {
  30801. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30802. }
  30803. }
  30804. }
  30805. if (!flat) {
  30806. for (i = 0; i < data.vertex.length; i++) {
  30807. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30808. uvs.push(0, 0);
  30809. }
  30810. for (f = 0; f < nbfaces; f++) {
  30811. for (i = 0; i < data.face[f].length - 2; i++) {
  30812. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30813. }
  30814. }
  30815. }
  30816. else {
  30817. for (f = 0; f < nbfaces; f++) {
  30818. var fl = data.face[f].length; // number of vertices of the current face
  30819. ang = 2 * Math.PI / fl;
  30820. x = 0.5 * Math.tan(ang / 2);
  30821. y = 0.5;
  30822. // positions, uvs, colors
  30823. for (i = 0; i < fl; i++) {
  30824. // positions
  30825. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  30826. indexes.push(index);
  30827. index++;
  30828. // uvs
  30829. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30830. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30831. uvs.push(u, v);
  30832. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30833. y = x * Math.sin(ang) + y * Math.cos(ang);
  30834. x = tmp;
  30835. // colors
  30836. if (faceColors) {
  30837. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30838. }
  30839. }
  30840. // indices from indexes
  30841. for (i = 0; i < fl - 2; i++) {
  30842. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30843. }
  30844. faceIdx += fl;
  30845. }
  30846. }
  30847. VertexData.ComputeNormals(positions, indices, normals);
  30848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30849. var vertexData = new VertexData();
  30850. vertexData.positions = positions;
  30851. vertexData.indices = indices;
  30852. vertexData.normals = normals;
  30853. vertexData.uvs = uvs;
  30854. if (faceColors && flat) {
  30855. vertexData.colors = colors;
  30856. }
  30857. return vertexData;
  30858. };
  30859. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30860. /**
  30861. * Creates the VertexData of the Torus Knot.
  30862. */
  30863. VertexData.CreateTorusKnot = function (options) {
  30864. var indices = new Array();
  30865. var positions = new Array();
  30866. var normals = new Array();
  30867. var uvs = new Array();
  30868. var radius = options.radius || 2;
  30869. var tube = options.tube || 0.5;
  30870. var radialSegments = options.radialSegments || 32;
  30871. var tubularSegments = options.tubularSegments || 32;
  30872. var p = options.p || 2;
  30873. var q = options.q || 3;
  30874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30875. // Helper
  30876. var getPos = function (angle) {
  30877. var cu = Math.cos(angle);
  30878. var su = Math.sin(angle);
  30879. var quOverP = q / p * angle;
  30880. var cs = Math.cos(quOverP);
  30881. var tx = radius * (2 + cs) * 0.5 * cu;
  30882. var ty = radius * (2 + cs) * su * 0.5;
  30883. var tz = radius * Math.sin(quOverP) * 0.5;
  30884. return new BABYLON.Vector3(tx, ty, tz);
  30885. };
  30886. // Vertices
  30887. var i;
  30888. var j;
  30889. for (i = 0; i <= radialSegments; i++) {
  30890. var modI = i % radialSegments;
  30891. var u = modI / radialSegments * 2 * p * Math.PI;
  30892. var p1 = getPos(u);
  30893. var p2 = getPos(u + 0.01);
  30894. var tang = p2.subtract(p1);
  30895. var n = p2.add(p1);
  30896. var bitan = BABYLON.Vector3.Cross(tang, n);
  30897. n = BABYLON.Vector3.Cross(bitan, tang);
  30898. bitan.normalize();
  30899. n.normalize();
  30900. for (j = 0; j < tubularSegments; j++) {
  30901. var modJ = j % tubularSegments;
  30902. var v = modJ / tubularSegments * 2 * Math.PI;
  30903. var cx = -tube * Math.cos(v);
  30904. var cy = tube * Math.sin(v);
  30905. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30906. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30907. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30908. uvs.push(i / radialSegments);
  30909. uvs.push(j / tubularSegments);
  30910. }
  30911. }
  30912. for (i = 0; i < radialSegments; i++) {
  30913. for (j = 0; j < tubularSegments; j++) {
  30914. var jNext = (j + 1) % tubularSegments;
  30915. var a = i * tubularSegments + j;
  30916. var b = (i + 1) * tubularSegments + j;
  30917. var c = (i + 1) * tubularSegments + jNext;
  30918. var d = i * tubularSegments + jNext;
  30919. indices.push(d);
  30920. indices.push(b);
  30921. indices.push(a);
  30922. indices.push(d);
  30923. indices.push(c);
  30924. indices.push(b);
  30925. }
  30926. }
  30927. // Normals
  30928. VertexData.ComputeNormals(positions, indices, normals);
  30929. // Sides
  30930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30931. // Result
  30932. var vertexData = new VertexData();
  30933. vertexData.indices = indices;
  30934. vertexData.positions = positions;
  30935. vertexData.normals = normals;
  30936. vertexData.uvs = uvs;
  30937. return vertexData;
  30938. };
  30939. // Tools
  30940. /**
  30941. * @param {any} - positions (number[] or Float32Array)
  30942. * @param {any} - indices (number[] or Uint16Array)
  30943. * @param {any} - normals (number[] or Float32Array)
  30944. * options (optional) :
  30945. * facetPositions : optional array of facet positions (vector3)
  30946. * facetNormals : optional array of facet normals (vector3)
  30947. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30948. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30949. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30950. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30951. * bInfo : optional bounding info, required for facetPartitioning computation
  30952. * useRightHandedSystem: optional boolean to for right handed system computation
  30953. * depthSort : optional boolean to enable the facet depth sort computation
  30954. * distanceTo : optional Vector3 to compute the facet depth from this location
  30955. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30956. */
  30957. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30958. // temporary scalar variables
  30959. var index = 0; // facet index
  30960. var p1p2x = 0.0; // p1p2 vector x coordinate
  30961. var p1p2y = 0.0; // p1p2 vector y coordinate
  30962. var p1p2z = 0.0; // p1p2 vector z coordinate
  30963. var p3p2x = 0.0; // p3p2 vector x coordinate
  30964. var p3p2y = 0.0; // p3p2 vector y coordinate
  30965. var p3p2z = 0.0; // p3p2 vector z coordinate
  30966. var faceNormalx = 0.0; // facet normal x coordinate
  30967. var faceNormaly = 0.0; // facet normal y coordinate
  30968. var faceNormalz = 0.0; // facet normal z coordinate
  30969. var length = 0.0; // facet normal length before normalization
  30970. var v1x = 0; // vector1 x index in the positions array
  30971. var v1y = 0; // vector1 y index in the positions array
  30972. var v1z = 0; // vector1 z index in the positions array
  30973. var v2x = 0; // vector2 x index in the positions array
  30974. var v2y = 0; // vector2 y index in the positions array
  30975. var v2z = 0; // vector2 z index in the positions array
  30976. var v3x = 0; // vector3 x index in the positions array
  30977. var v3y = 0; // vector3 y index in the positions array
  30978. var v3z = 0; // vector3 z index in the positions array
  30979. var computeFacetNormals = false;
  30980. var computeFacetPositions = false;
  30981. var computeFacetPartitioning = false;
  30982. var computeDepthSort = false;
  30983. var faceNormalSign = 1;
  30984. var ratio = 0;
  30985. var distanceTo = null;
  30986. if (options) {
  30987. computeFacetNormals = (options.facetNormals) ? true : false;
  30988. computeFacetPositions = (options.facetPositions) ? true : false;
  30989. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30990. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30991. ratio = options.ratio || 0;
  30992. computeDepthSort = (options.depthSort) ? true : false;
  30993. distanceTo = (options.distanceTo);
  30994. if (computeDepthSort) {
  30995. if (distanceTo === undefined) {
  30996. distanceTo = BABYLON.Vector3.Zero();
  30997. }
  30998. var depthSortedFacets = options.depthSortedFacets;
  30999. }
  31000. }
  31001. // facetPartitioning reinit if needed
  31002. var xSubRatio = 0;
  31003. var ySubRatio = 0;
  31004. var zSubRatio = 0;
  31005. var subSq = 0;
  31006. if (computeFacetPartitioning && options && options.bbSize) {
  31007. var ox = 0; // X partitioning index for facet position
  31008. var oy = 0; // Y partinioning index for facet position
  31009. var oz = 0; // Z partinioning index for facet position
  31010. var b1x = 0; // X partitioning index for facet v1 vertex
  31011. var b1y = 0; // Y partitioning index for facet v1 vertex
  31012. var b1z = 0; // z partitioning index for facet v1 vertex
  31013. var b2x = 0; // X partitioning index for facet v2 vertex
  31014. var b2y = 0; // Y partitioning index for facet v2 vertex
  31015. var b2z = 0; // Z partitioning index for facet v2 vertex
  31016. var b3x = 0; // X partitioning index for facet v3 vertex
  31017. var b3y = 0; // Y partitioning index for facet v3 vertex
  31018. var b3z = 0; // Z partitioning index for facet v3 vertex
  31019. var block_idx_o = 0; // facet barycenter block index
  31020. var block_idx_v1 = 0; // v1 vertex block index
  31021. var block_idx_v2 = 0; // v2 vertex block index
  31022. var block_idx_v3 = 0; // v3 vertex block index
  31023. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31024. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31025. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31026. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31027. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31028. subSq = options.subDiv.max * options.subDiv.max;
  31029. options.facetPartitioning.length = 0;
  31030. }
  31031. // reset the normals
  31032. for (index = 0; index < positions.length; index++) {
  31033. normals[index] = 0.0;
  31034. }
  31035. // Loop : 1 indice triplet = 1 facet
  31036. var nbFaces = (indices.length / 3) | 0;
  31037. for (index = 0; index < nbFaces; index++) {
  31038. // get the indexes of the coordinates of each vertex of the facet
  31039. v1x = indices[index * 3] * 3;
  31040. v1y = v1x + 1;
  31041. v1z = v1x + 2;
  31042. v2x = indices[index * 3 + 1] * 3;
  31043. v2y = v2x + 1;
  31044. v2z = v2x + 2;
  31045. v3x = indices[index * 3 + 2] * 3;
  31046. v3y = v3x + 1;
  31047. v3z = v3x + 2;
  31048. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31049. p1p2y = positions[v1y] - positions[v2y];
  31050. p1p2z = positions[v1z] - positions[v2z];
  31051. p3p2x = positions[v3x] - positions[v2x];
  31052. p3p2y = positions[v3y] - positions[v2y];
  31053. p3p2z = positions[v3z] - positions[v2z];
  31054. // compute the face normal with the cross product
  31055. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31056. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31057. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31058. // normalize this normal and store it in the array facetData
  31059. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31060. length = (length === 0) ? 1.0 : length;
  31061. faceNormalx /= length;
  31062. faceNormaly /= length;
  31063. faceNormalz /= length;
  31064. if (computeFacetNormals && options) {
  31065. options.facetNormals[index].x = faceNormalx;
  31066. options.facetNormals[index].y = faceNormaly;
  31067. options.facetNormals[index].z = faceNormalz;
  31068. }
  31069. if (computeFacetPositions && options) {
  31070. // compute and the facet barycenter coordinates in the array facetPositions
  31071. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31072. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31073. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31074. }
  31075. if (computeFacetPartitioning && options) {
  31076. // store the facet indexes in arrays in the main facetPartitioning array :
  31077. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31078. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31079. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31080. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31081. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31082. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31083. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31084. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31085. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31086. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31087. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31088. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31089. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31090. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31091. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31092. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31093. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31094. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31095. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31096. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31097. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31098. // push each facet index in each block containing the vertex
  31099. options.facetPartitioning[block_idx_v1].push(index);
  31100. if (block_idx_v2 != block_idx_v1) {
  31101. options.facetPartitioning[block_idx_v2].push(index);
  31102. }
  31103. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31104. options.facetPartitioning[block_idx_v3].push(index);
  31105. }
  31106. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31107. options.facetPartitioning[block_idx_o].push(index);
  31108. }
  31109. }
  31110. if (computeDepthSort && options && options.facetPositions) {
  31111. var dsf = depthSortedFacets[index];
  31112. dsf.ind = index * 3;
  31113. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31114. }
  31115. // compute the normals anyway
  31116. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31117. normals[v1y] += faceNormaly;
  31118. normals[v1z] += faceNormalz;
  31119. normals[v2x] += faceNormalx;
  31120. normals[v2y] += faceNormaly;
  31121. normals[v2z] += faceNormalz;
  31122. normals[v3x] += faceNormalx;
  31123. normals[v3y] += faceNormaly;
  31124. normals[v3z] += faceNormalz;
  31125. }
  31126. // last normalization of each normal
  31127. for (index = 0; index < normals.length / 3; index++) {
  31128. faceNormalx = normals[index * 3];
  31129. faceNormaly = normals[index * 3 + 1];
  31130. faceNormalz = normals[index * 3 + 2];
  31131. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31132. length = (length === 0) ? 1.0 : length;
  31133. faceNormalx /= length;
  31134. faceNormaly /= length;
  31135. faceNormalz /= length;
  31136. normals[index * 3] = faceNormalx;
  31137. normals[index * 3 + 1] = faceNormaly;
  31138. normals[index * 3 + 2] = faceNormalz;
  31139. }
  31140. };
  31141. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31142. var li = indices.length;
  31143. var ln = normals.length;
  31144. var i;
  31145. var n;
  31146. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31147. switch (sideOrientation) {
  31148. case BABYLON.Mesh.FRONTSIDE:
  31149. // nothing changed
  31150. break;
  31151. case BABYLON.Mesh.BACKSIDE:
  31152. var tmp;
  31153. // indices
  31154. for (i = 0; i < li; i += 3) {
  31155. tmp = indices[i];
  31156. indices[i] = indices[i + 2];
  31157. indices[i + 2] = tmp;
  31158. }
  31159. // normals
  31160. for (n = 0; n < ln; n++) {
  31161. normals[n] = -normals[n];
  31162. }
  31163. break;
  31164. case BABYLON.Mesh.DOUBLESIDE:
  31165. // positions
  31166. var lp = positions.length;
  31167. var l = lp / 3;
  31168. for (var p = 0; p < lp; p++) {
  31169. positions[lp + p] = positions[p];
  31170. }
  31171. // indices
  31172. for (i = 0; i < li; i += 3) {
  31173. indices[i + li] = indices[i + 2] + l;
  31174. indices[i + 1 + li] = indices[i + 1] + l;
  31175. indices[i + 2 + li] = indices[i] + l;
  31176. }
  31177. // normals
  31178. for (n = 0; n < ln; n++) {
  31179. normals[ln + n] = -normals[n];
  31180. }
  31181. // uvs
  31182. var lu = uvs.length;
  31183. var u = 0;
  31184. for (u = 0; u < lu; u++) {
  31185. uvs[u + lu] = uvs[u];
  31186. }
  31187. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31188. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31189. u = 0;
  31190. for (i = 0; i < lu / 2; i++) {
  31191. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31192. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31193. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31194. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31195. u += 2;
  31196. }
  31197. break;
  31198. }
  31199. };
  31200. /**
  31201. * Creates a new VertexData from the imported parameters.
  31202. */
  31203. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31204. var vertexData = new VertexData();
  31205. // positions
  31206. var positions = parsedVertexData.positions;
  31207. if (positions) {
  31208. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31209. }
  31210. // normals
  31211. var normals = parsedVertexData.normals;
  31212. if (normals) {
  31213. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31214. }
  31215. // tangents
  31216. var tangents = parsedVertexData.tangents;
  31217. if (tangents) {
  31218. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31219. }
  31220. // uvs
  31221. var uvs = parsedVertexData.uvs;
  31222. if (uvs) {
  31223. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31224. }
  31225. // uv2s
  31226. var uv2s = parsedVertexData.uv2s;
  31227. if (uv2s) {
  31228. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31229. }
  31230. // uv3s
  31231. var uv3s = parsedVertexData.uv3s;
  31232. if (uv3s) {
  31233. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31234. }
  31235. // uv4s
  31236. var uv4s = parsedVertexData.uv4s;
  31237. if (uv4s) {
  31238. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31239. }
  31240. // uv5s
  31241. var uv5s = parsedVertexData.uv5s;
  31242. if (uv5s) {
  31243. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31244. }
  31245. // uv6s
  31246. var uv6s = parsedVertexData.uv6s;
  31247. if (uv6s) {
  31248. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31249. }
  31250. // colors
  31251. var colors = parsedVertexData.colors;
  31252. if (colors) {
  31253. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31254. }
  31255. // matricesIndices
  31256. var matricesIndices = parsedVertexData.matricesIndices;
  31257. if (matricesIndices) {
  31258. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31259. }
  31260. // matricesWeights
  31261. var matricesWeights = parsedVertexData.matricesWeights;
  31262. if (matricesWeights) {
  31263. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31264. }
  31265. // indices
  31266. var indices = parsedVertexData.indices;
  31267. if (indices) {
  31268. vertexData.indices = indices;
  31269. }
  31270. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31271. };
  31272. return VertexData;
  31273. }());
  31274. BABYLON.VertexData = VertexData;
  31275. })(BABYLON || (BABYLON = {}));
  31276. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31277. var BABYLON;
  31278. (function (BABYLON) {
  31279. var Geometry = /** @class */ (function () {
  31280. function Geometry(id, scene, vertexData, updatable, mesh) {
  31281. if (updatable === void 0) { updatable = false; }
  31282. if (mesh === void 0) { mesh = null; }
  31283. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31284. this._totalVertices = 0;
  31285. this._isDisposed = false;
  31286. this._indexBufferIsUpdatable = false;
  31287. this.id = id;
  31288. this._engine = scene.getEngine();
  31289. this._meshes = [];
  31290. this._scene = scene;
  31291. //Init vertex buffer cache
  31292. this._vertexBuffers = {};
  31293. this._indices = [];
  31294. this._updatable = updatable;
  31295. // vertexData
  31296. if (vertexData) {
  31297. this.setAllVerticesData(vertexData, updatable);
  31298. }
  31299. else {
  31300. this._totalVertices = 0;
  31301. this._indices = [];
  31302. }
  31303. if (this._engine.getCaps().vertexArrayObject) {
  31304. this._vertexArrayObjects = {};
  31305. }
  31306. // applyToMesh
  31307. if (mesh) {
  31308. if (mesh.getClassName() === "LinesMesh") {
  31309. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31310. this.updateExtend();
  31311. }
  31312. this.applyToMesh(mesh);
  31313. mesh.computeWorldMatrix(true);
  31314. }
  31315. }
  31316. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31317. /**
  31318. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  31319. * @returns The Bias Vector
  31320. */
  31321. get: function () {
  31322. return this._boundingBias;
  31323. },
  31324. set: function (value) {
  31325. if (this._boundingBias && this._boundingBias.equals(value)) {
  31326. return;
  31327. }
  31328. this._boundingBias = value.clone();
  31329. this.updateBoundingInfo(true, null);
  31330. },
  31331. enumerable: true,
  31332. configurable: true
  31333. });
  31334. Geometry.CreateGeometryForMesh = function (mesh) {
  31335. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31336. geometry.applyToMesh(mesh);
  31337. return geometry;
  31338. };
  31339. Object.defineProperty(Geometry.prototype, "extend", {
  31340. get: function () {
  31341. return this._extend;
  31342. },
  31343. enumerable: true,
  31344. configurable: true
  31345. });
  31346. Geometry.prototype.getScene = function () {
  31347. return this._scene;
  31348. };
  31349. Geometry.prototype.getEngine = function () {
  31350. return this._engine;
  31351. };
  31352. Geometry.prototype.isReady = function () {
  31353. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31354. };
  31355. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31356. get: function () {
  31357. for (var index = 0; index < this._meshes.length; index++) {
  31358. if (!this._meshes[index].doNotSerialize) {
  31359. return false;
  31360. }
  31361. }
  31362. return true;
  31363. },
  31364. enumerable: true,
  31365. configurable: true
  31366. });
  31367. Geometry.prototype._rebuild = function () {
  31368. if (this._vertexArrayObjects) {
  31369. this._vertexArrayObjects = {};
  31370. }
  31371. // Index buffer
  31372. if (this._meshes.length !== 0 && this._indices) {
  31373. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31374. }
  31375. // Vertex buffers
  31376. for (var key in this._vertexBuffers) {
  31377. var vertexBuffer = this._vertexBuffers[key];
  31378. vertexBuffer._rebuild();
  31379. }
  31380. };
  31381. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31382. vertexData.applyToGeometry(this, updatable);
  31383. this.notifyUpdate();
  31384. };
  31385. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31386. if (updatable === void 0) { updatable = false; }
  31387. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31388. this.setVerticesBuffer(buffer);
  31389. };
  31390. Geometry.prototype.removeVerticesData = function (kind) {
  31391. if (this._vertexBuffers[kind]) {
  31392. this._vertexBuffers[kind].dispose();
  31393. delete this._vertexBuffers[kind];
  31394. }
  31395. };
  31396. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31397. var kind = buffer.getKind();
  31398. if (this._vertexBuffers[kind]) {
  31399. this._vertexBuffers[kind].dispose();
  31400. }
  31401. this._vertexBuffers[kind] = buffer;
  31402. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31403. var data = buffer.getData();
  31404. var stride = buffer.getStrideSize();
  31405. this._totalVertices = data.length / stride;
  31406. this.updateExtend(data, stride);
  31407. this._resetPointsArrayCache();
  31408. var meshes = this._meshes;
  31409. var numOfMeshes = meshes.length;
  31410. for (var index = 0; index < numOfMeshes; index++) {
  31411. var mesh = meshes[index];
  31412. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31413. mesh._createGlobalSubMesh(false);
  31414. mesh.computeWorldMatrix(true);
  31415. }
  31416. }
  31417. this.notifyUpdate(kind);
  31418. if (this._vertexArrayObjects) {
  31419. this._disposeVertexArrayObjects();
  31420. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31421. }
  31422. };
  31423. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31424. var vertexBuffer = this.getVertexBuffer(kind);
  31425. if (!vertexBuffer) {
  31426. return;
  31427. }
  31428. vertexBuffer.updateDirectly(data, offset);
  31429. this.notifyUpdate(kind);
  31430. };
  31431. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31432. if (updateExtends === void 0) { updateExtends = false; }
  31433. var vertexBuffer = this.getVertexBuffer(kind);
  31434. if (!vertexBuffer) {
  31435. return;
  31436. }
  31437. vertexBuffer.update(data);
  31438. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31439. var stride = vertexBuffer.getStrideSize();
  31440. this._totalVertices = data.length / stride;
  31441. this.updateBoundingInfo(updateExtends, data);
  31442. }
  31443. this.notifyUpdate(kind);
  31444. };
  31445. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31446. if (updateExtends) {
  31447. this.updateExtend(data);
  31448. }
  31449. var meshes = this._meshes;
  31450. var numOfMeshes = meshes.length;
  31451. this._resetPointsArrayCache();
  31452. for (var index = 0; index < numOfMeshes; index++) {
  31453. var mesh = meshes[index];
  31454. if (updateExtends) {
  31455. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31457. var subMesh = mesh.subMeshes[subIndex];
  31458. subMesh.refreshBoundingInfo();
  31459. }
  31460. }
  31461. }
  31462. };
  31463. Geometry.prototype._bind = function (effect, indexToBind) {
  31464. if (!effect) {
  31465. return;
  31466. }
  31467. if (indexToBind === undefined) {
  31468. indexToBind = this._indexBuffer;
  31469. }
  31470. var vbs = this.getVertexBuffers();
  31471. if (!vbs) {
  31472. return;
  31473. }
  31474. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31475. this._engine.bindBuffers(vbs, indexToBind, effect);
  31476. return;
  31477. }
  31478. // Using VAO
  31479. if (!this._vertexArrayObjects[effect.key]) {
  31480. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31481. }
  31482. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31483. };
  31484. Geometry.prototype.getTotalVertices = function () {
  31485. if (!this.isReady()) {
  31486. return 0;
  31487. }
  31488. return this._totalVertices;
  31489. };
  31490. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31491. var vertexBuffer = this.getVertexBuffer(kind);
  31492. if (!vertexBuffer) {
  31493. return null;
  31494. }
  31495. var orig = vertexBuffer.getData();
  31496. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31497. return orig;
  31498. }
  31499. else {
  31500. var len = orig.length;
  31501. var copy = [];
  31502. for (var i = 0; i < len; i++) {
  31503. copy.push(orig[i]);
  31504. }
  31505. return copy;
  31506. }
  31507. };
  31508. /**
  31509. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31510. * Possible `kind` values :
  31511. * - BABYLON.VertexBuffer.PositionKind
  31512. * - BABYLON.VertexBuffer.UVKind
  31513. * - BABYLON.VertexBuffer.UV2Kind
  31514. * - BABYLON.VertexBuffer.UV3Kind
  31515. * - BABYLON.VertexBuffer.UV4Kind
  31516. * - BABYLON.VertexBuffer.UV5Kind
  31517. * - BABYLON.VertexBuffer.UV6Kind
  31518. * - BABYLON.VertexBuffer.ColorKind
  31519. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31520. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31521. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31522. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31523. */
  31524. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31525. var vb = this._vertexBuffers[kind];
  31526. if (!vb) {
  31527. return false;
  31528. }
  31529. return vb.isUpdatable();
  31530. };
  31531. Geometry.prototype.getVertexBuffer = function (kind) {
  31532. if (!this.isReady()) {
  31533. return null;
  31534. }
  31535. return this._vertexBuffers[kind];
  31536. };
  31537. Geometry.prototype.getVertexBuffers = function () {
  31538. if (!this.isReady()) {
  31539. return null;
  31540. }
  31541. return this._vertexBuffers;
  31542. };
  31543. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31544. if (!this._vertexBuffers) {
  31545. if (this._delayInfo) {
  31546. return this._delayInfo.indexOf(kind) !== -1;
  31547. }
  31548. return false;
  31549. }
  31550. return this._vertexBuffers[kind] !== undefined;
  31551. };
  31552. Geometry.prototype.getVerticesDataKinds = function () {
  31553. var result = [];
  31554. var kind;
  31555. if (!this._vertexBuffers && this._delayInfo) {
  31556. for (kind in this._delayInfo) {
  31557. result.push(kind);
  31558. }
  31559. }
  31560. else {
  31561. for (kind in this._vertexBuffers) {
  31562. result.push(kind);
  31563. }
  31564. }
  31565. return result;
  31566. };
  31567. Geometry.prototype.updateIndices = function (indices, offset) {
  31568. if (!this._indexBuffer) {
  31569. return;
  31570. }
  31571. if (!this._indexBufferIsUpdatable) {
  31572. this.setIndices(indices, null, true);
  31573. }
  31574. else {
  31575. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31576. }
  31577. };
  31578. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31579. if (totalVertices === void 0) { totalVertices = null; }
  31580. if (updatable === void 0) { updatable = false; }
  31581. if (this._indexBuffer) {
  31582. this._engine._releaseBuffer(this._indexBuffer);
  31583. }
  31584. this._disposeVertexArrayObjects();
  31585. this._indices = indices;
  31586. this._indexBufferIsUpdatable = updatable;
  31587. if (this._meshes.length !== 0 && this._indices) {
  31588. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31589. }
  31590. if (totalVertices != undefined) {
  31591. this._totalVertices = totalVertices;
  31592. }
  31593. var meshes = this._meshes;
  31594. var numOfMeshes = meshes.length;
  31595. for (var index = 0; index < numOfMeshes; index++) {
  31596. meshes[index]._createGlobalSubMesh(true);
  31597. }
  31598. this.notifyUpdate();
  31599. };
  31600. Geometry.prototype.getTotalIndices = function () {
  31601. if (!this.isReady()) {
  31602. return 0;
  31603. }
  31604. return this._indices.length;
  31605. };
  31606. Geometry.prototype.getIndices = function (copyWhenShared) {
  31607. if (!this.isReady()) {
  31608. return null;
  31609. }
  31610. var orig = this._indices;
  31611. if (!copyWhenShared || this._meshes.length === 1) {
  31612. return orig;
  31613. }
  31614. else {
  31615. var len = orig.length;
  31616. var copy = [];
  31617. for (var i = 0; i < len; i++) {
  31618. copy.push(orig[i]);
  31619. }
  31620. return copy;
  31621. }
  31622. };
  31623. Geometry.prototype.getIndexBuffer = function () {
  31624. if (!this.isReady()) {
  31625. return null;
  31626. }
  31627. return this._indexBuffer;
  31628. };
  31629. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31630. if (effect === void 0) { effect = null; }
  31631. if (!effect || !this._vertexArrayObjects) {
  31632. return;
  31633. }
  31634. if (this._vertexArrayObjects[effect.key]) {
  31635. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31636. delete this._vertexArrayObjects[effect.key];
  31637. }
  31638. };
  31639. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31640. var meshes = this._meshes;
  31641. var index = meshes.indexOf(mesh);
  31642. if (index === -1) {
  31643. return;
  31644. }
  31645. meshes.splice(index, 1);
  31646. mesh._geometry = null;
  31647. if (meshes.length === 0 && shouldDispose) {
  31648. this.dispose();
  31649. }
  31650. };
  31651. Geometry.prototype.applyToMesh = function (mesh) {
  31652. if (mesh._geometry === this) {
  31653. return;
  31654. }
  31655. var previousGeometry = mesh._geometry;
  31656. if (previousGeometry) {
  31657. previousGeometry.releaseForMesh(mesh);
  31658. }
  31659. var meshes = this._meshes;
  31660. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31661. mesh._geometry = this;
  31662. this._scene.pushGeometry(this);
  31663. meshes.push(mesh);
  31664. if (this.isReady()) {
  31665. this._applyToMesh(mesh);
  31666. }
  31667. else {
  31668. mesh._boundingInfo = this._boundingInfo;
  31669. }
  31670. };
  31671. Geometry.prototype.updateExtend = function (data, stride) {
  31672. if (data === void 0) { data = null; }
  31673. if (!data) {
  31674. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31675. }
  31676. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31677. };
  31678. Geometry.prototype._applyToMesh = function (mesh) {
  31679. var numOfMeshes = this._meshes.length;
  31680. // vertexBuffers
  31681. for (var kind in this._vertexBuffers) {
  31682. if (numOfMeshes === 1) {
  31683. this._vertexBuffers[kind].create();
  31684. }
  31685. var buffer = this._vertexBuffers[kind].getBuffer();
  31686. if (buffer)
  31687. buffer.references = numOfMeshes;
  31688. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31689. if (!this._extend) {
  31690. this.updateExtend(this._vertexBuffers[kind].getData());
  31691. }
  31692. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31693. mesh._createGlobalSubMesh(false);
  31694. //bounding info was just created again, world matrix should be applied again.
  31695. mesh._updateBoundingInfo();
  31696. }
  31697. }
  31698. // indexBuffer
  31699. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31700. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31701. }
  31702. if (this._indexBuffer) {
  31703. this._indexBuffer.references = numOfMeshes;
  31704. }
  31705. };
  31706. Geometry.prototype.notifyUpdate = function (kind) {
  31707. if (this.onGeometryUpdated) {
  31708. this.onGeometryUpdated(this, kind);
  31709. }
  31710. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31711. var mesh = _a[_i];
  31712. mesh._markSubMeshesAsAttributesDirty();
  31713. }
  31714. };
  31715. Geometry.prototype.load = function (scene, onLoaded) {
  31716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31717. return;
  31718. }
  31719. if (this.isReady()) {
  31720. if (onLoaded) {
  31721. onLoaded();
  31722. }
  31723. return;
  31724. }
  31725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31726. this._queueLoad(scene, onLoaded);
  31727. };
  31728. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31729. var _this = this;
  31730. if (!this.delayLoadingFile) {
  31731. return;
  31732. }
  31733. scene._addPendingData(this);
  31734. scene._loadFile(this.delayLoadingFile, function (data) {
  31735. if (!_this._delayLoadingFunction) {
  31736. return;
  31737. }
  31738. _this._delayLoadingFunction(JSON.parse(data), _this);
  31739. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31740. _this._delayInfo = [];
  31741. scene._removePendingData(_this);
  31742. var meshes = _this._meshes;
  31743. var numOfMeshes = meshes.length;
  31744. for (var index = 0; index < numOfMeshes; index++) {
  31745. _this._applyToMesh(meshes[index]);
  31746. }
  31747. if (onLoaded) {
  31748. onLoaded();
  31749. }
  31750. }, undefined, true);
  31751. };
  31752. /**
  31753. * Invert the geometry to move from a right handed system to a left handed one.
  31754. */
  31755. Geometry.prototype.toLeftHanded = function () {
  31756. // Flip faces
  31757. var tIndices = this.getIndices(false);
  31758. if (tIndices != null && tIndices.length > 0) {
  31759. for (var i = 0; i < tIndices.length; i += 3) {
  31760. var tTemp = tIndices[i + 0];
  31761. tIndices[i + 0] = tIndices[i + 2];
  31762. tIndices[i + 2] = tTemp;
  31763. }
  31764. this.setIndices(tIndices);
  31765. }
  31766. // Negate position.z
  31767. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31768. if (tPositions != null && tPositions.length > 0) {
  31769. for (var i = 0; i < tPositions.length; i += 3) {
  31770. tPositions[i + 2] = -tPositions[i + 2];
  31771. }
  31772. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31773. }
  31774. // Negate normal.z
  31775. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31776. if (tNormals != null && tNormals.length > 0) {
  31777. for (var i = 0; i < tNormals.length; i += 3) {
  31778. tNormals[i + 2] = -tNormals[i + 2];
  31779. }
  31780. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31781. }
  31782. };
  31783. // Cache
  31784. Geometry.prototype._resetPointsArrayCache = function () {
  31785. this._positions = null;
  31786. };
  31787. Geometry.prototype._generatePointsArray = function () {
  31788. if (this._positions)
  31789. return true;
  31790. this._positions = [];
  31791. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31792. if (!data) {
  31793. return false;
  31794. }
  31795. for (var index = 0; index < data.length; index += 3) {
  31796. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31797. }
  31798. return true;
  31799. };
  31800. Geometry.prototype.isDisposed = function () {
  31801. return this._isDisposed;
  31802. };
  31803. Geometry.prototype._disposeVertexArrayObjects = function () {
  31804. if (this._vertexArrayObjects) {
  31805. for (var kind in this._vertexArrayObjects) {
  31806. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31807. }
  31808. this._vertexArrayObjects = {};
  31809. }
  31810. };
  31811. Geometry.prototype.dispose = function () {
  31812. var meshes = this._meshes;
  31813. var numOfMeshes = meshes.length;
  31814. var index;
  31815. for (index = 0; index < numOfMeshes; index++) {
  31816. this.releaseForMesh(meshes[index]);
  31817. }
  31818. this._meshes = [];
  31819. this._disposeVertexArrayObjects();
  31820. for (var kind in this._vertexBuffers) {
  31821. this._vertexBuffers[kind].dispose();
  31822. }
  31823. this._vertexBuffers = {};
  31824. this._totalVertices = 0;
  31825. if (this._indexBuffer) {
  31826. this._engine._releaseBuffer(this._indexBuffer);
  31827. }
  31828. this._indexBuffer = null;
  31829. this._indices = [];
  31830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31831. this.delayLoadingFile = null;
  31832. this._delayLoadingFunction = null;
  31833. this._delayInfo = [];
  31834. this._boundingInfo = null;
  31835. this._scene.removeGeometry(this);
  31836. this._isDisposed = true;
  31837. };
  31838. Geometry.prototype.copy = function (id) {
  31839. var vertexData = new BABYLON.VertexData();
  31840. vertexData.indices = [];
  31841. var indices = this.getIndices();
  31842. if (indices) {
  31843. for (var index = 0; index < indices.length; index++) {
  31844. vertexData.indices.push(indices[index]);
  31845. }
  31846. }
  31847. var updatable = false;
  31848. var stopChecking = false;
  31849. var kind;
  31850. for (kind in this._vertexBuffers) {
  31851. // using slice() to make a copy of the array and not just reference it
  31852. var data = this.getVerticesData(kind);
  31853. if (data instanceof Float32Array) {
  31854. vertexData.set(new Float32Array(data), kind);
  31855. }
  31856. else {
  31857. vertexData.set(data.slice(0), kind);
  31858. }
  31859. if (!stopChecking) {
  31860. var vb = this.getVertexBuffer(kind);
  31861. if (vb) {
  31862. updatable = vb.isUpdatable();
  31863. stopChecking = !updatable;
  31864. }
  31865. }
  31866. }
  31867. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31868. geometry.delayLoadState = this.delayLoadState;
  31869. geometry.delayLoadingFile = this.delayLoadingFile;
  31870. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31871. for (kind in this._delayInfo) {
  31872. geometry._delayInfo = geometry._delayInfo || [];
  31873. geometry._delayInfo.push(kind);
  31874. }
  31875. // Bounding info
  31876. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31877. return geometry;
  31878. };
  31879. Geometry.prototype.serialize = function () {
  31880. var serializationObject = {};
  31881. serializationObject.id = this.id;
  31882. serializationObject.updatable = this._updatable;
  31883. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31884. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31885. }
  31886. return serializationObject;
  31887. };
  31888. Geometry.prototype.toNumberArray = function (origin) {
  31889. if (Array.isArray(origin)) {
  31890. return origin;
  31891. }
  31892. else {
  31893. return Array.prototype.slice.call(origin);
  31894. }
  31895. };
  31896. Geometry.prototype.serializeVerticeData = function () {
  31897. var serializationObject = this.serialize();
  31898. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31899. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31900. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31901. serializationObject.positions._updatable = true;
  31902. }
  31903. }
  31904. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31905. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31906. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31907. serializationObject.normals._updatable = true;
  31908. }
  31909. }
  31910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31911. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31913. serializationObject.uvs._updatable = true;
  31914. }
  31915. }
  31916. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31917. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31918. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31919. serializationObject.uv2s._updatable = true;
  31920. }
  31921. }
  31922. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31923. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31924. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31925. serializationObject.uv3s._updatable = true;
  31926. }
  31927. }
  31928. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31929. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31930. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31931. serializationObject.uv4s._updatable = true;
  31932. }
  31933. }
  31934. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31935. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31937. serializationObject.uv5s._updatable = true;
  31938. }
  31939. }
  31940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31941. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31943. serializationObject.uv6s._updatable = true;
  31944. }
  31945. }
  31946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31947. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31949. serializationObject.colors._updatable = true;
  31950. }
  31951. }
  31952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31953. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31954. serializationObject.matricesIndices._isExpanded = true;
  31955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31956. serializationObject.matricesIndices._updatable = true;
  31957. }
  31958. }
  31959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31960. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31961. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31962. serializationObject.matricesWeights._updatable = true;
  31963. }
  31964. }
  31965. serializationObject.indices = this.toNumberArray(this.getIndices());
  31966. return serializationObject;
  31967. };
  31968. // Statics
  31969. Geometry.ExtractFromMesh = function (mesh, id) {
  31970. var geometry = mesh._geometry;
  31971. if (!geometry) {
  31972. return null;
  31973. }
  31974. return geometry.copy(id);
  31975. };
  31976. /**
  31977. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31978. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31979. * Be aware Math.random() could cause collisions, but:
  31980. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  31981. */
  31982. Geometry.RandomId = function () {
  31983. return BABYLON.Tools.RandomId();
  31984. };
  31985. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31986. var scene = mesh.getScene();
  31987. // Geometry
  31988. var geometryId = parsedGeometry.geometryId;
  31989. if (geometryId) {
  31990. var geometry = scene.getGeometryByID(geometryId);
  31991. if (geometry) {
  31992. geometry.applyToMesh(mesh);
  31993. }
  31994. }
  31995. else if (parsedGeometry instanceof ArrayBuffer) {
  31996. var binaryInfo = mesh._binaryInfo;
  31997. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31998. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31999. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32000. }
  32001. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32002. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32003. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32004. }
  32005. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32006. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32007. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32008. }
  32009. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32010. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32011. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32012. }
  32013. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32014. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32015. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32016. }
  32017. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32018. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32019. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32020. }
  32021. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32022. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32023. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32024. }
  32025. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32026. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32027. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32028. }
  32029. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32030. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32031. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32032. }
  32033. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32034. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32035. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32036. }
  32037. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32038. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32040. }
  32041. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32042. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32043. mesh.setIndices(indicesData, null);
  32044. }
  32045. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32046. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32047. mesh.subMeshes = [];
  32048. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32049. var materialIndex = subMeshesData[(i * 5) + 0];
  32050. var verticesStart = subMeshesData[(i * 5) + 1];
  32051. var verticesCount = subMeshesData[(i * 5) + 2];
  32052. var indexStart = subMeshesData[(i * 5) + 3];
  32053. var indexCount = subMeshesData[(i * 5) + 4];
  32054. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32055. }
  32056. }
  32057. }
  32058. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32059. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32060. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32061. if (parsedGeometry.uvs) {
  32062. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32063. }
  32064. if (parsedGeometry.uvs2) {
  32065. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32066. }
  32067. if (parsedGeometry.uvs3) {
  32068. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32069. }
  32070. if (parsedGeometry.uvs4) {
  32071. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32072. }
  32073. if (parsedGeometry.uvs5) {
  32074. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32075. }
  32076. if (parsedGeometry.uvs6) {
  32077. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32078. }
  32079. if (parsedGeometry.colors) {
  32080. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32081. }
  32082. if (parsedGeometry.matricesIndices) {
  32083. if (!parsedGeometry.matricesIndices._isExpanded) {
  32084. var floatIndices = [];
  32085. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32086. var matricesIndex = parsedGeometry.matricesIndices[i];
  32087. floatIndices.push(matricesIndex & 0x000000FF);
  32088. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32089. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32090. floatIndices.push(matricesIndex >> 24);
  32091. }
  32092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32093. }
  32094. else {
  32095. delete parsedGeometry.matricesIndices._isExpanded;
  32096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32097. }
  32098. }
  32099. if (parsedGeometry.matricesIndicesExtra) {
  32100. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32101. var floatIndices = [];
  32102. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32103. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32104. floatIndices.push(matricesIndex & 0x000000FF);
  32105. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32106. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32107. floatIndices.push(matricesIndex >> 24);
  32108. }
  32109. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32110. }
  32111. else {
  32112. delete parsedGeometry.matricesIndices._isExpanded;
  32113. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32114. }
  32115. }
  32116. if (parsedGeometry.matricesWeights) {
  32117. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32118. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32119. }
  32120. if (parsedGeometry.matricesWeightsExtra) {
  32121. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32122. }
  32123. mesh.setIndices(parsedGeometry.indices, null);
  32124. }
  32125. // SubMeshes
  32126. if (parsedGeometry.subMeshes) {
  32127. mesh.subMeshes = [];
  32128. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32129. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32130. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32131. }
  32132. }
  32133. // Flat shading
  32134. if (mesh._shouldGenerateFlatShading) {
  32135. mesh.convertToFlatShadedMesh();
  32136. delete mesh._shouldGenerateFlatShading;
  32137. }
  32138. // Update
  32139. mesh.computeWorldMatrix(true);
  32140. // Octree
  32141. var sceneOctree = scene.selectionOctree;
  32142. if (sceneOctree !== undefined && sceneOctree !== null) {
  32143. sceneOctree.addMesh(mesh);
  32144. }
  32145. };
  32146. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32147. var epsilon = 1e-3;
  32148. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32149. return;
  32150. }
  32151. var noInfluenceBoneIndex = 0.0;
  32152. if (parsedGeometry.skeletonId > -1) {
  32153. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32154. if (!skeleton) {
  32155. return;
  32156. }
  32157. noInfluenceBoneIndex = skeleton.bones.length;
  32158. }
  32159. else {
  32160. return;
  32161. }
  32162. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32163. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32164. var matricesWeights = parsedGeometry.matricesWeights;
  32165. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32166. var influencers = parsedGeometry.numBoneInfluencer;
  32167. var size = matricesWeights.length;
  32168. for (var i = 0; i < size; i += 4) {
  32169. var weight = 0.0;
  32170. var firstZeroWeight = -1;
  32171. for (var j = 0; j < 4; j++) {
  32172. var w = matricesWeights[i + j];
  32173. weight += w;
  32174. if (w < epsilon && firstZeroWeight < 0) {
  32175. firstZeroWeight = j;
  32176. }
  32177. }
  32178. if (matricesWeightsExtra) {
  32179. for (var j = 0; j < 4; j++) {
  32180. var w = matricesWeightsExtra[i + j];
  32181. weight += w;
  32182. if (w < epsilon && firstZeroWeight < 0) {
  32183. firstZeroWeight = j + 4;
  32184. }
  32185. }
  32186. }
  32187. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32188. firstZeroWeight = influencers - 1;
  32189. }
  32190. if (weight > epsilon) {
  32191. var mweight = 1.0 / weight;
  32192. for (var j = 0; j < 4; j++) {
  32193. matricesWeights[i + j] *= mweight;
  32194. }
  32195. if (matricesWeightsExtra) {
  32196. for (var j = 0; j < 4; j++) {
  32197. matricesWeightsExtra[i + j] *= mweight;
  32198. }
  32199. }
  32200. }
  32201. else {
  32202. if (firstZeroWeight >= 4) {
  32203. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32204. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32205. }
  32206. else {
  32207. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32208. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32209. }
  32210. }
  32211. }
  32212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32213. if (parsedGeometry.matricesWeightsExtra) {
  32214. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32215. }
  32216. };
  32217. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32218. if (scene.getGeometryByID(parsedVertexData.id)) {
  32219. return null; // null since geometry could be something else than a box...
  32220. }
  32221. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32222. if (BABYLON.Tags) {
  32223. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32224. }
  32225. if (parsedVertexData.delayLoadingFile) {
  32226. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32227. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32228. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32229. geometry._delayInfo = [];
  32230. if (parsedVertexData.hasUVs) {
  32231. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32232. }
  32233. if (parsedVertexData.hasUVs2) {
  32234. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32235. }
  32236. if (parsedVertexData.hasUVs3) {
  32237. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32238. }
  32239. if (parsedVertexData.hasUVs4) {
  32240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32241. }
  32242. if (parsedVertexData.hasUVs5) {
  32243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32244. }
  32245. if (parsedVertexData.hasUVs6) {
  32246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32247. }
  32248. if (parsedVertexData.hasColors) {
  32249. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32250. }
  32251. if (parsedVertexData.hasMatricesIndices) {
  32252. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32253. }
  32254. if (parsedVertexData.hasMatricesWeights) {
  32255. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32256. }
  32257. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32258. }
  32259. else {
  32260. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32261. }
  32262. scene.pushGeometry(geometry, true);
  32263. return geometry;
  32264. };
  32265. return Geometry;
  32266. }());
  32267. BABYLON.Geometry = Geometry;
  32268. /////// Primitives //////////////////////////////////////////////
  32269. //export module Geometry.Primitives {
  32270. /// Abstract class
  32271. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32272. __extends(_PrimitiveGeometry, _super);
  32273. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32274. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32275. if (mesh === void 0) { mesh = null; }
  32276. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32277. _this._canBeRegenerated = _canBeRegenerated;
  32278. _this._beingRegenerated = true;
  32279. _this.regenerate();
  32280. _this._beingRegenerated = false;
  32281. return _this;
  32282. }
  32283. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32284. return this._canBeRegenerated;
  32285. };
  32286. _PrimitiveGeometry.prototype.regenerate = function () {
  32287. if (!this._canBeRegenerated) {
  32288. return;
  32289. }
  32290. this._beingRegenerated = true;
  32291. this.setAllVerticesData(this._regenerateVertexData(), false);
  32292. this._beingRegenerated = false;
  32293. };
  32294. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32295. return _super.prototype.copy.call(this, id);
  32296. };
  32297. // overrides
  32298. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32299. if (!this._beingRegenerated) {
  32300. return;
  32301. }
  32302. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32303. };
  32304. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32305. if (!this._beingRegenerated) {
  32306. return;
  32307. }
  32308. _super.prototype.setVerticesData.call(this, kind, data, false);
  32309. };
  32310. // to override
  32311. // protected
  32312. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32313. throw new Error("Abstract method");
  32314. };
  32315. _PrimitiveGeometry.prototype.copy = function (id) {
  32316. throw new Error("Must be overriden in sub-classes.");
  32317. };
  32318. _PrimitiveGeometry.prototype.serialize = function () {
  32319. var serializationObject = _super.prototype.serialize.call(this);
  32320. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32321. return serializationObject;
  32322. };
  32323. return _PrimitiveGeometry;
  32324. }(Geometry));
  32325. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32326. var RibbonGeometry = /** @class */ (function (_super) {
  32327. __extends(RibbonGeometry, _super);
  32328. // Members
  32329. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32332. _this.pathArray = pathArray;
  32333. _this.closeArray = closeArray;
  32334. _this.closePath = closePath;
  32335. _this.offset = offset;
  32336. _this.side = side;
  32337. return _this;
  32338. }
  32339. RibbonGeometry.prototype._regenerateVertexData = function () {
  32340. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32341. };
  32342. RibbonGeometry.prototype.copy = function (id) {
  32343. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32344. };
  32345. return RibbonGeometry;
  32346. }(_PrimitiveGeometry));
  32347. BABYLON.RibbonGeometry = RibbonGeometry;
  32348. var BoxGeometry = /** @class */ (function (_super) {
  32349. __extends(BoxGeometry, _super);
  32350. // Members
  32351. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32352. if (mesh === void 0) { mesh = null; }
  32353. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32354. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32355. _this.size = size;
  32356. _this.side = side;
  32357. return _this;
  32358. }
  32359. BoxGeometry.prototype._regenerateVertexData = function () {
  32360. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32361. };
  32362. BoxGeometry.prototype.copy = function (id) {
  32363. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32364. };
  32365. BoxGeometry.prototype.serialize = function () {
  32366. var serializationObject = _super.prototype.serialize.call(this);
  32367. serializationObject.size = this.size;
  32368. return serializationObject;
  32369. };
  32370. BoxGeometry.Parse = function (parsedBox, scene) {
  32371. if (scene.getGeometryByID(parsedBox.id)) {
  32372. return null; // null since geometry could be something else than a box...
  32373. }
  32374. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32375. if (BABYLON.Tags) {
  32376. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32377. }
  32378. scene.pushGeometry(box, true);
  32379. return box;
  32380. };
  32381. return BoxGeometry;
  32382. }(_PrimitiveGeometry));
  32383. BABYLON.BoxGeometry = BoxGeometry;
  32384. var SphereGeometry = /** @class */ (function (_super) {
  32385. __extends(SphereGeometry, _super);
  32386. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32387. if (mesh === void 0) { mesh = null; }
  32388. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32389. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32390. _this.segments = segments;
  32391. _this.diameter = diameter;
  32392. _this.side = side;
  32393. return _this;
  32394. }
  32395. SphereGeometry.prototype._regenerateVertexData = function () {
  32396. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32397. };
  32398. SphereGeometry.prototype.copy = function (id) {
  32399. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32400. };
  32401. SphereGeometry.prototype.serialize = function () {
  32402. var serializationObject = _super.prototype.serialize.call(this);
  32403. serializationObject.segments = this.segments;
  32404. serializationObject.diameter = this.diameter;
  32405. return serializationObject;
  32406. };
  32407. SphereGeometry.Parse = function (parsedSphere, scene) {
  32408. if (scene.getGeometryByID(parsedSphere.id)) {
  32409. return null; // null since geometry could be something else than a sphere...
  32410. }
  32411. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32412. if (BABYLON.Tags) {
  32413. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32414. }
  32415. scene.pushGeometry(sphere, true);
  32416. return sphere;
  32417. };
  32418. return SphereGeometry;
  32419. }(_PrimitiveGeometry));
  32420. BABYLON.SphereGeometry = SphereGeometry;
  32421. var DiscGeometry = /** @class */ (function (_super) {
  32422. __extends(DiscGeometry, _super);
  32423. // Members
  32424. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32425. if (mesh === void 0) { mesh = null; }
  32426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32428. _this.radius = radius;
  32429. _this.tessellation = tessellation;
  32430. _this.side = side;
  32431. return _this;
  32432. }
  32433. DiscGeometry.prototype._regenerateVertexData = function () {
  32434. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32435. };
  32436. DiscGeometry.prototype.copy = function (id) {
  32437. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32438. };
  32439. return DiscGeometry;
  32440. }(_PrimitiveGeometry));
  32441. BABYLON.DiscGeometry = DiscGeometry;
  32442. var CylinderGeometry = /** @class */ (function (_super) {
  32443. __extends(CylinderGeometry, _super);
  32444. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32445. if (subdivisions === void 0) { subdivisions = 1; }
  32446. if (mesh === void 0) { mesh = null; }
  32447. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32448. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32449. _this.height = height;
  32450. _this.diameterTop = diameterTop;
  32451. _this.diameterBottom = diameterBottom;
  32452. _this.tessellation = tessellation;
  32453. _this.subdivisions = subdivisions;
  32454. _this.side = side;
  32455. return _this;
  32456. }
  32457. CylinderGeometry.prototype._regenerateVertexData = function () {
  32458. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32459. };
  32460. CylinderGeometry.prototype.copy = function (id) {
  32461. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32462. };
  32463. CylinderGeometry.prototype.serialize = function () {
  32464. var serializationObject = _super.prototype.serialize.call(this);
  32465. serializationObject.height = this.height;
  32466. serializationObject.diameterTop = this.diameterTop;
  32467. serializationObject.diameterBottom = this.diameterBottom;
  32468. serializationObject.tessellation = this.tessellation;
  32469. return serializationObject;
  32470. };
  32471. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32472. if (scene.getGeometryByID(parsedCylinder.id)) {
  32473. return null; // null since geometry could be something else than a cylinder...
  32474. }
  32475. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32476. if (BABYLON.Tags) {
  32477. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32478. }
  32479. scene.pushGeometry(cylinder, true);
  32480. return cylinder;
  32481. };
  32482. return CylinderGeometry;
  32483. }(_PrimitiveGeometry));
  32484. BABYLON.CylinderGeometry = CylinderGeometry;
  32485. var TorusGeometry = /** @class */ (function (_super) {
  32486. __extends(TorusGeometry, _super);
  32487. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32488. if (mesh === void 0) { mesh = null; }
  32489. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32490. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32491. _this.diameter = diameter;
  32492. _this.thickness = thickness;
  32493. _this.tessellation = tessellation;
  32494. _this.side = side;
  32495. return _this;
  32496. }
  32497. TorusGeometry.prototype._regenerateVertexData = function () {
  32498. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32499. };
  32500. TorusGeometry.prototype.copy = function (id) {
  32501. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32502. };
  32503. TorusGeometry.prototype.serialize = function () {
  32504. var serializationObject = _super.prototype.serialize.call(this);
  32505. serializationObject.diameter = this.diameter;
  32506. serializationObject.thickness = this.thickness;
  32507. serializationObject.tessellation = this.tessellation;
  32508. return serializationObject;
  32509. };
  32510. TorusGeometry.Parse = function (parsedTorus, scene) {
  32511. if (scene.getGeometryByID(parsedTorus.id)) {
  32512. return null; // null since geometry could be something else than a torus...
  32513. }
  32514. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32515. if (BABYLON.Tags) {
  32516. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32517. }
  32518. scene.pushGeometry(torus, true);
  32519. return torus;
  32520. };
  32521. return TorusGeometry;
  32522. }(_PrimitiveGeometry));
  32523. BABYLON.TorusGeometry = TorusGeometry;
  32524. var GroundGeometry = /** @class */ (function (_super) {
  32525. __extends(GroundGeometry, _super);
  32526. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32527. if (mesh === void 0) { mesh = null; }
  32528. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32529. _this.width = width;
  32530. _this.height = height;
  32531. _this.subdivisions = subdivisions;
  32532. return _this;
  32533. }
  32534. GroundGeometry.prototype._regenerateVertexData = function () {
  32535. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32536. };
  32537. GroundGeometry.prototype.copy = function (id) {
  32538. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32539. };
  32540. GroundGeometry.prototype.serialize = function () {
  32541. var serializationObject = _super.prototype.serialize.call(this);
  32542. serializationObject.width = this.width;
  32543. serializationObject.height = this.height;
  32544. serializationObject.subdivisions = this.subdivisions;
  32545. return serializationObject;
  32546. };
  32547. GroundGeometry.Parse = function (parsedGround, scene) {
  32548. if (scene.getGeometryByID(parsedGround.id)) {
  32549. return null; // null since geometry could be something else than a ground...
  32550. }
  32551. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32552. if (BABYLON.Tags) {
  32553. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32554. }
  32555. scene.pushGeometry(ground, true);
  32556. return ground;
  32557. };
  32558. return GroundGeometry;
  32559. }(_PrimitiveGeometry));
  32560. BABYLON.GroundGeometry = GroundGeometry;
  32561. var TiledGroundGeometry = /** @class */ (function (_super) {
  32562. __extends(TiledGroundGeometry, _super);
  32563. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32564. if (mesh === void 0) { mesh = null; }
  32565. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32566. _this.xmin = xmin;
  32567. _this.zmin = zmin;
  32568. _this.xmax = xmax;
  32569. _this.zmax = zmax;
  32570. _this.subdivisions = subdivisions;
  32571. _this.precision = precision;
  32572. return _this;
  32573. }
  32574. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32575. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32576. };
  32577. TiledGroundGeometry.prototype.copy = function (id) {
  32578. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32579. };
  32580. return TiledGroundGeometry;
  32581. }(_PrimitiveGeometry));
  32582. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32583. var PlaneGeometry = /** @class */ (function (_super) {
  32584. __extends(PlaneGeometry, _super);
  32585. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32586. if (mesh === void 0) { mesh = null; }
  32587. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32588. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32589. _this.size = size;
  32590. _this.side = side;
  32591. return _this;
  32592. }
  32593. PlaneGeometry.prototype._regenerateVertexData = function () {
  32594. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32595. };
  32596. PlaneGeometry.prototype.copy = function (id) {
  32597. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32598. };
  32599. PlaneGeometry.prototype.serialize = function () {
  32600. var serializationObject = _super.prototype.serialize.call(this);
  32601. serializationObject.size = this.size;
  32602. return serializationObject;
  32603. };
  32604. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32605. if (scene.getGeometryByID(parsedPlane.id)) {
  32606. return null; // null since geometry could be something else than a ground...
  32607. }
  32608. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32609. if (BABYLON.Tags) {
  32610. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32611. }
  32612. scene.pushGeometry(plane, true);
  32613. return plane;
  32614. };
  32615. return PlaneGeometry;
  32616. }(_PrimitiveGeometry));
  32617. BABYLON.PlaneGeometry = PlaneGeometry;
  32618. var TorusKnotGeometry = /** @class */ (function (_super) {
  32619. __extends(TorusKnotGeometry, _super);
  32620. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32621. if (mesh === void 0) { mesh = null; }
  32622. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32623. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32624. _this.radius = radius;
  32625. _this.tube = tube;
  32626. _this.radialSegments = radialSegments;
  32627. _this.tubularSegments = tubularSegments;
  32628. _this.p = p;
  32629. _this.q = q;
  32630. _this.side = side;
  32631. return _this;
  32632. }
  32633. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32634. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  32635. };
  32636. TorusKnotGeometry.prototype.copy = function (id) {
  32637. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32638. };
  32639. TorusKnotGeometry.prototype.serialize = function () {
  32640. var serializationObject = _super.prototype.serialize.call(this);
  32641. serializationObject.radius = this.radius;
  32642. serializationObject.tube = this.tube;
  32643. serializationObject.radialSegments = this.radialSegments;
  32644. serializationObject.tubularSegments = this.tubularSegments;
  32645. serializationObject.p = this.p;
  32646. serializationObject.q = this.q;
  32647. return serializationObject;
  32648. };
  32649. ;
  32650. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32651. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32652. return null; // null since geometry could be something else than a ground...
  32653. }
  32654. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32655. if (BABYLON.Tags) {
  32656. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32657. }
  32658. scene.pushGeometry(torusKnot, true);
  32659. return torusKnot;
  32660. };
  32661. return TorusKnotGeometry;
  32662. }(_PrimitiveGeometry));
  32663. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32664. //}
  32665. })(BABYLON || (BABYLON = {}));
  32666. //# sourceMappingURL=babylon.geometry.js.map
  32667. var BABYLON;
  32668. (function (BABYLON) {
  32669. var PostProcessManager = /** @class */ (function () {
  32670. function PostProcessManager(scene) {
  32671. this._vertexBuffers = {};
  32672. this._scene = scene;
  32673. }
  32674. PostProcessManager.prototype._prepareBuffers = function () {
  32675. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32676. return;
  32677. }
  32678. // VBO
  32679. var vertices = [];
  32680. vertices.push(1, 1);
  32681. vertices.push(-1, 1);
  32682. vertices.push(-1, -1);
  32683. vertices.push(1, -1);
  32684. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32685. this._buildIndexBuffer();
  32686. };
  32687. PostProcessManager.prototype._buildIndexBuffer = function () {
  32688. // Indices
  32689. var indices = [];
  32690. indices.push(0);
  32691. indices.push(1);
  32692. indices.push(2);
  32693. indices.push(0);
  32694. indices.push(2);
  32695. indices.push(3);
  32696. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32697. };
  32698. PostProcessManager.prototype._rebuild = function () {
  32699. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32700. if (!vb) {
  32701. return;
  32702. }
  32703. vb._rebuild();
  32704. this._buildIndexBuffer();
  32705. };
  32706. // Methods
  32707. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32708. if (sourceTexture === void 0) { sourceTexture = null; }
  32709. if (postProcesses === void 0) { postProcesses = null; }
  32710. var camera = this._scene.activeCamera;
  32711. if (!camera) {
  32712. return false;
  32713. }
  32714. var postProcesses = postProcesses || camera._postProcesses;
  32715. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32716. return false;
  32717. }
  32718. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32719. return true;
  32720. };
  32721. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32722. if (targetTexture === void 0) { targetTexture = null; }
  32723. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32724. var engine = this._scene.getEngine();
  32725. for (var index = 0; index < postProcesses.length; index++) {
  32726. if (index < postProcesses.length - 1) {
  32727. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32728. }
  32729. else {
  32730. if (targetTexture) {
  32731. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32732. }
  32733. else {
  32734. engine.restoreDefaultFramebuffer();
  32735. }
  32736. }
  32737. var pp = postProcesses[index];
  32738. var effect = pp.apply();
  32739. if (effect) {
  32740. pp.onBeforeRenderObservable.notifyObservers(effect);
  32741. // VBOs
  32742. this._prepareBuffers();
  32743. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32744. // Draw order
  32745. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32746. pp.onAfterRenderObservable.notifyObservers(effect);
  32747. }
  32748. }
  32749. // Restore depth buffer
  32750. engine.setDepthBuffer(true);
  32751. engine.setDepthWrite(true);
  32752. };
  32753. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32754. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32755. var camera = this._scene.activeCamera;
  32756. if (!camera) {
  32757. return;
  32758. }
  32759. postProcesses = postProcesses || camera._postProcesses;
  32760. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32761. return;
  32762. }
  32763. var engine = this._scene.getEngine();
  32764. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32765. if (index < len - 1) {
  32766. postProcesses[index + 1].activate(camera, targetTexture);
  32767. }
  32768. else {
  32769. if (targetTexture) {
  32770. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32771. }
  32772. else {
  32773. engine.restoreDefaultFramebuffer();
  32774. }
  32775. }
  32776. if (doNotPresent) {
  32777. break;
  32778. }
  32779. var pp = postProcesses[index];
  32780. var effect = pp.apply();
  32781. if (effect) {
  32782. pp.onBeforeRenderObservable.notifyObservers(effect);
  32783. // VBOs
  32784. this._prepareBuffers();
  32785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32786. // Draw order
  32787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32788. pp.onAfterRenderObservable.notifyObservers(effect);
  32789. }
  32790. }
  32791. // Restore states
  32792. engine.setDepthBuffer(true);
  32793. engine.setDepthWrite(true);
  32794. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32795. };
  32796. PostProcessManager.prototype.dispose = function () {
  32797. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32798. if (buffer) {
  32799. buffer.dispose();
  32800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32801. }
  32802. if (this._indexBuffer) {
  32803. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32804. this._indexBuffer = null;
  32805. }
  32806. };
  32807. return PostProcessManager;
  32808. }());
  32809. BABYLON.PostProcessManager = PostProcessManager;
  32810. })(BABYLON || (BABYLON = {}));
  32811. //# sourceMappingURL=babylon.postProcessManager.js.map
  32812. BABYLON.Effect.IncludesShadersStore['depthPrePass'] = "#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";
  32813. BABYLON.Effect.IncludesShadersStore['bonesDeclaration'] = "#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif";
  32814. BABYLON.Effect.IncludesShadersStore['instancesDeclaration'] = "#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif";
  32815. BABYLON.Effect.IncludesShadersStore['pointCloudVertexDeclaration'] = "#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  32816. BABYLON.Effect.IncludesShadersStore['bumpVertexDeclaration'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";
  32817. BABYLON.Effect.IncludesShadersStore['clipPlaneVertexDeclaration'] = "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif";
  32818. BABYLON.Effect.IncludesShadersStore['fogVertexDeclaration'] = "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";
  32819. BABYLON.Effect.IncludesShadersStore['morphTargetsVertexGlobalDeclaration'] = "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";
  32820. BABYLON.Effect.IncludesShadersStore['morphTargetsVertexDeclaration'] = "#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif";
  32821. BABYLON.Effect.IncludesShadersStore['logDepthDeclaration'] = "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";
  32822. BABYLON.Effect.IncludesShadersStore['morphTargetsVertex'] = "#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif";
  32823. BABYLON.Effect.IncludesShadersStore['instancesVertex'] = "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";
  32824. BABYLON.Effect.IncludesShadersStore['bonesVertex'] = "#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif";
  32825. BABYLON.Effect.IncludesShadersStore['bumpVertex'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif";
  32826. BABYLON.Effect.IncludesShadersStore['clipPlaneVertex'] = "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif";
  32827. BABYLON.Effect.IncludesShadersStore['fogVertex'] = "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";
  32828. BABYLON.Effect.IncludesShadersStore['shadowsVertex'] = "#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif";
  32829. BABYLON.Effect.IncludesShadersStore['pointCloudVertex'] = "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";
  32830. BABYLON.Effect.IncludesShadersStore['logDepthVertex'] = "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";
  32831. BABYLON.Effect.IncludesShadersStore['helperFunctions'] = "const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}";
  32832. BABYLON.Effect.IncludesShadersStore['lightFragmentDeclaration'] = "#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif";
  32833. BABYLON.Effect.IncludesShadersStore['lightsFragmentFunctions'] = "\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n";
  32834. BABYLON.Effect.IncludesShadersStore['lightUboDeclaration'] = "#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif";
  32835. BABYLON.Effect.IncludesShadersStore['defaultVertexDeclaration'] = "\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";
  32836. BABYLON.Effect.IncludesShadersStore['defaultFragmentDeclaration'] = "uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif";
  32837. BABYLON.Effect.IncludesShadersStore['defaultUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  32838. BABYLON.Effect.IncludesShadersStore['shadowsFragmentFunctions'] = "#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n";
  32839. BABYLON.Effect.IncludesShadersStore['fresnelFunction'] = "#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif";
  32840. BABYLON.Effect.IncludesShadersStore['reflectionFunction'] = "vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}";
  32841. BABYLON.Effect.IncludesShadersStore['imageProcessingDeclaration'] = "#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif";
  32842. BABYLON.Effect.IncludesShadersStore['imageProcessingFunctions'] = "#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}";
  32843. BABYLON.Effect.IncludesShadersStore['bumpFragmentFunctions'] = "#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif";
  32844. BABYLON.Effect.IncludesShadersStore['clipPlaneFragmentDeclaration'] = "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif";
  32845. BABYLON.Effect.IncludesShadersStore['fogFragmentDeclaration'] = "#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif";
  32846. BABYLON.Effect.IncludesShadersStore['clipPlaneFragment'] = "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif";
  32847. BABYLON.Effect.IncludesShadersStore['bumpFragment'] = "vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif";
  32848. BABYLON.Effect.IncludesShadersStore['lightFragment'] = "#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif";
  32849. BABYLON.Effect.IncludesShadersStore['logDepthFragment'] = "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";
  32850. BABYLON.Effect.IncludesShadersStore['fogFragment'] = "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";
  32851. var BABYLON;
  32852. (function (BABYLON) {
  32853. /**
  32854. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32855. */
  32856. var PerformanceMonitor = /** @class */ (function () {
  32857. /**
  32858. * constructor
  32859. * @param frameSampleSize The number of samples required to saturate the sliding window
  32860. */
  32861. function PerformanceMonitor(frameSampleSize) {
  32862. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32863. this._enabled = true;
  32864. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32865. }
  32866. /**
  32867. * Samples current frame
  32868. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32869. */
  32870. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32871. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32872. if (!this._enabled)
  32873. return;
  32874. if (this._lastFrameTimeMs != null) {
  32875. var dt = timeMs - this._lastFrameTimeMs;
  32876. this._rollingFrameTime.add(dt);
  32877. }
  32878. this._lastFrameTimeMs = timeMs;
  32879. };
  32880. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32881. /**
  32882. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32883. * @return Average frame time in milliseconds
  32884. */
  32885. get: function () {
  32886. return this._rollingFrameTime.average;
  32887. },
  32888. enumerable: true,
  32889. configurable: true
  32890. });
  32891. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32892. /**
  32893. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32894. * @return Frame time variance in milliseconds squared
  32895. */
  32896. get: function () {
  32897. return this._rollingFrameTime.variance;
  32898. },
  32899. enumerable: true,
  32900. configurable: true
  32901. });
  32902. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32903. /**
  32904. * Returns the frame time of the most recent frame
  32905. * @return Frame time in milliseconds
  32906. */
  32907. get: function () {
  32908. return this._rollingFrameTime.history(0);
  32909. },
  32910. enumerable: true,
  32911. configurable: true
  32912. });
  32913. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32914. /**
  32915. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32916. * @return Framerate in frames per second
  32917. */
  32918. get: function () {
  32919. return 1000.0 / this._rollingFrameTime.average;
  32920. },
  32921. enumerable: true,
  32922. configurable: true
  32923. });
  32924. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32925. /**
  32926. * Returns the average framerate in frames per second using the most recent frame time
  32927. * @return Framerate in frames per second
  32928. */
  32929. get: function () {
  32930. var history = this._rollingFrameTime.history(0);
  32931. if (history === 0) {
  32932. return 0;
  32933. }
  32934. return 1000.0 / history;
  32935. },
  32936. enumerable: true,
  32937. configurable: true
  32938. });
  32939. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32940. /**
  32941. * Returns true if enough samples have been taken to completely fill the sliding window
  32942. * @return true if saturated
  32943. */
  32944. get: function () {
  32945. return this._rollingFrameTime.isSaturated();
  32946. },
  32947. enumerable: true,
  32948. configurable: true
  32949. });
  32950. /**
  32951. * Enables contributions to the sliding window sample set
  32952. */
  32953. PerformanceMonitor.prototype.enable = function () {
  32954. this._enabled = true;
  32955. };
  32956. /**
  32957. * Disables contributions to the sliding window sample set
  32958. * Samples will not be interpolated over the disabled period
  32959. */
  32960. PerformanceMonitor.prototype.disable = function () {
  32961. this._enabled = false;
  32962. //clear last sample to avoid interpolating over the disabled period when next enabled
  32963. this._lastFrameTimeMs = null;
  32964. };
  32965. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32966. /**
  32967. * Returns true if sampling is enabled
  32968. * @return true if enabled
  32969. */
  32970. get: function () {
  32971. return this._enabled;
  32972. },
  32973. enumerable: true,
  32974. configurable: true
  32975. });
  32976. /**
  32977. * Resets performance monitor
  32978. */
  32979. PerformanceMonitor.prototype.reset = function () {
  32980. //clear last sample to avoid interpolating over the disabled period when next enabled
  32981. this._lastFrameTimeMs = null;
  32982. //wipe record
  32983. this._rollingFrameTime.reset();
  32984. };
  32985. return PerformanceMonitor;
  32986. }());
  32987. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32988. /**
  32989. * RollingAverage
  32990. *
  32991. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32992. */
  32993. var RollingAverage = /** @class */ (function () {
  32994. /**
  32995. * constructor
  32996. * @param length The number of samples required to saturate the sliding window
  32997. */
  32998. function RollingAverage(length) {
  32999. this._samples = new Array(length);
  33000. this.reset();
  33001. }
  33002. /**
  33003. * Adds a sample to the sample set
  33004. * @param v The sample value
  33005. */
  33006. RollingAverage.prototype.add = function (v) {
  33007. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33008. var delta;
  33009. //we need to check if we've already wrapped round
  33010. if (this.isSaturated()) {
  33011. //remove bottom of stack from mean
  33012. var bottomValue = this._samples[this._pos];
  33013. delta = bottomValue - this.average;
  33014. this.average -= delta / (this._sampleCount - 1);
  33015. this._m2 -= delta * (bottomValue - this.average);
  33016. }
  33017. else {
  33018. this._sampleCount++;
  33019. }
  33020. //add new value to mean
  33021. delta = v - this.average;
  33022. this.average += delta / (this._sampleCount);
  33023. this._m2 += delta * (v - this.average);
  33024. //set the new variance
  33025. this.variance = this._m2 / (this._sampleCount - 1);
  33026. this._samples[this._pos] = v;
  33027. this._pos++;
  33028. this._pos %= this._samples.length; //positive wrap around
  33029. };
  33030. /**
  33031. * Returns previously added values or null if outside of history or outside the sliding window domain
  33032. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33033. * @return Value previously recorded with add() or null if outside of range
  33034. */
  33035. RollingAverage.prototype.history = function (i) {
  33036. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33037. return 0;
  33038. }
  33039. var i0 = this._wrapPosition(this._pos - 1.0);
  33040. return this._samples[this._wrapPosition(i0 - i)];
  33041. };
  33042. /**
  33043. * Returns true if enough samples have been taken to completely fill the sliding window
  33044. * @return true if sample-set saturated
  33045. */
  33046. RollingAverage.prototype.isSaturated = function () {
  33047. return this._sampleCount >= this._samples.length;
  33048. };
  33049. /**
  33050. * Resets the rolling average (equivalent to 0 samples taken so far)
  33051. */
  33052. RollingAverage.prototype.reset = function () {
  33053. this.average = 0;
  33054. this.variance = 0;
  33055. this._sampleCount = 0;
  33056. this._pos = 0;
  33057. this._m2 = 0;
  33058. };
  33059. /**
  33060. * Wraps a value around the sample range boundaries
  33061. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33062. * @return Wrapped position in sample range
  33063. */
  33064. RollingAverage.prototype._wrapPosition = function (i) {
  33065. var max = this._samples.length;
  33066. return ((i % max) + max) % max;
  33067. };
  33068. return RollingAverage;
  33069. }());
  33070. BABYLON.RollingAverage = RollingAverage;
  33071. })(BABYLON || (BABYLON = {}));
  33072. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33073. var BABYLON;
  33074. (function (BABYLON) {
  33075. /**
  33076. * This groups together the common properties used for image processing either in direct forward pass
  33077. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33078. * or not.
  33079. */
  33080. var ImageProcessingConfiguration = /** @class */ (function () {
  33081. function ImageProcessingConfiguration() {
  33082. /**
  33083. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33084. */
  33085. this.colorCurves = new BABYLON.ColorCurves();
  33086. this._colorCurvesEnabled = false;
  33087. this._colorGradingEnabled = false;
  33088. this._colorGradingWithGreenDepth = true;
  33089. this._colorGradingBGR = true;
  33090. this._exposure = 1.0;
  33091. this._toneMappingEnabled = false;
  33092. this._contrast = 1.0;
  33093. /**
  33094. * Vignette stretch size.
  33095. */
  33096. this.vignetteStretch = 0;
  33097. /**
  33098. * Vignette centre X Offset.
  33099. */
  33100. this.vignetteCentreX = 0;
  33101. /**
  33102. * Vignette centre Y Offset.
  33103. */
  33104. this.vignetteCentreY = 0;
  33105. /**
  33106. * Vignette weight or intensity of the vignette effect.
  33107. */
  33108. this.vignetteWeight = 1.5;
  33109. /**
  33110. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33111. * if vignetteEnabled is set to true.
  33112. */
  33113. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33114. /**
  33115. * Camera field of view used by the Vignette effect.
  33116. */
  33117. this.vignetteCameraFov = 0.5;
  33118. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33119. this._vignetteEnabled = false;
  33120. this._applyByPostProcess = false;
  33121. this._isEnabled = true;
  33122. /**
  33123. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33124. * @type {BABYLON.Observable}
  33125. */
  33126. this.onUpdateParameters = new BABYLON.Observable();
  33127. }
  33128. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33129. /**
  33130. * Gets wether the color curves effect is enabled.
  33131. */
  33132. get: function () {
  33133. return this._colorCurvesEnabled;
  33134. },
  33135. /**
  33136. * Sets wether the color curves effect is enabled.
  33137. */
  33138. set: function (value) {
  33139. if (this._colorCurvesEnabled === value) {
  33140. return;
  33141. }
  33142. this._colorCurvesEnabled = value;
  33143. this._updateParameters();
  33144. },
  33145. enumerable: true,
  33146. configurable: true
  33147. });
  33148. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33149. /**
  33150. * Gets wether the color grading effect is enabled.
  33151. */
  33152. get: function () {
  33153. return this._colorGradingEnabled;
  33154. },
  33155. /**
  33156. * Sets wether the color grading effect is enabled.
  33157. */
  33158. set: function (value) {
  33159. if (this._colorGradingEnabled === value) {
  33160. return;
  33161. }
  33162. this._colorGradingEnabled = value;
  33163. this._updateParameters();
  33164. },
  33165. enumerable: true,
  33166. configurable: true
  33167. });
  33168. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33169. /**
  33170. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33171. */
  33172. get: function () {
  33173. return this._colorGradingWithGreenDepth;
  33174. },
  33175. /**
  33176. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33177. */
  33178. set: function (value) {
  33179. if (this._colorGradingWithGreenDepth === value) {
  33180. return;
  33181. }
  33182. this._colorGradingWithGreenDepth = value;
  33183. this._updateParameters();
  33184. },
  33185. enumerable: true,
  33186. configurable: true
  33187. });
  33188. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33189. /**
  33190. * Gets wether the color grading texture contains BGR values.
  33191. */
  33192. get: function () {
  33193. return this._colorGradingBGR;
  33194. },
  33195. /**
  33196. * Sets wether the color grading texture contains BGR values.
  33197. */
  33198. set: function (value) {
  33199. if (this._colorGradingBGR === value) {
  33200. return;
  33201. }
  33202. this._colorGradingBGR = value;
  33203. this._updateParameters();
  33204. },
  33205. enumerable: true,
  33206. configurable: true
  33207. });
  33208. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33209. /**
  33210. * Gets the Exposure used in the effect.
  33211. */
  33212. get: function () {
  33213. return this._exposure;
  33214. },
  33215. /**
  33216. * Sets the Exposure used in the effect.
  33217. */
  33218. set: function (value) {
  33219. if (this._exposure === value) {
  33220. return;
  33221. }
  33222. this._exposure = value;
  33223. this._updateParameters();
  33224. },
  33225. enumerable: true,
  33226. configurable: true
  33227. });
  33228. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33229. /**
  33230. * Gets wether the tone mapping effect is enabled.
  33231. */
  33232. get: function () {
  33233. return this._toneMappingEnabled;
  33234. },
  33235. /**
  33236. * Sets wether the tone mapping effect is enabled.
  33237. */
  33238. set: function (value) {
  33239. if (this._toneMappingEnabled === value) {
  33240. return;
  33241. }
  33242. this._toneMappingEnabled = value;
  33243. this._updateParameters();
  33244. },
  33245. enumerable: true,
  33246. configurable: true
  33247. });
  33248. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33249. /**
  33250. * Gets the contrast used in the effect.
  33251. */
  33252. get: function () {
  33253. return this._contrast;
  33254. },
  33255. /**
  33256. * Sets the contrast used in the effect.
  33257. */
  33258. set: function (value) {
  33259. if (this._contrast === value) {
  33260. return;
  33261. }
  33262. this._contrast = value;
  33263. this._updateParameters();
  33264. },
  33265. enumerable: true,
  33266. configurable: true
  33267. });
  33268. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33269. /**
  33270. * Gets the vignette blend mode allowing different kind of effect.
  33271. */
  33272. get: function () {
  33273. return this._vignetteBlendMode;
  33274. },
  33275. /**
  33276. * Sets the vignette blend mode allowing different kind of effect.
  33277. */
  33278. set: function (value) {
  33279. if (this._vignetteBlendMode === value) {
  33280. return;
  33281. }
  33282. this._vignetteBlendMode = value;
  33283. this._updateParameters();
  33284. },
  33285. enumerable: true,
  33286. configurable: true
  33287. });
  33288. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33289. /**
  33290. * Gets wether the vignette effect is enabled.
  33291. */
  33292. get: function () {
  33293. return this._vignetteEnabled;
  33294. },
  33295. /**
  33296. * Sets wether the vignette effect is enabled.
  33297. */
  33298. set: function (value) {
  33299. if (this._vignetteEnabled === value) {
  33300. return;
  33301. }
  33302. this._vignetteEnabled = value;
  33303. this._updateParameters();
  33304. },
  33305. enumerable: true,
  33306. configurable: true
  33307. });
  33308. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33309. /**
  33310. * Gets wether the image processing is applied through a post process or not.
  33311. */
  33312. get: function () {
  33313. return this._applyByPostProcess;
  33314. },
  33315. /**
  33316. * Sets wether the image processing is applied through a post process or not.
  33317. */
  33318. set: function (value) {
  33319. if (this._applyByPostProcess === value) {
  33320. return;
  33321. }
  33322. this._applyByPostProcess = value;
  33323. this._updateParameters();
  33324. },
  33325. enumerable: true,
  33326. configurable: true
  33327. });
  33328. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33329. /**
  33330. * Gets wether the image processing is enabled or not.
  33331. */
  33332. get: function () {
  33333. return this._isEnabled;
  33334. },
  33335. /**
  33336. * Sets wether the image processing is enabled or not.
  33337. */
  33338. set: function (value) {
  33339. if (this._isEnabled === value) {
  33340. return;
  33341. }
  33342. this._isEnabled = value;
  33343. this._updateParameters();
  33344. },
  33345. enumerable: true,
  33346. configurable: true
  33347. });
  33348. /**
  33349. * Method called each time the image processing information changes requires to recompile the effect.
  33350. */
  33351. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33352. this.onUpdateParameters.notifyObservers(this);
  33353. };
  33354. ImageProcessingConfiguration.prototype.getClassName = function () {
  33355. return "ImageProcessingConfiguration";
  33356. };
  33357. /**
  33358. * Prepare the list of uniforms associated with the Image Processing effects.
  33359. * @param uniformsList The list of uniforms used in the effect
  33360. * @param defines the list of defines currently in use
  33361. */
  33362. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33363. if (defines.EXPOSURE) {
  33364. uniforms.push("exposureLinear");
  33365. }
  33366. if (defines.CONTRAST) {
  33367. uniforms.push("contrast");
  33368. }
  33369. if (defines.COLORGRADING) {
  33370. uniforms.push("colorTransformSettings");
  33371. }
  33372. if (defines.VIGNETTE) {
  33373. uniforms.push("vInverseScreenSize");
  33374. uniforms.push("vignetteSettings1");
  33375. uniforms.push("vignetteSettings2");
  33376. }
  33377. if (defines.COLORCURVES) {
  33378. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33379. }
  33380. };
  33381. /**
  33382. * Prepare the list of samplers associated with the Image Processing effects.
  33383. * @param uniformsList The list of uniforms used in the effect
  33384. * @param defines the list of defines currently in use
  33385. */
  33386. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33387. if (defines.COLORGRADING) {
  33388. samplersList.push("txColorTransform");
  33389. }
  33390. };
  33391. /**
  33392. * Prepare the list of defines associated to the shader.
  33393. * @param defines the list of defines to complete
  33394. */
  33395. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33396. if (forPostProcess === void 0) { forPostProcess = false; }
  33397. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33398. defines.VIGNETTE = false;
  33399. defines.TONEMAPPING = false;
  33400. defines.CONTRAST = false;
  33401. defines.EXPOSURE = false;
  33402. defines.COLORCURVES = false;
  33403. defines.COLORGRADING = false;
  33404. defines.COLORGRADING3D = false;
  33405. defines.IMAGEPROCESSING = false;
  33406. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33407. return;
  33408. }
  33409. defines.VIGNETTE = this.vignetteEnabled;
  33410. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33411. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33412. defines.TONEMAPPING = this.toneMappingEnabled;
  33413. defines.CONTRAST = (this.contrast !== 1.0);
  33414. defines.EXPOSURE = (this.exposure !== 1.0);
  33415. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33416. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33417. if (defines.COLORGRADING) {
  33418. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33419. }
  33420. else {
  33421. defines.COLORGRADING3D = false;
  33422. }
  33423. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33424. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33425. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33426. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33427. };
  33428. /**
  33429. * Returns true if all the image processing information are ready.
  33430. */
  33431. ImageProcessingConfiguration.prototype.isReady = function () {
  33432. // Color Grading texure can not be none blocking.
  33433. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33434. };
  33435. /**
  33436. * Binds the image processing to the shader.
  33437. * @param effect The effect to bind to
  33438. */
  33439. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33440. if (aspectRatio === void 0) { aspectRatio = 1; }
  33441. // Color Curves
  33442. if (this._colorCurvesEnabled && this.colorCurves) {
  33443. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33444. }
  33445. // Vignette
  33446. if (this._vignetteEnabled) {
  33447. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33448. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33449. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33450. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33451. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33452. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33453. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33454. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33455. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33456. var vignettePower = -2.0 * this.vignetteWeight;
  33457. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33458. }
  33459. // Exposure
  33460. effect.setFloat("exposureLinear", this.exposure);
  33461. // Contrast
  33462. effect.setFloat("contrast", this.contrast);
  33463. // Color transform settings
  33464. if (this.colorGradingTexture) {
  33465. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33466. var textureSize = this.colorGradingTexture.getSize().height;
  33467. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33468. 0.5 / textureSize, // textureOffset
  33469. textureSize, // textureSize
  33470. this.colorGradingTexture.level // weight
  33471. );
  33472. }
  33473. };
  33474. /**
  33475. * Clones the current image processing instance.
  33476. * @return The cloned image processing
  33477. */
  33478. ImageProcessingConfiguration.prototype.clone = function () {
  33479. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33480. };
  33481. /**
  33482. * Serializes the current image processing instance to a json representation.
  33483. * @return a JSON representation
  33484. */
  33485. ImageProcessingConfiguration.prototype.serialize = function () {
  33486. return BABYLON.SerializationHelper.Serialize(this);
  33487. };
  33488. /**
  33489. * Parses the image processing from a json representation.
  33490. * @param source the JSON source to parse
  33491. * @return The parsed image processing
  33492. */
  33493. ImageProcessingConfiguration.Parse = function (source) {
  33494. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33495. };
  33496. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33497. /**
  33498. * Used to apply the vignette as a mix with the pixel color.
  33499. */
  33500. get: function () {
  33501. return this._VIGNETTEMODE_MULTIPLY;
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33507. /**
  33508. * Used to apply the vignette as a replacement of the pixel color.
  33509. */
  33510. get: function () {
  33511. return this._VIGNETTEMODE_OPAQUE;
  33512. },
  33513. enumerable: true,
  33514. configurable: true
  33515. });
  33516. // Static constants associated to the image processing.
  33517. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33518. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33519. __decorate([
  33520. BABYLON.serializeAsColorCurves()
  33521. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33522. __decorate([
  33523. BABYLON.serialize()
  33524. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33525. __decorate([
  33526. BABYLON.serializeAsTexture()
  33527. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33528. __decorate([
  33529. BABYLON.serialize()
  33530. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33531. __decorate([
  33532. BABYLON.serialize()
  33533. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33534. __decorate([
  33535. BABYLON.serialize()
  33536. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33537. __decorate([
  33538. BABYLON.serialize()
  33539. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33540. __decorate([
  33541. BABYLON.serialize()
  33542. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33543. __decorate([
  33544. BABYLON.serialize()
  33545. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33546. __decorate([
  33547. BABYLON.serialize()
  33548. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33549. __decorate([
  33550. BABYLON.serialize()
  33551. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33552. __decorate([
  33553. BABYLON.serialize()
  33554. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33555. __decorate([
  33556. BABYLON.serialize()
  33557. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33558. __decorate([
  33559. BABYLON.serializeAsColor4()
  33560. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33561. __decorate([
  33562. BABYLON.serialize()
  33563. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33564. __decorate([
  33565. BABYLON.serialize()
  33566. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33567. __decorate([
  33568. BABYLON.serialize()
  33569. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33570. __decorate([
  33571. BABYLON.serialize()
  33572. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33573. __decorate([
  33574. BABYLON.serialize()
  33575. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33576. return ImageProcessingConfiguration;
  33577. }());
  33578. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33579. })(BABYLON || (BABYLON = {}));
  33580. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33581. var BABYLON;
  33582. (function (BABYLON) {
  33583. /**
  33584. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33585. * It can help converting any input color in a desired output one. This can then be used to create effects
  33586. * from sepia, black and white to sixties or futuristic rendering...
  33587. *
  33588. * The only supported format is currently 3dl.
  33589. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33590. */
  33591. var ColorGradingTexture = /** @class */ (function (_super) {
  33592. __extends(ColorGradingTexture, _super);
  33593. /**
  33594. * Instantiates a ColorGradingTexture from the following parameters.
  33595. *
  33596. * @param url The location of the color gradind data (currently only supporting 3dl)
  33597. * @param scene The scene the texture will be used in
  33598. */
  33599. function ColorGradingTexture(url, scene) {
  33600. var _this = _super.call(this, scene) || this;
  33601. if (!url) {
  33602. return _this;
  33603. }
  33604. _this._engine = scene.getEngine();
  33605. _this._textureMatrix = BABYLON.Matrix.Identity();
  33606. _this.name = url;
  33607. _this.url = url;
  33608. _this.hasAlpha = false;
  33609. _this.isCube = false;
  33610. _this.is3D = _this._engine.webGLVersion > 1;
  33611. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33612. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33613. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33614. _this.anisotropicFilteringLevel = 1;
  33615. _this._texture = _this._getFromCache(url, true);
  33616. if (!_this._texture) {
  33617. if (!scene.useDelayedTextureLoading) {
  33618. _this.loadTexture();
  33619. }
  33620. else {
  33621. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33622. }
  33623. }
  33624. return _this;
  33625. }
  33626. /**
  33627. * Returns the texture matrix used in most of the material.
  33628. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33629. */
  33630. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33631. return this._textureMatrix;
  33632. };
  33633. /**
  33634. * Occurs when the file being loaded is a .3dl LUT file.
  33635. */
  33636. ColorGradingTexture.prototype.load3dlTexture = function () {
  33637. var engine = this._engine;
  33638. var texture;
  33639. if (engine.webGLVersion === 1) {
  33640. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33641. }
  33642. else {
  33643. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33644. }
  33645. this._texture = texture;
  33646. var callback = function (text) {
  33647. if (typeof text !== "string") {
  33648. return;
  33649. }
  33650. var data = null;
  33651. var tempData = null;
  33652. var line;
  33653. var lines = text.split('\n');
  33654. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33655. var maxColor = 0;
  33656. for (var i = 0; i < lines.length; i++) {
  33657. line = lines[i];
  33658. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33659. continue;
  33660. if (line.indexOf('#') === 0)
  33661. continue;
  33662. var words = line.split(" ");
  33663. if (size === 0) {
  33664. // Number of space + one
  33665. size = words.length;
  33666. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33667. tempData = new Float32Array(size * size * size * 4);
  33668. continue;
  33669. }
  33670. if (size != 0) {
  33671. var r = Math.max(parseInt(words[0]), 0);
  33672. var g = Math.max(parseInt(words[1]), 0);
  33673. var b = Math.max(parseInt(words[2]), 0);
  33674. maxColor = Math.max(r, maxColor);
  33675. maxColor = Math.max(g, maxColor);
  33676. maxColor = Math.max(b, maxColor);
  33677. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33678. if (tempData) {
  33679. tempData[pixelStorageIndex + 0] = r;
  33680. tempData[pixelStorageIndex + 1] = g;
  33681. tempData[pixelStorageIndex + 2] = b;
  33682. }
  33683. pixelIndexSlice++;
  33684. if (pixelIndexSlice % size == 0) {
  33685. pixelIndexH++;
  33686. pixelIndexSlice = 0;
  33687. if (pixelIndexH % size == 0) {
  33688. pixelIndexW++;
  33689. pixelIndexH = 0;
  33690. }
  33691. }
  33692. }
  33693. }
  33694. if (tempData && data) {
  33695. for (var i = 0; i < tempData.length; i++) {
  33696. if (i > 0 && (i + 1) % 4 === 0) {
  33697. data[i] = 255;
  33698. }
  33699. else {
  33700. var value = tempData[i];
  33701. data[i] = (value / maxColor * 255);
  33702. }
  33703. }
  33704. }
  33705. if (texture.is3D) {
  33706. texture.updateSize(size, size, size);
  33707. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33708. }
  33709. else {
  33710. texture.updateSize(size * size, size);
  33711. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33712. }
  33713. };
  33714. var scene = this.getScene();
  33715. if (scene) {
  33716. scene._loadFile(this.url, callback);
  33717. }
  33718. else {
  33719. this._engine._loadFile(this.url, callback);
  33720. }
  33721. return this._texture;
  33722. };
  33723. /**
  33724. * Starts the loading process of the texture.
  33725. */
  33726. ColorGradingTexture.prototype.loadTexture = function () {
  33727. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33728. this.load3dlTexture();
  33729. }
  33730. };
  33731. /**
  33732. * Clones the color gradind texture.
  33733. */
  33734. ColorGradingTexture.prototype.clone = function () {
  33735. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33736. // Base texture
  33737. newTexture.level = this.level;
  33738. return newTexture;
  33739. };
  33740. /**
  33741. * Called during delayed load for textures.
  33742. */
  33743. ColorGradingTexture.prototype.delayLoad = function () {
  33744. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33745. return;
  33746. }
  33747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33748. this._texture = this._getFromCache(this.url, true);
  33749. if (!this._texture) {
  33750. this.loadTexture();
  33751. }
  33752. };
  33753. /**
  33754. * Parses a color grading texture serialized by Babylon.
  33755. * @param parsedTexture The texture information being parsedTexture
  33756. * @param scene The scene to load the texture in
  33757. * @param rootUrl The root url of the data assets to load
  33758. * @return A color gradind texture
  33759. */
  33760. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33761. var texture = null;
  33762. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33763. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33764. texture.name = parsedTexture.name;
  33765. texture.level = parsedTexture.level;
  33766. }
  33767. return texture;
  33768. };
  33769. /**
  33770. * Serializes the LUT texture to json format.
  33771. */
  33772. ColorGradingTexture.prototype.serialize = function () {
  33773. if (!this.name) {
  33774. return null;
  33775. }
  33776. var serializationObject = {};
  33777. serializationObject.name = this.name;
  33778. serializationObject.level = this.level;
  33779. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33780. return serializationObject;
  33781. };
  33782. /**
  33783. * Empty line regex stored for GC.
  33784. */
  33785. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33786. return ColorGradingTexture;
  33787. }(BABYLON.BaseTexture));
  33788. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33789. })(BABYLON || (BABYLON = {}));
  33790. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33791. var BABYLON;
  33792. (function (BABYLON) {
  33793. /**
  33794. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33795. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33796. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  33797. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33798. */
  33799. var ColorCurves = /** @class */ (function () {
  33800. function ColorCurves() {
  33801. this._dirty = true;
  33802. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33803. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33804. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33805. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33806. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33807. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33808. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33809. this._globalHue = 30;
  33810. this._globalDensity = 0;
  33811. this._globalSaturation = 0;
  33812. this._globalExposure = 0;
  33813. this._highlightsHue = 30;
  33814. this._highlightsDensity = 0;
  33815. this._highlightsSaturation = 0;
  33816. this._highlightsExposure = 0;
  33817. this._midtonesHue = 30;
  33818. this._midtonesDensity = 0;
  33819. this._midtonesSaturation = 0;
  33820. this._midtonesExposure = 0;
  33821. this._shadowsHue = 30;
  33822. this._shadowsDensity = 0;
  33823. this._shadowsSaturation = 0;
  33824. this._shadowsExposure = 0;
  33825. }
  33826. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33827. /**
  33828. * Gets the global Hue value.
  33829. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33830. */
  33831. get: function () {
  33832. return this._globalHue;
  33833. },
  33834. /**
  33835. * Sets the global Hue value.
  33836. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33837. */
  33838. set: function (value) {
  33839. this._globalHue = value;
  33840. this._dirty = true;
  33841. },
  33842. enumerable: true,
  33843. configurable: true
  33844. });
  33845. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33846. /**
  33847. * Gets the global Density value.
  33848. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33849. * Values less than zero provide a filter of opposite hue.
  33850. */
  33851. get: function () {
  33852. return this._globalDensity;
  33853. },
  33854. /**
  33855. * Sets the global Density value.
  33856. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33857. * Values less than zero provide a filter of opposite hue.
  33858. */
  33859. set: function (value) {
  33860. this._globalDensity = value;
  33861. this._dirty = true;
  33862. },
  33863. enumerable: true,
  33864. configurable: true
  33865. });
  33866. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33867. /**
  33868. * Gets the global Saturation value.
  33869. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33870. */
  33871. get: function () {
  33872. return this._globalSaturation;
  33873. },
  33874. /**
  33875. * Sets the global Saturation value.
  33876. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33877. */
  33878. set: function (value) {
  33879. this._globalSaturation = value;
  33880. this._dirty = true;
  33881. },
  33882. enumerable: true,
  33883. configurable: true
  33884. });
  33885. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33886. /**
  33887. * Gets the highlights Hue value.
  33888. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33889. */
  33890. get: function () {
  33891. return this._highlightsHue;
  33892. },
  33893. /**
  33894. * Sets the highlights Hue value.
  33895. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33896. */
  33897. set: function (value) {
  33898. this._highlightsHue = value;
  33899. this._dirty = true;
  33900. },
  33901. enumerable: true,
  33902. configurable: true
  33903. });
  33904. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33905. /**
  33906. * Gets the highlights Density value.
  33907. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33908. * Values less than zero provide a filter of opposite hue.
  33909. */
  33910. get: function () {
  33911. return this._highlightsDensity;
  33912. },
  33913. /**
  33914. * Sets the highlights Density value.
  33915. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33916. * Values less than zero provide a filter of opposite hue.
  33917. */
  33918. set: function (value) {
  33919. this._highlightsDensity = value;
  33920. this._dirty = true;
  33921. },
  33922. enumerable: true,
  33923. configurable: true
  33924. });
  33925. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33926. /**
  33927. * Gets the highlights Saturation value.
  33928. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33929. */
  33930. get: function () {
  33931. return this._highlightsSaturation;
  33932. },
  33933. /**
  33934. * Sets the highlights Saturation value.
  33935. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  33936. */
  33937. set: function (value) {
  33938. this._highlightsSaturation = value;
  33939. this._dirty = true;
  33940. },
  33941. enumerable: true,
  33942. configurable: true
  33943. });
  33944. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33945. /**
  33946. * Gets the highlights Exposure value.
  33947. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33948. */
  33949. get: function () {
  33950. return this._highlightsExposure;
  33951. },
  33952. /**
  33953. * Sets the highlights Exposure value.
  33954. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  33955. */
  33956. set: function (value) {
  33957. this._highlightsExposure = value;
  33958. this._dirty = true;
  33959. },
  33960. enumerable: true,
  33961. configurable: true
  33962. });
  33963. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33964. /**
  33965. * Gets the midtones Hue value.
  33966. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33967. */
  33968. get: function () {
  33969. return this._midtonesHue;
  33970. },
  33971. /**
  33972. * Sets the midtones Hue value.
  33973. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  33974. */
  33975. set: function (value) {
  33976. this._midtonesHue = value;
  33977. this._dirty = true;
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33983. /**
  33984. * Gets the midtones Density value.
  33985. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33986. * Values less than zero provide a filter of opposite hue.
  33987. */
  33988. get: function () {
  33989. return this._midtonesDensity;
  33990. },
  33991. /**
  33992. * Sets the midtones Density value.
  33993. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  33994. * Values less than zero provide a filter of opposite hue.
  33995. */
  33996. set: function (value) {
  33997. this._midtonesDensity = value;
  33998. this._dirty = true;
  33999. },
  34000. enumerable: true,
  34001. configurable: true
  34002. });
  34003. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34004. /**
  34005. * Gets the midtones Saturation value.
  34006. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  34007. */
  34008. get: function () {
  34009. return this._midtonesSaturation;
  34010. },
  34011. /**
  34012. * Sets the midtones Saturation value.
  34013. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  34014. */
  34015. set: function (value) {
  34016. this._midtonesSaturation = value;
  34017. this._dirty = true;
  34018. },
  34019. enumerable: true,
  34020. configurable: true
  34021. });
  34022. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34023. /**
  34024. * Gets the midtones Exposure value.
  34025. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  34026. */
  34027. get: function () {
  34028. return this._midtonesExposure;
  34029. },
  34030. /**
  34031. * Sets the midtones Exposure value.
  34032. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  34033. */
  34034. set: function (value) {
  34035. this._midtonesExposure = value;
  34036. this._dirty = true;
  34037. },
  34038. enumerable: true,
  34039. configurable: true
  34040. });
  34041. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34042. /**
  34043. * Gets the shadows Hue value.
  34044. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  34045. */
  34046. get: function () {
  34047. return this._shadowsHue;
  34048. },
  34049. /**
  34050. * Sets the shadows Hue value.
  34051. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  34052. */
  34053. set: function (value) {
  34054. this._shadowsHue = value;
  34055. this._dirty = true;
  34056. },
  34057. enumerable: true,
  34058. configurable: true
  34059. });
  34060. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34061. /**
  34062. * Gets the shadows Density value.
  34063. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  34064. * Values less than zero provide a filter of opposite hue.
  34065. */
  34066. get: function () {
  34067. return this._shadowsDensity;
  34068. },
  34069. /**
  34070. * Sets the shadows Density value.
  34071. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  34072. * Values less than zero provide a filter of opposite hue.
  34073. */
  34074. set: function (value) {
  34075. this._shadowsDensity = value;
  34076. this._dirty = true;
  34077. },
  34078. enumerable: true,
  34079. configurable: true
  34080. });
  34081. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34082. /**
  34083. * Gets the shadows Saturation value.
  34084. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  34085. */
  34086. get: function () {
  34087. return this._shadowsSaturation;
  34088. },
  34089. /**
  34090. * Sets the shadows Saturation value.
  34091. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  34092. */
  34093. set: function (value) {
  34094. this._shadowsSaturation = value;
  34095. this._dirty = true;
  34096. },
  34097. enumerable: true,
  34098. configurable: true
  34099. });
  34100. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34101. /**
  34102. * Gets the shadows Exposure value.
  34103. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  34104. */
  34105. get: function () {
  34106. return this._shadowsExposure;
  34107. },
  34108. /**
  34109. * Sets the shadows Exposure value.
  34110. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  34111. */
  34112. set: function (value) {
  34113. this._shadowsExposure = value;
  34114. this._dirty = true;
  34115. },
  34116. enumerable: true,
  34117. configurable: true
  34118. });
  34119. ColorCurves.prototype.getClassName = function () {
  34120. return "ColorCurves";
  34121. };
  34122. /**
  34123. * Binds the color curves to the shader.
  34124. * @param colorCurves The color curve to bind
  34125. * @param effect The effect to bind to
  34126. */
  34127. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34128. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34129. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34130. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34131. if (colorCurves._dirty) {
  34132. colorCurves._dirty = false;
  34133. // Fill in global info.
  34134. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34135. // Compute highlights info.
  34136. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34137. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34138. // Compute midtones info.
  34139. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34140. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34141. // Compute shadows info.
  34142. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34143. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34144. // Compute deltas (neutral is midtones).
  34145. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34146. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34147. }
  34148. if (effect) {
  34149. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34150. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34151. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34152. }
  34153. };
  34154. /**
  34155. * Prepare the list of uniforms associated with the ColorCurves effects.
  34156. * @param uniformsList The list of uniforms used in the effect
  34157. */
  34158. ColorCurves.PrepareUniforms = function (uniformsList) {
  34159. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34160. };
  34161. /**
  34162. * Returns color grading data based on a hue, density, saturation and exposure value.
  34163. * @param filterHue The hue of the color filter.
  34164. * @param filterDensity The density of the color filter.
  34165. * @param saturation The saturation.
  34166. * @param exposure The exposure.
  34167. * @param result The result data container.
  34168. */
  34169. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34170. if (hue == null) {
  34171. return;
  34172. }
  34173. hue = ColorCurves.clamp(hue, 0, 360);
  34174. density = ColorCurves.clamp(density, -100, 100);
  34175. saturation = ColorCurves.clamp(saturation, -100, 100);
  34176. exposure = ColorCurves.clamp(exposure, -100, 100);
  34177. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34178. // so that the maximum filter density is only 50% control. This provides fine control
  34179. // for small values and reasonable range.
  34180. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34181. density *= 0.5;
  34182. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34183. if (density < 0) {
  34184. density *= -1;
  34185. hue = (hue + 180) % 360;
  34186. }
  34187. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34188. result.scaleToRef(2, result);
  34189. result.a = 1 + 0.01 * saturation;
  34190. };
  34191. /**
  34192. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34193. * @param value The input slider value in range [-100,100].
  34194. * @returns Adjusted value.
  34195. */
  34196. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34197. value /= 100;
  34198. var x = Math.abs(value);
  34199. x = Math.pow(x, 2);
  34200. if (value < 0) {
  34201. x *= -1;
  34202. }
  34203. x *= 100;
  34204. return x;
  34205. };
  34206. /**
  34207. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34208. * @param hue The hue (H) input.
  34209. * @param saturation The saturation (S) input.
  34210. * @param brightness The brightness (B) input.
  34211. * @result An RGBA color represented as Vector4.
  34212. */
  34213. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34214. var h = ColorCurves.clamp(hue, 0, 360);
  34215. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34216. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34217. if (s === 0) {
  34218. result.r = v;
  34219. result.g = v;
  34220. result.b = v;
  34221. }
  34222. else {
  34223. // sector 0 to 5
  34224. h /= 60;
  34225. var i = Math.floor(h);
  34226. // fractional part of h
  34227. var f = h - i;
  34228. var p = v * (1 - s);
  34229. var q = v * (1 - s * f);
  34230. var t = v * (1 - s * (1 - f));
  34231. switch (i) {
  34232. case 0:
  34233. result.r = v;
  34234. result.g = t;
  34235. result.b = p;
  34236. break;
  34237. case 1:
  34238. result.r = q;
  34239. result.g = v;
  34240. result.b = p;
  34241. break;
  34242. case 2:
  34243. result.r = p;
  34244. result.g = v;
  34245. result.b = t;
  34246. break;
  34247. case 3:
  34248. result.r = p;
  34249. result.g = q;
  34250. result.b = v;
  34251. break;
  34252. case 4:
  34253. result.r = t;
  34254. result.g = p;
  34255. result.b = v;
  34256. break;
  34257. default:// case 5:
  34258. result.r = v;
  34259. result.g = p;
  34260. result.b = q;
  34261. break;
  34262. }
  34263. }
  34264. result.a = 1;
  34265. };
  34266. /**
  34267. * Returns a value clamped between min and max
  34268. * @param value The value to clamp
  34269. * @param min The minimum of value
  34270. * @param max The maximum of value
  34271. * @returns The clamped value.
  34272. */
  34273. ColorCurves.clamp = function (value, min, max) {
  34274. return Math.min(Math.max(value, min), max);
  34275. };
  34276. /**
  34277. * Clones the current color curve instance.
  34278. * @return The cloned curves
  34279. */
  34280. ColorCurves.prototype.clone = function () {
  34281. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34282. };
  34283. /**
  34284. * Serializes the current color curve instance to a json representation.
  34285. * @return a JSON representation
  34286. */
  34287. ColorCurves.prototype.serialize = function () {
  34288. return BABYLON.SerializationHelper.Serialize(this);
  34289. };
  34290. /**
  34291. * Parses the color curve from a json representation.
  34292. * @param source the JSON source to parse
  34293. * @return The parsed curves
  34294. */
  34295. ColorCurves.Parse = function (source) {
  34296. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34297. };
  34298. __decorate([
  34299. BABYLON.serialize()
  34300. ], ColorCurves.prototype, "_globalHue", void 0);
  34301. __decorate([
  34302. BABYLON.serialize()
  34303. ], ColorCurves.prototype, "_globalDensity", void 0);
  34304. __decorate([
  34305. BABYLON.serialize()
  34306. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34307. __decorate([
  34308. BABYLON.serialize()
  34309. ], ColorCurves.prototype, "_globalExposure", void 0);
  34310. __decorate([
  34311. BABYLON.serialize()
  34312. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34313. __decorate([
  34314. BABYLON.serialize()
  34315. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34316. __decorate([
  34317. BABYLON.serialize()
  34318. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34319. __decorate([
  34320. BABYLON.serialize()
  34321. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34322. __decorate([
  34323. BABYLON.serialize()
  34324. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34325. __decorate([
  34326. BABYLON.serialize()
  34327. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34328. __decorate([
  34329. BABYLON.serialize()
  34330. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34331. __decorate([
  34332. BABYLON.serialize()
  34333. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34334. return ColorCurves;
  34335. }());
  34336. BABYLON.ColorCurves = ColorCurves;
  34337. })(BABYLON || (BABYLON = {}));
  34338. //# sourceMappingURL=babylon.colorCurves.js.map
  34339. //# sourceMappingURL=babylon.behavior.js.map
  34340. var BABYLON;
  34341. (function (BABYLON) {
  34342. var MaterialHelper = /** @class */ (function () {
  34343. function MaterialHelper() {
  34344. }
  34345. MaterialHelper.BindEyePosition = function (effect, scene) {
  34346. if (scene._forcedViewPosition) {
  34347. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34348. return;
  34349. }
  34350. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34351. };
  34352. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34353. defines._needUVs = true;
  34354. defines[key] = true;
  34355. if (texture.getTextureMatrix().isIdentity(true)) {
  34356. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34357. if (texture.coordinatesIndex === 0) {
  34358. defines["MAINUV1"] = true;
  34359. }
  34360. else {
  34361. defines["MAINUV2"] = true;
  34362. }
  34363. }
  34364. else {
  34365. defines[key + "DIRECTUV"] = 0;
  34366. }
  34367. };
  34368. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34369. var matrix = texture.getTextureMatrix();
  34370. if (!matrix.isIdentity(true)) {
  34371. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34372. }
  34373. };
  34374. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34375. if (defines._areMiscDirty) {
  34376. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34377. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34378. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34379. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34380. }
  34381. };
  34382. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34383. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34384. var changed = false;
  34385. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34386. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34387. changed = true;
  34388. }
  34389. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34390. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34391. changed = true;
  34392. }
  34393. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34394. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34395. changed = true;
  34396. }
  34397. if (defines["INSTANCES"] !== useInstances) {
  34398. defines["INSTANCES"] = useInstances;
  34399. changed = true;
  34400. }
  34401. if (changed) {
  34402. defines.markAsUnprocessed();
  34403. }
  34404. };
  34405. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34406. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34407. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34408. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34409. return false;
  34410. }
  34411. defines._normals = defines._needNormals;
  34412. defines._uvs = defines._needUVs;
  34413. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34414. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34415. defines["TANGENT"] = true;
  34416. }
  34417. if (defines._needUVs) {
  34418. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34419. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34420. }
  34421. else {
  34422. defines["UV1"] = false;
  34423. defines["UV2"] = false;
  34424. }
  34425. if (useVertexColor) {
  34426. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34427. defines["VERTEXCOLOR"] = hasVertexColors;
  34428. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34429. }
  34430. if (useBones) {
  34431. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34432. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34433. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34434. }
  34435. else {
  34436. defines["NUM_BONE_INFLUENCERS"] = 0;
  34437. defines["BonesPerMesh"] = 0;
  34438. }
  34439. }
  34440. if (useMorphTargets) {
  34441. var manager = mesh.morphTargetManager;
  34442. if (manager) {
  34443. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34444. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34445. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34446. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34447. }
  34448. else {
  34449. defines["MORPHTARGETS_TANGENT"] = false;
  34450. defines["MORPHTARGETS_NORMAL"] = false;
  34451. defines["MORPHTARGETS"] = false;
  34452. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34453. }
  34454. }
  34455. return true;
  34456. };
  34457. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34458. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34459. if (disableLighting === void 0) { disableLighting = false; }
  34460. if (!defines._areLightsDirty) {
  34461. return defines._needNormals;
  34462. }
  34463. var lightIndex = 0;
  34464. var needNormals = false;
  34465. var needRebuild = false;
  34466. var lightmapMode = false;
  34467. var shadowEnabled = false;
  34468. var specularEnabled = false;
  34469. if (scene.lightsEnabled && !disableLighting) {
  34470. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34471. var light = _a[_i];
  34472. needNormals = true;
  34473. if (defines["LIGHT" + lightIndex] === undefined) {
  34474. needRebuild = true;
  34475. }
  34476. defines["LIGHT" + lightIndex] = true;
  34477. defines["SPOTLIGHT" + lightIndex] = false;
  34478. defines["HEMILIGHT" + lightIndex] = false;
  34479. defines["POINTLIGHT" + lightIndex] = false;
  34480. defines["DIRLIGHT" + lightIndex] = false;
  34481. var type;
  34482. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34483. type = "SPOTLIGHT" + lightIndex;
  34484. }
  34485. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34486. type = "HEMILIGHT" + lightIndex;
  34487. }
  34488. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34489. type = "POINTLIGHT" + lightIndex;
  34490. }
  34491. else {
  34492. type = "DIRLIGHT" + lightIndex;
  34493. }
  34494. defines[type] = true;
  34495. // Specular
  34496. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34497. specularEnabled = true;
  34498. }
  34499. // Shadows
  34500. defines["SHADOW" + lightIndex] = false;
  34501. defines["SHADOWPCF" + lightIndex] = false;
  34502. defines["SHADOWESM" + lightIndex] = false;
  34503. defines["SHADOWCUBE" + lightIndex] = false;
  34504. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34505. var shadowGenerator = light.getShadowGenerator();
  34506. if (shadowGenerator) {
  34507. shadowEnabled = true;
  34508. shadowGenerator.prepareDefines(defines, lightIndex);
  34509. }
  34510. }
  34511. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34512. lightmapMode = true;
  34513. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34514. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34515. }
  34516. else {
  34517. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34518. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34519. }
  34520. lightIndex++;
  34521. if (lightIndex === maxSimultaneousLights)
  34522. break;
  34523. }
  34524. }
  34525. defines["SPECULARTERM"] = specularEnabled;
  34526. defines["SHADOWS"] = shadowEnabled;
  34527. // Resetting all other lights if any
  34528. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34529. if (defines["LIGHT" + index] !== undefined) {
  34530. defines["LIGHT" + index] = false;
  34531. defines["HEMILIGHT" + lightIndex] = false;
  34532. defines["POINTLIGHT" + lightIndex] = false;
  34533. defines["DIRLIGHT" + lightIndex] = false;
  34534. defines["SPOTLIGHT" + lightIndex] = false;
  34535. defines["SHADOW" + lightIndex] = false;
  34536. }
  34537. }
  34538. var caps = scene.getEngine().getCaps();
  34539. if (defines["SHADOWFLOAT"] === undefined) {
  34540. needRebuild = true;
  34541. }
  34542. defines["SHADOWFLOAT"] = shadowEnabled &&
  34543. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34544. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34545. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34546. if (needRebuild) {
  34547. defines.rebuild();
  34548. }
  34549. return needNormals;
  34550. };
  34551. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34552. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34553. var uniformsList;
  34554. var uniformBuffersList = null;
  34555. if (uniformsListOrOptions.uniformsNames) {
  34556. var options = uniformsListOrOptions;
  34557. uniformsList = options.uniformsNames;
  34558. uniformBuffersList = options.uniformBuffersNames;
  34559. samplersList = options.samplers;
  34560. defines = options.defines;
  34561. maxSimultaneousLights = options.maxSimultaneousLights;
  34562. }
  34563. else {
  34564. uniformsList = uniformsListOrOptions;
  34565. if (!samplersList) {
  34566. samplersList = [];
  34567. }
  34568. }
  34569. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34570. if (!defines["LIGHT" + lightIndex]) {
  34571. break;
  34572. }
  34573. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34574. if (uniformBuffersList) {
  34575. uniformBuffersList.push("Light" + lightIndex);
  34576. }
  34577. samplersList.push("shadowSampler" + lightIndex);
  34578. }
  34579. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34580. uniformsList.push("morphTargetInfluences");
  34581. }
  34582. };
  34583. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34584. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34585. if (rank === void 0) { rank = 0; }
  34586. var lightFallbackRank = 0;
  34587. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34588. if (!defines["LIGHT" + lightIndex]) {
  34589. break;
  34590. }
  34591. if (lightIndex > 0) {
  34592. lightFallbackRank = rank + lightIndex;
  34593. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34594. }
  34595. if (!defines["SHADOWS"]) {
  34596. if (defines["SHADOW" + lightIndex]) {
  34597. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34598. }
  34599. if (defines["SHADOWPCF" + lightIndex]) {
  34600. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34601. }
  34602. if (defines["SHADOWESM" + lightIndex]) {
  34603. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34604. }
  34605. }
  34606. }
  34607. return lightFallbackRank++;
  34608. };
  34609. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34610. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34611. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34612. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34613. var manager = mesh.morphTargetManager;
  34614. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34615. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34616. for (var index = 0; index < influencers; index++) {
  34617. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34618. if (normal) {
  34619. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34620. }
  34621. if (tangent) {
  34622. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34623. }
  34624. if (attribs.length > maxAttributesCount) {
  34625. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34626. }
  34627. }
  34628. }
  34629. };
  34630. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34631. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34632. fallbacks.addCPUSkinningFallback(0, mesh);
  34633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34635. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34638. }
  34639. }
  34640. };
  34641. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34642. if (defines["INSTANCES"]) {
  34643. attribs.push("world0");
  34644. attribs.push("world1");
  34645. attribs.push("world2");
  34646. attribs.push("world3");
  34647. }
  34648. };
  34649. // Bindings
  34650. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34651. if (light.shadowEnabled && mesh.receiveShadows) {
  34652. var shadowGenerator = light.getShadowGenerator();
  34653. if (shadowGenerator) {
  34654. shadowGenerator.bindShadowLight(lightIndex, effect);
  34655. }
  34656. }
  34657. };
  34658. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34659. light.transferToEffect(effect, lightIndex + "");
  34660. };
  34661. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34662. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34663. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34664. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34665. for (var i = 0; i < len; i++) {
  34666. var light = mesh._lightSources[i];
  34667. var iAsString = i.toString();
  34668. var scaledIntensity = light.getScaledIntensity();
  34669. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34670. MaterialHelper.BindLightProperties(light, effect, i);
  34671. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34672. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34673. if (defines["SPECULARTERM"]) {
  34674. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34675. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34676. }
  34677. // Shadows
  34678. if (scene.shadowsEnabled) {
  34679. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34680. }
  34681. light._uniformBuffer.update();
  34682. }
  34683. };
  34684. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34685. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34686. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34687. effect.setColor3("vFogColor", scene.fogColor);
  34688. }
  34689. };
  34690. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34691. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34692. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34693. if (matrices && effect) {
  34694. effect.setMatrices("mBones", matrices);
  34695. }
  34696. }
  34697. };
  34698. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34699. var manager = abstractMesh.morphTargetManager;
  34700. if (!abstractMesh || !manager) {
  34701. return;
  34702. }
  34703. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34704. };
  34705. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34706. if (defines["LOGARITHMICDEPTH"]) {
  34707. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34708. }
  34709. };
  34710. MaterialHelper.BindClipPlane = function (effect, scene) {
  34711. if (scene.clipPlane) {
  34712. var clipPlane = scene.clipPlane;
  34713. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34714. }
  34715. };
  34716. return MaterialHelper;
  34717. }());
  34718. BABYLON.MaterialHelper = MaterialHelper;
  34719. })(BABYLON || (BABYLON = {}));
  34720. //# sourceMappingURL=babylon.materialHelper.js.map
  34721. var BABYLON;
  34722. (function (BABYLON) {
  34723. var PushMaterial = /** @class */ (function (_super) {
  34724. __extends(PushMaterial, _super);
  34725. function PushMaterial(name, scene) {
  34726. var _this = _super.call(this, name, scene) || this;
  34727. _this.storeEffectOnSubMeshes = true;
  34728. return _this;
  34729. }
  34730. PushMaterial.prototype.getEffect = function () {
  34731. return this._activeEffect;
  34732. };
  34733. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34734. if (!mesh) {
  34735. return false;
  34736. }
  34737. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34738. return true;
  34739. }
  34740. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34741. };
  34742. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34743. this._activeEffect.setMatrix("world", world);
  34744. };
  34745. PushMaterial.prototype.bind = function (world, mesh) {
  34746. if (!mesh) {
  34747. return;
  34748. }
  34749. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34750. };
  34751. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34752. if (effect === void 0) { effect = null; }
  34753. _super.prototype._afterBind.call(this, mesh);
  34754. this.getScene()._cachedEffect = effect;
  34755. };
  34756. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34757. if (visibility === void 0) { visibility = 1; }
  34758. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34759. };
  34760. return PushMaterial;
  34761. }(BABYLON.Material));
  34762. BABYLON.PushMaterial = PushMaterial;
  34763. })(BABYLON || (BABYLON = {}));
  34764. //# sourceMappingURL=babylon.pushMaterial.js.map
  34765. var BABYLON;
  34766. (function (BABYLON) {
  34767. var StandardMaterialDefines = /** @class */ (function (_super) {
  34768. __extends(StandardMaterialDefines, _super);
  34769. function StandardMaterialDefines() {
  34770. var _this = _super.call(this) || this;
  34771. _this.MAINUV1 = false;
  34772. _this.MAINUV2 = false;
  34773. _this.DIFFUSE = false;
  34774. _this.DIFFUSEDIRECTUV = 0;
  34775. _this.AMBIENT = false;
  34776. _this.AMBIENTDIRECTUV = 0;
  34777. _this.OPACITY = false;
  34778. _this.OPACITYDIRECTUV = 0;
  34779. _this.OPACITYRGB = false;
  34780. _this.REFLECTION = false;
  34781. _this.EMISSIVE = false;
  34782. _this.EMISSIVEDIRECTUV = 0;
  34783. _this.SPECULAR = false;
  34784. _this.SPECULARDIRECTUV = 0;
  34785. _this.BUMP = false;
  34786. _this.BUMPDIRECTUV = 0;
  34787. _this.PARALLAX = false;
  34788. _this.PARALLAXOCCLUSION = false;
  34789. _this.SPECULAROVERALPHA = false;
  34790. _this.CLIPPLANE = false;
  34791. _this.ALPHATEST = false;
  34792. _this.DEPTHPREPASS = false;
  34793. _this.ALPHAFROMDIFFUSE = false;
  34794. _this.POINTSIZE = false;
  34795. _this.FOG = false;
  34796. _this.SPECULARTERM = false;
  34797. _this.DIFFUSEFRESNEL = false;
  34798. _this.OPACITYFRESNEL = false;
  34799. _this.REFLECTIONFRESNEL = false;
  34800. _this.REFRACTIONFRESNEL = false;
  34801. _this.EMISSIVEFRESNEL = false;
  34802. _this.FRESNEL = false;
  34803. _this.NORMAL = false;
  34804. _this.UV1 = false;
  34805. _this.UV2 = false;
  34806. _this.VERTEXCOLOR = false;
  34807. _this.VERTEXALPHA = false;
  34808. _this.NUM_BONE_INFLUENCERS = 0;
  34809. _this.BonesPerMesh = 0;
  34810. _this.INSTANCES = false;
  34811. _this.GLOSSINESS = false;
  34812. _this.ROUGHNESS = false;
  34813. _this.EMISSIVEASILLUMINATION = false;
  34814. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34815. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34816. _this.LIGHTMAP = false;
  34817. _this.LIGHTMAPDIRECTUV = 0;
  34818. _this.USELIGHTMAPASSHADOWMAP = false;
  34819. _this.REFLECTIONMAP_3D = false;
  34820. _this.REFLECTIONMAP_SPHERICAL = false;
  34821. _this.REFLECTIONMAP_PLANAR = false;
  34822. _this.REFLECTIONMAP_CUBIC = false;
  34823. _this.REFLECTIONMAP_PROJECTION = false;
  34824. _this.REFLECTIONMAP_SKYBOX = false;
  34825. _this.REFLECTIONMAP_EXPLICIT = false;
  34826. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34827. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34828. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34829. _this.INVERTCUBICMAP = false;
  34830. _this.LOGARITHMICDEPTH = false;
  34831. _this.REFRACTION = false;
  34832. _this.REFRACTIONMAP_3D = false;
  34833. _this.REFLECTIONOVERALPHA = false;
  34834. _this.TWOSIDEDLIGHTING = false;
  34835. _this.SHADOWFLOAT = false;
  34836. _this.MORPHTARGETS = false;
  34837. _this.MORPHTARGETS_NORMAL = false;
  34838. _this.MORPHTARGETS_TANGENT = false;
  34839. _this.NUM_MORPH_INFLUENCERS = 0;
  34840. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34841. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34842. _this.IMAGEPROCESSING = false;
  34843. _this.VIGNETTE = false;
  34844. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34845. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34846. _this.TONEMAPPING = false;
  34847. _this.CONTRAST = false;
  34848. _this.COLORCURVES = false;
  34849. _this.COLORGRADING = false;
  34850. _this.COLORGRADING3D = false;
  34851. _this.SAMPLER3DGREENDEPTH = false;
  34852. _this.SAMPLER3DBGRMAP = false;
  34853. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34854. _this.EXPOSURE = false;
  34855. _this.rebuild();
  34856. return _this;
  34857. }
  34858. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34859. var modes = [
  34860. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34861. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34862. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34863. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34864. ];
  34865. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34866. var mode = modes_1[_i];
  34867. this[mode] = (mode === modeToEnable);
  34868. }
  34869. };
  34870. return StandardMaterialDefines;
  34871. }(BABYLON.MaterialDefines));
  34872. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34873. var StandardMaterial = /** @class */ (function (_super) {
  34874. __extends(StandardMaterial, _super);
  34875. function StandardMaterial(name, scene) {
  34876. var _this = _super.call(this, name, scene) || this;
  34877. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34878. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34879. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34880. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34881. _this.specularPower = 64;
  34882. _this._useAlphaFromDiffuseTexture = false;
  34883. _this._useEmissiveAsIllumination = false;
  34884. _this._linkEmissiveWithDiffuse = false;
  34885. _this._useSpecularOverAlpha = false;
  34886. _this._useReflectionOverAlpha = false;
  34887. _this._disableLighting = false;
  34888. _this._useParallax = false;
  34889. _this._useParallaxOcclusion = false;
  34890. _this.parallaxScaleBias = 0.05;
  34891. _this._roughness = 0;
  34892. _this.indexOfRefraction = 0.98;
  34893. _this.invertRefractionY = true;
  34894. _this._useLightmapAsShadowmap = false;
  34895. _this._useReflectionFresnelFromSpecular = false;
  34896. _this._useGlossinessFromSpecularMapAlpha = false;
  34897. _this._maxSimultaneousLights = 4;
  34898. /**
  34899. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34900. */
  34901. _this._invertNormalMapX = false;
  34902. /**
  34903. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34904. */
  34905. _this._invertNormalMapY = false;
  34906. /**
  34907. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34908. */
  34909. _this._twoSidedLighting = false;
  34910. _this._renderTargets = new BABYLON.SmartArray(16);
  34911. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34912. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34913. // Setup the default processing configuration to the scene.
  34914. _this._attachImageProcessingConfiguration(null);
  34915. _this.getRenderTargetTextures = function () {
  34916. _this._renderTargets.reset();
  34917. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34918. _this._renderTargets.push(_this._reflectionTexture);
  34919. }
  34920. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34921. _this._renderTargets.push(_this._refractionTexture);
  34922. }
  34923. return _this._renderTargets;
  34924. };
  34925. return _this;
  34926. }
  34927. ;
  34928. ;
  34929. ;
  34930. ;
  34931. ;
  34932. ;
  34933. ;
  34934. ;
  34935. ;
  34936. ;
  34937. ;
  34938. ;
  34939. ;
  34940. ;
  34941. ;
  34942. ;
  34943. ;
  34944. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34945. /**
  34946. * Gets the image processing configuration used either in this material.
  34947. */
  34948. get: function () {
  34949. return this._imageProcessingConfiguration;
  34950. },
  34951. /**
  34952. * Sets the Default image processing configuration used either in the this material.
  34953. *
  34954. * If sets to null, the scene one is in use.
  34955. */
  34956. set: function (value) {
  34957. this._attachImageProcessingConfiguration(value);
  34958. // Ensure the effect will be rebuilt.
  34959. this._markAllSubMeshesAsTexturesDirty();
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. /**
  34965. * Attaches a new image processing configuration to the Standard Material.
  34966. * @param configuration
  34967. */
  34968. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34969. var _this = this;
  34970. if (configuration === this._imageProcessingConfiguration) {
  34971. return;
  34972. }
  34973. // Detaches observer.
  34974. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34975. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34976. }
  34977. // Pick the scene configuration if needed.
  34978. if (!configuration) {
  34979. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34980. }
  34981. else {
  34982. this._imageProcessingConfiguration = configuration;
  34983. }
  34984. // Attaches observer.
  34985. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34986. _this._markAllSubMeshesAsImageProcessingDirty();
  34987. });
  34988. };
  34989. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34990. /**
  34991. * Gets wether the color curves effect is enabled.
  34992. */
  34993. get: function () {
  34994. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34995. },
  34996. /**
  34997. * Sets wether the color curves effect is enabled.
  34998. */
  34999. set: function (value) {
  35000. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35001. },
  35002. enumerable: true,
  35003. configurable: true
  35004. });
  35005. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35006. /**
  35007. * Gets wether the color grading effect is enabled.
  35008. */
  35009. get: function () {
  35010. return this.imageProcessingConfiguration.colorGradingEnabled;
  35011. },
  35012. /**
  35013. * Gets wether the color grading effect is enabled.
  35014. */
  35015. set: function (value) {
  35016. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35017. },
  35018. enumerable: true,
  35019. configurable: true
  35020. });
  35021. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35022. /**
  35023. * Gets wether tonemapping is enabled or not.
  35024. */
  35025. get: function () {
  35026. return this._imageProcessingConfiguration.toneMappingEnabled;
  35027. },
  35028. /**
  35029. * Sets wether tonemapping is enabled or not
  35030. */
  35031. set: function (value) {
  35032. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. ;
  35038. ;
  35039. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35040. /**
  35041. * The camera exposure used on this material.
  35042. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35043. * This corresponds to a photographic exposure.
  35044. */
  35045. get: function () {
  35046. return this._imageProcessingConfiguration.exposure;
  35047. },
  35048. /**
  35049. * The camera exposure used on this material.
  35050. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35051. * This corresponds to a photographic exposure.
  35052. */
  35053. set: function (value) {
  35054. this._imageProcessingConfiguration.exposure = value;
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. ;
  35060. ;
  35061. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35062. /**
  35063. * Gets The camera contrast used on this material.
  35064. */
  35065. get: function () {
  35066. return this._imageProcessingConfiguration.contrast;
  35067. },
  35068. /**
  35069. * Sets The camera contrast used on this material.
  35070. */
  35071. set: function (value) {
  35072. this._imageProcessingConfiguration.contrast = value;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35078. /**
  35079. * Gets the Color Grading 2D Lookup Texture.
  35080. */
  35081. get: function () {
  35082. return this._imageProcessingConfiguration.colorGradingTexture;
  35083. },
  35084. /**
  35085. * Sets the Color Grading 2D Lookup Texture.
  35086. */
  35087. set: function (value) {
  35088. this._imageProcessingConfiguration.colorGradingTexture = value;
  35089. },
  35090. enumerable: true,
  35091. configurable: true
  35092. });
  35093. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35094. /**
  35095. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35096. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35097. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  35098. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35099. */
  35100. get: function () {
  35101. return this._imageProcessingConfiguration.colorCurves;
  35102. },
  35103. /**
  35104. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35105. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35106. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  35107. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35108. */
  35109. set: function (value) {
  35110. this._imageProcessingConfiguration.colorCurves = value;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. StandardMaterial.prototype.getClassName = function () {
  35116. return "StandardMaterial";
  35117. };
  35118. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35119. get: function () {
  35120. return this._useLogarithmicDepth;
  35121. },
  35122. set: function (value) {
  35123. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35124. this._markAllSubMeshesAsMiscDirty();
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. StandardMaterial.prototype.needAlphaBlending = function () {
  35130. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35131. };
  35132. StandardMaterial.prototype.needAlphaTesting = function () {
  35133. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35134. };
  35135. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35136. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35137. };
  35138. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35139. return this._diffuseTexture;
  35140. };
  35141. /**
  35142. * Child classes can use it to update shaders
  35143. */
  35144. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35145. if (useInstances === void 0) { useInstances = false; }
  35146. if (subMesh.effect && this.isFrozen) {
  35147. if (this._wasPreviouslyReady && subMesh.effect) {
  35148. return true;
  35149. }
  35150. }
  35151. if (!subMesh._materialDefines) {
  35152. subMesh._materialDefines = new StandardMaterialDefines();
  35153. }
  35154. var scene = this.getScene();
  35155. var defines = subMesh._materialDefines;
  35156. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35157. if (defines._renderId === scene.getRenderId()) {
  35158. return true;
  35159. }
  35160. }
  35161. var engine = scene.getEngine();
  35162. // Lights
  35163. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35164. // Textures
  35165. if (defines._areTexturesDirty) {
  35166. defines._needUVs = false;
  35167. defines.MAINUV1 = false;
  35168. defines.MAINUV2 = false;
  35169. if (scene.texturesEnabled) {
  35170. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35171. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35172. return false;
  35173. }
  35174. else {
  35175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35176. }
  35177. }
  35178. else {
  35179. defines.DIFFUSE = false;
  35180. }
  35181. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35182. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35183. return false;
  35184. }
  35185. else {
  35186. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35187. }
  35188. }
  35189. else {
  35190. defines.AMBIENT = false;
  35191. }
  35192. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35193. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35194. return false;
  35195. }
  35196. else {
  35197. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35198. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35199. }
  35200. }
  35201. else {
  35202. defines.OPACITY = false;
  35203. }
  35204. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35205. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35206. return false;
  35207. }
  35208. else {
  35209. defines._needNormals = true;
  35210. defines.REFLECTION = true;
  35211. defines.ROUGHNESS = (this._roughness > 0);
  35212. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35213. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35214. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35215. switch (this._reflectionTexture.coordinatesMode) {
  35216. case BABYLON.Texture.CUBIC_MODE:
  35217. case BABYLON.Texture.INVCUBIC_MODE:
  35218. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35219. break;
  35220. case BABYLON.Texture.EXPLICIT_MODE:
  35221. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35222. break;
  35223. case BABYLON.Texture.PLANAR_MODE:
  35224. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35225. break;
  35226. case BABYLON.Texture.PROJECTION_MODE:
  35227. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35228. break;
  35229. case BABYLON.Texture.SKYBOX_MODE:
  35230. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35231. break;
  35232. case BABYLON.Texture.SPHERICAL_MODE:
  35233. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35234. break;
  35235. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35236. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35237. break;
  35238. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35239. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35240. break;
  35241. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35242. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35243. break;
  35244. }
  35245. }
  35246. }
  35247. else {
  35248. defines.REFLECTION = false;
  35249. }
  35250. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35251. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35252. return false;
  35253. }
  35254. else {
  35255. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35256. }
  35257. }
  35258. else {
  35259. defines.EMISSIVE = false;
  35260. }
  35261. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35262. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35263. return false;
  35264. }
  35265. else {
  35266. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35267. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35268. }
  35269. }
  35270. else {
  35271. defines.LIGHTMAP = false;
  35272. }
  35273. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35274. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35275. return false;
  35276. }
  35277. else {
  35278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35279. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35280. }
  35281. }
  35282. else {
  35283. defines.SPECULAR = false;
  35284. }
  35285. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35286. // Bump texure can not be not blocking.
  35287. if (!this._bumpTexture.isReady()) {
  35288. return false;
  35289. }
  35290. else {
  35291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35292. defines.PARALLAX = this._useParallax;
  35293. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35294. }
  35295. }
  35296. else {
  35297. defines.BUMP = false;
  35298. }
  35299. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35300. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35301. return false;
  35302. }
  35303. else {
  35304. defines._needUVs = true;
  35305. defines.REFRACTION = true;
  35306. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35307. }
  35308. }
  35309. else {
  35310. defines.REFRACTION = false;
  35311. }
  35312. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35313. }
  35314. else {
  35315. defines.DIFFUSE = false;
  35316. defines.AMBIENT = false;
  35317. defines.OPACITY = false;
  35318. defines.REFLECTION = false;
  35319. defines.EMISSIVE = false;
  35320. defines.LIGHTMAP = false;
  35321. defines.BUMP = false;
  35322. defines.REFRACTION = false;
  35323. }
  35324. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35325. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35326. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35327. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35328. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35329. }
  35330. if (defines._areImageProcessingDirty) {
  35331. if (!this._imageProcessingConfiguration.isReady()) {
  35332. return false;
  35333. }
  35334. this._imageProcessingConfiguration.prepareDefines(defines);
  35335. }
  35336. if (defines._areFresnelDirty) {
  35337. if (StandardMaterial.FresnelEnabled) {
  35338. // Fresnel
  35339. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35340. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35341. this._reflectionFresnelParameters) {
  35342. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35343. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35344. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35345. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35346. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35347. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35348. defines._needNormals = true;
  35349. defines.FRESNEL = true;
  35350. }
  35351. }
  35352. else {
  35353. defines.FRESNEL = false;
  35354. }
  35355. }
  35356. // Misc.
  35357. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35358. // Attribs
  35359. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35360. // Values that need to be evaluated on every frame
  35361. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35362. // Get correct effect
  35363. if (defines.isDirty) {
  35364. defines.markAsProcessed();
  35365. scene.resetCachedMaterial();
  35366. // Fallbacks
  35367. var fallbacks = new BABYLON.EffectFallbacks();
  35368. if (defines.REFLECTION) {
  35369. fallbacks.addFallback(0, "REFLECTION");
  35370. }
  35371. if (defines.SPECULAR) {
  35372. fallbacks.addFallback(0, "SPECULAR");
  35373. }
  35374. if (defines.BUMP) {
  35375. fallbacks.addFallback(0, "BUMP");
  35376. }
  35377. if (defines.PARALLAX) {
  35378. fallbacks.addFallback(1, "PARALLAX");
  35379. }
  35380. if (defines.PARALLAXOCCLUSION) {
  35381. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35382. }
  35383. if (defines.SPECULAROVERALPHA) {
  35384. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35385. }
  35386. if (defines.FOG) {
  35387. fallbacks.addFallback(1, "FOG");
  35388. }
  35389. if (defines.POINTSIZE) {
  35390. fallbacks.addFallback(0, "POINTSIZE");
  35391. }
  35392. if (defines.LOGARITHMICDEPTH) {
  35393. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35394. }
  35395. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35396. if (defines.SPECULARTERM) {
  35397. fallbacks.addFallback(0, "SPECULARTERM");
  35398. }
  35399. if (defines.DIFFUSEFRESNEL) {
  35400. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35401. }
  35402. if (defines.OPACITYFRESNEL) {
  35403. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35404. }
  35405. if (defines.REFLECTIONFRESNEL) {
  35406. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35407. }
  35408. if (defines.EMISSIVEFRESNEL) {
  35409. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35410. }
  35411. if (defines.FRESNEL) {
  35412. fallbacks.addFallback(4, "FRESNEL");
  35413. }
  35414. //Attributes
  35415. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35416. if (defines.NORMAL) {
  35417. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35418. }
  35419. if (defines.UV1) {
  35420. attribs.push(BABYLON.VertexBuffer.UVKind);
  35421. }
  35422. if (defines.UV2) {
  35423. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35424. }
  35425. if (defines.VERTEXCOLOR) {
  35426. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35427. }
  35428. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35429. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35430. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35431. var shaderName = "default";
  35432. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35433. "vFogInfos", "vFogColor", "pointSize",
  35434. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35435. "mBones",
  35436. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35437. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35438. "logarithmicDepthConstant", "vTangentSpaceParams"
  35439. ];
  35440. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35441. var uniformBuffers = ["Material", "Scene"];
  35442. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35443. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35444. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35445. uniformsNames: uniforms,
  35446. uniformBuffersNames: uniformBuffers,
  35447. samplers: samplers,
  35448. defines: defines,
  35449. maxSimultaneousLights: this._maxSimultaneousLights
  35450. });
  35451. if (this.customShaderNameResolve) {
  35452. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35453. }
  35454. var join = defines.toString();
  35455. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35456. attributes: attribs,
  35457. uniformsNames: uniforms,
  35458. uniformBuffersNames: uniformBuffers,
  35459. samplers: samplers,
  35460. defines: join,
  35461. fallbacks: fallbacks,
  35462. onCompiled: this.onCompiled,
  35463. onError: this.onError,
  35464. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35465. }, engine), defines);
  35466. this.buildUniformLayout();
  35467. }
  35468. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35469. return false;
  35470. }
  35471. defines._renderId = scene.getRenderId();
  35472. this._wasPreviouslyReady = true;
  35473. return true;
  35474. };
  35475. StandardMaterial.prototype.buildUniformLayout = function () {
  35476. // Order is important !
  35477. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35478. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35479. this._uniformBuffer.addUniform("opacityParts", 4);
  35480. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35481. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35482. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35483. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35484. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35485. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35486. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35487. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35488. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35489. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35490. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35491. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35492. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35493. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35494. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35495. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35496. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35497. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35498. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35499. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35500. this._uniformBuffer.addUniform("specularMatrix", 16);
  35501. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35502. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35503. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35504. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35505. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35506. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35507. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35508. this._uniformBuffer.addUniform("pointSize", 1);
  35509. this._uniformBuffer.create();
  35510. };
  35511. StandardMaterial.prototype.unbind = function () {
  35512. if (this._activeEffect) {
  35513. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35514. this._activeEffect.setTexture("reflection2DSampler", null);
  35515. }
  35516. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35517. this._activeEffect.setTexture("refraction2DSampler", null);
  35518. }
  35519. }
  35520. _super.prototype.unbind.call(this);
  35521. };
  35522. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35523. var scene = this.getScene();
  35524. var defines = subMesh._materialDefines;
  35525. if (!defines) {
  35526. return;
  35527. }
  35528. var effect = subMesh.effect;
  35529. if (!effect) {
  35530. return;
  35531. }
  35532. this._activeEffect = effect;
  35533. // Matrices
  35534. this.bindOnlyWorldMatrix(world);
  35535. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35536. // Bones
  35537. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35538. if (mustRebind) {
  35539. this._uniformBuffer.bindToEffect(effect, "Material");
  35540. this.bindViewProjection(effect);
  35541. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35542. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35543. // Fresnel
  35544. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35545. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35546. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35547. }
  35548. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35549. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35550. }
  35551. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35552. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35553. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35554. }
  35555. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35556. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35557. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35558. }
  35559. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35560. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35561. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35562. }
  35563. }
  35564. // Textures
  35565. if (scene.texturesEnabled) {
  35566. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35567. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35568. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35569. }
  35570. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35571. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35572. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35573. }
  35574. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35575. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35576. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35577. }
  35578. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35579. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35580. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35581. }
  35582. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35583. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35584. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35585. }
  35586. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35587. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35588. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35589. }
  35590. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35591. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35592. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35593. }
  35594. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35595. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35596. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35597. if (scene._mirroredCameraPosition) {
  35598. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35599. }
  35600. else {
  35601. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35602. }
  35603. }
  35604. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35605. var depth = 1.0;
  35606. if (!this._refractionTexture.isCube) {
  35607. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35608. if (this._refractionTexture.depth) {
  35609. depth = this._refractionTexture.depth;
  35610. }
  35611. }
  35612. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35613. }
  35614. }
  35615. // Point size
  35616. if (this.pointsCloud) {
  35617. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35618. }
  35619. if (defines.SPECULARTERM) {
  35620. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35621. }
  35622. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35623. // Diffuse
  35624. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35625. }
  35626. // Textures
  35627. if (scene.texturesEnabled) {
  35628. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35629. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35630. }
  35631. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35632. effect.setTexture("ambientSampler", this._ambientTexture);
  35633. }
  35634. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35635. effect.setTexture("opacitySampler", this._opacityTexture);
  35636. }
  35637. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35638. if (this._reflectionTexture.isCube) {
  35639. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35640. }
  35641. else {
  35642. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35643. }
  35644. }
  35645. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35646. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35647. }
  35648. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35649. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35650. }
  35651. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35652. effect.setTexture("specularSampler", this._specularTexture);
  35653. }
  35654. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35655. effect.setTexture("bumpSampler", this._bumpTexture);
  35656. }
  35657. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35658. var depth = 1.0;
  35659. if (this._refractionTexture.isCube) {
  35660. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35661. }
  35662. else {
  35663. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35664. }
  35665. }
  35666. }
  35667. // Clip plane
  35668. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35669. // Colors
  35670. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35671. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35672. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35673. }
  35674. if (mustRebind || !this.isFrozen) {
  35675. // Lights
  35676. if (scene.lightsEnabled && !this._disableLighting) {
  35677. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35678. }
  35679. // View
  35680. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35681. this.bindView(effect);
  35682. }
  35683. // Fog
  35684. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35685. // Morph targets
  35686. if (defines.NUM_MORPH_INFLUENCERS) {
  35687. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35688. }
  35689. // Log. depth
  35690. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35691. // image processing
  35692. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35693. this._imageProcessingConfiguration.bind(this._activeEffect);
  35694. }
  35695. }
  35696. this._uniformBuffer.update();
  35697. this._afterBind(mesh, this._activeEffect);
  35698. };
  35699. StandardMaterial.prototype.getAnimatables = function () {
  35700. var results = [];
  35701. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35702. results.push(this._diffuseTexture);
  35703. }
  35704. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35705. results.push(this._ambientTexture);
  35706. }
  35707. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35708. results.push(this._opacityTexture);
  35709. }
  35710. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35711. results.push(this._reflectionTexture);
  35712. }
  35713. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35714. results.push(this._emissiveTexture);
  35715. }
  35716. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35717. results.push(this._specularTexture);
  35718. }
  35719. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35720. results.push(this._bumpTexture);
  35721. }
  35722. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35723. results.push(this._lightmapTexture);
  35724. }
  35725. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35726. results.push(this._refractionTexture);
  35727. }
  35728. return results;
  35729. };
  35730. StandardMaterial.prototype.getActiveTextures = function () {
  35731. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35732. if (this._diffuseTexture) {
  35733. activeTextures.push(this._diffuseTexture);
  35734. }
  35735. if (this._ambientTexture) {
  35736. activeTextures.push(this._ambientTexture);
  35737. }
  35738. if (this._opacityTexture) {
  35739. activeTextures.push(this._opacityTexture);
  35740. }
  35741. if (this._reflectionTexture) {
  35742. activeTextures.push(this._reflectionTexture);
  35743. }
  35744. if (this._emissiveTexture) {
  35745. activeTextures.push(this._emissiveTexture);
  35746. }
  35747. if (this._specularTexture) {
  35748. activeTextures.push(this._specularTexture);
  35749. }
  35750. if (this._bumpTexture) {
  35751. activeTextures.push(this._bumpTexture);
  35752. }
  35753. if (this._lightmapTexture) {
  35754. activeTextures.push(this._lightmapTexture);
  35755. }
  35756. if (this._refractionTexture) {
  35757. activeTextures.push(this._refractionTexture);
  35758. }
  35759. return activeTextures;
  35760. };
  35761. StandardMaterial.prototype.hasTexture = function (texture) {
  35762. if (_super.prototype.hasTexture.call(this, texture)) {
  35763. return true;
  35764. }
  35765. if (this._diffuseTexture === texture) {
  35766. return true;
  35767. }
  35768. if (this._ambientTexture === texture) {
  35769. return true;
  35770. }
  35771. if (this._opacityTexture === texture) {
  35772. return true;
  35773. }
  35774. if (this._reflectionTexture === texture) {
  35775. return true;
  35776. }
  35777. if (this._emissiveTexture === texture) {
  35778. return true;
  35779. }
  35780. if (this._specularTexture === texture) {
  35781. return true;
  35782. }
  35783. if (this._bumpTexture === texture) {
  35784. return true;
  35785. }
  35786. if (this._lightmapTexture === texture) {
  35787. return true;
  35788. }
  35789. if (this._refractionTexture === texture) {
  35790. return true;
  35791. }
  35792. return false;
  35793. };
  35794. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35795. if (forceDisposeTextures) {
  35796. if (this._diffuseTexture) {
  35797. this._diffuseTexture.dispose();
  35798. }
  35799. if (this._ambientTexture) {
  35800. this._ambientTexture.dispose();
  35801. }
  35802. if (this._opacityTexture) {
  35803. this._opacityTexture.dispose();
  35804. }
  35805. if (this._reflectionTexture) {
  35806. this._reflectionTexture.dispose();
  35807. }
  35808. if (this._emissiveTexture) {
  35809. this._emissiveTexture.dispose();
  35810. }
  35811. if (this._specularTexture) {
  35812. this._specularTexture.dispose();
  35813. }
  35814. if (this._bumpTexture) {
  35815. this._bumpTexture.dispose();
  35816. }
  35817. if (this._lightmapTexture) {
  35818. this._lightmapTexture.dispose();
  35819. }
  35820. if (this._refractionTexture) {
  35821. this._refractionTexture.dispose();
  35822. }
  35823. }
  35824. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35825. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35826. }
  35827. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35828. };
  35829. StandardMaterial.prototype.clone = function (name) {
  35830. var _this = this;
  35831. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35832. result.name = name;
  35833. result.id = name;
  35834. return result;
  35835. };
  35836. StandardMaterial.prototype.serialize = function () {
  35837. return BABYLON.SerializationHelper.Serialize(this);
  35838. };
  35839. // Statics
  35840. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35841. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35842. };
  35843. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35844. get: function () {
  35845. return StandardMaterial._DiffuseTextureEnabled;
  35846. },
  35847. set: function (value) {
  35848. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35849. return;
  35850. }
  35851. StandardMaterial._DiffuseTextureEnabled = value;
  35852. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35853. },
  35854. enumerable: true,
  35855. configurable: true
  35856. });
  35857. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35858. get: function () {
  35859. return StandardMaterial._AmbientTextureEnabled;
  35860. },
  35861. set: function (value) {
  35862. if (StandardMaterial._AmbientTextureEnabled === value) {
  35863. return;
  35864. }
  35865. StandardMaterial._AmbientTextureEnabled = value;
  35866. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35867. },
  35868. enumerable: true,
  35869. configurable: true
  35870. });
  35871. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35872. get: function () {
  35873. return StandardMaterial._OpacityTextureEnabled;
  35874. },
  35875. set: function (value) {
  35876. if (StandardMaterial._OpacityTextureEnabled === value) {
  35877. return;
  35878. }
  35879. StandardMaterial._OpacityTextureEnabled = value;
  35880. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35881. },
  35882. enumerable: true,
  35883. configurable: true
  35884. });
  35885. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35886. get: function () {
  35887. return StandardMaterial._ReflectionTextureEnabled;
  35888. },
  35889. set: function (value) {
  35890. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35891. return;
  35892. }
  35893. StandardMaterial._ReflectionTextureEnabled = value;
  35894. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35895. },
  35896. enumerable: true,
  35897. configurable: true
  35898. });
  35899. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35900. get: function () {
  35901. return StandardMaterial._EmissiveTextureEnabled;
  35902. },
  35903. set: function (value) {
  35904. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35905. return;
  35906. }
  35907. StandardMaterial._EmissiveTextureEnabled = value;
  35908. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35909. },
  35910. enumerable: true,
  35911. configurable: true
  35912. });
  35913. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35914. get: function () {
  35915. return StandardMaterial._SpecularTextureEnabled;
  35916. },
  35917. set: function (value) {
  35918. if (StandardMaterial._SpecularTextureEnabled === value) {
  35919. return;
  35920. }
  35921. StandardMaterial._SpecularTextureEnabled = value;
  35922. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35923. },
  35924. enumerable: true,
  35925. configurable: true
  35926. });
  35927. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35928. get: function () {
  35929. return StandardMaterial._BumpTextureEnabled;
  35930. },
  35931. set: function (value) {
  35932. if (StandardMaterial._BumpTextureEnabled === value) {
  35933. return;
  35934. }
  35935. StandardMaterial._BumpTextureEnabled = value;
  35936. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35937. },
  35938. enumerable: true,
  35939. configurable: true
  35940. });
  35941. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35942. get: function () {
  35943. return StandardMaterial._LightmapTextureEnabled;
  35944. },
  35945. set: function (value) {
  35946. if (StandardMaterial._LightmapTextureEnabled === value) {
  35947. return;
  35948. }
  35949. StandardMaterial._LightmapTextureEnabled = value;
  35950. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35951. },
  35952. enumerable: true,
  35953. configurable: true
  35954. });
  35955. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35956. get: function () {
  35957. return StandardMaterial._RefractionTextureEnabled;
  35958. },
  35959. set: function (value) {
  35960. if (StandardMaterial._RefractionTextureEnabled === value) {
  35961. return;
  35962. }
  35963. StandardMaterial._RefractionTextureEnabled = value;
  35964. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35965. },
  35966. enumerable: true,
  35967. configurable: true
  35968. });
  35969. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35970. get: function () {
  35971. return StandardMaterial._ColorGradingTextureEnabled;
  35972. },
  35973. set: function (value) {
  35974. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35975. return;
  35976. }
  35977. StandardMaterial._ColorGradingTextureEnabled = value;
  35978. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35979. },
  35980. enumerable: true,
  35981. configurable: true
  35982. });
  35983. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35984. get: function () {
  35985. return StandardMaterial._FresnelEnabled;
  35986. },
  35987. set: function (value) {
  35988. if (StandardMaterial._FresnelEnabled === value) {
  35989. return;
  35990. }
  35991. StandardMaterial._FresnelEnabled = value;
  35992. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35993. },
  35994. enumerable: true,
  35995. configurable: true
  35996. });
  35997. // Flags used to enable or disable a type of texture for all Standard Materials
  35998. StandardMaterial._DiffuseTextureEnabled = true;
  35999. StandardMaterial._AmbientTextureEnabled = true;
  36000. StandardMaterial._OpacityTextureEnabled = true;
  36001. StandardMaterial._ReflectionTextureEnabled = true;
  36002. StandardMaterial._EmissiveTextureEnabled = true;
  36003. StandardMaterial._SpecularTextureEnabled = true;
  36004. StandardMaterial._BumpTextureEnabled = true;
  36005. StandardMaterial._LightmapTextureEnabled = true;
  36006. StandardMaterial._RefractionTextureEnabled = true;
  36007. StandardMaterial._ColorGradingTextureEnabled = true;
  36008. StandardMaterial._FresnelEnabled = true;
  36009. __decorate([
  36010. BABYLON.serializeAsTexture("diffuseTexture")
  36011. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36012. __decorate([
  36013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36014. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36015. __decorate([
  36016. BABYLON.serializeAsTexture("ambientTexture")
  36017. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36018. __decorate([
  36019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36020. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36021. __decorate([
  36022. BABYLON.serializeAsTexture("opacityTexture")
  36023. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36024. __decorate([
  36025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36026. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36027. __decorate([
  36028. BABYLON.serializeAsTexture("reflectionTexture")
  36029. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36030. __decorate([
  36031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36032. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36033. __decorate([
  36034. BABYLON.serializeAsTexture("emissiveTexture")
  36035. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36036. __decorate([
  36037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36038. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36039. __decorate([
  36040. BABYLON.serializeAsTexture("specularTexture")
  36041. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36042. __decorate([
  36043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36044. ], StandardMaterial.prototype, "specularTexture", void 0);
  36045. __decorate([
  36046. BABYLON.serializeAsTexture("bumpTexture")
  36047. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36048. __decorate([
  36049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36050. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36051. __decorate([
  36052. BABYLON.serializeAsTexture("lightmapTexture")
  36053. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36054. __decorate([
  36055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36056. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36057. __decorate([
  36058. BABYLON.serializeAsTexture("refractionTexture")
  36059. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36060. __decorate([
  36061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36062. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36063. __decorate([
  36064. BABYLON.serializeAsColor3("ambient")
  36065. ], StandardMaterial.prototype, "ambientColor", void 0);
  36066. __decorate([
  36067. BABYLON.serializeAsColor3("diffuse")
  36068. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36069. __decorate([
  36070. BABYLON.serializeAsColor3("specular")
  36071. ], StandardMaterial.prototype, "specularColor", void 0);
  36072. __decorate([
  36073. BABYLON.serializeAsColor3("emissive")
  36074. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], StandardMaterial.prototype, "specularPower", void 0);
  36078. __decorate([
  36079. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36080. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36081. __decorate([
  36082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36083. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36084. __decorate([
  36085. BABYLON.serialize("useEmissiveAsIllumination")
  36086. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36087. __decorate([
  36088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36089. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36090. __decorate([
  36091. BABYLON.serialize("linkEmissiveWithDiffuse")
  36092. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36093. __decorate([
  36094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36095. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36096. __decorate([
  36097. BABYLON.serialize("useSpecularOverAlpha")
  36098. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36099. __decorate([
  36100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36101. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36102. __decorate([
  36103. BABYLON.serialize("useReflectionOverAlpha")
  36104. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36105. __decorate([
  36106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36107. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36108. __decorate([
  36109. BABYLON.serialize("disableLighting")
  36110. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36111. __decorate([
  36112. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36113. ], StandardMaterial.prototype, "disableLighting", void 0);
  36114. __decorate([
  36115. BABYLON.serialize("useParallax")
  36116. ], StandardMaterial.prototype, "_useParallax", void 0);
  36117. __decorate([
  36118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36119. ], StandardMaterial.prototype, "useParallax", void 0);
  36120. __decorate([
  36121. BABYLON.serialize("useParallaxOcclusion")
  36122. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36123. __decorate([
  36124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36125. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36126. __decorate([
  36127. BABYLON.serialize()
  36128. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36129. __decorate([
  36130. BABYLON.serialize("roughness")
  36131. ], StandardMaterial.prototype, "_roughness", void 0);
  36132. __decorate([
  36133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36134. ], StandardMaterial.prototype, "roughness", void 0);
  36135. __decorate([
  36136. BABYLON.serialize()
  36137. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36138. __decorate([
  36139. BABYLON.serialize()
  36140. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36141. __decorate([
  36142. BABYLON.serialize("useLightmapAsShadowmap")
  36143. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36144. __decorate([
  36145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36146. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36147. __decorate([
  36148. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36149. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36150. __decorate([
  36151. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36152. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36153. __decorate([
  36154. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36155. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36156. __decorate([
  36157. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36158. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36159. __decorate([
  36160. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36161. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36162. __decorate([
  36163. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36164. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36165. __decorate([
  36166. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36167. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36168. __decorate([
  36169. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36170. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36171. __decorate([
  36172. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36173. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36174. __decorate([
  36175. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36176. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36177. __decorate([
  36178. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36179. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36180. __decorate([
  36181. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36182. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36183. __decorate([
  36184. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36185. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36186. __decorate([
  36187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36188. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36189. __decorate([
  36190. BABYLON.serialize("maxSimultaneousLights")
  36191. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36192. __decorate([
  36193. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36194. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36195. __decorate([
  36196. BABYLON.serialize("invertNormalMapX")
  36197. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36198. __decorate([
  36199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36200. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36201. __decorate([
  36202. BABYLON.serialize("invertNormalMapY")
  36203. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36204. __decorate([
  36205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36206. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36207. __decorate([
  36208. BABYLON.serialize("twoSidedLighting")
  36209. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36210. __decorate([
  36211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36212. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36213. __decorate([
  36214. BABYLON.serialize()
  36215. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36216. return StandardMaterial;
  36217. }(BABYLON.PushMaterial));
  36218. BABYLON.StandardMaterial = StandardMaterial;
  36219. })(BABYLON || (BABYLON = {}));
  36220. //# sourceMappingURL=babylon.standardMaterial.js.map
  36221. (function() {
  36222. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  36223. globalObject["BABYLON"] = BABYLON;
  36224. })();;
  36225. var EffectFallbacks = BABYLON.EffectFallbacks;
  36226. var EffectCreationOptions = BABYLON.EffectCreationOptions;
  36227. var Effect = BABYLON.Effect;
  36228. var KeyboardEventTypes = BABYLON.KeyboardEventTypes;
  36229. var KeyboardInfo = BABYLON.KeyboardInfo;
  36230. var KeyboardInfoPre = BABYLON.KeyboardInfoPre;
  36231. var PointerEventTypes = BABYLON.PointerEventTypes;
  36232. var PointerInfoBase = BABYLON.PointerInfoBase;
  36233. var PointerInfoPre = BABYLON.PointerInfoPre;
  36234. var PointerInfo = BABYLON.PointerInfo;
  36235. var ToGammaSpace = BABYLON.ToGammaSpace;
  36236. var ToLinearSpace = BABYLON.ToLinearSpace;
  36237. var Epsilon = BABYLON.Epsilon;
  36238. var Color3 = BABYLON.Color3;
  36239. var Color4 = BABYLON.Color4;
  36240. var Vector2 = BABYLON.Vector2;
  36241. var Vector3 = BABYLON.Vector3;
  36242. var Vector4 = BABYLON.Vector4;
  36243. var Size = BABYLON.Size;
  36244. var Quaternion = BABYLON.Quaternion;
  36245. var Matrix = BABYLON.Matrix;
  36246. var Plane = BABYLON.Plane;
  36247. var Viewport = BABYLON.Viewport;
  36248. var Frustum = BABYLON.Frustum;
  36249. var Space = BABYLON.Space;
  36250. var Axis = BABYLON.Axis;
  36251. var BezierCurve = BABYLON.BezierCurve;
  36252. var Orientation = BABYLON.Orientation;
  36253. var Angle = BABYLON.Angle;
  36254. var Arc2 = BABYLON.Arc2;
  36255. var Path2 = BABYLON.Path2;
  36256. var Path3D = BABYLON.Path3D;
  36257. var Curve3 = BABYLON.Curve3;
  36258. var PositionNormalVertex = BABYLON.PositionNormalVertex;
  36259. var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;
  36260. var Tmp = BABYLON.Tmp;
  36261. var Scalar = BABYLON.Scalar;
  36262. var expandToProperty = BABYLON.expandToProperty;
  36263. var serialize = BABYLON.serialize;
  36264. var serializeAsTexture = BABYLON.serializeAsTexture;
  36265. var serializeAsColor3 = BABYLON.serializeAsColor3;
  36266. var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;
  36267. var serializeAsVector2 = BABYLON.serializeAsVector2;
  36268. var serializeAsVector3 = BABYLON.serializeAsVector3;
  36269. var serializeAsMeshReference = BABYLON.serializeAsMeshReference;
  36270. var serializeAsColorCurves = BABYLON.serializeAsColorCurves;
  36271. var serializeAsColor4 = BABYLON.serializeAsColor4;
  36272. var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;
  36273. var serializeAsQuaternion = BABYLON.serializeAsQuaternion;
  36274. var SerializationHelper = BABYLON.SerializationHelper;
  36275. var EventState = BABYLON.EventState;
  36276. var Observer = BABYLON.Observer;
  36277. var MultiObserver = BABYLON.MultiObserver;
  36278. var Observable = BABYLON.Observable;
  36279. var SmartArray = BABYLON.SmartArray;
  36280. var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;
  36281. var LoadFileError = BABYLON.LoadFileError;
  36282. var RetryStrategy = BABYLON.RetryStrategy;
  36283. var Tools = BABYLON.Tools;
  36284. var PerfCounter = BABYLON.PerfCounter;
  36285. var className = BABYLON.className;
  36286. var AsyncLoop = BABYLON.AsyncLoop;
  36287. var _AlphaState = BABYLON._AlphaState;
  36288. var _DepthCullingState = BABYLON._DepthCullingState;
  36289. var _StencilState = BABYLON._StencilState;
  36290. var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;
  36291. var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;
  36292. var EngineCapabilities = BABYLON.EngineCapabilities;
  36293. var Engine = BABYLON.Engine;
  36294. var Node = BABYLON.Node;
  36295. var BoundingSphere = BABYLON.BoundingSphere;
  36296. var BoundingBox = BABYLON.BoundingBox;
  36297. var BoundingInfo = BABYLON.BoundingInfo;
  36298. var TransformNode = BABYLON.TransformNode;
  36299. var AbstractMesh = BABYLON.AbstractMesh;
  36300. var Light = BABYLON.Light;
  36301. var Camera = BABYLON.Camera;
  36302. var RenderingManager = BABYLON.RenderingManager;
  36303. var RenderingGroup = BABYLON.RenderingGroup;
  36304. var RenderingGroupInfo = BABYLON.RenderingGroupInfo;
  36305. var Scene = BABYLON.Scene;
  36306. var Buffer = BABYLON.Buffer;
  36307. var VertexBuffer = BABYLON.VertexBuffer;
  36308. var InternalTexture = BABYLON.InternalTexture;
  36309. var BaseTexture = BABYLON.BaseTexture;
  36310. var Texture = BABYLON.Texture;
  36311. var _InstancesBatch = BABYLON._InstancesBatch;
  36312. var Mesh = BABYLON.Mesh;
  36313. var BaseSubMesh = BABYLON.BaseSubMesh;
  36314. var SubMesh = BABYLON.SubMesh;
  36315. var MaterialDefines = BABYLON.MaterialDefines;
  36316. var Material = BABYLON.Material;
  36317. var UniformBuffer = BABYLON.UniformBuffer;
  36318. var VertexData = BABYLON.VertexData;
  36319. var Geometry = BABYLON.Geometry;
  36320. var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;
  36321. var RibbonGeometry = BABYLON.RibbonGeometry;
  36322. var BoxGeometry = BABYLON.BoxGeometry;
  36323. var SphereGeometry = BABYLON.SphereGeometry;
  36324. var DiscGeometry = BABYLON.DiscGeometry;
  36325. var CylinderGeometry = BABYLON.CylinderGeometry;
  36326. var TorusGeometry = BABYLON.TorusGeometry;
  36327. var GroundGeometry = BABYLON.GroundGeometry;
  36328. var TiledGroundGeometry = BABYLON.TiledGroundGeometry;
  36329. var PlaneGeometry = BABYLON.PlaneGeometry;
  36330. var TorusKnotGeometry = BABYLON.TorusKnotGeometry;
  36331. var PostProcessManager = BABYLON.PostProcessManager;
  36332. var PerformanceMonitor = BABYLON.PerformanceMonitor;
  36333. var RollingAverage = BABYLON.RollingAverage;
  36334. var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;
  36335. var ColorGradingTexture = BABYLON.ColorGradingTexture;
  36336. var ColorCurves = BABYLON.ColorCurves;
  36337. var MaterialHelper = BABYLON.MaterialHelper;
  36338. var PushMaterial = BABYLON.PushMaterial;
  36339. var StandardMaterialDefines = BABYLON.StandardMaterialDefines;
  36340. var StandardMaterial = BABYLON.StandardMaterial;
  36341. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,ToGammaSpace,ToLinearSpace,Epsilon,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Space,Axis,BezierCurve,Orientation,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,Buffer,VertexBuffer,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial };