index.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285
  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. if(typeof require !== 'undefined'){
  18. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  19. var BABYLON = globalObject["BABYLON"] || {};
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var EffectFallbacks = /** @class */ (function () {
  23. function EffectFallbacks() {
  24. this._defines = {};
  25. this._currentRank = 32;
  26. this._maxRank = -1;
  27. }
  28. EffectFallbacks.prototype.unBindMesh = function () {
  29. this._mesh = null;
  30. };
  31. EffectFallbacks.prototype.addFallback = function (rank, define) {
  32. if (!this._defines[rank]) {
  33. if (rank < this._currentRank) {
  34. this._currentRank = rank;
  35. }
  36. if (rank > this._maxRank) {
  37. this._maxRank = rank;
  38. }
  39. this._defines[rank] = new Array();
  40. }
  41. this._defines[rank].push(define);
  42. };
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. get: function () {
  54. return this._currentRank <= this._maxRank;
  55. },
  56. enumerable: true,
  57. configurable: true
  58. });
  59. EffectFallbacks.prototype.reduce = function (currentDefines) {
  60. // First we try to switch to CPU skinning
  61. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  62. this._mesh.computeBonesUsingShaders = false;
  63. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  64. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  65. var scene = this._mesh.getScene();
  66. for (var index = 0; index < scene.meshes.length; index++) {
  67. var otherMesh = scene.meshes[index];
  68. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  69. otherMesh.computeBonesUsingShaders = false;
  70. }
  71. }
  72. }
  73. else {
  74. var currentFallbacks = this._defines[this._currentRank];
  75. if (currentFallbacks) {
  76. for (var index = 0; index < currentFallbacks.length; index++) {
  77. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  78. }
  79. }
  80. this._currentRank++;
  81. }
  82. return currentDefines;
  83. };
  84. return EffectFallbacks;
  85. }());
  86. BABYLON.EffectFallbacks = EffectFallbacks;
  87. var EffectCreationOptions = /** @class */ (function () {
  88. function EffectCreationOptions() {
  89. }
  90. return EffectCreationOptions;
  91. }());
  92. BABYLON.EffectCreationOptions = EffectCreationOptions;
  93. var Effect = /** @class */ (function () {
  94. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  95. if (samplers === void 0) { samplers = null; }
  96. if (defines === void 0) { defines = null; }
  97. if (fallbacks === void 0) { fallbacks = null; }
  98. if (onCompiled === void 0) { onCompiled = null; }
  99. if (onError === void 0) { onError = null; }
  100. var _this = this;
  101. this.uniqueId = 0;
  102. this.onCompileObservable = new BABYLON.Observable();
  103. this.onErrorObservable = new BABYLON.Observable();
  104. this.onBindObservable = new BABYLON.Observable();
  105. this._uniformBuffersNames = {};
  106. this._isReady = false;
  107. this._compilationError = "";
  108. this.name = baseName;
  109. if (attributesNamesOrOptions.attributes) {
  110. var options = attributesNamesOrOptions;
  111. this._engine = uniformsNamesOrEngine;
  112. this._attributesNames = options.attributes;
  113. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  114. this._samplers = options.samplers;
  115. this.defines = options.defines;
  116. this.onError = options.onError;
  117. this.onCompiled = options.onCompiled;
  118. this._fallbacks = options.fallbacks;
  119. this._indexParameters = options.indexParameters;
  120. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  121. if (options.uniformBuffersNames) {
  122. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  123. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  124. }
  125. }
  126. }
  127. else {
  128. this._engine = engine;
  129. this.defines = defines;
  130. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  131. this._samplers = samplers;
  132. this._attributesNames = attributesNamesOrOptions;
  133. this.onError = onError;
  134. this.onCompiled = onCompiled;
  135. this._indexParameters = indexParameters;
  136. this._fallbacks = fallbacks;
  137. }
  138. this.uniqueId = Effect._uniqueIdSeed++;
  139. var vertexSource;
  140. var fragmentSource;
  141. if (baseName.vertexElement) {
  142. vertexSource = document.getElementById(baseName.vertexElement);
  143. if (!vertexSource) {
  144. vertexSource = baseName.vertexElement;
  145. }
  146. }
  147. else {
  148. vertexSource = baseName.vertex || baseName;
  149. }
  150. if (baseName.fragmentElement) {
  151. fragmentSource = document.getElementById(baseName.fragmentElement);
  152. if (!fragmentSource) {
  153. fragmentSource = baseName.fragmentElement;
  154. }
  155. }
  156. else {
  157. fragmentSource = baseName.fragment || baseName;
  158. }
  159. this._loadVertexShader(vertexSource, function (vertexCode) {
  160. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  161. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  162. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  163. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  164. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  165. if (baseName) {
  166. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  167. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  168. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  169. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  170. }
  171. else {
  172. _this._vertexSourceCode = migratedVertexCode;
  173. _this._fragmentSourceCode = migratedFragmentCode;
  174. }
  175. _this._prepareEffect();
  176. });
  177. });
  178. });
  179. });
  180. });
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. Effect.prototype._loadVertexShader = function (vertex, callback) {
  236. if (BABYLON.Tools.IsWindowObjectExist()) {
  237. // DOM element ?
  238. if (vertex instanceof HTMLElement) {
  239. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  240. callback(vertexCode);
  241. return;
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. callback(vertexBinary);
  248. return;
  249. }
  250. // Is in local store ?
  251. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  252. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  253. return;
  254. }
  255. var vertexShaderUrl;
  256. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  257. vertexShaderUrl = vertex;
  258. }
  259. else {
  260. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  261. }
  262. // Vertex shader
  263. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  264. };
  265. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  266. if (BABYLON.Tools.IsWindowObjectExist()) {
  267. // DOM element ?
  268. if (fragment instanceof HTMLElement) {
  269. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  270. callback(fragmentCode);
  271. return;
  272. }
  273. }
  274. // Base64 encoded ?
  275. if (fragment.substr(0, 7) === "base64:") {
  276. var fragmentBinary = window.atob(fragment.substr(7));
  277. callback(fragmentBinary);
  278. return;
  279. }
  280. // Is in local store ?
  281. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  282. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  283. return;
  284. }
  285. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  286. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  287. return;
  288. }
  289. var fragmentShaderUrl;
  290. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  291. fragmentShaderUrl = fragment;
  292. }
  293. else {
  294. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  295. }
  296. // Fragment shader
  297. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  298. };
  299. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  300. // Rebuild shaders source code
  301. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  302. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  303. vertexCode = prefix + vertexCode;
  304. fragmentCode = prefix + fragmentCode;
  305. // Number lines of shaders source code
  306. var i = 2;
  307. var regex = /\n/gm;
  308. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  309. i = 2;
  310. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  311. // Dump shaders name and formatted source code
  312. if (this.name.vertexElement) {
  313. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  314. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  315. }
  316. else if (this.name.vertex) {
  317. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  318. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  319. }
  320. else {
  321. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  322. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  323. }
  324. };
  325. ;
  326. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  327. var preparedSourceCode = this._processPrecision(sourceCode);
  328. if (this._engine.webGLVersion == 1) {
  329. callback(preparedSourceCode);
  330. return;
  331. }
  332. // Already converted
  333. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  334. callback(preparedSourceCode.replace("#version 300 es", ""));
  335. return;
  336. }
  337. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  338. // Remove extensions
  339. // #extension GL_OES_standard_derivatives : enable
  340. // #extension GL_EXT_shader_texture_lod : enable
  341. // #extension GL_EXT_frag_depth : enable
  342. // #extension GL_EXT_draw_buffers : require
  343. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  344. var result = preparedSourceCode.replace(regex, "");
  345. // Migrate to GLSL v300
  346. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  347. result = result.replace(/attribute[ \t]/g, "in ");
  348. result = result.replace(/[ \t]attribute/g, " in");
  349. if (isFragment) {
  350. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  351. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  352. result = result.replace(/texture2D\s*\(/g, "texture(");
  353. result = result.replace(/textureCube\s*\(/g, "texture(");
  354. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  355. result = result.replace(/gl_FragColor/g, "glFragColor");
  356. result = result.replace(/gl_FragData/g, "glFragData");
  357. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  358. }
  359. callback(result);
  360. };
  361. Effect.prototype._processIncludes = function (sourceCode, callback) {
  362. var _this = this;
  363. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  364. var match = regex.exec(sourceCode);
  365. var returnValue = new String(sourceCode);
  366. while (match != null) {
  367. var includeFile = match[1];
  368. // Uniform declaration
  369. if (includeFile.indexOf("__decl__") !== -1) {
  370. includeFile = includeFile.replace(/__decl__/, "");
  371. if (this._engine.supportsUniformBuffers) {
  372. includeFile = includeFile.replace(/Vertex/, "Ubo");
  373. includeFile = includeFile.replace(/Fragment/, "Ubo");
  374. }
  375. includeFile = includeFile + "Declaration";
  376. }
  377. if (Effect.IncludesShadersStore[includeFile]) {
  378. // Substitution
  379. var includeContent = Effect.IncludesShadersStore[includeFile];
  380. if (match[2]) {
  381. var splits = match[3].split(",");
  382. for (var index = 0; index < splits.length; index += 2) {
  383. var source = new RegExp(splits[index], "g");
  384. var dest = splits[index + 1];
  385. includeContent = includeContent.replace(source, dest);
  386. }
  387. }
  388. if (match[4]) {
  389. var indexString = match[5];
  390. if (indexString.indexOf("..") !== -1) {
  391. var indexSplits = indexString.split("..");
  392. var minIndex = parseInt(indexSplits[0]);
  393. var maxIndex = parseInt(indexSplits[1]);
  394. var sourceIncludeContent = includeContent.slice(0);
  395. includeContent = "";
  396. if (isNaN(maxIndex)) {
  397. maxIndex = this._indexParameters[indexSplits[1]];
  398. }
  399. for (var i = minIndex; i < maxIndex; i++) {
  400. if (!this._engine.supportsUniformBuffers) {
  401. // Ubo replacement
  402. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  403. return p1 + "{X}";
  404. });
  405. }
  406. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  407. }
  408. }
  409. else {
  410. if (!this._engine.supportsUniformBuffers) {
  411. // Ubo replacement
  412. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  413. return p1 + "{X}";
  414. });
  415. }
  416. includeContent = includeContent.replace(/\{X\}/g, indexString);
  417. }
  418. }
  419. // Replace
  420. returnValue = returnValue.replace(match[0], includeContent);
  421. }
  422. else {
  423. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  424. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  425. Effect.IncludesShadersStore[includeFile] = fileContent;
  426. _this._processIncludes(returnValue, callback);
  427. });
  428. return;
  429. }
  430. match = regex.exec(sourceCode);
  431. }
  432. callback(returnValue);
  433. };
  434. Effect.prototype._processPrecision = function (source) {
  435. if (source.indexOf("precision highp float") === -1) {
  436. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  437. source = "precision mediump float;\n" + source;
  438. }
  439. else {
  440. source = "precision highp float;\n" + source;
  441. }
  442. }
  443. else {
  444. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  445. source = source.replace("precision highp float", "precision mediump float");
  446. }
  447. }
  448. return source;
  449. };
  450. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  451. var _this = this;
  452. this._isReady = false;
  453. this._vertexSourceCodeOverride = vertexSourceCode;
  454. this._fragmentSourceCodeOverride = fragmentSourceCode;
  455. this.onError = function (effect, error) {
  456. if (onError) {
  457. onError(error);
  458. }
  459. };
  460. this.onCompiled = function () {
  461. var scenes = _this.getEngine().scenes;
  462. for (var i = 0; i < scenes.length; i++) {
  463. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  464. }
  465. if (onCompiled) {
  466. onCompiled(_this._program);
  467. }
  468. };
  469. this._fallbacks = null;
  470. this._prepareEffect();
  471. };
  472. Effect.prototype.getSpecificUniformLocations = function (names) {
  473. var engine = this._engine;
  474. return engine.getUniforms(this._program, names);
  475. };
  476. Effect.prototype._prepareEffect = function () {
  477. var attributesNames = this._attributesNames;
  478. var defines = this.defines;
  479. var fallbacks = this._fallbacks;
  480. this._valueCache = {};
  481. var previousProgram = this._program;
  482. try {
  483. var engine = this._engine;
  484. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  485. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  486. }
  487. else {
  488. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  489. }
  490. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  491. if (engine.supportsUniformBuffers) {
  492. for (var name in this._uniformBuffersNames) {
  493. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  494. }
  495. }
  496. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  497. this._attributes = engine.getAttributes(this._program, attributesNames);
  498. var index;
  499. for (index = 0; index < this._samplers.length; index++) {
  500. var sampler = this.getUniform(this._samplers[index]);
  501. if (sampler == null) {
  502. this._samplers.splice(index, 1);
  503. index--;
  504. }
  505. }
  506. engine.bindSamplers(this);
  507. this._compilationError = "";
  508. this._isReady = true;
  509. if (this.onCompiled) {
  510. this.onCompiled(this);
  511. }
  512. this.onCompileObservable.notifyObservers(this);
  513. this.onCompileObservable.clear();
  514. // Unbind mesh reference in fallbacks
  515. if (this._fallbacks) {
  516. this._fallbacks.unBindMesh();
  517. }
  518. if (previousProgram) {
  519. this.getEngine()._deleteProgram(previousProgram);
  520. }
  521. }
  522. catch (e) {
  523. this._compilationError = e.message;
  524. // Let's go through fallbacks then
  525. BABYLON.Tools.Error("Unable to compile effect:");
  526. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  527. return " " + uniform;
  528. }));
  529. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  530. return " " + attribute;
  531. }));
  532. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  533. BABYLON.Tools.Error("Error: " + this._compilationError);
  534. if (previousProgram) {
  535. this._program = previousProgram;
  536. this._isReady = true;
  537. if (this.onError) {
  538. this.onError(this, this._compilationError);
  539. }
  540. this.onErrorObservable.notifyObservers(this);
  541. }
  542. if (fallbacks && fallbacks.isMoreFallbacks) {
  543. BABYLON.Tools.Error("Trying next fallback.");
  544. this.defines = fallbacks.reduce(this.defines);
  545. this._prepareEffect();
  546. }
  547. else {
  548. if (this.onError) {
  549. this.onError(this, this._compilationError);
  550. }
  551. this.onErrorObservable.notifyObservers(this);
  552. this.onErrorObservable.clear();
  553. // Unbind mesh reference in fallbacks
  554. if (this._fallbacks) {
  555. this._fallbacks.unBindMesh();
  556. }
  557. }
  558. }
  559. };
  560. Object.defineProperty(Effect.prototype, "isSupported", {
  561. get: function () {
  562. return this._compilationError === "";
  563. },
  564. enumerable: true,
  565. configurable: true
  566. });
  567. Effect.prototype._bindTexture = function (channel, texture) {
  568. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  569. };
  570. Effect.prototype.setTexture = function (channel, texture) {
  571. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  572. };
  573. Effect.prototype.setTextureArray = function (channel, textures) {
  574. if (this._samplers.indexOf(channel + "Ex") === -1) {
  575. var initialPos = this._samplers.indexOf(channel);
  576. for (var index = 1; index < textures.length; index++) {
  577. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  578. }
  579. }
  580. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  581. };
  582. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  583. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  584. };
  585. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  586. var cache = this._valueCache[uniformName];
  587. var flag = matrix.updateFlag;
  588. if (cache !== undefined && cache === flag) {
  589. return false;
  590. }
  591. this._valueCache[uniformName] = flag;
  592. return true;
  593. };
  594. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  595. var cache = this._valueCache[uniformName];
  596. if (!cache) {
  597. cache = [x, y];
  598. this._valueCache[uniformName] = cache;
  599. return true;
  600. }
  601. var changed = false;
  602. if (cache[0] !== x) {
  603. cache[0] = x;
  604. changed = true;
  605. }
  606. if (cache[1] !== y) {
  607. cache[1] = y;
  608. changed = true;
  609. }
  610. return changed;
  611. };
  612. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  613. var cache = this._valueCache[uniformName];
  614. if (!cache) {
  615. cache = [x, y, z];
  616. this._valueCache[uniformName] = cache;
  617. return true;
  618. }
  619. var changed = false;
  620. if (cache[0] !== x) {
  621. cache[0] = x;
  622. changed = true;
  623. }
  624. if (cache[1] !== y) {
  625. cache[1] = y;
  626. changed = true;
  627. }
  628. if (cache[2] !== z) {
  629. cache[2] = z;
  630. changed = true;
  631. }
  632. return changed;
  633. };
  634. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  635. var cache = this._valueCache[uniformName];
  636. if (!cache) {
  637. cache = [x, y, z, w];
  638. this._valueCache[uniformName] = cache;
  639. return true;
  640. }
  641. var changed = false;
  642. if (cache[0] !== x) {
  643. cache[0] = x;
  644. changed = true;
  645. }
  646. if (cache[1] !== y) {
  647. cache[1] = y;
  648. changed = true;
  649. }
  650. if (cache[2] !== z) {
  651. cache[2] = z;
  652. changed = true;
  653. }
  654. if (cache[3] !== w) {
  655. cache[3] = w;
  656. changed = true;
  657. }
  658. return changed;
  659. };
  660. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  661. var bufferName = this._uniformBuffersNames[name];
  662. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  663. return;
  664. }
  665. Effect._baseCache[bufferName] = buffer;
  666. this._engine.bindUniformBufferBase(buffer, bufferName);
  667. };
  668. Effect.prototype.bindUniformBlock = function (blockName, index) {
  669. this._engine.bindUniformBlock(this._program, blockName, index);
  670. };
  671. Effect.prototype.setInt = function (uniformName, value) {
  672. var cache = this._valueCache[uniformName];
  673. if (cache !== undefined && cache === value)
  674. return this;
  675. this._valueCache[uniformName] = value;
  676. this._engine.setInt(this.getUniform(uniformName), value);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setIntArray2 = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setIntArray2(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setIntArray3 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setIntArray3(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setIntArray4 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setIntArray4(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setArray2 = function (uniformName, array) {
  725. this._valueCache[uniformName] = null;
  726. this._engine.setArray2(this.getUniform(uniformName), array);
  727. return this;
  728. };
  729. Effect.prototype.setArray3 = function (uniformName, array) {
  730. this._valueCache[uniformName] = null;
  731. this._engine.setArray3(this.getUniform(uniformName), array);
  732. return this;
  733. };
  734. Effect.prototype.setArray4 = function (uniformName, array) {
  735. this._valueCache[uniformName] = null;
  736. this._engine.setArray4(this.getUniform(uniformName), array);
  737. return this;
  738. };
  739. Effect.prototype.setMatrices = function (uniformName, matrices) {
  740. if (!matrices) {
  741. return this;
  742. }
  743. this._valueCache[uniformName] = null;
  744. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  745. return this;
  746. };
  747. Effect.prototype.setMatrix = function (uniformName, matrix) {
  748. if (this._cacheMatrix(uniformName, matrix)) {
  749. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  750. }
  751. return this;
  752. };
  753. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  754. this._valueCache[uniformName] = null;
  755. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  756. return this;
  757. };
  758. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  759. this._valueCache[uniformName] = null;
  760. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  761. return this;
  762. };
  763. Effect.prototype.setFloat = function (uniformName, value) {
  764. var cache = this._valueCache[uniformName];
  765. if (cache !== undefined && cache === value)
  766. return this;
  767. this._valueCache[uniformName] = value;
  768. this._engine.setFloat(this.getUniform(uniformName), value);
  769. return this;
  770. };
  771. Effect.prototype.setBool = function (uniformName, bool) {
  772. var cache = this._valueCache[uniformName];
  773. if (cache !== undefined && cache === bool)
  774. return this;
  775. this._valueCache[uniformName] = bool;
  776. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  777. return this;
  778. };
  779. Effect.prototype.setVector2 = function (uniformName, vector2) {
  780. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  781. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  782. }
  783. return this;
  784. };
  785. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  786. if (this._cacheFloat2(uniformName, x, y)) {
  787. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  788. }
  789. return this;
  790. };
  791. Effect.prototype.setVector3 = function (uniformName, vector3) {
  792. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  793. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  794. }
  795. return this;
  796. };
  797. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  798. if (this._cacheFloat3(uniformName, x, y, z)) {
  799. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  800. }
  801. return this;
  802. };
  803. Effect.prototype.setVector4 = function (uniformName, vector4) {
  804. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  805. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  806. }
  807. return this;
  808. };
  809. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  810. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  811. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  812. }
  813. return this;
  814. };
  815. Effect.prototype.setColor3 = function (uniformName, color3) {
  816. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  817. this._engine.setColor3(this.getUniform(uniformName), color3);
  818. }
  819. return this;
  820. };
  821. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  822. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  823. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  824. }
  825. return this;
  826. };
  827. Effect.ResetCache = function () {
  828. Effect._baseCache = {};
  829. };
  830. Effect._uniqueIdSeed = 0;
  831. Effect._baseCache = {};
  832. // Statics
  833. Effect.ShadersStore = {};
  834. Effect.IncludesShadersStore = {};
  835. return Effect;
  836. }());
  837. BABYLON.Effect = Effect;
  838. })(BABYLON || (BABYLON = {}));
  839. //# sourceMappingURL=babylon.effect.js.map
  840. //# sourceMappingURL=babylon.types.js.map
  841. 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}";
  842. 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}";
  843. var BABYLON;
  844. (function (BABYLON) {
  845. var KeyboardEventTypes = /** @class */ (function () {
  846. function KeyboardEventTypes() {
  847. }
  848. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  849. get: function () {
  850. return KeyboardEventTypes._KEYDOWN;
  851. },
  852. enumerable: true,
  853. configurable: true
  854. });
  855. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  856. get: function () {
  857. return KeyboardEventTypes._KEYUP;
  858. },
  859. enumerable: true,
  860. configurable: true
  861. });
  862. KeyboardEventTypes._KEYDOWN = 0x01;
  863. KeyboardEventTypes._KEYUP = 0x02;
  864. return KeyboardEventTypes;
  865. }());
  866. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  867. var KeyboardInfo = /** @class */ (function () {
  868. function KeyboardInfo(type, event) {
  869. this.type = type;
  870. this.event = event;
  871. }
  872. return KeyboardInfo;
  873. }());
  874. BABYLON.KeyboardInfo = KeyboardInfo;
  875. /**
  876. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  877. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  878. */
  879. var KeyboardInfoPre = /** @class */ (function (_super) {
  880. __extends(KeyboardInfoPre, _super);
  881. function KeyboardInfoPre(type, event) {
  882. var _this = _super.call(this, type, event) || this;
  883. _this.skipOnPointerObservable = false;
  884. return _this;
  885. }
  886. return KeyboardInfoPre;
  887. }(KeyboardInfo));
  888. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  889. })(BABYLON || (BABYLON = {}));
  890. //# sourceMappingURL=babylon.keyboardEvents.js.map
  891. var BABYLON;
  892. (function (BABYLON) {
  893. var PointerEventTypes = /** @class */ (function () {
  894. function PointerEventTypes() {
  895. }
  896. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  897. get: function () {
  898. return PointerEventTypes._POINTERDOWN;
  899. },
  900. enumerable: true,
  901. configurable: true
  902. });
  903. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  904. get: function () {
  905. return PointerEventTypes._POINTERUP;
  906. },
  907. enumerable: true,
  908. configurable: true
  909. });
  910. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  911. get: function () {
  912. return PointerEventTypes._POINTERMOVE;
  913. },
  914. enumerable: true,
  915. configurable: true
  916. });
  917. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  918. get: function () {
  919. return PointerEventTypes._POINTERWHEEL;
  920. },
  921. enumerable: true,
  922. configurable: true
  923. });
  924. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  925. get: function () {
  926. return PointerEventTypes._POINTERPICK;
  927. },
  928. enumerable: true,
  929. configurable: true
  930. });
  931. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  932. get: function () {
  933. return PointerEventTypes._POINTERTAP;
  934. },
  935. enumerable: true,
  936. configurable: true
  937. });
  938. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  939. get: function () {
  940. return PointerEventTypes._POINTERDOUBLETAP;
  941. },
  942. enumerable: true,
  943. configurable: true
  944. });
  945. PointerEventTypes._POINTERDOWN = 0x01;
  946. PointerEventTypes._POINTERUP = 0x02;
  947. PointerEventTypes._POINTERMOVE = 0x04;
  948. PointerEventTypes._POINTERWHEEL = 0x08;
  949. PointerEventTypes._POINTERPICK = 0x10;
  950. PointerEventTypes._POINTERTAP = 0x20;
  951. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  952. return PointerEventTypes;
  953. }());
  954. BABYLON.PointerEventTypes = PointerEventTypes;
  955. var PointerInfoBase = /** @class */ (function () {
  956. function PointerInfoBase(type, event) {
  957. this.type = type;
  958. this.event = event;
  959. }
  960. return PointerInfoBase;
  961. }());
  962. BABYLON.PointerInfoBase = PointerInfoBase;
  963. /**
  964. * This class is used to store pointer related info for the onPrePointerObservable event.
  965. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  966. */
  967. var PointerInfoPre = /** @class */ (function (_super) {
  968. __extends(PointerInfoPre, _super);
  969. function PointerInfoPre(type, event, localX, localY) {
  970. var _this = _super.call(this, type, event) || this;
  971. _this.skipOnPointerObservable = false;
  972. _this.localPosition = new BABYLON.Vector2(localX, localY);
  973. return _this;
  974. }
  975. return PointerInfoPre;
  976. }(PointerInfoBase));
  977. BABYLON.PointerInfoPre = PointerInfoPre;
  978. /**
  979. * This type contains all the data related to a pointer event in Babylon.js.
  980. * 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.
  981. */
  982. var PointerInfo = /** @class */ (function (_super) {
  983. __extends(PointerInfo, _super);
  984. function PointerInfo(type, event, pickInfo) {
  985. var _this = _super.call(this, type, event) || this;
  986. _this.pickInfo = pickInfo;
  987. return _this;
  988. }
  989. return PointerInfo;
  990. }(PointerInfoBase));
  991. BABYLON.PointerInfo = PointerInfo;
  992. })(BABYLON || (BABYLON = {}));
  993. //# sourceMappingURL=babylon.pointerEvents.js.map
  994. var BABYLON;
  995. (function (BABYLON) {
  996. BABYLON.ToGammaSpace = 1 / 2.2;
  997. BABYLON.ToLinearSpace = 2.2;
  998. BABYLON.Epsilon = 0.001;
  999. var Color3 = /** @class */ (function () {
  1000. /**
  1001. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  1002. */
  1003. function Color3(r, g, b) {
  1004. if (r === void 0) { r = 0; }
  1005. if (g === void 0) { g = 0; }
  1006. if (b === void 0) { b = 0; }
  1007. this.r = r;
  1008. this.g = g;
  1009. this.b = b;
  1010. }
  1011. /**
  1012. * Returns a string with the Color3 current values.
  1013. */
  1014. Color3.prototype.toString = function () {
  1015. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1016. };
  1017. /**
  1018. * Returns the string "Color3".
  1019. */
  1020. Color3.prototype.getClassName = function () {
  1021. return "Color3";
  1022. };
  1023. /**
  1024. * Returns the Color3 hash code.
  1025. */
  1026. Color3.prototype.getHashCode = function () {
  1027. var hash = this.r || 0;
  1028. hash = (hash * 397) ^ (this.g || 0);
  1029. hash = (hash * 397) ^ (this.b || 0);
  1030. return hash;
  1031. };
  1032. // Operators
  1033. /**
  1034. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1035. * Returns the Color3.
  1036. */
  1037. Color3.prototype.toArray = function (array, index) {
  1038. if (index === undefined) {
  1039. index = 0;
  1040. }
  1041. array[index] = this.r;
  1042. array[index + 1] = this.g;
  1043. array[index + 2] = this.b;
  1044. return this;
  1045. };
  1046. /**
  1047. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1048. */
  1049. Color3.prototype.toColor4 = function (alpha) {
  1050. if (alpha === void 0) { alpha = 1; }
  1051. return new Color4(this.r, this.g, this.b, alpha);
  1052. };
  1053. /**
  1054. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1055. */
  1056. Color3.prototype.asArray = function () {
  1057. var result = new Array();
  1058. this.toArray(result, 0);
  1059. return result;
  1060. };
  1061. /**
  1062. * Returns the luminance value (float).
  1063. */
  1064. Color3.prototype.toLuminance = function () {
  1065. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1066. };
  1067. /**
  1068. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1069. * Returns this new object.
  1070. */
  1071. Color3.prototype.multiply = function (otherColor) {
  1072. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1073. };
  1074. /**
  1075. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1076. * Returns the current Color3.
  1077. */
  1078. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1079. result.r = this.r * otherColor.r;
  1080. result.g = this.g * otherColor.g;
  1081. result.b = this.b * otherColor.b;
  1082. return this;
  1083. };
  1084. /**
  1085. * Boolean : True if the rgb values are equal to the passed ones.
  1086. */
  1087. Color3.prototype.equals = function (otherColor) {
  1088. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1089. };
  1090. /**
  1091. * Boolean : True if the rgb values are equal to the passed ones.
  1092. */
  1093. Color3.prototype.equalsFloats = function (r, g, b) {
  1094. return this.r === r && this.g === g && this.b === b;
  1095. };
  1096. /**
  1097. * Multiplies in place each rgb value by scale.
  1098. * Returns the updated Color3.
  1099. */
  1100. Color3.prototype.scale = function (scale) {
  1101. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1102. };
  1103. /**
  1104. * Multiplies the rgb values by scale and stores the result into "result".
  1105. * Returns the unmodified current Color3.
  1106. */
  1107. Color3.prototype.scaleToRef = function (scale, result) {
  1108. result.r = this.r * scale;
  1109. result.g = this.g * scale;
  1110. result.b = this.b * scale;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1115. */
  1116. Color3.prototype.add = function (otherColor) {
  1117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1118. };
  1119. /**
  1120. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1121. * Returns the unmodified current Color3.
  1122. */
  1123. Color3.prototype.addToRef = function (otherColor, result) {
  1124. result.r = this.r + otherColor.r;
  1125. result.g = this.g + otherColor.g;
  1126. result.b = this.b + otherColor.b;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1131. */
  1132. Color3.prototype.subtract = function (otherColor) {
  1133. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1134. };
  1135. /**
  1136. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1137. * Returns the unmodified current Color3.
  1138. */
  1139. Color3.prototype.subtractToRef = function (otherColor, result) {
  1140. result.r = this.r - otherColor.r;
  1141. result.g = this.g - otherColor.g;
  1142. result.b = this.b - otherColor.b;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Color3 copied the current one.
  1147. */
  1148. Color3.prototype.clone = function () {
  1149. return new Color3(this.r, this.g, this.b);
  1150. };
  1151. /**
  1152. * Copies the rgb values from the source in the current Color3.
  1153. * Returns the updated Color3.
  1154. */
  1155. Color3.prototype.copyFrom = function (source) {
  1156. this.r = source.r;
  1157. this.g = source.g;
  1158. this.b = source.b;
  1159. return this;
  1160. };
  1161. /**
  1162. * Updates the Color3 rgb values from the passed floats.
  1163. * Returns the Color3.
  1164. */
  1165. Color3.prototype.copyFromFloats = function (r, g, b) {
  1166. this.r = r;
  1167. this.g = g;
  1168. this.b = b;
  1169. return this;
  1170. };
  1171. /**
  1172. * Updates the Color3 rgb values from the passed floats.
  1173. * Returns the Color3.
  1174. */
  1175. Color3.prototype.set = function (r, g, b) {
  1176. return this.copyFromFloats(r, g, b);
  1177. };
  1178. /**
  1179. * Returns the Color3 hexadecimal code as a string.
  1180. */
  1181. Color3.prototype.toHexString = function () {
  1182. var intR = (this.r * 255) | 0;
  1183. var intG = (this.g * 255) | 0;
  1184. var intB = (this.b * 255) | 0;
  1185. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1186. };
  1187. /**
  1188. * Returns a new Color3 converted to linear space.
  1189. */
  1190. Color3.prototype.toLinearSpace = function () {
  1191. var convertedColor = new Color3();
  1192. this.toLinearSpaceToRef(convertedColor);
  1193. return convertedColor;
  1194. };
  1195. /**
  1196. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1197. * Returns the unmodified Color3.
  1198. */
  1199. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1200. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1201. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1202. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1203. return this;
  1204. };
  1205. /**
  1206. * Returns a new Color3 converted to gamma space.
  1207. */
  1208. Color3.prototype.toGammaSpace = function () {
  1209. var convertedColor = new Color3();
  1210. this.toGammaSpaceToRef(convertedColor);
  1211. return convertedColor;
  1212. };
  1213. /**
  1214. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1215. * Returns the unmodified Color3.
  1216. */
  1217. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1218. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1219. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1220. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1221. return this;
  1222. };
  1223. // Statics
  1224. /**
  1225. * Creates a new Color3 from the string containing valid hexadecimal values.
  1226. */
  1227. Color3.FromHexString = function (hex) {
  1228. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1229. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1230. return new Color3(0, 0, 0);
  1231. }
  1232. var r = parseInt(hex.substring(1, 3), 16);
  1233. var g = parseInt(hex.substring(3, 5), 16);
  1234. var b = parseInt(hex.substring(5, 7), 16);
  1235. return Color3.FromInts(r, g, b);
  1236. };
  1237. /**
  1238. * Creates a new Vector3 from the startind index of the passed array.
  1239. */
  1240. Color3.FromArray = function (array, offset) {
  1241. if (offset === void 0) { offset = 0; }
  1242. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1243. };
  1244. /**
  1245. * Creates a new Color3 from integer values ( < 256).
  1246. */
  1247. Color3.FromInts = function (r, g, b) {
  1248. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1249. };
  1250. /**
  1251. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1252. */
  1253. Color3.Lerp = function (start, end, amount) {
  1254. var r = start.r + ((end.r - start.r) * amount);
  1255. var g = start.g + ((end.g - start.g) * amount);
  1256. var b = start.b + ((end.b - start.b) * amount);
  1257. return new Color3(r, g, b);
  1258. };
  1259. Color3.Red = function () { return new Color3(1, 0, 0); };
  1260. Color3.Green = function () { return new Color3(0, 1, 0); };
  1261. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1262. Color3.Black = function () { return new Color3(0, 0, 0); };
  1263. Color3.White = function () { return new Color3(1, 1, 1); };
  1264. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1265. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1266. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1267. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1268. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1269. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1270. return Color3;
  1271. }());
  1272. BABYLON.Color3 = Color3;
  1273. var Color4 = /** @class */ (function () {
  1274. /**
  1275. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1276. */
  1277. function Color4(r, g, b, a) {
  1278. if (r === void 0) { r = 0; }
  1279. if (g === void 0) { g = 0; }
  1280. if (b === void 0) { b = 0; }
  1281. if (a === void 0) { a = 1; }
  1282. this.r = r;
  1283. this.g = g;
  1284. this.b = b;
  1285. this.a = a;
  1286. }
  1287. // Operators
  1288. /**
  1289. * Adds in place the passed Color4 values to the current Color4.
  1290. * Returns the updated Color4.
  1291. */
  1292. Color4.prototype.addInPlace = function (right) {
  1293. this.r += right.r;
  1294. this.g += right.g;
  1295. this.b += right.b;
  1296. this.a += right.a;
  1297. return this;
  1298. };
  1299. /**
  1300. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1301. */
  1302. Color4.prototype.asArray = function () {
  1303. var result = new Array();
  1304. this.toArray(result, 0);
  1305. return result;
  1306. };
  1307. /**
  1308. * Stores from the starting index in the passed array the Color4 successive values.
  1309. * Returns the Color4.
  1310. */
  1311. Color4.prototype.toArray = function (array, index) {
  1312. if (index === undefined) {
  1313. index = 0;
  1314. }
  1315. array[index] = this.r;
  1316. array[index + 1] = this.g;
  1317. array[index + 2] = this.b;
  1318. array[index + 3] = this.a;
  1319. return this;
  1320. };
  1321. /**
  1322. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1323. */
  1324. Color4.prototype.add = function (right) {
  1325. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1326. };
  1327. /**
  1328. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1329. */
  1330. Color4.prototype.subtract = function (right) {
  1331. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1332. };
  1333. /**
  1334. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1335. * Returns the Color4.
  1336. */
  1337. Color4.prototype.subtractToRef = function (right, result) {
  1338. result.r = this.r - right.r;
  1339. result.g = this.g - right.g;
  1340. result.b = this.b - right.b;
  1341. result.a = this.a - right.a;
  1342. return this;
  1343. };
  1344. /**
  1345. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1346. */
  1347. Color4.prototype.scale = function (scale) {
  1348. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1349. };
  1350. /**
  1351. * Multiplies the current Color4 values by scale and stores the result in "result".
  1352. * Returns the Color4.
  1353. */
  1354. Color4.prototype.scaleToRef = function (scale, result) {
  1355. result.r = this.r * scale;
  1356. result.g = this.g * scale;
  1357. result.b = this.b * scale;
  1358. result.a = this.a * scale;
  1359. return this;
  1360. };
  1361. /**
  1362. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1363. * @param color The Color4 (RGBA) value to multiply by
  1364. * @returns A new Color4.
  1365. */
  1366. Color4.prototype.multiply = function (color) {
  1367. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1368. };
  1369. /**
  1370. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1371. * @param color The Color4 (RGBA) value to multiply by
  1372. * @param result The Color4 (RGBA) to fill the result in
  1373. * @returns the result Color4.
  1374. */
  1375. Color4.prototype.multiplyToRef = function (color, result) {
  1376. result.r = this.r * color.r;
  1377. result.g = this.g * color.g;
  1378. result.b = this.b * color.b;
  1379. result.a = this.a * color.a;
  1380. return result;
  1381. };
  1382. /**
  1383. * Returns a string with the Color4 values.
  1384. */
  1385. Color4.prototype.toString = function () {
  1386. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1387. };
  1388. /**
  1389. * Returns the string "Color4"
  1390. */
  1391. Color4.prototype.getClassName = function () {
  1392. return "Color4";
  1393. };
  1394. /**
  1395. * Return the Color4 hash code as a number.
  1396. */
  1397. Color4.prototype.getHashCode = function () {
  1398. var hash = this.r || 0;
  1399. hash = (hash * 397) ^ (this.g || 0);
  1400. hash = (hash * 397) ^ (this.b || 0);
  1401. hash = (hash * 397) ^ (this.a || 0);
  1402. return hash;
  1403. };
  1404. /**
  1405. * Creates a new Color4 copied from the current one.
  1406. */
  1407. Color4.prototype.clone = function () {
  1408. return new Color4(this.r, this.g, this.b, this.a);
  1409. };
  1410. /**
  1411. * Copies the passed Color4 values into the current one.
  1412. * Returns the updated Color4.
  1413. */
  1414. Color4.prototype.copyFrom = function (source) {
  1415. this.r = source.r;
  1416. this.g = source.g;
  1417. this.b = source.b;
  1418. this.a = source.a;
  1419. return this;
  1420. };
  1421. /**
  1422. * Copies the passed float values into the current one.
  1423. * Returns the updated Color4.
  1424. */
  1425. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. this.a = a;
  1430. return this;
  1431. };
  1432. /**
  1433. * Copies the passed float values into the current one.
  1434. * Returns the updated Color4.
  1435. */
  1436. Color4.prototype.set = function (r, g, b, a) {
  1437. return this.copyFromFloats(r, g, b, a);
  1438. };
  1439. /**
  1440. * Returns a string containing the hexadecimal Color4 code.
  1441. */
  1442. Color4.prototype.toHexString = function () {
  1443. var intR = (this.r * 255) | 0;
  1444. var intG = (this.g * 255) | 0;
  1445. var intB = (this.b * 255) | 0;
  1446. var intA = (this.a * 255) | 0;
  1447. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1448. };
  1449. /**
  1450. * Returns a new Color4 converted to linear space.
  1451. */
  1452. Color4.prototype.toLinearSpace = function () {
  1453. var convertedColor = new Color4();
  1454. this.toLinearSpaceToRef(convertedColor);
  1455. return convertedColor;
  1456. };
  1457. /**
  1458. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1459. * Returns the unmodified Color4.
  1460. */
  1461. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1462. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1463. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1464. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1465. convertedColor.a = this.a;
  1466. return this;
  1467. };
  1468. /**
  1469. * Returns a new Color4 converted to gamma space.
  1470. */
  1471. Color4.prototype.toGammaSpace = function () {
  1472. var convertedColor = new Color4();
  1473. this.toGammaSpaceToRef(convertedColor);
  1474. return convertedColor;
  1475. };
  1476. /**
  1477. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1478. * Returns the unmodified Color4.
  1479. */
  1480. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1481. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1482. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1483. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1484. convertedColor.a = this.a;
  1485. return this;
  1486. };
  1487. // Statics
  1488. /**
  1489. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1490. */
  1491. Color4.FromHexString = function (hex) {
  1492. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1493. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1494. return new Color4(0.0, 0.0, 0.0, 0.0);
  1495. }
  1496. var r = parseInt(hex.substring(1, 3), 16);
  1497. var g = parseInt(hex.substring(3, 5), 16);
  1498. var b = parseInt(hex.substring(5, 7), 16);
  1499. var a = parseInt(hex.substring(7, 9), 16);
  1500. return Color4.FromInts(r, g, b, a);
  1501. };
  1502. /**
  1503. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1504. */
  1505. Color4.Lerp = function (left, right, amount) {
  1506. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1507. Color4.LerpToRef(left, right, amount, result);
  1508. return result;
  1509. };
  1510. /**
  1511. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1512. */
  1513. Color4.LerpToRef = function (left, right, amount, result) {
  1514. result.r = left.r + (right.r - left.r) * amount;
  1515. result.g = left.g + (right.g - left.g) * amount;
  1516. result.b = left.b + (right.b - left.b) * amount;
  1517. result.a = left.a + (right.a - left.a) * amount;
  1518. };
  1519. /**
  1520. * Creates a new Color4 from the starting index element of the passed array.
  1521. */
  1522. Color4.FromArray = function (array, offset) {
  1523. if (offset === void 0) { offset = 0; }
  1524. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1525. };
  1526. /**
  1527. * Creates a new Color4 from the passed integers ( < 256 ).
  1528. */
  1529. Color4.FromInts = function (r, g, b, a) {
  1530. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1531. };
  1532. Color4.CheckColors4 = function (colors, count) {
  1533. // Check if color3 was used
  1534. if (colors.length === count * 3) {
  1535. var colors4 = [];
  1536. for (var index = 0; index < colors.length; index += 3) {
  1537. var newIndex = (index / 3) * 4;
  1538. colors4[newIndex] = colors[index];
  1539. colors4[newIndex + 1] = colors[index + 1];
  1540. colors4[newIndex + 2] = colors[index + 2];
  1541. colors4[newIndex + 3] = 1.0;
  1542. }
  1543. return colors4;
  1544. }
  1545. return colors;
  1546. };
  1547. return Color4;
  1548. }());
  1549. BABYLON.Color4 = Color4;
  1550. var Vector2 = /** @class */ (function () {
  1551. /**
  1552. * Creates a new Vector2 from the passed x and y coordinates.
  1553. */
  1554. function Vector2(x, y) {
  1555. this.x = x;
  1556. this.y = y;
  1557. }
  1558. /**
  1559. * Returns a string with the Vector2 coordinates.
  1560. */
  1561. Vector2.prototype.toString = function () {
  1562. return "{X: " + this.x + " Y:" + this.y + "}";
  1563. };
  1564. /**
  1565. * Returns the string "Vector2"
  1566. */
  1567. Vector2.prototype.getClassName = function () {
  1568. return "Vector2";
  1569. };
  1570. /**
  1571. * Returns the Vector2 hash code as a number.
  1572. */
  1573. Vector2.prototype.getHashCode = function () {
  1574. var hash = this.x || 0;
  1575. hash = (hash * 397) ^ (this.y || 0);
  1576. return hash;
  1577. };
  1578. // Operators
  1579. /**
  1580. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1581. * Returns the Vector2.
  1582. */
  1583. Vector2.prototype.toArray = function (array, index) {
  1584. if (index === void 0) { index = 0; }
  1585. array[index] = this.x;
  1586. array[index + 1] = this.y;
  1587. return this;
  1588. };
  1589. /**
  1590. * Returns a new array with 2 elements : the Vector2 coordinates.
  1591. */
  1592. Vector2.prototype.asArray = function () {
  1593. var result = new Array();
  1594. this.toArray(result, 0);
  1595. return result;
  1596. };
  1597. /**
  1598. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1599. * Returns the updated Vector2.
  1600. */
  1601. Vector2.prototype.copyFrom = function (source) {
  1602. this.x = source.x;
  1603. this.y = source.y;
  1604. return this;
  1605. };
  1606. /**
  1607. * Sets the Vector2 coordinates with the passed floats.
  1608. * Returns the updated Vector2.
  1609. */
  1610. Vector2.prototype.copyFromFloats = function (x, y) {
  1611. this.x = x;
  1612. this.y = y;
  1613. return this;
  1614. };
  1615. /**
  1616. * Sets the Vector2 coordinates with the passed floats.
  1617. * Returns the updated Vector2.
  1618. */
  1619. Vector2.prototype.set = function (x, y) {
  1620. return this.copyFromFloats(x, y);
  1621. };
  1622. /**
  1623. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1624. */
  1625. Vector2.prototype.add = function (otherVector) {
  1626. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1627. };
  1628. /**
  1629. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1630. * Returns the Vector2.
  1631. */
  1632. Vector2.prototype.addToRef = function (otherVector, result) {
  1633. result.x = this.x + otherVector.x;
  1634. result.y = this.y + otherVector.y;
  1635. return this;
  1636. };
  1637. /**
  1638. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1639. * Returns the updated Vector2.
  1640. */
  1641. Vector2.prototype.addInPlace = function (otherVector) {
  1642. this.x += otherVector.x;
  1643. this.y += otherVector.y;
  1644. return this;
  1645. };
  1646. /**
  1647. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1648. */
  1649. Vector2.prototype.addVector3 = function (otherVector) {
  1650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1651. };
  1652. /**
  1653. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1654. */
  1655. Vector2.prototype.subtract = function (otherVector) {
  1656. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1657. };
  1658. /**
  1659. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1660. * Returns the Vector2.
  1661. */
  1662. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1663. result.x = this.x - otherVector.x;
  1664. result.y = this.y - otherVector.y;
  1665. return this;
  1666. };
  1667. /**
  1668. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1669. * Returns the updated Vector2.
  1670. */
  1671. Vector2.prototype.subtractInPlace = function (otherVector) {
  1672. this.x -= otherVector.x;
  1673. this.y -= otherVector.y;
  1674. return this;
  1675. };
  1676. /**
  1677. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1678. * Returns the updated Vector2.
  1679. */
  1680. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1681. this.x *= otherVector.x;
  1682. this.y *= otherVector.y;
  1683. return this;
  1684. };
  1685. /**
  1686. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1687. */
  1688. Vector2.prototype.multiply = function (otherVector) {
  1689. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1690. };
  1691. /**
  1692. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1693. * Returns the Vector2.
  1694. */
  1695. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1696. result.x = this.x * otherVector.x;
  1697. result.y = this.y * otherVector.y;
  1698. return this;
  1699. };
  1700. /**
  1701. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1702. */
  1703. Vector2.prototype.multiplyByFloats = function (x, y) {
  1704. return new Vector2(this.x * x, this.y * y);
  1705. };
  1706. /**
  1707. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1708. */
  1709. Vector2.prototype.divide = function (otherVector) {
  1710. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1711. };
  1712. /**
  1713. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1714. * Returns the Vector2.
  1715. */
  1716. Vector2.prototype.divideToRef = function (otherVector, result) {
  1717. result.x = this.x / otherVector.x;
  1718. result.y = this.y / otherVector.y;
  1719. return this;
  1720. };
  1721. /**
  1722. * Returns a new Vector2 with current Vector2 negated coordinates.
  1723. */
  1724. Vector2.prototype.negate = function () {
  1725. return new Vector2(-this.x, -this.y);
  1726. };
  1727. /**
  1728. * Multiply the Vector2 coordinates by scale.
  1729. * Returns the updated Vector2.
  1730. */
  1731. Vector2.prototype.scaleInPlace = function (scale) {
  1732. this.x *= scale;
  1733. this.y *= scale;
  1734. return this;
  1735. };
  1736. /**
  1737. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1738. */
  1739. Vector2.prototype.scale = function (scale) {
  1740. return new Vector2(this.x * scale, this.y * scale);
  1741. };
  1742. /**
  1743. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1744. */
  1745. Vector2.prototype.equals = function (otherVector) {
  1746. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1747. };
  1748. /**
  1749. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1750. */
  1751. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1753. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1754. };
  1755. // Properties
  1756. /**
  1757. * Returns the vector length (float).
  1758. */
  1759. Vector2.prototype.length = function () {
  1760. return Math.sqrt(this.x * this.x + this.y * this.y);
  1761. };
  1762. /**
  1763. * Returns the vector squared length (float);
  1764. */
  1765. Vector2.prototype.lengthSquared = function () {
  1766. return (this.x * this.x + this.y * this.y);
  1767. };
  1768. // Methods
  1769. /**
  1770. * Normalize the vector.
  1771. * Returns the updated Vector2.
  1772. */
  1773. Vector2.prototype.normalize = function () {
  1774. var len = this.length();
  1775. if (len === 0)
  1776. return this;
  1777. var num = 1.0 / len;
  1778. this.x *= num;
  1779. this.y *= num;
  1780. return this;
  1781. };
  1782. /**
  1783. * Returns a new Vector2 copied from the Vector2.
  1784. */
  1785. Vector2.prototype.clone = function () {
  1786. return new Vector2(this.x, this.y);
  1787. };
  1788. // Statics
  1789. /**
  1790. * Returns a new Vector2(0, 0)
  1791. */
  1792. Vector2.Zero = function () {
  1793. return new Vector2(0, 0);
  1794. };
  1795. /**
  1796. * Returns a new Vector2(1, 1)
  1797. */
  1798. Vector2.One = function () {
  1799. return new Vector2(1, 1);
  1800. };
  1801. /**
  1802. * Returns a new Vector2 set from the passed index element of the passed array.
  1803. */
  1804. Vector2.FromArray = function (array, offset) {
  1805. if (offset === void 0) { offset = 0; }
  1806. return new Vector2(array[offset], array[offset + 1]);
  1807. };
  1808. /**
  1809. * Sets "result" from the passed index element of the passed array.
  1810. */
  1811. Vector2.FromArrayToRef = function (array, offset, result) {
  1812. result.x = array[offset];
  1813. result.y = array[offset + 1];
  1814. };
  1815. /**
  1816. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1817. */
  1818. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1819. var squared = amount * amount;
  1820. var cubed = amount * squared;
  1821. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1822. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1823. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1824. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1825. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1826. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1827. return new Vector2(x, y);
  1828. };
  1829. /**
  1830. * 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".
  1831. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1832. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1833. */
  1834. Vector2.Clamp = function (value, min, max) {
  1835. var x = value.x;
  1836. x = (x > max.x) ? max.x : x;
  1837. x = (x < min.x) ? min.x : x;
  1838. var y = value.y;
  1839. y = (y > max.y) ? max.y : y;
  1840. y = (y < min.y) ? min.y : y;
  1841. return new Vector2(x, y);
  1842. };
  1843. /**
  1844. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1845. */
  1846. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1847. var squared = amount * amount;
  1848. var cubed = amount * squared;
  1849. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1850. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1851. var part3 = (cubed - (2.0 * squared)) + amount;
  1852. var part4 = cubed - squared;
  1853. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1854. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1855. return new Vector2(x, y);
  1856. };
  1857. /**
  1858. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1859. */
  1860. Vector2.Lerp = function (start, end, amount) {
  1861. var x = start.x + ((end.x - start.x) * amount);
  1862. var y = start.y + ((end.y - start.y) * amount);
  1863. return new Vector2(x, y);
  1864. };
  1865. /**
  1866. * Returns the dot product (float) of the vector "left" and the vector "right".
  1867. */
  1868. Vector2.Dot = function (left, right) {
  1869. return left.x * right.x + left.y * right.y;
  1870. };
  1871. /**
  1872. * Returns a new Vector2 equal to the normalized passed vector.
  1873. */
  1874. Vector2.Normalize = function (vector) {
  1875. var newVector = vector.clone();
  1876. newVector.normalize();
  1877. return newVector;
  1878. };
  1879. /**
  1880. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1881. */
  1882. Vector2.Minimize = function (left, right) {
  1883. var x = (left.x < right.x) ? left.x : right.x;
  1884. var y = (left.y < right.y) ? left.y : right.y;
  1885. return new Vector2(x, y);
  1886. };
  1887. /**
  1888. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1889. */
  1890. Vector2.Maximize = function (left, right) {
  1891. var x = (left.x > right.x) ? left.x : right.x;
  1892. var y = (left.y > right.y) ? left.y : right.y;
  1893. return new Vector2(x, y);
  1894. };
  1895. /**
  1896. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1897. */
  1898. Vector2.Transform = function (vector, transformation) {
  1899. var r = Vector2.Zero();
  1900. Vector2.TransformToRef(vector, transformation, r);
  1901. return r;
  1902. };
  1903. /**
  1904. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1905. */
  1906. Vector2.TransformToRef = function (vector, transformation, result) {
  1907. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1908. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1909. result.x = x;
  1910. result.y = y;
  1911. };
  1912. /**
  1913. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1914. */
  1915. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1916. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1917. var sign = a < 0 ? -1 : 1;
  1918. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1919. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1920. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1921. };
  1922. /**
  1923. * Returns the distance (float) between the vectors "value1" and "value2".
  1924. */
  1925. Vector2.Distance = function (value1, value2) {
  1926. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1927. };
  1928. /**
  1929. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1930. */
  1931. Vector2.DistanceSquared = function (value1, value2) {
  1932. var x = value1.x - value2.x;
  1933. var y = value1.y - value2.y;
  1934. return (x * x) + (y * y);
  1935. };
  1936. /**
  1937. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1938. */
  1939. Vector2.Center = function (value1, value2) {
  1940. var center = value1.add(value2);
  1941. center.scaleInPlace(0.5);
  1942. return center;
  1943. };
  1944. /**
  1945. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1946. */
  1947. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1948. var l2 = Vector2.DistanceSquared(segA, segB);
  1949. if (l2 === 0.0) {
  1950. return Vector2.Distance(p, segA);
  1951. }
  1952. var v = segB.subtract(segA);
  1953. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1954. var proj = segA.add(v.multiplyByFloats(t, t));
  1955. return Vector2.Distance(p, proj);
  1956. };
  1957. return Vector2;
  1958. }());
  1959. BABYLON.Vector2 = Vector2;
  1960. var Vector3 = /** @class */ (function () {
  1961. /**
  1962. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1963. * A Vector3 is the main object used in 3D geometry.
  1964. * It can represent etiher the coordinates of a point the space, either a direction.
  1965. */
  1966. function Vector3(x, y, z) {
  1967. this.x = x;
  1968. this.y = y;
  1969. this.z = z;
  1970. }
  1971. /**
  1972. * Returns a string with the Vector3 coordinates.
  1973. */
  1974. Vector3.prototype.toString = function () {
  1975. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1976. };
  1977. /**
  1978. * Returns the string "Vector3"
  1979. */
  1980. Vector3.prototype.getClassName = function () {
  1981. return "Vector3";
  1982. };
  1983. /**
  1984. * Returns the Vector hash code.
  1985. */
  1986. Vector3.prototype.getHashCode = function () {
  1987. var hash = this.x || 0;
  1988. hash = (hash * 397) ^ (this.y || 0);
  1989. hash = (hash * 397) ^ (this.z || 0);
  1990. return hash;
  1991. };
  1992. // Operators
  1993. /**
  1994. * Returns a new array with three elements : the coordinates the Vector3.
  1995. */
  1996. Vector3.prototype.asArray = function () {
  1997. var result = [];
  1998. this.toArray(result, 0);
  1999. return result;
  2000. };
  2001. /**
  2002. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2003. * Returns the Vector3.
  2004. */
  2005. Vector3.prototype.toArray = function (array, index) {
  2006. if (index === void 0) { index = 0; }
  2007. array[index] = this.x;
  2008. array[index + 1] = this.y;
  2009. array[index + 2] = this.z;
  2010. return this;
  2011. };
  2012. /**
  2013. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2014. */
  2015. Vector3.prototype.toQuaternion = function () {
  2016. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2017. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2018. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2019. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2020. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2021. var cosy = Math.cos(this.y * 0.5);
  2022. var siny = Math.sin(this.y * 0.5);
  2023. result.x = coszMinusx * siny;
  2024. result.y = -sinzMinusx * siny;
  2025. result.z = sinxPlusz * cosy;
  2026. result.w = cosxPlusz * cosy;
  2027. return result;
  2028. };
  2029. /**
  2030. * Adds the passed vector to the current Vector3.
  2031. * Returns the updated Vector3.
  2032. */
  2033. Vector3.prototype.addInPlace = function (otherVector) {
  2034. this.x += otherVector.x;
  2035. this.y += otherVector.y;
  2036. this.z += otherVector.z;
  2037. return this;
  2038. };
  2039. /**
  2040. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2041. */
  2042. Vector3.prototype.add = function (otherVector) {
  2043. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2044. };
  2045. /**
  2046. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2047. * Returns the current Vector3.
  2048. */
  2049. Vector3.prototype.addToRef = function (otherVector, result) {
  2050. result.x = this.x + otherVector.x;
  2051. result.y = this.y + otherVector.y;
  2052. result.z = this.z + otherVector.z;
  2053. return this;
  2054. };
  2055. /**
  2056. * Subtract the passed vector from the current Vector3.
  2057. * Returns the updated Vector3.
  2058. */
  2059. Vector3.prototype.subtractInPlace = function (otherVector) {
  2060. this.x -= otherVector.x;
  2061. this.y -= otherVector.y;
  2062. this.z -= otherVector.z;
  2063. return this;
  2064. };
  2065. /**
  2066. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2067. */
  2068. Vector3.prototype.subtract = function (otherVector) {
  2069. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2070. };
  2071. /**
  2072. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2073. * Returns the current Vector3.
  2074. */
  2075. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2076. result.x = this.x - otherVector.x;
  2077. result.y = this.y - otherVector.y;
  2078. result.z = this.z - otherVector.z;
  2079. return this;
  2080. };
  2081. /**
  2082. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2083. */
  2084. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2085. return new Vector3(this.x - x, this.y - y, this.z - z);
  2086. };
  2087. /**
  2088. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2089. * Returns the current Vector3.
  2090. */
  2091. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2092. result.x = this.x - x;
  2093. result.y = this.y - y;
  2094. result.z = this.z - z;
  2095. return this;
  2096. };
  2097. /**
  2098. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2099. */
  2100. Vector3.prototype.negate = function () {
  2101. return new Vector3(-this.x, -this.y, -this.z);
  2102. };
  2103. /**
  2104. * Multiplies the Vector3 coordinates by the float "scale".
  2105. * Returns the updated Vector3.
  2106. */
  2107. Vector3.prototype.scaleInPlace = function (scale) {
  2108. this.x *= scale;
  2109. this.y *= scale;
  2110. this.z *= scale;
  2111. return this;
  2112. };
  2113. /**
  2114. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2115. */
  2116. Vector3.prototype.scale = function (scale) {
  2117. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2118. };
  2119. /**
  2120. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2121. * Returns the current Vector3.
  2122. */
  2123. Vector3.prototype.scaleToRef = function (scale, result) {
  2124. result.x = this.x * scale;
  2125. result.y = this.y * scale;
  2126. result.z = this.z * scale;
  2127. return this;
  2128. };
  2129. /**
  2130. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2131. */
  2132. Vector3.prototype.equals = function (otherVector) {
  2133. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2134. };
  2135. /**
  2136. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2137. */
  2138. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2139. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2140. 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);
  2141. };
  2142. /**
  2143. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2144. */
  2145. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2146. return this.x === x && this.y === y && this.z === z;
  2147. };
  2148. /**
  2149. * Muliplies the current Vector3 coordinates by the passed ones.
  2150. * Returns the updated Vector3.
  2151. */
  2152. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2153. this.x *= otherVector.x;
  2154. this.y *= otherVector.y;
  2155. this.z *= otherVector.z;
  2156. return this;
  2157. };
  2158. /**
  2159. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2160. */
  2161. Vector3.prototype.multiply = function (otherVector) {
  2162. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2163. };
  2164. /**
  2165. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2166. * Returns the current Vector3.
  2167. */
  2168. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2169. result.x = this.x * otherVector.x;
  2170. result.y = this.y * otherVector.y;
  2171. result.z = this.z * otherVector.z;
  2172. return this;
  2173. };
  2174. /**
  2175. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2176. */
  2177. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2178. return new Vector3(this.x * x, this.y * y, this.z * z);
  2179. };
  2180. /**
  2181. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2182. */
  2183. Vector3.prototype.divide = function (otherVector) {
  2184. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2185. };
  2186. /**
  2187. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2188. * Returns the current Vector3.
  2189. */
  2190. Vector3.prototype.divideToRef = function (otherVector, result) {
  2191. result.x = this.x / otherVector.x;
  2192. result.y = this.y / otherVector.y;
  2193. result.z = this.z / otherVector.z;
  2194. return this;
  2195. };
  2196. /**
  2197. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2198. * Returns the updated Vector3.
  2199. */
  2200. Vector3.prototype.MinimizeInPlace = function (other) {
  2201. if (other.x < this.x)
  2202. this.x = other.x;
  2203. if (other.y < this.y)
  2204. this.y = other.y;
  2205. if (other.z < this.z)
  2206. this.z = other.z;
  2207. return this;
  2208. };
  2209. /**
  2210. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2211. * Returns the updated Vector3.
  2212. */
  2213. Vector3.prototype.MaximizeInPlace = function (other) {
  2214. if (other.x > this.x)
  2215. this.x = other.x;
  2216. if (other.y > this.y)
  2217. this.y = other.y;
  2218. if (other.z > this.z)
  2219. this.z = other.z;
  2220. return this;
  2221. };
  2222. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2223. /**
  2224. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2225. */
  2226. get: function () {
  2227. var absX = Math.abs(this.x);
  2228. var absY = Math.abs(this.y);
  2229. if (absX !== absY) {
  2230. return true;
  2231. }
  2232. var absZ = Math.abs(this.z);
  2233. if (absX !== absZ) {
  2234. return true;
  2235. }
  2236. if (absY !== absZ) {
  2237. return true;
  2238. }
  2239. return false;
  2240. },
  2241. enumerable: true,
  2242. configurable: true
  2243. });
  2244. // Properties
  2245. /**
  2246. * Returns the length of the Vector3 (float).
  2247. */
  2248. Vector3.prototype.length = function () {
  2249. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2250. };
  2251. /**
  2252. * Returns the squared length of the Vector3 (float).
  2253. */
  2254. Vector3.prototype.lengthSquared = function () {
  2255. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2256. };
  2257. /**
  2258. * Normalize the current Vector3.
  2259. * Returns the updated Vector3.
  2260. * /!\ In place operation.
  2261. */
  2262. Vector3.prototype.normalize = function () {
  2263. var len = this.length();
  2264. if (len === 0 || len === 1.0)
  2265. return this;
  2266. var num = 1.0 / len;
  2267. this.x *= num;
  2268. this.y *= num;
  2269. this.z *= num;
  2270. return this;
  2271. };
  2272. /**
  2273. * Normalize the current Vector3 to a new vector.
  2274. * @returns the new Vector3.
  2275. */
  2276. Vector3.prototype.normalizeToNew = function () {
  2277. var normalized = new Vector3(0, 0, 0);
  2278. this.normalizeToRef(normalized);
  2279. return normalized;
  2280. };
  2281. /**
  2282. * Normalize the current Vector3 to the reference.
  2283. * @param the reference to update.
  2284. * @returns the updated Vector3.
  2285. */
  2286. Vector3.prototype.normalizeToRef = function (reference) {
  2287. var len = this.length();
  2288. if (len === 0 || len === 1.0) {
  2289. reference.set(this.x, this.y, this.z);
  2290. return reference;
  2291. }
  2292. var scale = 1.0 / len;
  2293. this.scaleToRef(scale, reference);
  2294. return reference;
  2295. };
  2296. /**
  2297. * Returns a new Vector3 copied from the current Vector3.
  2298. */
  2299. Vector3.prototype.clone = function () {
  2300. return new Vector3(this.x, this.y, this.z);
  2301. };
  2302. /**
  2303. * Copies the passed vector coordinates to the current Vector3 ones.
  2304. * Returns the updated Vector3.
  2305. */
  2306. Vector3.prototype.copyFrom = function (source) {
  2307. this.x = source.x;
  2308. this.y = source.y;
  2309. this.z = source.z;
  2310. return this;
  2311. };
  2312. /**
  2313. * Copies the passed floats to the current Vector3 coordinates.
  2314. * Returns the updated Vector3.
  2315. */
  2316. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2317. this.x = x;
  2318. this.y = y;
  2319. this.z = z;
  2320. return this;
  2321. };
  2322. /**
  2323. * Copies the passed floats to the current Vector3 coordinates.
  2324. * Returns the updated Vector3.
  2325. */
  2326. Vector3.prototype.set = function (x, y, z) {
  2327. return this.copyFromFloats(x, y, z);
  2328. };
  2329. // Statics
  2330. /**
  2331. *
  2332. */
  2333. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2334. var d0 = Vector3.Dot(vector0, axis) - size;
  2335. var d1 = Vector3.Dot(vector1, axis) - size;
  2336. var s = d0 / (d0 - d1);
  2337. return s;
  2338. };
  2339. /**
  2340. * Returns a new Vector3 set from the index "offset" of the passed array.
  2341. */
  2342. Vector3.FromArray = function (array, offset) {
  2343. if (!offset) {
  2344. offset = 0;
  2345. }
  2346. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2347. };
  2348. /**
  2349. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2350. * This function is deprecated. Use FromArray instead.
  2351. */
  2352. Vector3.FromFloatArray = function (array, offset) {
  2353. return Vector3.FromArray(array, offset);
  2354. };
  2355. /**
  2356. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2357. */
  2358. Vector3.FromArrayToRef = function (array, offset, result) {
  2359. result.x = array[offset];
  2360. result.y = array[offset + 1];
  2361. result.z = array[offset + 2];
  2362. };
  2363. /**
  2364. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2365. * This function is deprecated. Use FromArrayToRef instead.
  2366. */
  2367. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2368. return Vector3.FromArrayToRef(array, offset, result);
  2369. };
  2370. /**
  2371. * Sets the passed vector "result" with the passed floats.
  2372. */
  2373. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2374. result.x = x;
  2375. result.y = y;
  2376. result.z = z;
  2377. };
  2378. /**
  2379. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2380. */
  2381. Vector3.Zero = function () {
  2382. return new Vector3(0.0, 0.0, 0.0);
  2383. };
  2384. /**
  2385. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2386. */
  2387. Vector3.One = function () {
  2388. return new Vector3(1.0, 1.0, 1.0);
  2389. };
  2390. /**
  2391. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2392. */
  2393. Vector3.Up = function () {
  2394. return new Vector3(0.0, 1.0, 0.0);
  2395. };
  2396. /**
  2397. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2398. */
  2399. Vector3.Forward = function () {
  2400. return new Vector3(0.0, 0.0, 1.0);
  2401. };
  2402. /**
  2403. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2404. */
  2405. Vector3.Right = function () {
  2406. return new Vector3(1.0, 0.0, 0.0);
  2407. };
  2408. /**
  2409. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2410. */
  2411. Vector3.Left = function () {
  2412. return new Vector3(-1.0, 0.0, 0.0);
  2413. };
  2414. /**
  2415. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2416. * This method computes tranformed coordinates only, not transformed direction vectors.
  2417. */
  2418. Vector3.TransformCoordinates = function (vector, transformation) {
  2419. var result = Vector3.Zero();
  2420. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2421. return result;
  2422. };
  2423. /**
  2424. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2425. * This method computes tranformed coordinates only, not transformed direction vectors.
  2426. */
  2427. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2428. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2429. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2430. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2431. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2432. result.x = x / w;
  2433. result.y = y / w;
  2434. result.z = z / w;
  2435. };
  2436. /**
  2437. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2438. * This method computes tranformed coordinates only, not transformed direction vectors.
  2439. */
  2440. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2441. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2442. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2443. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2444. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2445. result.x = rx / rw;
  2446. result.y = ry / rw;
  2447. result.z = rz / rw;
  2448. };
  2449. /**
  2450. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2451. * This methods computes transformed normalized direction vectors only.
  2452. */
  2453. Vector3.TransformNormal = function (vector, transformation) {
  2454. var result = Vector3.Zero();
  2455. Vector3.TransformNormalToRef(vector, transformation, result);
  2456. return result;
  2457. };
  2458. /**
  2459. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2460. * This methods computes transformed normalized direction vectors only.
  2461. */
  2462. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2463. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2464. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2465. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2466. result.x = x;
  2467. result.y = y;
  2468. result.z = z;
  2469. };
  2470. /**
  2471. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2472. * This methods computes transformed normalized direction vectors only.
  2473. */
  2474. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2475. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2476. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2477. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2478. };
  2479. /**
  2480. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2481. */
  2482. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2483. var squared = amount * amount;
  2484. var cubed = amount * squared;
  2485. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2486. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2487. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2488. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2489. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2490. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2491. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2492. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2493. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2494. return new Vector3(x, y, z);
  2495. };
  2496. /**
  2497. * 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".
  2498. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2499. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2500. */
  2501. Vector3.Clamp = function (value, min, max) {
  2502. var x = value.x;
  2503. x = (x > max.x) ? max.x : x;
  2504. x = (x < min.x) ? min.x : x;
  2505. var y = value.y;
  2506. y = (y > max.y) ? max.y : y;
  2507. y = (y < min.y) ? min.y : y;
  2508. var z = value.z;
  2509. z = (z > max.z) ? max.z : z;
  2510. z = (z < min.z) ? min.z : z;
  2511. return new Vector3(x, y, z);
  2512. };
  2513. /**
  2514. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2515. */
  2516. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2517. var squared = amount * amount;
  2518. var cubed = amount * squared;
  2519. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2520. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2521. var part3 = (cubed - (2.0 * squared)) + amount;
  2522. var part4 = cubed - squared;
  2523. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2524. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2525. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2526. return new Vector3(x, y, z);
  2527. };
  2528. /**
  2529. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2530. */
  2531. Vector3.Lerp = function (start, end, amount) {
  2532. var result = new Vector3(0, 0, 0);
  2533. Vector3.LerpToRef(start, end, amount, result);
  2534. return result;
  2535. };
  2536. /**
  2537. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2538. */
  2539. Vector3.LerpToRef = function (start, end, amount, result) {
  2540. result.x = start.x + ((end.x - start.x) * amount);
  2541. result.y = start.y + ((end.y - start.y) * amount);
  2542. result.z = start.z + ((end.z - start.z) * amount);
  2543. };
  2544. /**
  2545. * Returns the dot product (float) between the vectors "left" and "right".
  2546. */
  2547. Vector3.Dot = function (left, right) {
  2548. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2549. };
  2550. /**
  2551. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2552. * The cross product is then orthogonal to both "left" and "right".
  2553. */
  2554. Vector3.Cross = function (left, right) {
  2555. var result = Vector3.Zero();
  2556. Vector3.CrossToRef(left, right, result);
  2557. return result;
  2558. };
  2559. /**
  2560. * Sets the passed vector "result" with the cross product of "left" and "right".
  2561. * The cross product is then orthogonal to both "left" and "right".
  2562. */
  2563. Vector3.CrossToRef = function (left, right, result) {
  2564. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2565. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2566. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2567. result.copyFrom(MathTmp.Vector3[0]);
  2568. };
  2569. /**
  2570. * Returns a new Vector3 as the normalization of the passed vector.
  2571. */
  2572. Vector3.Normalize = function (vector) {
  2573. var result = Vector3.Zero();
  2574. Vector3.NormalizeToRef(vector, result);
  2575. return result;
  2576. };
  2577. /**
  2578. * Sets the passed vector "result" with the normalization of the passed first vector.
  2579. */
  2580. Vector3.NormalizeToRef = function (vector, result) {
  2581. result.copyFrom(vector);
  2582. result.normalize();
  2583. };
  2584. Vector3.Project = function (vector, world, transform, viewport) {
  2585. var cw = viewport.width;
  2586. var ch = viewport.height;
  2587. var cx = viewport.x;
  2588. var cy = viewport.y;
  2589. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2590. 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);
  2591. var matrix = MathTmp.Matrix[0];
  2592. world.multiplyToRef(transform, matrix);
  2593. matrix.multiplyToRef(viewportMatrix, matrix);
  2594. return Vector3.TransformCoordinates(vector, matrix);
  2595. };
  2596. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2597. var matrix = MathTmp.Matrix[0];
  2598. world.multiplyToRef(transform, matrix);
  2599. matrix.invert();
  2600. source.x = source.x / viewportWidth * 2 - 1;
  2601. source.y = -(source.y / viewportHeight * 2 - 1);
  2602. var vector = Vector3.TransformCoordinates(source, matrix);
  2603. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2604. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2605. vector = vector.scale(1.0 / num);
  2606. }
  2607. return vector;
  2608. };
  2609. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2610. var result = Vector3.Zero();
  2611. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2612. return result;
  2613. };
  2614. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2615. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2616. };
  2617. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2618. var matrix = MathTmp.Matrix[0];
  2619. world.multiplyToRef(view, matrix);
  2620. matrix.multiplyToRef(projection, matrix);
  2621. matrix.invert();
  2622. var screenSource = MathTmp.Vector3[0];
  2623. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2624. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2625. screenSource.z = 2 * sourceZ - 1.0;
  2626. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2627. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2628. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2629. result.scaleInPlace(1.0 / num);
  2630. }
  2631. };
  2632. Vector3.Minimize = function (left, right) {
  2633. var min = left.clone();
  2634. min.MinimizeInPlace(right);
  2635. return min;
  2636. };
  2637. Vector3.Maximize = function (left, right) {
  2638. var max = left.clone();
  2639. max.MaximizeInPlace(right);
  2640. return max;
  2641. };
  2642. /**
  2643. * Returns the distance (float) between the vectors "value1" and "value2".
  2644. */
  2645. Vector3.Distance = function (value1, value2) {
  2646. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2647. };
  2648. /**
  2649. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2650. */
  2651. Vector3.DistanceSquared = function (value1, value2) {
  2652. var x = value1.x - value2.x;
  2653. var y = value1.y - value2.y;
  2654. var z = value1.z - value2.z;
  2655. return (x * x) + (y * y) + (z * z);
  2656. };
  2657. /**
  2658. * Returns a new Vector3 located at the center between "value1" and "value2".
  2659. */
  2660. Vector3.Center = function (value1, value2) {
  2661. var center = value1.add(value2);
  2662. center.scaleInPlace(0.5);
  2663. return center;
  2664. };
  2665. /**
  2666. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2667. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2668. * to something in order to rotate it from its local system to the given target system.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. * Returns a new Vector3.
  2671. */
  2672. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2673. var rotation = Vector3.Zero();
  2674. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2675. return rotation;
  2676. };
  2677. /**
  2678. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2679. */
  2680. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2681. var quat = MathTmp.Quaternion[0];
  2682. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2683. quat.toEulerAnglesToRef(ref);
  2684. };
  2685. return Vector3;
  2686. }());
  2687. BABYLON.Vector3 = Vector3;
  2688. //Vector4 class created for EulerAngle class conversion to Quaternion
  2689. var Vector4 = /** @class */ (function () {
  2690. /**
  2691. * Creates a Vector4 object from the passed floats.
  2692. */
  2693. function Vector4(x, y, z, w) {
  2694. this.x = x;
  2695. this.y = y;
  2696. this.z = z;
  2697. this.w = w;
  2698. }
  2699. /**
  2700. * Returns the string with the Vector4 coordinates.
  2701. */
  2702. Vector4.prototype.toString = function () {
  2703. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2704. };
  2705. /**
  2706. * Returns the string "Vector4".
  2707. */
  2708. Vector4.prototype.getClassName = function () {
  2709. return "Vector4";
  2710. };
  2711. /**
  2712. * Returns the Vector4 hash code.
  2713. */
  2714. Vector4.prototype.getHashCode = function () {
  2715. var hash = this.x || 0;
  2716. hash = (hash * 397) ^ (this.y || 0);
  2717. hash = (hash * 397) ^ (this.z || 0);
  2718. hash = (hash * 397) ^ (this.w || 0);
  2719. return hash;
  2720. };
  2721. // Operators
  2722. /**
  2723. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2724. */
  2725. Vector4.prototype.asArray = function () {
  2726. var result = new Array();
  2727. this.toArray(result, 0);
  2728. return result;
  2729. };
  2730. /**
  2731. * Populates the passed array from the passed index with the Vector4 coordinates.
  2732. * Returns the Vector4.
  2733. */
  2734. Vector4.prototype.toArray = function (array, index) {
  2735. if (index === undefined) {
  2736. index = 0;
  2737. }
  2738. array[index] = this.x;
  2739. array[index + 1] = this.y;
  2740. array[index + 2] = this.z;
  2741. array[index + 3] = this.w;
  2742. return this;
  2743. };
  2744. /**
  2745. * Adds the passed vector to the current Vector4.
  2746. * Returns the updated Vector4.
  2747. */
  2748. Vector4.prototype.addInPlace = function (otherVector) {
  2749. this.x += otherVector.x;
  2750. this.y += otherVector.y;
  2751. this.z += otherVector.z;
  2752. this.w += otherVector.w;
  2753. return this;
  2754. };
  2755. /**
  2756. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2757. */
  2758. Vector4.prototype.add = function (otherVector) {
  2759. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2760. };
  2761. /**
  2762. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2763. * Returns the current Vector4.
  2764. */
  2765. Vector4.prototype.addToRef = function (otherVector, result) {
  2766. result.x = this.x + otherVector.x;
  2767. result.y = this.y + otherVector.y;
  2768. result.z = this.z + otherVector.z;
  2769. result.w = this.w + otherVector.w;
  2770. return this;
  2771. };
  2772. /**
  2773. * Subtract in place the passed vector from the current Vector4.
  2774. * Returns the updated Vector4.
  2775. */
  2776. Vector4.prototype.subtractInPlace = function (otherVector) {
  2777. this.x -= otherVector.x;
  2778. this.y -= otherVector.y;
  2779. this.z -= otherVector.z;
  2780. this.w -= otherVector.w;
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2785. */
  2786. Vector4.prototype.subtract = function (otherVector) {
  2787. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2788. };
  2789. /**
  2790. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2791. * Returns the current Vector4.
  2792. */
  2793. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2794. result.x = this.x - otherVector.x;
  2795. result.y = this.y - otherVector.y;
  2796. result.z = this.z - otherVector.z;
  2797. result.w = this.w - otherVector.w;
  2798. return this;
  2799. };
  2800. /**
  2801. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2802. */
  2803. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2804. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2805. };
  2806. /**
  2807. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2808. * Returns the current Vector4.
  2809. */
  2810. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2811. result.x = this.x - x;
  2812. result.y = this.y - y;
  2813. result.z = this.z - z;
  2814. result.w = this.w - w;
  2815. return this;
  2816. };
  2817. /**
  2818. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2819. */
  2820. Vector4.prototype.negate = function () {
  2821. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2822. };
  2823. /**
  2824. * Multiplies the current Vector4 coordinates by scale (float).
  2825. * Returns the updated Vector4.
  2826. */
  2827. Vector4.prototype.scaleInPlace = function (scale) {
  2828. this.x *= scale;
  2829. this.y *= scale;
  2830. this.z *= scale;
  2831. this.w *= scale;
  2832. return this;
  2833. };
  2834. /**
  2835. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2836. */
  2837. Vector4.prototype.scale = function (scale) {
  2838. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2839. };
  2840. /**
  2841. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2842. * Returns the current Vector4.
  2843. */
  2844. Vector4.prototype.scaleToRef = function (scale, result) {
  2845. result.x = this.x * scale;
  2846. result.y = this.y * scale;
  2847. result.z = this.z * scale;
  2848. result.w = this.w * scale;
  2849. return this;
  2850. };
  2851. /**
  2852. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2853. */
  2854. Vector4.prototype.equals = function (otherVector) {
  2855. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2856. };
  2857. /**
  2858. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2859. */
  2860. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2861. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2862. return otherVector
  2863. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2864. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2865. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2866. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2867. };
  2868. /**
  2869. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2870. */
  2871. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2872. return this.x === x && this.y === y && this.z === z && this.w === w;
  2873. };
  2874. /**
  2875. * Multiplies in place the current Vector4 by the passed one.
  2876. * Returns the updated Vector4.
  2877. */
  2878. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. this.w *= otherVector.w;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2887. */
  2888. Vector4.prototype.multiply = function (otherVector) {
  2889. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2890. };
  2891. /**
  2892. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2893. * Returns the current Vector4.
  2894. */
  2895. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2896. result.x = this.x * otherVector.x;
  2897. result.y = this.y * otherVector.y;
  2898. result.z = this.z * otherVector.z;
  2899. result.w = this.w * otherVector.w;
  2900. return this;
  2901. };
  2902. /**
  2903. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2904. */
  2905. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2906. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2907. };
  2908. /**
  2909. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2910. */
  2911. Vector4.prototype.divide = function (otherVector) {
  2912. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2913. };
  2914. /**
  2915. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2916. * Returns the current Vector4.
  2917. */
  2918. Vector4.prototype.divideToRef = function (otherVector, result) {
  2919. result.x = this.x / otherVector.x;
  2920. result.y = this.y / otherVector.y;
  2921. result.z = this.z / otherVector.z;
  2922. result.w = this.w / otherVector.w;
  2923. return this;
  2924. };
  2925. /**
  2926. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2927. */
  2928. Vector4.prototype.MinimizeInPlace = function (other) {
  2929. if (other.x < this.x)
  2930. this.x = other.x;
  2931. if (other.y < this.y)
  2932. this.y = other.y;
  2933. if (other.z < this.z)
  2934. this.z = other.z;
  2935. if (other.w < this.w)
  2936. this.w = other.w;
  2937. return this;
  2938. };
  2939. /**
  2940. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2941. */
  2942. Vector4.prototype.MaximizeInPlace = function (other) {
  2943. if (other.x > this.x)
  2944. this.x = other.x;
  2945. if (other.y > this.y)
  2946. this.y = other.y;
  2947. if (other.z > this.z)
  2948. this.z = other.z;
  2949. if (other.w > this.w)
  2950. this.w = other.w;
  2951. return this;
  2952. };
  2953. // Properties
  2954. /**
  2955. * Returns the Vector4 length (float).
  2956. */
  2957. Vector4.prototype.length = function () {
  2958. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2959. };
  2960. /**
  2961. * Returns the Vector4 squared length (float).
  2962. */
  2963. Vector4.prototype.lengthSquared = function () {
  2964. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2965. };
  2966. // Methods
  2967. /**
  2968. * Normalizes in place the Vector4.
  2969. * Returns the updated Vector4.
  2970. */
  2971. Vector4.prototype.normalize = function () {
  2972. var len = this.length();
  2973. if (len === 0)
  2974. return this;
  2975. var num = 1.0 / len;
  2976. this.x *= num;
  2977. this.y *= num;
  2978. this.z *= num;
  2979. this.w *= num;
  2980. return this;
  2981. };
  2982. /**
  2983. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2984. */
  2985. Vector4.prototype.toVector3 = function () {
  2986. return new Vector3(this.x, this.y, this.z);
  2987. };
  2988. /**
  2989. * Returns a new Vector4 copied from the current one.
  2990. */
  2991. Vector4.prototype.clone = function () {
  2992. return new Vector4(this.x, this.y, this.z, this.w);
  2993. };
  2994. /**
  2995. * Updates the current Vector4 with the passed one coordinates.
  2996. * Returns the updated Vector4.
  2997. */
  2998. Vector4.prototype.copyFrom = function (source) {
  2999. this.x = source.x;
  3000. this.y = source.y;
  3001. this.z = source.z;
  3002. this.w = source.w;
  3003. return this;
  3004. };
  3005. /**
  3006. * Updates the current Vector4 coordinates with the passed floats.
  3007. * Returns the updated Vector4.
  3008. */
  3009. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3010. this.x = x;
  3011. this.y = y;
  3012. this.z = z;
  3013. this.w = w;
  3014. return this;
  3015. };
  3016. /**
  3017. * Updates the current Vector4 coordinates with the passed floats.
  3018. * Returns the updated Vector4.
  3019. */
  3020. Vector4.prototype.set = function (x, y, z, w) {
  3021. return this.copyFromFloats(x, y, z, w);
  3022. };
  3023. // Statics
  3024. /**
  3025. * Returns a new Vector4 set from the starting index of the passed array.
  3026. */
  3027. Vector4.FromArray = function (array, offset) {
  3028. if (!offset) {
  3029. offset = 0;
  3030. }
  3031. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3032. };
  3033. /**
  3034. * Updates the passed vector "result" from the starting index of the passed array.
  3035. */
  3036. Vector4.FromArrayToRef = function (array, offset, result) {
  3037. result.x = array[offset];
  3038. result.y = array[offset + 1];
  3039. result.z = array[offset + 2];
  3040. result.w = array[offset + 3];
  3041. };
  3042. /**
  3043. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3044. */
  3045. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3046. Vector4.FromArrayToRef(array, offset, result);
  3047. };
  3048. /**
  3049. * Updates the passed vector "result" coordinates from the passed floats.
  3050. */
  3051. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3052. result.x = x;
  3053. result.y = y;
  3054. result.z = z;
  3055. result.w = w;
  3056. };
  3057. /**
  3058. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3059. */
  3060. Vector4.Zero = function () {
  3061. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3062. };
  3063. /**
  3064. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3065. */
  3066. Vector4.One = function () {
  3067. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3068. };
  3069. /**
  3070. * Returns a new normalized Vector4 from the passed one.
  3071. */
  3072. Vector4.Normalize = function (vector) {
  3073. var result = Vector4.Zero();
  3074. Vector4.NormalizeToRef(vector, result);
  3075. return result;
  3076. };
  3077. /**
  3078. * Updates the passed vector "result" from the normalization of the passed one.
  3079. */
  3080. Vector4.NormalizeToRef = function (vector, result) {
  3081. result.copyFrom(vector);
  3082. result.normalize();
  3083. };
  3084. Vector4.Minimize = function (left, right) {
  3085. var min = left.clone();
  3086. min.MinimizeInPlace(right);
  3087. return min;
  3088. };
  3089. Vector4.Maximize = function (left, right) {
  3090. var max = left.clone();
  3091. max.MaximizeInPlace(right);
  3092. return max;
  3093. };
  3094. /**
  3095. * Returns the distance (float) between the vectors "value1" and "value2".
  3096. */
  3097. Vector4.Distance = function (value1, value2) {
  3098. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3099. };
  3100. /**
  3101. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3102. */
  3103. Vector4.DistanceSquared = function (value1, value2) {
  3104. var x = value1.x - value2.x;
  3105. var y = value1.y - value2.y;
  3106. var z = value1.z - value2.z;
  3107. var w = value1.w - value2.w;
  3108. return (x * x) + (y * y) + (z * z) + (w * w);
  3109. };
  3110. /**
  3111. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3112. */
  3113. Vector4.Center = function (value1, value2) {
  3114. var center = value1.add(value2);
  3115. center.scaleInPlace(0.5);
  3116. return center;
  3117. };
  3118. /**
  3119. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3120. * This methods computes transformed normalized direction vectors only.
  3121. */
  3122. Vector4.TransformNormal = function (vector, transformation) {
  3123. var result = Vector4.Zero();
  3124. Vector4.TransformNormalToRef(vector, transformation, result);
  3125. return result;
  3126. };
  3127. /**
  3128. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3129. * This methods computes transformed normalized direction vectors only.
  3130. */
  3131. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3132. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3133. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3134. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3135. result.x = x;
  3136. result.y = y;
  3137. result.z = z;
  3138. result.w = vector.w;
  3139. };
  3140. /**
  3141. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3142. * This methods computes transformed normalized direction vectors only.
  3143. */
  3144. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3145. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3146. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3147. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3148. result.w = w;
  3149. };
  3150. return Vector4;
  3151. }());
  3152. BABYLON.Vector4 = Vector4;
  3153. var Size = /** @class */ (function () {
  3154. /**
  3155. * Creates a Size object from the passed width and height (floats).
  3156. */
  3157. function Size(width, height) {
  3158. this.width = width;
  3159. this.height = height;
  3160. }
  3161. // Returns a string with the Size width and height.
  3162. Size.prototype.toString = function () {
  3163. return "{W: " + this.width + ", H: " + this.height + "}";
  3164. };
  3165. /**
  3166. * Returns the string "Size"
  3167. */
  3168. Size.prototype.getClassName = function () {
  3169. return "Size";
  3170. };
  3171. /**
  3172. * Returns the Size hash code.
  3173. */
  3174. Size.prototype.getHashCode = function () {
  3175. var hash = this.width || 0;
  3176. hash = (hash * 397) ^ (this.height || 0);
  3177. return hash;
  3178. };
  3179. /**
  3180. * Updates the current size from the passed one.
  3181. * Returns the updated Size.
  3182. */
  3183. Size.prototype.copyFrom = function (src) {
  3184. this.width = src.width;
  3185. this.height = src.height;
  3186. };
  3187. /**
  3188. * Updates in place the current Size from the passed floats.
  3189. * Returns the updated Size.
  3190. */
  3191. Size.prototype.copyFromFloats = function (width, height) {
  3192. this.width = width;
  3193. this.height = height;
  3194. return this;
  3195. };
  3196. /**
  3197. * Updates in place the current Size from the passed floats.
  3198. * Returns the updated Size.
  3199. */
  3200. Size.prototype.set = function (width, height) {
  3201. return this.copyFromFloats(width, height);
  3202. };
  3203. /**
  3204. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3205. */
  3206. Size.prototype.multiplyByFloats = function (w, h) {
  3207. return new Size(this.width * w, this.height * h);
  3208. };
  3209. /**
  3210. * Returns a new Size copied from the passed one.
  3211. */
  3212. Size.prototype.clone = function () {
  3213. return new Size(this.width, this.height);
  3214. };
  3215. /**
  3216. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3217. */
  3218. Size.prototype.equals = function (other) {
  3219. if (!other) {
  3220. return false;
  3221. }
  3222. return (this.width === other.width) && (this.height === other.height);
  3223. };
  3224. Object.defineProperty(Size.prototype, "surface", {
  3225. /**
  3226. * Returns the surface of the Size : width * height (float).
  3227. */
  3228. get: function () {
  3229. return this.width * this.height;
  3230. },
  3231. enumerable: true,
  3232. configurable: true
  3233. });
  3234. /**
  3235. * Returns a new Size set to (0.0, 0.0)
  3236. */
  3237. Size.Zero = function () {
  3238. return new Size(0.0, 0.0);
  3239. };
  3240. /**
  3241. * Returns a new Size set as the addition result of the current Size and the passed one.
  3242. */
  3243. Size.prototype.add = function (otherSize) {
  3244. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3245. return r;
  3246. };
  3247. /**
  3248. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3249. */
  3250. Size.prototype.subtract = function (otherSize) {
  3251. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3252. return r;
  3253. };
  3254. /**
  3255. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3256. */
  3257. Size.Lerp = function (start, end, amount) {
  3258. var w = start.width + ((end.width - start.width) * amount);
  3259. var h = start.height + ((end.height - start.height) * amount);
  3260. return new Size(w, h);
  3261. };
  3262. return Size;
  3263. }());
  3264. BABYLON.Size = Size;
  3265. var Quaternion = /** @class */ (function () {
  3266. /**
  3267. * Creates a new Quaternion from the passed floats.
  3268. */
  3269. function Quaternion(x, y, z, w) {
  3270. if (x === void 0) { x = 0.0; }
  3271. if (y === void 0) { y = 0.0; }
  3272. if (z === void 0) { z = 0.0; }
  3273. if (w === void 0) { w = 1.0; }
  3274. this.x = x;
  3275. this.y = y;
  3276. this.z = z;
  3277. this.w = w;
  3278. }
  3279. /**
  3280. * Returns a string with the Quaternion coordinates.
  3281. */
  3282. Quaternion.prototype.toString = function () {
  3283. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3284. };
  3285. /**
  3286. * Returns the string "Quaternion".
  3287. */
  3288. Quaternion.prototype.getClassName = function () {
  3289. return "Quaternion";
  3290. };
  3291. /**
  3292. * Returns the Quaternion hash code.
  3293. */
  3294. Quaternion.prototype.getHashCode = function () {
  3295. var hash = this.x || 0;
  3296. hash = (hash * 397) ^ (this.y || 0);
  3297. hash = (hash * 397) ^ (this.z || 0);
  3298. hash = (hash * 397) ^ (this.w || 0);
  3299. return hash;
  3300. };
  3301. /**
  3302. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3303. */
  3304. Quaternion.prototype.asArray = function () {
  3305. return [this.x, this.y, this.z, this.w];
  3306. };
  3307. /**
  3308. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3309. */
  3310. Quaternion.prototype.equals = function (otherQuaternion) {
  3311. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3312. };
  3313. /**
  3314. * Returns a new Quaternion copied from the current one.
  3315. */
  3316. Quaternion.prototype.clone = function () {
  3317. return new Quaternion(this.x, this.y, this.z, this.w);
  3318. };
  3319. /**
  3320. * Updates the current Quaternion from the passed one coordinates.
  3321. * Returns the updated Quaterion.
  3322. */
  3323. Quaternion.prototype.copyFrom = function (other) {
  3324. this.x = other.x;
  3325. this.y = other.y;
  3326. this.z = other.z;
  3327. this.w = other.w;
  3328. return this;
  3329. };
  3330. /**
  3331. * Updates the current Quaternion from the passed float coordinates.
  3332. * Returns the updated Quaterion.
  3333. */
  3334. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3335. this.x = x;
  3336. this.y = y;
  3337. this.z = z;
  3338. this.w = w;
  3339. return this;
  3340. };
  3341. /**
  3342. * Updates the current Quaternion from the passed float coordinates.
  3343. * Returns the updated Quaterion.
  3344. */
  3345. Quaternion.prototype.set = function (x, y, z, w) {
  3346. return this.copyFromFloats(x, y, z, w);
  3347. };
  3348. /**
  3349. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3350. */
  3351. Quaternion.prototype.add = function (other) {
  3352. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3353. };
  3354. /**
  3355. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3356. */
  3357. Quaternion.prototype.subtract = function (other) {
  3358. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3359. };
  3360. /**
  3361. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3362. */
  3363. Quaternion.prototype.scale = function (value) {
  3364. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3365. };
  3366. /**
  3367. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3368. */
  3369. Quaternion.prototype.multiply = function (q1) {
  3370. var result = new Quaternion(0, 0, 0, 1.0);
  3371. this.multiplyToRef(q1, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3376. * Returns the current Quaternion.
  3377. */
  3378. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3379. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3380. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3381. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3382. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3383. result.copyFromFloats(x, y, z, w);
  3384. return this;
  3385. };
  3386. /**
  3387. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3388. * Returns the updated Quaternion.
  3389. */
  3390. Quaternion.prototype.multiplyInPlace = function (q1) {
  3391. this.multiplyToRef(q1, this);
  3392. return this;
  3393. };
  3394. /**
  3395. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3396. * Returns the current Quaternion.
  3397. */
  3398. Quaternion.prototype.conjugateToRef = function (ref) {
  3399. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3400. return this;
  3401. };
  3402. /**
  3403. * Conjugates in place the current Quaternion.
  3404. * Returns the updated Quaternion.
  3405. */
  3406. Quaternion.prototype.conjugateInPlace = function () {
  3407. this.x *= -1;
  3408. this.y *= -1;
  3409. this.z *= -1;
  3410. return this;
  3411. };
  3412. /**
  3413. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3414. */
  3415. Quaternion.prototype.conjugate = function () {
  3416. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3417. return result;
  3418. };
  3419. /**
  3420. * Returns the Quaternion length (float).
  3421. */
  3422. Quaternion.prototype.length = function () {
  3423. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3424. };
  3425. /**
  3426. * Normalize in place the current Quaternion.
  3427. * Returns the updated Quaternion.
  3428. */
  3429. Quaternion.prototype.normalize = function () {
  3430. var length = 1.0 / this.length();
  3431. this.x *= length;
  3432. this.y *= length;
  3433. this.z *= length;
  3434. this.w *= length;
  3435. return this;
  3436. };
  3437. /**
  3438. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3439. */
  3440. Quaternion.prototype.toEulerAngles = function (order) {
  3441. if (order === void 0) { order = "YZX"; }
  3442. var result = Vector3.Zero();
  3443. this.toEulerAnglesToRef(result, order);
  3444. return result;
  3445. };
  3446. /**
  3447. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3448. * Returns the current Quaternion.
  3449. */
  3450. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3451. if (order === void 0) { order = "YZX"; }
  3452. var qz = this.z;
  3453. var qx = this.x;
  3454. var qy = this.y;
  3455. var qw = this.w;
  3456. var sqw = qw * qw;
  3457. var sqz = qz * qz;
  3458. var sqx = qx * qx;
  3459. var sqy = qy * qy;
  3460. var zAxisY = qy * qz - qx * qw;
  3461. var limit = .4999999;
  3462. if (zAxisY < -limit) {
  3463. result.y = 2 * Math.atan2(qy, qw);
  3464. result.x = Math.PI / 2;
  3465. result.z = 0;
  3466. }
  3467. else if (zAxisY > limit) {
  3468. result.y = 2 * Math.atan2(qy, qw);
  3469. result.x = -Math.PI / 2;
  3470. result.z = 0;
  3471. }
  3472. else {
  3473. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3474. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3475. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3476. }
  3477. return this;
  3478. };
  3479. /**
  3480. * Updates the passed rotation matrix with the current Quaternion values.
  3481. * Returns the current Quaternion.
  3482. */
  3483. Quaternion.prototype.toRotationMatrix = function (result) {
  3484. var xx = this.x * this.x;
  3485. var yy = this.y * this.y;
  3486. var zz = this.z * this.z;
  3487. var xy = this.x * this.y;
  3488. var zw = this.z * this.w;
  3489. var zx = this.z * this.x;
  3490. var yw = this.y * this.w;
  3491. var yz = this.y * this.z;
  3492. var xw = this.x * this.w;
  3493. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3494. result.m[1] = 2.0 * (xy + zw);
  3495. result.m[2] = 2.0 * (zx - yw);
  3496. result.m[3] = 0;
  3497. result.m[4] = 2.0 * (xy - zw);
  3498. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3499. result.m[6] = 2.0 * (yz + xw);
  3500. result.m[7] = 0;
  3501. result.m[8] = 2.0 * (zx + yw);
  3502. result.m[9] = 2.0 * (yz - xw);
  3503. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3504. result.m[11] = 0;
  3505. result.m[12] = 0;
  3506. result.m[13] = 0;
  3507. result.m[14] = 0;
  3508. result.m[15] = 1.0;
  3509. result._markAsUpdated();
  3510. return this;
  3511. };
  3512. /**
  3513. * Updates the current Quaternion from the passed rotation matrix values.
  3514. * Returns the updated Quaternion.
  3515. */
  3516. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3517. Quaternion.FromRotationMatrixToRef(matrix, this);
  3518. return this;
  3519. };
  3520. // Statics
  3521. /**
  3522. * Returns a new Quaternion set from the passed rotation matrix values.
  3523. */
  3524. Quaternion.FromRotationMatrix = function (matrix) {
  3525. var result = new Quaternion();
  3526. Quaternion.FromRotationMatrixToRef(matrix, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3531. */
  3532. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3533. var data = matrix.m;
  3534. var m11 = data[0], m12 = data[4], m13 = data[8];
  3535. var m21 = data[1], m22 = data[5], m23 = data[9];
  3536. var m31 = data[2], m32 = data[6], m33 = data[10];
  3537. var trace = m11 + m22 + m33;
  3538. var s;
  3539. if (trace > 0) {
  3540. s = 0.5 / Math.sqrt(trace + 1.0);
  3541. result.w = 0.25 / s;
  3542. result.x = (m32 - m23) * s;
  3543. result.y = (m13 - m31) * s;
  3544. result.z = (m21 - m12) * s;
  3545. }
  3546. else if (m11 > m22 && m11 > m33) {
  3547. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3548. result.w = (m32 - m23) / s;
  3549. result.x = 0.25 * s;
  3550. result.y = (m12 + m21) / s;
  3551. result.z = (m13 + m31) / s;
  3552. }
  3553. else if (m22 > m33) {
  3554. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3555. result.w = (m13 - m31) / s;
  3556. result.x = (m12 + m21) / s;
  3557. result.y = 0.25 * s;
  3558. result.z = (m23 + m32) / s;
  3559. }
  3560. else {
  3561. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3562. result.w = (m21 - m12) / s;
  3563. result.x = (m13 + m31) / s;
  3564. result.y = (m23 + m32) / s;
  3565. result.z = 0.25 * s;
  3566. }
  3567. };
  3568. /**
  3569. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3570. */
  3571. Quaternion.Zero = function () {
  3572. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3573. };
  3574. /**
  3575. * Returns a new Quaternion as the inverted current Quaternion.
  3576. */
  3577. Quaternion.Inverse = function (q) {
  3578. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3579. };
  3580. /**
  3581. * Returns the identity Quaternion.
  3582. */
  3583. Quaternion.Identity = function () {
  3584. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3585. };
  3586. Quaternion.IsIdentity = function (quaternion) {
  3587. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3588. };
  3589. /**
  3590. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3591. */
  3592. Quaternion.RotationAxis = function (axis, angle) {
  3593. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3594. };
  3595. /**
  3596. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3597. */
  3598. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3599. var sin = Math.sin(angle / 2);
  3600. axis.normalize();
  3601. result.w = Math.cos(angle / 2);
  3602. result.x = axis.x * sin;
  3603. result.y = axis.y * sin;
  3604. result.z = axis.z * sin;
  3605. return result;
  3606. };
  3607. /**
  3608. * Retuns a new Quaternion set from the starting index of the passed array.
  3609. */
  3610. Quaternion.FromArray = function (array, offset) {
  3611. if (!offset) {
  3612. offset = 0;
  3613. }
  3614. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3615. };
  3616. /**
  3617. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3618. */
  3619. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3620. var q = new Quaternion();
  3621. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3622. return q;
  3623. };
  3624. /**
  3625. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3626. */
  3627. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3628. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3629. var halfRoll = roll * 0.5;
  3630. var halfPitch = pitch * 0.5;
  3631. var halfYaw = yaw * 0.5;
  3632. var sinRoll = Math.sin(halfRoll);
  3633. var cosRoll = Math.cos(halfRoll);
  3634. var sinPitch = Math.sin(halfPitch);
  3635. var cosPitch = Math.cos(halfPitch);
  3636. var sinYaw = Math.sin(halfYaw);
  3637. var cosYaw = Math.cos(halfYaw);
  3638. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3639. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3640. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3641. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3642. };
  3643. /**
  3644. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3645. */
  3646. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3647. var result = new Quaternion();
  3648. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3649. return result;
  3650. };
  3651. /**
  3652. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3653. */
  3654. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3655. // Produces a quaternion from Euler angles in the z-x-z orientation
  3656. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3657. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3658. var halfBeta = beta * 0.5;
  3659. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3660. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3661. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3662. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3663. };
  3664. /**
  3665. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3666. * cf to Vector3.RotationFromAxis() documentation.
  3667. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3668. */
  3669. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3670. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3671. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3672. return quat;
  3673. };
  3674. /**
  3675. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3676. * cf to Vector3.RotationFromAxis() documentation.
  3677. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3678. */
  3679. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3680. var rotMat = MathTmp.Matrix[0];
  3681. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3682. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3683. };
  3684. Quaternion.Slerp = function (left, right, amount) {
  3685. var result = Quaternion.Identity();
  3686. Quaternion.SlerpToRef(left, right, amount, result);
  3687. return result;
  3688. };
  3689. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3690. var num2;
  3691. var num3;
  3692. var num = amount;
  3693. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3694. var flag = false;
  3695. if (num4 < 0) {
  3696. flag = true;
  3697. num4 = -num4;
  3698. }
  3699. if (num4 > 0.999999) {
  3700. num3 = 1 - num;
  3701. num2 = flag ? -num : num;
  3702. }
  3703. else {
  3704. var num5 = Math.acos(num4);
  3705. var num6 = (1.0 / Math.sin(num5));
  3706. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3707. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3708. }
  3709. result.x = (num3 * left.x) + (num2 * right.x);
  3710. result.y = (num3 * left.y) + (num2 * right.y);
  3711. result.z = (num3 * left.z) + (num2 * right.z);
  3712. result.w = (num3 * left.w) + (num2 * right.w);
  3713. };
  3714. /**
  3715. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3716. */
  3717. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3718. var squared = amount * amount;
  3719. var cubed = amount * squared;
  3720. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3721. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3722. var part3 = (cubed - (2.0 * squared)) + amount;
  3723. var part4 = cubed - squared;
  3724. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3725. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3726. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3727. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3728. return new Quaternion(x, y, z, w);
  3729. };
  3730. return Quaternion;
  3731. }());
  3732. BABYLON.Quaternion = Quaternion;
  3733. var Matrix = /** @class */ (function () {
  3734. function Matrix() {
  3735. this._isIdentity = false;
  3736. this._isIdentityDirty = true;
  3737. this.m = new Float32Array(16);
  3738. this._markAsUpdated();
  3739. }
  3740. Matrix.prototype._markAsUpdated = function () {
  3741. this.updateFlag = Matrix._updateFlagSeed++;
  3742. this._isIdentityDirty = true;
  3743. };
  3744. // Properties
  3745. /**
  3746. * Boolean : True is the matrix is the identity matrix
  3747. */
  3748. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3749. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3750. if (this._isIdentityDirty) {
  3751. this._isIdentityDirty = false;
  3752. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3753. this._isIdentity = false;
  3754. }
  3755. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3756. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3757. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3758. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3759. this._isIdentity = false;
  3760. }
  3761. else {
  3762. this._isIdentity = true;
  3763. }
  3764. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3765. this._isIdentity = false;
  3766. }
  3767. }
  3768. return this._isIdentity;
  3769. };
  3770. /**
  3771. * Returns the matrix determinant (float).
  3772. */
  3773. Matrix.prototype.determinant = function () {
  3774. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3775. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3776. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3777. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3778. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3779. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3780. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3781. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3782. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3783. };
  3784. // Methods
  3785. /**
  3786. * Returns the matrix underlying array.
  3787. */
  3788. Matrix.prototype.toArray = function () {
  3789. return this.m;
  3790. };
  3791. /**
  3792. * Returns the matrix underlying array.
  3793. */
  3794. Matrix.prototype.asArray = function () {
  3795. return this.toArray();
  3796. };
  3797. /**
  3798. * Inverts in place the Matrix.
  3799. * Returns the Matrix inverted.
  3800. */
  3801. Matrix.prototype.invert = function () {
  3802. this.invertToRef(this);
  3803. return this;
  3804. };
  3805. /**
  3806. * Sets all the matrix elements to zero.
  3807. * Returns the Matrix.
  3808. */
  3809. Matrix.prototype.reset = function () {
  3810. for (var index = 0; index < 16; index++) {
  3811. this.m[index] = 0.0;
  3812. }
  3813. this._markAsUpdated();
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3818. */
  3819. Matrix.prototype.add = function (other) {
  3820. var result = new Matrix();
  3821. this.addToRef(other, result);
  3822. return result;
  3823. };
  3824. /**
  3825. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3826. * Returns the Matrix.
  3827. */
  3828. Matrix.prototype.addToRef = function (other, result) {
  3829. for (var index = 0; index < 16; index++) {
  3830. result.m[index] = this.m[index] + other.m[index];
  3831. }
  3832. result._markAsUpdated();
  3833. return this;
  3834. };
  3835. /**
  3836. * Adds in place the passed matrix to the current Matrix.
  3837. * Returns the updated Matrix.
  3838. */
  3839. Matrix.prototype.addToSelf = function (other) {
  3840. for (var index = 0; index < 16; index++) {
  3841. this.m[index] += other.m[index];
  3842. }
  3843. this._markAsUpdated();
  3844. return this;
  3845. };
  3846. /**
  3847. * Sets the passed matrix with the current inverted Matrix.
  3848. * Returns the unmodified current Matrix.
  3849. */
  3850. Matrix.prototype.invertToRef = function (other) {
  3851. var l1 = this.m[0];
  3852. var l2 = this.m[1];
  3853. var l3 = this.m[2];
  3854. var l4 = this.m[3];
  3855. var l5 = this.m[4];
  3856. var l6 = this.m[5];
  3857. var l7 = this.m[6];
  3858. var l8 = this.m[7];
  3859. var l9 = this.m[8];
  3860. var l10 = this.m[9];
  3861. var l11 = this.m[10];
  3862. var l12 = this.m[11];
  3863. var l13 = this.m[12];
  3864. var l14 = this.m[13];
  3865. var l15 = this.m[14];
  3866. var l16 = this.m[15];
  3867. var l17 = (l11 * l16) - (l12 * l15);
  3868. var l18 = (l10 * l16) - (l12 * l14);
  3869. var l19 = (l10 * l15) - (l11 * l14);
  3870. var l20 = (l9 * l16) - (l12 * l13);
  3871. var l21 = (l9 * l15) - (l11 * l13);
  3872. var l22 = (l9 * l14) - (l10 * l13);
  3873. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3874. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3875. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3876. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3877. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3878. var l28 = (l7 * l16) - (l8 * l15);
  3879. var l29 = (l6 * l16) - (l8 * l14);
  3880. var l30 = (l6 * l15) - (l7 * l14);
  3881. var l31 = (l5 * l16) - (l8 * l13);
  3882. var l32 = (l5 * l15) - (l7 * l13);
  3883. var l33 = (l5 * l14) - (l6 * l13);
  3884. var l34 = (l7 * l12) - (l8 * l11);
  3885. var l35 = (l6 * l12) - (l8 * l10);
  3886. var l36 = (l6 * l11) - (l7 * l10);
  3887. var l37 = (l5 * l12) - (l8 * l9);
  3888. var l38 = (l5 * l11) - (l7 * l9);
  3889. var l39 = (l5 * l10) - (l6 * l9);
  3890. other.m[0] = l23 * l27;
  3891. other.m[4] = l24 * l27;
  3892. other.m[8] = l25 * l27;
  3893. other.m[12] = l26 * l27;
  3894. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3895. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3896. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3897. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3898. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3899. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3900. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3901. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3902. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3903. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3904. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3905. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3906. other._markAsUpdated();
  3907. return this;
  3908. };
  3909. /**
  3910. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3911. * Returns the updated Matrix.
  3912. */
  3913. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3914. this.m[12] = x;
  3915. this.m[13] = y;
  3916. this.m[14] = z;
  3917. this._markAsUpdated();
  3918. return this;
  3919. };
  3920. /**
  3921. * Inserts the translation vector in the current Matrix.
  3922. * Returns the updated Matrix.
  3923. */
  3924. Matrix.prototype.setTranslation = function (vector3) {
  3925. this.m[12] = vector3.x;
  3926. this.m[13] = vector3.y;
  3927. this.m[14] = vector3.z;
  3928. this._markAsUpdated();
  3929. return this;
  3930. };
  3931. /**
  3932. * Returns a new Vector3 as the extracted translation from the Matrix.
  3933. */
  3934. Matrix.prototype.getTranslation = function () {
  3935. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3936. };
  3937. /**
  3938. * Fill a Vector3 with the extracted translation from the Matrix.
  3939. */
  3940. Matrix.prototype.getTranslationToRef = function (result) {
  3941. result.x = this.m[12];
  3942. result.y = this.m[13];
  3943. result.z = this.m[14];
  3944. return this;
  3945. };
  3946. /**
  3947. * Remove rotation and scaling part from the Matrix.
  3948. * Returns the updated Matrix.
  3949. */
  3950. Matrix.prototype.removeRotationAndScaling = function () {
  3951. this.setRowFromFloats(0, 1, 0, 0, 0);
  3952. this.setRowFromFloats(1, 0, 1, 0, 0);
  3953. this.setRowFromFloats(2, 0, 0, 1, 0);
  3954. return this;
  3955. };
  3956. /**
  3957. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3958. */
  3959. Matrix.prototype.multiply = function (other) {
  3960. var result = new Matrix();
  3961. this.multiplyToRef(other, result);
  3962. return result;
  3963. };
  3964. /**
  3965. * Updates the current Matrix from the passed one values.
  3966. * Returns the updated Matrix.
  3967. */
  3968. Matrix.prototype.copyFrom = function (other) {
  3969. for (var index = 0; index < 16; index++) {
  3970. this.m[index] = other.m[index];
  3971. }
  3972. this._markAsUpdated();
  3973. return this;
  3974. };
  3975. /**
  3976. * Populates the passed array from the starting index with the Matrix values.
  3977. * Returns the Matrix.
  3978. */
  3979. Matrix.prototype.copyToArray = function (array, offset) {
  3980. if (offset === void 0) { offset = 0; }
  3981. for (var index = 0; index < 16; index++) {
  3982. array[offset + index] = this.m[index];
  3983. }
  3984. return this;
  3985. };
  3986. /**
  3987. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3988. */
  3989. Matrix.prototype.multiplyToRef = function (other, result) {
  3990. this.multiplyToArray(other, result.m, 0);
  3991. result._markAsUpdated();
  3992. return this;
  3993. };
  3994. /**
  3995. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3996. */
  3997. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3998. var tm0 = this.m[0];
  3999. var tm1 = this.m[1];
  4000. var tm2 = this.m[2];
  4001. var tm3 = this.m[3];
  4002. var tm4 = this.m[4];
  4003. var tm5 = this.m[5];
  4004. var tm6 = this.m[6];
  4005. var tm7 = this.m[7];
  4006. var tm8 = this.m[8];
  4007. var tm9 = this.m[9];
  4008. var tm10 = this.m[10];
  4009. var tm11 = this.m[11];
  4010. var tm12 = this.m[12];
  4011. var tm13 = this.m[13];
  4012. var tm14 = this.m[14];
  4013. var tm15 = this.m[15];
  4014. var om0 = other.m[0];
  4015. var om1 = other.m[1];
  4016. var om2 = other.m[2];
  4017. var om3 = other.m[3];
  4018. var om4 = other.m[4];
  4019. var om5 = other.m[5];
  4020. var om6 = other.m[6];
  4021. var om7 = other.m[7];
  4022. var om8 = other.m[8];
  4023. var om9 = other.m[9];
  4024. var om10 = other.m[10];
  4025. var om11 = other.m[11];
  4026. var om12 = other.m[12];
  4027. var om13 = other.m[13];
  4028. var om14 = other.m[14];
  4029. var om15 = other.m[15];
  4030. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4031. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4032. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4033. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4034. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4035. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4036. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4037. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4038. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4039. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4040. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4041. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4042. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4043. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4044. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4045. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4046. return this;
  4047. };
  4048. /**
  4049. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4050. */
  4051. Matrix.prototype.equals = function (value) {
  4052. return value &&
  4053. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4054. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4055. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4056. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4057. };
  4058. /**
  4059. * Returns a new Matrix from the current Matrix.
  4060. */
  4061. Matrix.prototype.clone = function () {
  4062. 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]);
  4063. };
  4064. /**
  4065. * Returns the string "Matrix"
  4066. */
  4067. Matrix.prototype.getClassName = function () {
  4068. return "Matrix";
  4069. };
  4070. /**
  4071. * Returns the Matrix hash code.
  4072. */
  4073. Matrix.prototype.getHashCode = function () {
  4074. var hash = this.m[0] || 0;
  4075. for (var i = 1; i < 16; i++) {
  4076. hash = (hash * 397) ^ (this.m[i] || 0);
  4077. }
  4078. return hash;
  4079. };
  4080. /**
  4081. * Decomposes the current Matrix into :
  4082. * - a scale vector3 passed as a reference to update,
  4083. * - a rotation quaternion passed as a reference to update,
  4084. * - a translation vector3 passed as a reference to update.
  4085. * Returns the boolean `true`.
  4086. */
  4087. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4088. translation.x = this.m[12];
  4089. translation.y = this.m[13];
  4090. translation.z = this.m[14];
  4091. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4092. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4093. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4094. if (this.determinant() <= 0) {
  4095. scale.y *= -1;
  4096. }
  4097. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4098. rotation.x = 0;
  4099. rotation.y = 0;
  4100. rotation.z = 0;
  4101. rotation.w = 1;
  4102. return false;
  4103. }
  4104. 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]);
  4105. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4106. return true;
  4107. };
  4108. /**
  4109. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4110. */
  4111. Matrix.prototype.getRotationMatrix = function () {
  4112. var result = Matrix.Identity();
  4113. this.getRotationMatrixToRef(result);
  4114. return result;
  4115. };
  4116. /**
  4117. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4118. * Returns the current Matrix.
  4119. */
  4120. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4121. var m = this.m;
  4122. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4123. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4124. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4125. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4126. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4127. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4128. 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);
  4129. return this;
  4130. };
  4131. // Statics
  4132. /**
  4133. * Returns a new Matrix set from the starting index of the passed array.
  4134. */
  4135. Matrix.FromArray = function (array, offset) {
  4136. var result = new Matrix();
  4137. if (!offset) {
  4138. offset = 0;
  4139. }
  4140. Matrix.FromArrayToRef(array, offset, result);
  4141. return result;
  4142. };
  4143. /**
  4144. * Sets the passed "result" matrix from the starting index of the passed array.
  4145. */
  4146. Matrix.FromArrayToRef = function (array, offset, result) {
  4147. for (var index = 0; index < 16; index++) {
  4148. result.m[index] = array[index + offset];
  4149. }
  4150. result._markAsUpdated();
  4151. };
  4152. /**
  4153. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4154. */
  4155. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4156. for (var index = 0; index < 16; index++) {
  4157. result.m[index] = array[index + offset] * scale;
  4158. }
  4159. result._markAsUpdated();
  4160. };
  4161. /**
  4162. * Sets the passed matrix "result" with the 16 passed floats.
  4163. */
  4164. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4165. result.m[0] = initialM11;
  4166. result.m[1] = initialM12;
  4167. result.m[2] = initialM13;
  4168. result.m[3] = initialM14;
  4169. result.m[4] = initialM21;
  4170. result.m[5] = initialM22;
  4171. result.m[6] = initialM23;
  4172. result.m[7] = initialM24;
  4173. result.m[8] = initialM31;
  4174. result.m[9] = initialM32;
  4175. result.m[10] = initialM33;
  4176. result.m[11] = initialM34;
  4177. result.m[12] = initialM41;
  4178. result.m[13] = initialM42;
  4179. result.m[14] = initialM43;
  4180. result.m[15] = initialM44;
  4181. result._markAsUpdated();
  4182. };
  4183. /**
  4184. * Returns the index-th row of the current matrix as a new Vector4.
  4185. */
  4186. Matrix.prototype.getRow = function (index) {
  4187. if (index < 0 || index > 3) {
  4188. return null;
  4189. }
  4190. var i = index * 4;
  4191. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4192. };
  4193. /**
  4194. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4195. * Returns the updated Matrix.
  4196. */
  4197. Matrix.prototype.setRow = function (index, row) {
  4198. if (index < 0 || index > 3) {
  4199. return this;
  4200. }
  4201. var i = index * 4;
  4202. this.m[i + 0] = row.x;
  4203. this.m[i + 1] = row.y;
  4204. this.m[i + 2] = row.z;
  4205. this.m[i + 3] = row.w;
  4206. this._markAsUpdated();
  4207. return this;
  4208. };
  4209. /**
  4210. * Compute the transpose of the matrix.
  4211. * Returns a new Matrix.
  4212. */
  4213. Matrix.prototype.transpose = function () {
  4214. return Matrix.Transpose(this);
  4215. };
  4216. /**
  4217. * Compute the transpose of the matrix.
  4218. * Returns the current matrix.
  4219. */
  4220. Matrix.prototype.transposeToRef = function (result) {
  4221. Matrix.TransposeToRef(this, result);
  4222. return this;
  4223. };
  4224. /**
  4225. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4226. * Returns the updated Matrix.
  4227. */
  4228. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4229. if (index < 0 || index > 3) {
  4230. return this;
  4231. }
  4232. var i = index * 4;
  4233. this.m[i + 0] = x;
  4234. this.m[i + 1] = y;
  4235. this.m[i + 2] = z;
  4236. this.m[i + 3] = w;
  4237. this._markAsUpdated();
  4238. return this;
  4239. };
  4240. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4241. /**
  4242. * Static identity matrix to be used as readonly matrix
  4243. * Must not be updated.
  4244. */
  4245. get: function () {
  4246. return Matrix._identityReadOnly;
  4247. },
  4248. enumerable: true,
  4249. configurable: true
  4250. });
  4251. /**
  4252. * Returns a new Matrix set from the 16 passed floats.
  4253. */
  4254. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4255. var result = new Matrix();
  4256. result.m[0] = initialM11;
  4257. result.m[1] = initialM12;
  4258. result.m[2] = initialM13;
  4259. result.m[3] = initialM14;
  4260. result.m[4] = initialM21;
  4261. result.m[5] = initialM22;
  4262. result.m[6] = initialM23;
  4263. result.m[7] = initialM24;
  4264. result.m[8] = initialM31;
  4265. result.m[9] = initialM32;
  4266. result.m[10] = initialM33;
  4267. result.m[11] = initialM34;
  4268. result.m[12] = initialM41;
  4269. result.m[13] = initialM42;
  4270. result.m[14] = initialM43;
  4271. result.m[15] = initialM44;
  4272. return result;
  4273. };
  4274. /**
  4275. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4276. */
  4277. Matrix.Compose = function (scale, rotation, translation) {
  4278. var result = Matrix.Identity();
  4279. Matrix.ComposeToRef(scale, rotation, translation, result);
  4280. return result;
  4281. };
  4282. /**
  4283. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4284. */
  4285. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4286. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4287. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4288. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4289. result.setTranslation(translation);
  4290. };
  4291. /**
  4292. * Returns a new indentity Matrix.
  4293. */
  4294. Matrix.Identity = function () {
  4295. 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);
  4296. };
  4297. /**
  4298. * Sets the passed "result" as an identity matrix.
  4299. */
  4300. Matrix.IdentityToRef = function (result) {
  4301. 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);
  4302. };
  4303. /**
  4304. * Returns a new zero Matrix.
  4305. */
  4306. Matrix.Zero = function () {
  4307. 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);
  4308. };
  4309. /**
  4310. * Returns a new rotation matrix for "angle" radians around the X axis.
  4311. */
  4312. Matrix.RotationX = function (angle) {
  4313. var result = new Matrix();
  4314. Matrix.RotationXToRef(angle, result);
  4315. return result;
  4316. };
  4317. /**
  4318. * Returns a new Matrix as the passed inverted one.
  4319. */
  4320. Matrix.Invert = function (source) {
  4321. var result = new Matrix();
  4322. source.invertToRef(result);
  4323. return result;
  4324. };
  4325. /**
  4326. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4327. */
  4328. Matrix.RotationXToRef = function (angle, result) {
  4329. var s = Math.sin(angle);
  4330. var c = Math.cos(angle);
  4331. result.m[0] = 1.0;
  4332. result.m[15] = 1.0;
  4333. result.m[5] = c;
  4334. result.m[10] = c;
  4335. result.m[9] = -s;
  4336. result.m[6] = s;
  4337. result.m[1] = 0.0;
  4338. result.m[2] = 0.0;
  4339. result.m[3] = 0.0;
  4340. result.m[4] = 0.0;
  4341. result.m[7] = 0.0;
  4342. result.m[8] = 0.0;
  4343. result.m[11] = 0.0;
  4344. result.m[12] = 0.0;
  4345. result.m[13] = 0.0;
  4346. result.m[14] = 0.0;
  4347. result._markAsUpdated();
  4348. };
  4349. /**
  4350. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4351. */
  4352. Matrix.RotationY = function (angle) {
  4353. var result = new Matrix();
  4354. Matrix.RotationYToRef(angle, result);
  4355. return result;
  4356. };
  4357. /**
  4358. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4359. */
  4360. Matrix.RotationYToRef = function (angle, result) {
  4361. var s = Math.sin(angle);
  4362. var c = Math.cos(angle);
  4363. result.m[5] = 1.0;
  4364. result.m[15] = 1.0;
  4365. result.m[0] = c;
  4366. result.m[2] = -s;
  4367. result.m[8] = s;
  4368. result.m[10] = c;
  4369. result.m[1] = 0.0;
  4370. result.m[3] = 0.0;
  4371. result.m[4] = 0.0;
  4372. result.m[6] = 0.0;
  4373. result.m[7] = 0.0;
  4374. result.m[9] = 0.0;
  4375. result.m[11] = 0.0;
  4376. result.m[12] = 0.0;
  4377. result.m[13] = 0.0;
  4378. result.m[14] = 0.0;
  4379. result._markAsUpdated();
  4380. };
  4381. /**
  4382. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4383. */
  4384. Matrix.RotationZ = function (angle) {
  4385. var result = new Matrix();
  4386. Matrix.RotationZToRef(angle, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4391. */
  4392. Matrix.RotationZToRef = function (angle, result) {
  4393. var s = Math.sin(angle);
  4394. var c = Math.cos(angle);
  4395. result.m[10] = 1.0;
  4396. result.m[15] = 1.0;
  4397. result.m[0] = c;
  4398. result.m[1] = s;
  4399. result.m[4] = -s;
  4400. result.m[5] = c;
  4401. result.m[2] = 0.0;
  4402. result.m[3] = 0.0;
  4403. result.m[6] = 0.0;
  4404. result.m[7] = 0.0;
  4405. result.m[8] = 0.0;
  4406. result.m[9] = 0.0;
  4407. result.m[11] = 0.0;
  4408. result.m[12] = 0.0;
  4409. result.m[13] = 0.0;
  4410. result.m[14] = 0.0;
  4411. result._markAsUpdated();
  4412. };
  4413. /**
  4414. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4415. */
  4416. Matrix.RotationAxis = function (axis, angle) {
  4417. var result = Matrix.Zero();
  4418. Matrix.RotationAxisToRef(axis, angle, result);
  4419. return result;
  4420. };
  4421. /**
  4422. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4423. */
  4424. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4425. var s = Math.sin(-angle);
  4426. var c = Math.cos(-angle);
  4427. var c1 = 1 - c;
  4428. axis.normalize();
  4429. result.m[0] = (axis.x * axis.x) * c1 + c;
  4430. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4431. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4432. result.m[3] = 0.0;
  4433. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4434. result.m[5] = (axis.y * axis.y) * c1 + c;
  4435. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4436. result.m[7] = 0.0;
  4437. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4438. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4439. result.m[10] = (axis.z * axis.z) * c1 + c;
  4440. result.m[11] = 0.0;
  4441. result.m[15] = 1.0;
  4442. result._markAsUpdated();
  4443. };
  4444. /**
  4445. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4446. */
  4447. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4448. var result = new Matrix();
  4449. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4450. return result;
  4451. };
  4452. /**
  4453. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4454. */
  4455. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4456. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4457. this._tempQuaternion.toRotationMatrix(result);
  4458. };
  4459. /**
  4460. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4461. */
  4462. Matrix.Scaling = function (x, y, z) {
  4463. var result = Matrix.Zero();
  4464. Matrix.ScalingToRef(x, y, z, result);
  4465. return result;
  4466. };
  4467. /**
  4468. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4469. */
  4470. Matrix.ScalingToRef = function (x, y, z, result) {
  4471. result.m[0] = x;
  4472. result.m[1] = 0.0;
  4473. result.m[2] = 0.0;
  4474. result.m[3] = 0.0;
  4475. result.m[4] = 0.0;
  4476. result.m[5] = y;
  4477. result.m[6] = 0.0;
  4478. result.m[7] = 0.0;
  4479. result.m[8] = 0.0;
  4480. result.m[9] = 0.0;
  4481. result.m[10] = z;
  4482. result.m[11] = 0.0;
  4483. result.m[12] = 0.0;
  4484. result.m[13] = 0.0;
  4485. result.m[14] = 0.0;
  4486. result.m[15] = 1.0;
  4487. result._markAsUpdated();
  4488. };
  4489. /**
  4490. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4491. */
  4492. Matrix.Translation = function (x, y, z) {
  4493. var result = Matrix.Identity();
  4494. Matrix.TranslationToRef(x, y, z, result);
  4495. return result;
  4496. };
  4497. /**
  4498. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4499. */
  4500. Matrix.TranslationToRef = function (x, y, z, result) {
  4501. 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);
  4502. };
  4503. /**
  4504. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4505. */
  4506. Matrix.Lerp = function (startValue, endValue, gradient) {
  4507. var result = Matrix.Zero();
  4508. for (var index = 0; index < 16; index++) {
  4509. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4510. }
  4511. result._markAsUpdated();
  4512. return result;
  4513. };
  4514. /**
  4515. * Returns a new Matrix whose values are computed by :
  4516. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4517. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4518. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4519. */
  4520. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4521. var startScale = new Vector3(0, 0, 0);
  4522. var startRotation = new Quaternion();
  4523. var startTranslation = new Vector3(0, 0, 0);
  4524. startValue.decompose(startScale, startRotation, startTranslation);
  4525. var endScale = new Vector3(0, 0, 0);
  4526. var endRotation = new Quaternion();
  4527. var endTranslation = new Vector3(0, 0, 0);
  4528. endValue.decompose(endScale, endRotation, endTranslation);
  4529. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4530. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4531. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4532. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4533. };
  4534. /**
  4535. * 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".
  4536. * This methods works for a Left-Handed system.
  4537. */
  4538. Matrix.LookAtLH = function (eye, target, up) {
  4539. var result = Matrix.Zero();
  4540. Matrix.LookAtLHToRef(eye, target, up, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * 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".
  4545. * This methods works for a Left-Handed system.
  4546. */
  4547. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4548. // Z axis
  4549. target.subtractToRef(eye, this._zAxis);
  4550. this._zAxis.normalize();
  4551. // X axis
  4552. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4553. if (this._xAxis.lengthSquared() === 0) {
  4554. this._xAxis.x = 1.0;
  4555. }
  4556. else {
  4557. this._xAxis.normalize();
  4558. }
  4559. // Y axis
  4560. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4561. this._yAxis.normalize();
  4562. // Eye angles
  4563. var ex = -Vector3.Dot(this._xAxis, eye);
  4564. var ey = -Vector3.Dot(this._yAxis, eye);
  4565. var ez = -Vector3.Dot(this._zAxis, eye);
  4566. 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);
  4567. };
  4568. /**
  4569. * 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".
  4570. * This methods works for a Right-Handed system.
  4571. */
  4572. Matrix.LookAtRH = function (eye, target, up) {
  4573. var result = Matrix.Zero();
  4574. Matrix.LookAtRHToRef(eye, target, up, result);
  4575. return result;
  4576. };
  4577. /**
  4578. * 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".
  4579. * This methods works for a Left-Handed system.
  4580. */
  4581. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4582. // Z axis
  4583. eye.subtractToRef(target, this._zAxis);
  4584. this._zAxis.normalize();
  4585. // X axis
  4586. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4587. if (this._xAxis.lengthSquared() === 0) {
  4588. this._xAxis.x = 1.0;
  4589. }
  4590. else {
  4591. this._xAxis.normalize();
  4592. }
  4593. // Y axis
  4594. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4595. this._yAxis.normalize();
  4596. // Eye angles
  4597. var ex = -Vector3.Dot(this._xAxis, eye);
  4598. var ey = -Vector3.Dot(this._yAxis, eye);
  4599. var ez = -Vector3.Dot(this._zAxis, eye);
  4600. 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);
  4601. };
  4602. /**
  4603. * 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.
  4604. */
  4605. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4606. var matrix = Matrix.Zero();
  4607. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4608. return matrix;
  4609. };
  4610. /**
  4611. * 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.
  4612. */
  4613. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4614. var n = znear;
  4615. var f = zfar;
  4616. var a = 2.0 / width;
  4617. var b = 2.0 / height;
  4618. var c = 2.0 / (f - n);
  4619. var d = -(f + n) / (f - n);
  4620. 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);
  4621. };
  4622. /**
  4623. * 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.
  4624. */
  4625. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4626. var matrix = Matrix.Zero();
  4627. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4628. return matrix;
  4629. };
  4630. /**
  4631. * 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.
  4632. */
  4633. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4634. var n = znear;
  4635. var f = zfar;
  4636. var a = 2.0 / (right - left);
  4637. var b = 2.0 / (top - bottom);
  4638. var c = 2.0 / (f - n);
  4639. var d = -(f + n) / (f - n);
  4640. var i0 = (left + right) / (left - right);
  4641. var i1 = (top + bottom) / (bottom - top);
  4642. 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);
  4643. };
  4644. /**
  4645. * 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.
  4646. */
  4647. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4648. var matrix = Matrix.Zero();
  4649. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4650. return matrix;
  4651. };
  4652. /**
  4653. * 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.
  4654. */
  4655. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4656. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4657. result.m[10] *= -1.0;
  4658. };
  4659. /**
  4660. * 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.
  4661. */
  4662. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4663. var matrix = Matrix.Zero();
  4664. var n = znear;
  4665. var f = zfar;
  4666. var a = 2.0 * n / width;
  4667. var b = 2.0 * n / height;
  4668. var c = (f + n) / (f - n);
  4669. var d = -2.0 * f * n / (f - n);
  4670. 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);
  4671. return matrix;
  4672. };
  4673. /**
  4674. * 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.
  4675. */
  4676. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4677. var matrix = Matrix.Zero();
  4678. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4679. return matrix;
  4680. };
  4681. /**
  4682. * 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.
  4683. */
  4684. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4685. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4686. var n = znear;
  4687. var f = zfar;
  4688. var t = 1.0 / (Math.tan(fov * 0.5));
  4689. var a = isVerticalFovFixed ? (t / aspect) : t;
  4690. var b = isVerticalFovFixed ? t : (t * aspect);
  4691. var c = (f + n) / (f - n);
  4692. var d = -2.0 * f * n / (f - n);
  4693. 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);
  4694. };
  4695. /**
  4696. * 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.
  4697. */
  4698. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4699. var matrix = Matrix.Zero();
  4700. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4701. return matrix;
  4702. };
  4703. /**
  4704. * 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.
  4705. */
  4706. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4707. //alternatively this could be expressed as:
  4708. // m = PerspectiveFovLHToRef
  4709. // m[10] *= -1.0;
  4710. // m[11] *= -1.0;
  4711. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4712. var n = znear;
  4713. var f = zfar;
  4714. var t = 1.0 / (Math.tan(fov * 0.5));
  4715. var a = isVerticalFovFixed ? (t / aspect) : t;
  4716. var b = isVerticalFovFixed ? t : (t * aspect);
  4717. var c = -(f + n) / (f - n);
  4718. var d = -2 * f * n / (f - n);
  4719. 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);
  4720. };
  4721. /**
  4722. * 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.
  4723. */
  4724. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4725. if (rightHanded === void 0) { rightHanded = false; }
  4726. var rightHandedFactor = rightHanded ? -1 : 1;
  4727. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4728. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4729. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4730. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4731. var xScale = 2.0 / (leftTan + rightTan);
  4732. var yScale = 2.0 / (upTan + downTan);
  4733. result.m[0] = xScale;
  4734. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4735. result.m[5] = yScale;
  4736. result.m[6] = result.m[7] = 0.0;
  4737. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4738. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4739. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4740. result.m[10] = -zfar / (znear - zfar);
  4741. result.m[11] = 1.0 * rightHandedFactor;
  4742. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4743. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4744. // result.m[14] = (znear * zfar) / (znear - zfar);
  4745. result._markAsUpdated();
  4746. };
  4747. /**
  4748. * Returns the final transformation matrix : world * view * projection * viewport
  4749. */
  4750. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4751. var cw = viewport.width;
  4752. var ch = viewport.height;
  4753. var cx = viewport.x;
  4754. var cy = viewport.y;
  4755. 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);
  4756. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4757. };
  4758. /**
  4759. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4760. */
  4761. Matrix.GetAsMatrix2x2 = function (matrix) {
  4762. return new Float32Array([
  4763. matrix.m[0], matrix.m[1],
  4764. matrix.m[4], matrix.m[5]
  4765. ]);
  4766. };
  4767. /**
  4768. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4769. */
  4770. Matrix.GetAsMatrix3x3 = function (matrix) {
  4771. return new Float32Array([
  4772. matrix.m[0], matrix.m[1], matrix.m[2],
  4773. matrix.m[4], matrix.m[5], matrix.m[6],
  4774. matrix.m[8], matrix.m[9], matrix.m[10]
  4775. ]);
  4776. };
  4777. /**
  4778. * Compute the transpose of the passed Matrix.
  4779. * Returns a new Matrix.
  4780. */
  4781. Matrix.Transpose = function (matrix) {
  4782. var result = new Matrix();
  4783. Matrix.TransposeToRef(matrix, result);
  4784. return result;
  4785. };
  4786. /**
  4787. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4788. */
  4789. Matrix.TransposeToRef = function (matrix, result) {
  4790. result.m[0] = matrix.m[0];
  4791. result.m[1] = matrix.m[4];
  4792. result.m[2] = matrix.m[8];
  4793. result.m[3] = matrix.m[12];
  4794. result.m[4] = matrix.m[1];
  4795. result.m[5] = matrix.m[5];
  4796. result.m[6] = matrix.m[9];
  4797. result.m[7] = matrix.m[13];
  4798. result.m[8] = matrix.m[2];
  4799. result.m[9] = matrix.m[6];
  4800. result.m[10] = matrix.m[10];
  4801. result.m[11] = matrix.m[14];
  4802. result.m[12] = matrix.m[3];
  4803. result.m[13] = matrix.m[7];
  4804. result.m[14] = matrix.m[11];
  4805. result.m[15] = matrix.m[15];
  4806. };
  4807. /**
  4808. * Returns a new Matrix as the reflection matrix across the passed plane.
  4809. */
  4810. Matrix.Reflection = function (plane) {
  4811. var matrix = new Matrix();
  4812. Matrix.ReflectionToRef(plane, matrix);
  4813. return matrix;
  4814. };
  4815. /**
  4816. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4817. */
  4818. Matrix.ReflectionToRef = function (plane, result) {
  4819. plane.normalize();
  4820. var x = plane.normal.x;
  4821. var y = plane.normal.y;
  4822. var z = plane.normal.z;
  4823. var temp = -2 * x;
  4824. var temp2 = -2 * y;
  4825. var temp3 = -2 * z;
  4826. result.m[0] = (temp * x) + 1;
  4827. result.m[1] = temp2 * x;
  4828. result.m[2] = temp3 * x;
  4829. result.m[3] = 0.0;
  4830. result.m[4] = temp * y;
  4831. result.m[5] = (temp2 * y) + 1;
  4832. result.m[6] = temp3 * y;
  4833. result.m[7] = 0.0;
  4834. result.m[8] = temp * z;
  4835. result.m[9] = temp2 * z;
  4836. result.m[10] = (temp3 * z) + 1;
  4837. result.m[11] = 0.0;
  4838. result.m[12] = temp * plane.d;
  4839. result.m[13] = temp2 * plane.d;
  4840. result.m[14] = temp3 * plane.d;
  4841. result.m[15] = 1.0;
  4842. result._markAsUpdated();
  4843. };
  4844. /**
  4845. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4846. */
  4847. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4848. result.m[0] = xaxis.x;
  4849. result.m[1] = xaxis.y;
  4850. result.m[2] = xaxis.z;
  4851. result.m[3] = 0.0;
  4852. result.m[4] = yaxis.x;
  4853. result.m[5] = yaxis.y;
  4854. result.m[6] = yaxis.z;
  4855. result.m[7] = 0.0;
  4856. result.m[8] = zaxis.x;
  4857. result.m[9] = zaxis.y;
  4858. result.m[10] = zaxis.z;
  4859. result.m[11] = 0.0;
  4860. result.m[12] = 0.0;
  4861. result.m[13] = 0.0;
  4862. result.m[14] = 0.0;
  4863. result.m[15] = 1.0;
  4864. result._markAsUpdated();
  4865. };
  4866. /**
  4867. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4868. */
  4869. Matrix.FromQuaternionToRef = function (quat, result) {
  4870. var xx = quat.x * quat.x;
  4871. var yy = quat.y * quat.y;
  4872. var zz = quat.z * quat.z;
  4873. var xy = quat.x * quat.y;
  4874. var zw = quat.z * quat.w;
  4875. var zx = quat.z * quat.x;
  4876. var yw = quat.y * quat.w;
  4877. var yz = quat.y * quat.z;
  4878. var xw = quat.x * quat.w;
  4879. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4880. result.m[1] = 2.0 * (xy + zw);
  4881. result.m[2] = 2.0 * (zx - yw);
  4882. result.m[3] = 0.0;
  4883. result.m[4] = 2.0 * (xy - zw);
  4884. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4885. result.m[6] = 2.0 * (yz + xw);
  4886. result.m[7] = 0.0;
  4887. result.m[8] = 2.0 * (zx + yw);
  4888. result.m[9] = 2.0 * (yz - xw);
  4889. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4890. result.m[11] = 0.0;
  4891. result.m[12] = 0.0;
  4892. result.m[13] = 0.0;
  4893. result.m[14] = 0.0;
  4894. result.m[15] = 1.0;
  4895. result._markAsUpdated();
  4896. };
  4897. Matrix._tempQuaternion = new Quaternion();
  4898. Matrix._xAxis = Vector3.Zero();
  4899. Matrix._yAxis = Vector3.Zero();
  4900. Matrix._zAxis = Vector3.Zero();
  4901. Matrix._updateFlagSeed = 0;
  4902. Matrix._identityReadOnly = Matrix.Identity();
  4903. return Matrix;
  4904. }());
  4905. BABYLON.Matrix = Matrix;
  4906. var Plane = /** @class */ (function () {
  4907. /**
  4908. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4909. */
  4910. function Plane(a, b, c, d) {
  4911. this.normal = new Vector3(a, b, c);
  4912. this.d = d;
  4913. }
  4914. /**
  4915. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4916. */
  4917. Plane.prototype.asArray = function () {
  4918. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4919. };
  4920. // Methods
  4921. /**
  4922. * Returns a new plane copied from the current Plane.
  4923. */
  4924. Plane.prototype.clone = function () {
  4925. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4926. };
  4927. /**
  4928. * Returns the string "Plane".
  4929. */
  4930. Plane.prototype.getClassName = function () {
  4931. return "Plane";
  4932. };
  4933. /**
  4934. * Returns the Plane hash code.
  4935. */
  4936. Plane.prototype.getHashCode = function () {
  4937. var hash = this.normal.getHashCode();
  4938. hash = (hash * 397) ^ (this.d || 0);
  4939. return hash;
  4940. };
  4941. /**
  4942. * Normalize the current Plane in place.
  4943. * Returns the updated Plane.
  4944. */
  4945. Plane.prototype.normalize = function () {
  4946. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4947. var magnitude = 0.0;
  4948. if (norm !== 0) {
  4949. magnitude = 1.0 / norm;
  4950. }
  4951. this.normal.x *= magnitude;
  4952. this.normal.y *= magnitude;
  4953. this.normal.z *= magnitude;
  4954. this.d *= magnitude;
  4955. return this;
  4956. };
  4957. /**
  4958. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4959. */
  4960. Plane.prototype.transform = function (transformation) {
  4961. var transposedMatrix = Matrix.Transpose(transformation);
  4962. var x = this.normal.x;
  4963. var y = this.normal.y;
  4964. var z = this.normal.z;
  4965. var d = this.d;
  4966. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4967. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4968. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4969. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4970. return new Plane(normalX, normalY, normalZ, finalD);
  4971. };
  4972. /**
  4973. * Returns the dot product (float) of the point coordinates and the plane normal.
  4974. */
  4975. Plane.prototype.dotCoordinate = function (point) {
  4976. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4977. };
  4978. /**
  4979. * Updates the current Plane from the plane defined by the three passed points.
  4980. * Returns the updated Plane.
  4981. */
  4982. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4983. var x1 = point2.x - point1.x;
  4984. var y1 = point2.y - point1.y;
  4985. var z1 = point2.z - point1.z;
  4986. var x2 = point3.x - point1.x;
  4987. var y2 = point3.y - point1.y;
  4988. var z2 = point3.z - point1.z;
  4989. var yz = (y1 * z2) - (z1 * y2);
  4990. var xz = (z1 * x2) - (x1 * z2);
  4991. var xy = (x1 * y2) - (y1 * x2);
  4992. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4993. var invPyth;
  4994. if (pyth !== 0) {
  4995. invPyth = 1.0 / pyth;
  4996. }
  4997. else {
  4998. invPyth = 0.0;
  4999. }
  5000. this.normal.x = yz * invPyth;
  5001. this.normal.y = xz * invPyth;
  5002. this.normal.z = xy * invPyth;
  5003. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5004. return this;
  5005. };
  5006. /**
  5007. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5008. */
  5009. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5010. var dot = Vector3.Dot(this.normal, direction);
  5011. return (dot <= epsilon);
  5012. };
  5013. /**
  5014. * Returns the signed distance (float) from the passed point to the Plane.
  5015. */
  5016. Plane.prototype.signedDistanceTo = function (point) {
  5017. return Vector3.Dot(point, this.normal) + this.d;
  5018. };
  5019. // Statics
  5020. /**
  5021. * Returns a new Plane from the passed array.
  5022. */
  5023. Plane.FromArray = function (array) {
  5024. return new Plane(array[0], array[1], array[2], array[3]);
  5025. };
  5026. /**
  5027. * Returns a new Plane defined by the three passed points.
  5028. */
  5029. Plane.FromPoints = function (point1, point2, point3) {
  5030. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5031. result.copyFromPoints(point1, point2, point3);
  5032. return result;
  5033. };
  5034. /**
  5035. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5036. * Note : the vector "normal" is updated because normalized.
  5037. */
  5038. Plane.FromPositionAndNormal = function (origin, normal) {
  5039. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5040. normal.normalize();
  5041. result.normal = normal;
  5042. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5043. return result;
  5044. };
  5045. /**
  5046. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5047. */
  5048. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5049. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5050. return Vector3.Dot(point, normal) + d;
  5051. };
  5052. return Plane;
  5053. }());
  5054. BABYLON.Plane = Plane;
  5055. var Viewport = /** @class */ (function () {
  5056. /**
  5057. * Creates a Viewport object located at (x, y) and sized (width, height).
  5058. */
  5059. function Viewport(x, y, width, height) {
  5060. this.x = x;
  5061. this.y = y;
  5062. this.width = width;
  5063. this.height = height;
  5064. }
  5065. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5066. if (renderWidthOrEngine.getRenderWidth) {
  5067. var engine = renderWidthOrEngine;
  5068. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5069. }
  5070. var renderWidth = renderWidthOrEngine;
  5071. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5072. };
  5073. /**
  5074. * Returns a new Viewport copied from the current one.
  5075. */
  5076. Viewport.prototype.clone = function () {
  5077. return new Viewport(this.x, this.y, this.width, this.height);
  5078. };
  5079. return Viewport;
  5080. }());
  5081. BABYLON.Viewport = Viewport;
  5082. var Frustum = /** @class */ (function () {
  5083. function Frustum() {
  5084. }
  5085. /**
  5086. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5087. */
  5088. Frustum.GetPlanes = function (transform) {
  5089. var frustumPlanes = [];
  5090. for (var index = 0; index < 6; index++) {
  5091. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5092. }
  5093. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5094. return frustumPlanes;
  5095. };
  5096. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5097. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5098. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5099. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5100. frustumPlane.d = transform.m[15] + transform.m[14];
  5101. frustumPlane.normalize();
  5102. };
  5103. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5104. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5105. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5106. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5107. frustumPlane.d = transform.m[15] - transform.m[14];
  5108. frustumPlane.normalize();
  5109. };
  5110. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5111. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5112. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5113. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5114. frustumPlane.d = transform.m[15] + transform.m[12];
  5115. frustumPlane.normalize();
  5116. };
  5117. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5118. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5119. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5120. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5121. frustumPlane.d = transform.m[15] - transform.m[12];
  5122. frustumPlane.normalize();
  5123. };
  5124. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5125. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5126. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5127. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5128. frustumPlane.d = transform.m[15] - transform.m[13];
  5129. frustumPlane.normalize();
  5130. };
  5131. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5132. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5133. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5134. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5135. frustumPlane.d = transform.m[15] + transform.m[13];
  5136. frustumPlane.normalize();
  5137. };
  5138. /**
  5139. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5140. */
  5141. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5142. // Near
  5143. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5144. // Far
  5145. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5146. // Left
  5147. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5148. // Right
  5149. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5150. // Top
  5151. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5152. // Bottom
  5153. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5154. };
  5155. return Frustum;
  5156. }());
  5157. BABYLON.Frustum = Frustum;
  5158. var Space;
  5159. (function (Space) {
  5160. Space[Space["LOCAL"] = 0] = "LOCAL";
  5161. Space[Space["WORLD"] = 1] = "WORLD";
  5162. Space[Space["BONE"] = 2] = "BONE";
  5163. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5164. var Axis = /** @class */ (function () {
  5165. function Axis() {
  5166. }
  5167. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5168. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5169. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5170. return Axis;
  5171. }());
  5172. BABYLON.Axis = Axis;
  5173. ;
  5174. var BezierCurve = /** @class */ (function () {
  5175. function BezierCurve() {
  5176. }
  5177. /**
  5178. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5179. */
  5180. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5181. // Extract X (which is equal to time here)
  5182. var f0 = 1 - 3 * x2 + 3 * x1;
  5183. var f1 = 3 * x2 - 6 * x1;
  5184. var f2 = 3 * x1;
  5185. var refinedT = t;
  5186. for (var i = 0; i < 5; i++) {
  5187. var refinedT2 = refinedT * refinedT;
  5188. var refinedT3 = refinedT2 * refinedT;
  5189. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5190. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5191. refinedT -= (x - t) * slope;
  5192. refinedT = Math.min(1, Math.max(0, refinedT));
  5193. }
  5194. // Resolve cubic bezier for the given x
  5195. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5196. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5197. Math.pow(refinedT, 3);
  5198. };
  5199. return BezierCurve;
  5200. }());
  5201. BABYLON.BezierCurve = BezierCurve;
  5202. var Orientation;
  5203. (function (Orientation) {
  5204. Orientation[Orientation["CW"] = 0] = "CW";
  5205. Orientation[Orientation["CCW"] = 1] = "CCW";
  5206. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5207. var Angle = /** @class */ (function () {
  5208. /**
  5209. * Creates an Angle object of "radians" radians (float).
  5210. */
  5211. function Angle(radians) {
  5212. var _this = this;
  5213. /**
  5214. * Returns the Angle value in degrees (float).
  5215. */
  5216. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5217. /**
  5218. * Returns the Angle value in radians (float).
  5219. */
  5220. this.radians = function () { return _this._radians; };
  5221. this._radians = radians;
  5222. if (this._radians < 0.0)
  5223. this._radians += (2.0 * Math.PI);
  5224. }
  5225. /**
  5226. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5227. */
  5228. Angle.BetweenTwoPoints = function (a, b) {
  5229. var delta = b.subtract(a);
  5230. var theta = Math.atan2(delta.y, delta.x);
  5231. return new Angle(theta);
  5232. };
  5233. /**
  5234. * Returns a new Angle object from the passed float in radians.
  5235. */
  5236. Angle.FromRadians = function (radians) {
  5237. return new Angle(radians);
  5238. };
  5239. /**
  5240. * Returns a new Angle object from the passed float in degrees.
  5241. */
  5242. Angle.FromDegrees = function (degrees) {
  5243. return new Angle(degrees * Math.PI / 180.0);
  5244. };
  5245. return Angle;
  5246. }());
  5247. BABYLON.Angle = Angle;
  5248. var Arc2 = /** @class */ (function () {
  5249. /**
  5250. * Creates an Arc object from the three passed points : start, middle and end.
  5251. */
  5252. function Arc2(startPoint, midPoint, endPoint) {
  5253. this.startPoint = startPoint;
  5254. this.midPoint = midPoint;
  5255. this.endPoint = endPoint;
  5256. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5257. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5258. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5259. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5260. 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);
  5261. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5262. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5263. var a1 = this.startAngle.degrees();
  5264. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5265. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5266. // angles correction
  5267. if (a2 - a1 > +180.0)
  5268. a2 -= 360.0;
  5269. if (a2 - a1 < -180.0)
  5270. a2 += 360.0;
  5271. if (a3 - a2 > +180.0)
  5272. a3 -= 360.0;
  5273. if (a3 - a2 < -180.0)
  5274. a3 += 360.0;
  5275. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5276. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5277. }
  5278. return Arc2;
  5279. }());
  5280. BABYLON.Arc2 = Arc2;
  5281. var Path2 = /** @class */ (function () {
  5282. /**
  5283. * Creates a Path2 object from the starting 2D coordinates x and y.
  5284. */
  5285. function Path2(x, y) {
  5286. this._points = new Array();
  5287. this._length = 0.0;
  5288. this.closed = false;
  5289. this._points.push(new Vector2(x, y));
  5290. }
  5291. /**
  5292. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5293. * Returns the updated Path2.
  5294. */
  5295. Path2.prototype.addLineTo = function (x, y) {
  5296. if (this.closed) {
  5297. //Tools.Error("cannot add lines to closed paths");
  5298. return this;
  5299. }
  5300. var newPoint = new Vector2(x, y);
  5301. var previousPoint = this._points[this._points.length - 1];
  5302. this._points.push(newPoint);
  5303. this._length += newPoint.subtract(previousPoint).length();
  5304. return this;
  5305. };
  5306. /**
  5307. * 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.
  5308. * Returns the updated Path2.
  5309. */
  5310. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5311. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5312. if (this.closed) {
  5313. //Tools.Error("cannot add arcs to closed paths");
  5314. return this;
  5315. }
  5316. var startPoint = this._points[this._points.length - 1];
  5317. var midPoint = new Vector2(midX, midY);
  5318. var endPoint = new Vector2(endX, endY);
  5319. var arc = new Arc2(startPoint, midPoint, endPoint);
  5320. var increment = arc.angle.radians() / numberOfSegments;
  5321. if (arc.orientation === Orientation.CW)
  5322. increment *= -1;
  5323. var currentAngle = arc.startAngle.radians() + increment;
  5324. for (var i = 0; i < numberOfSegments; i++) {
  5325. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5326. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5327. this.addLineTo(x, y);
  5328. currentAngle += increment;
  5329. }
  5330. return this;
  5331. };
  5332. /**
  5333. * Closes the Path2.
  5334. * Returns the Path2.
  5335. */
  5336. Path2.prototype.close = function () {
  5337. this.closed = true;
  5338. return this;
  5339. };
  5340. /**
  5341. * Returns the Path2 total length (float).
  5342. */
  5343. Path2.prototype.length = function () {
  5344. var result = this._length;
  5345. if (!this.closed) {
  5346. var lastPoint = this._points[this._points.length - 1];
  5347. var firstPoint = this._points[0];
  5348. result += (firstPoint.subtract(lastPoint).length());
  5349. }
  5350. return result;
  5351. };
  5352. /**
  5353. * Returns the Path2 internal array of points.
  5354. */
  5355. Path2.prototype.getPoints = function () {
  5356. return this._points;
  5357. };
  5358. /**
  5359. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5360. */
  5361. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5362. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5363. //Tools.Error("normalized length position should be between 0 and 1.");
  5364. return Vector2.Zero();
  5365. }
  5366. var lengthPosition = normalizedLengthPosition * this.length();
  5367. var previousOffset = 0;
  5368. for (var i = 0; i < this._points.length; i++) {
  5369. var j = (i + 1) % this._points.length;
  5370. var a = this._points[i];
  5371. var b = this._points[j];
  5372. var bToA = b.subtract(a);
  5373. var nextOffset = (bToA.length() + previousOffset);
  5374. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5375. var dir = bToA.normalize();
  5376. var localOffset = lengthPosition - previousOffset;
  5377. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5378. }
  5379. previousOffset = nextOffset;
  5380. }
  5381. //Tools.Error("internal error");
  5382. return Vector2.Zero();
  5383. };
  5384. /**
  5385. * Returns a new Path2 starting at the coordinates (x, y).
  5386. */
  5387. Path2.StartingAt = function (x, y) {
  5388. return new Path2(x, y);
  5389. };
  5390. return Path2;
  5391. }());
  5392. BABYLON.Path2 = Path2;
  5393. var Path3D = /** @class */ (function () {
  5394. /**
  5395. * new Path3D(path, normal, raw)
  5396. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5397. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5398. * path : an array of Vector3, the curve axis of the Path3D
  5399. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5400. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5401. */
  5402. function Path3D(path, firstNormal, raw) {
  5403. if (firstNormal === void 0) { firstNormal = null; }
  5404. this.path = path;
  5405. this._curve = new Array();
  5406. this._distances = new Array();
  5407. this._tangents = new Array();
  5408. this._normals = new Array();
  5409. this._binormals = new Array();
  5410. for (var p = 0; p < path.length; p++) {
  5411. this._curve[p] = path[p].clone(); // hard copy
  5412. }
  5413. this._raw = raw || false;
  5414. this._compute(firstNormal);
  5415. }
  5416. /**
  5417. * Returns the Path3D array of successive Vector3 designing its curve.
  5418. */
  5419. Path3D.prototype.getCurve = function () {
  5420. return this._curve;
  5421. };
  5422. /**
  5423. * Returns an array populated with tangent vectors on each Path3D curve point.
  5424. */
  5425. Path3D.prototype.getTangents = function () {
  5426. return this._tangents;
  5427. };
  5428. /**
  5429. * Returns an array populated with normal vectors on each Path3D curve point.
  5430. */
  5431. Path3D.prototype.getNormals = function () {
  5432. return this._normals;
  5433. };
  5434. /**
  5435. * Returns an array populated with binormal vectors on each Path3D curve point.
  5436. */
  5437. Path3D.prototype.getBinormals = function () {
  5438. return this._binormals;
  5439. };
  5440. /**
  5441. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5442. */
  5443. Path3D.prototype.getDistances = function () {
  5444. return this._distances;
  5445. };
  5446. /**
  5447. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5448. * Returns the same object updated.
  5449. */
  5450. Path3D.prototype.update = function (path, firstNormal) {
  5451. if (firstNormal === void 0) { firstNormal = null; }
  5452. for (var p = 0; p < path.length; p++) {
  5453. this._curve[p].x = path[p].x;
  5454. this._curve[p].y = path[p].y;
  5455. this._curve[p].z = path[p].z;
  5456. }
  5457. this._compute(firstNormal);
  5458. return this;
  5459. };
  5460. // private function compute() : computes tangents, normals and binormals
  5461. Path3D.prototype._compute = function (firstNormal) {
  5462. var l = this._curve.length;
  5463. // first and last tangents
  5464. this._tangents[0] = this._getFirstNonNullVector(0);
  5465. if (!this._raw) {
  5466. this._tangents[0].normalize();
  5467. }
  5468. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5469. if (!this._raw) {
  5470. this._tangents[l - 1].normalize();
  5471. }
  5472. // normals and binormals at first point : arbitrary vector with _normalVector()
  5473. var tg0 = this._tangents[0];
  5474. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5475. this._normals[0] = pp0;
  5476. if (!this._raw) {
  5477. this._normals[0].normalize();
  5478. }
  5479. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5480. if (!this._raw) {
  5481. this._binormals[0].normalize();
  5482. }
  5483. this._distances[0] = 0.0;
  5484. // normals and binormals : next points
  5485. var prev; // previous vector (segment)
  5486. var cur; // current vector (segment)
  5487. var curTang; // current tangent
  5488. // previous normal
  5489. var prevBinor; // previous binormal
  5490. for (var i = 1; i < l; i++) {
  5491. // tangents
  5492. prev = this._getLastNonNullVector(i);
  5493. if (i < l - 1) {
  5494. cur = this._getFirstNonNullVector(i);
  5495. this._tangents[i] = prev.add(cur);
  5496. this._tangents[i].normalize();
  5497. }
  5498. this._distances[i] = this._distances[i - 1] + prev.length();
  5499. // normals and binormals
  5500. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5501. curTang = this._tangents[i];
  5502. prevBinor = this._binormals[i - 1];
  5503. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5504. if (!this._raw) {
  5505. this._normals[i].normalize();
  5506. }
  5507. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5508. if (!this._raw) {
  5509. this._binormals[i].normalize();
  5510. }
  5511. }
  5512. };
  5513. // private function getFirstNonNullVector(index)
  5514. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5515. Path3D.prototype._getFirstNonNullVector = function (index) {
  5516. var i = 1;
  5517. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5518. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5519. i++;
  5520. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5521. }
  5522. return nNVector;
  5523. };
  5524. // private function getLastNonNullVector(index)
  5525. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5526. Path3D.prototype._getLastNonNullVector = function (index) {
  5527. var i = 1;
  5528. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5529. while (nLVector.length() === 0 && index > i + 1) {
  5530. i++;
  5531. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5532. }
  5533. return nLVector;
  5534. };
  5535. // private function normalVector(v0, vt, va) :
  5536. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5537. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5538. Path3D.prototype._normalVector = function (v0, vt, va) {
  5539. var normal0;
  5540. var tgl = vt.length();
  5541. if (tgl === 0.0) {
  5542. tgl = 1.0;
  5543. }
  5544. if (va === undefined || va === null) {
  5545. var point;
  5546. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5547. point = new Vector3(0.0, -1.0, 0.0);
  5548. }
  5549. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5550. point = new Vector3(1.0, 0.0, 0.0);
  5551. }
  5552. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5553. point = new Vector3(0.0, 0.0, 1.0);
  5554. }
  5555. else {
  5556. point = Vector3.Zero();
  5557. }
  5558. normal0 = Vector3.Cross(vt, point);
  5559. }
  5560. else {
  5561. normal0 = Vector3.Cross(vt, va);
  5562. Vector3.CrossToRef(normal0, vt, normal0);
  5563. }
  5564. normal0.normalize();
  5565. return normal0;
  5566. };
  5567. return Path3D;
  5568. }());
  5569. BABYLON.Path3D = Path3D;
  5570. var Curve3 = /** @class */ (function () {
  5571. /**
  5572. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5573. * A Curve3 is designed from a series of successive Vector3.
  5574. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5575. */
  5576. function Curve3(points) {
  5577. this._length = 0.0;
  5578. this._points = points;
  5579. this._length = this._computeLength(points);
  5580. }
  5581. /**
  5582. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5583. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5584. * @param v1 (Vector3) the control point
  5585. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5586. * @param nbPoints (integer) the wanted number of points in the curve
  5587. */
  5588. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5589. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5590. var bez = new Array();
  5591. var equation = function (t, val0, val1, val2) {
  5592. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5593. return res;
  5594. };
  5595. for (var i = 0; i <= nbPoints; i++) {
  5596. 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)));
  5597. }
  5598. return new Curve3(bez);
  5599. };
  5600. /**
  5601. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5602. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5603. * @param v1 (Vector3) the first control point
  5604. * @param v2 (Vector3) the second control point
  5605. * @param v3 (Vector3) the end point of the Cubic Bezier
  5606. * @param nbPoints (integer) the wanted number of points in the curve
  5607. */
  5608. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5609. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5610. var bez = new Array();
  5611. var equation = function (t, val0, val1, val2, val3) {
  5612. 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;
  5613. return res;
  5614. };
  5615. for (var i = 0; i <= nbPoints; i++) {
  5616. 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)));
  5617. }
  5618. return new Curve3(bez);
  5619. };
  5620. /**
  5621. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5622. * @param p1 (Vector3) the origin point of the Hermite Spline
  5623. * @param t1 (Vector3) the tangent vector at the origin point
  5624. * @param p2 (Vector3) the end point of the Hermite Spline
  5625. * @param t2 (Vector3) the tangent vector at the end point
  5626. * @param nbPoints (integer) the wanted number of points in the curve
  5627. */
  5628. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5629. var hermite = new Array();
  5630. var step = 1.0 / nbPoints;
  5631. for (var i = 0; i <= nbPoints; i++) {
  5632. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5633. }
  5634. return new Curve3(hermite);
  5635. };
  5636. /**
  5637. * Returns a Curve3 object along a CatmullRom Spline curve :
  5638. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5639. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5640. */
  5641. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5642. var totalPoints = new Array();
  5643. totalPoints.push(points[0].clone());
  5644. Array.prototype.push.apply(totalPoints, points);
  5645. totalPoints.push(points[points.length - 1].clone());
  5646. var catmullRom = new Array();
  5647. var step = 1.0 / nbPoints;
  5648. var amount = 0.0;
  5649. for (var i = 0; i < totalPoints.length - 3; i++) {
  5650. amount = 0;
  5651. for (var c = 0; c < nbPoints; c++) {
  5652. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5653. amount += step;
  5654. }
  5655. }
  5656. i--;
  5657. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5658. return new Curve3(catmullRom);
  5659. };
  5660. /**
  5661. * Returns the Curve3 stored array of successive Vector3
  5662. */
  5663. Curve3.prototype.getPoints = function () {
  5664. return this._points;
  5665. };
  5666. /**
  5667. * Returns the computed length (float) of the curve.
  5668. */
  5669. Curve3.prototype.length = function () {
  5670. return this._length;
  5671. };
  5672. /**
  5673. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5674. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5675. * curveA and curveB keep unchanged.
  5676. */
  5677. Curve3.prototype.continue = function (curve) {
  5678. var lastPoint = this._points[this._points.length - 1];
  5679. var continuedPoints = this._points.slice();
  5680. var curvePoints = curve.getPoints();
  5681. for (var i = 1; i < curvePoints.length; i++) {
  5682. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5683. }
  5684. var continuedCurve = new Curve3(continuedPoints);
  5685. return continuedCurve;
  5686. };
  5687. Curve3.prototype._computeLength = function (path) {
  5688. var l = 0;
  5689. for (var i = 1; i < path.length; i++) {
  5690. l += (path[i].subtract(path[i - 1])).length();
  5691. }
  5692. return l;
  5693. };
  5694. return Curve3;
  5695. }());
  5696. BABYLON.Curve3 = Curve3;
  5697. // Vertex formats
  5698. var PositionNormalVertex = /** @class */ (function () {
  5699. function PositionNormalVertex(position, normal) {
  5700. if (position === void 0) { position = Vector3.Zero(); }
  5701. if (normal === void 0) { normal = Vector3.Up(); }
  5702. this.position = position;
  5703. this.normal = normal;
  5704. }
  5705. PositionNormalVertex.prototype.clone = function () {
  5706. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5707. };
  5708. return PositionNormalVertex;
  5709. }());
  5710. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5711. var PositionNormalTextureVertex = /** @class */ (function () {
  5712. function PositionNormalTextureVertex(position, normal, uv) {
  5713. if (position === void 0) { position = Vector3.Zero(); }
  5714. if (normal === void 0) { normal = Vector3.Up(); }
  5715. if (uv === void 0) { uv = Vector2.Zero(); }
  5716. this.position = position;
  5717. this.normal = normal;
  5718. this.uv = uv;
  5719. }
  5720. PositionNormalTextureVertex.prototype.clone = function () {
  5721. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5722. };
  5723. return PositionNormalTextureVertex;
  5724. }());
  5725. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5726. // Temporary pre-allocated objects for engine internal use
  5727. // usage in any internal function :
  5728. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5729. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5730. var Tmp = /** @class */ (function () {
  5731. function Tmp() {
  5732. }
  5733. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5734. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5735. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5736. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5737. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5738. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5739. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5740. Matrix.Zero(), Matrix.Zero(),
  5741. Matrix.Zero(), Matrix.Zero(),
  5742. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5743. return Tmp;
  5744. }());
  5745. BABYLON.Tmp = Tmp;
  5746. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5747. var MathTmp = /** @class */ (function () {
  5748. function MathTmp() {
  5749. }
  5750. MathTmp.Vector3 = [Vector3.Zero()];
  5751. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5752. MathTmp.Quaternion = [Quaternion.Zero()];
  5753. return MathTmp;
  5754. }());
  5755. })(BABYLON || (BABYLON = {}));
  5756. //# sourceMappingURL=babylon.math.js.map
  5757. var BABYLON;
  5758. (function (BABYLON) {
  5759. var Scalar = /** @class */ (function () {
  5760. function Scalar() {
  5761. }
  5762. /**
  5763. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5764. */
  5765. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5766. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5767. var num = a - b;
  5768. return -epsilon <= num && num <= epsilon;
  5769. };
  5770. /**
  5771. * Returns a string : the upper case translation of the number i to hexadecimal.
  5772. */
  5773. Scalar.ToHex = function (i) {
  5774. var str = i.toString(16);
  5775. if (i <= 15) {
  5776. return ("0" + str).toUpperCase();
  5777. }
  5778. return str.toUpperCase();
  5779. };
  5780. /**
  5781. * Returns -1 if value is negative and +1 is value is positive.
  5782. * Returns the value itself if it's equal to zero.
  5783. */
  5784. Scalar.Sign = function (value) {
  5785. value = +value; // convert to a number
  5786. if (value === 0 || isNaN(value))
  5787. return value;
  5788. return value > 0 ? 1 : -1;
  5789. };
  5790. /**
  5791. * Returns the value itself if it's between min and max.
  5792. * Returns min if the value is lower than min.
  5793. * Returns max if the value is greater than max.
  5794. */
  5795. Scalar.Clamp = function (value, min, max) {
  5796. if (min === void 0) { min = 0; }
  5797. if (max === void 0) { max = 1; }
  5798. return Math.min(max, Math.max(min, value));
  5799. };
  5800. /**
  5801. * Returns the log2 of value.
  5802. */
  5803. Scalar.Log2 = function (value) {
  5804. return Math.log(value) * Math.LOG2E;
  5805. };
  5806. /**
  5807. * Loops the value, so that it is never larger than length and never smaller than 0.
  5808. *
  5809. * This is similar to the modulo operator but it works with floating point numbers.
  5810. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5811. * With t = 5 and length = 2.5, the result would be 0.0.
  5812. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5813. */
  5814. Scalar.Repeat = function (value, length) {
  5815. return value - Math.floor(value / length) * length;
  5816. };
  5817. /**
  5818. * Normalize the value between 0.0 and 1.0 using min and max values
  5819. */
  5820. Scalar.Normalize = function (value, min, max) {
  5821. return (value - min) / (max - min);
  5822. };
  5823. /**
  5824. * Denormalize the value from 0.0 and 1.0 using min and max values
  5825. */
  5826. Scalar.Denormalize = function (normalized, min, max) {
  5827. return (normalized * (max - min) + min);
  5828. };
  5829. /**
  5830. * Calculates the shortest difference between two given angles given in degrees.
  5831. */
  5832. Scalar.DeltaAngle = function (current, target) {
  5833. var num = Scalar.Repeat(target - current, 360.0);
  5834. if (num > 180.0) {
  5835. num -= 360.0;
  5836. }
  5837. return num;
  5838. };
  5839. /**
  5840. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5841. *
  5842. * The returned value will move back and forth between 0 and length
  5843. */
  5844. Scalar.PingPong = function (tx, length) {
  5845. var t = Scalar.Repeat(tx, length * 2.0);
  5846. return length - Math.abs(t - length);
  5847. };
  5848. /**
  5849. * Interpolates between min and max with smoothing at the limits.
  5850. *
  5851. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5852. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5853. */
  5854. Scalar.SmoothStep = function (from, to, tx) {
  5855. var t = Scalar.Clamp(tx);
  5856. t = -2.0 * t * t * t + 3.0 * t * t;
  5857. return to * t + from * (1.0 - t);
  5858. };
  5859. /**
  5860. * Moves a value current towards target.
  5861. *
  5862. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5863. * Negative values of maxDelta pushes the value away from target.
  5864. */
  5865. Scalar.MoveTowards = function (current, target, maxDelta) {
  5866. var result = 0;
  5867. if (Math.abs(target - current) <= maxDelta) {
  5868. result = target;
  5869. }
  5870. else {
  5871. result = current + Scalar.Sign(target - current) * maxDelta;
  5872. }
  5873. return result;
  5874. };
  5875. /**
  5876. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5877. *
  5878. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5879. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5880. */
  5881. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5882. var num = Scalar.DeltaAngle(current, target);
  5883. var result = 0;
  5884. if (-maxDelta < num && num < maxDelta) {
  5885. result = target;
  5886. }
  5887. else {
  5888. target = current + num;
  5889. result = Scalar.MoveTowards(current, target, maxDelta);
  5890. }
  5891. return result;
  5892. };
  5893. /**
  5894. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5895. */
  5896. Scalar.Lerp = function (start, end, amount) {
  5897. return start + ((end - start) * amount);
  5898. };
  5899. /**
  5900. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5901. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5902. */
  5903. Scalar.LerpAngle = function (start, end, amount) {
  5904. var num = Scalar.Repeat(end - start, 360.0);
  5905. if (num > 180.0) {
  5906. num -= 360.0;
  5907. }
  5908. return start + num * Scalar.Clamp(amount);
  5909. };
  5910. /**
  5911. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5912. */
  5913. Scalar.InverseLerp = function (a, b, value) {
  5914. var result = 0;
  5915. if (a != b) {
  5916. result = Scalar.Clamp((value - a) / (b - a));
  5917. }
  5918. else {
  5919. result = 0.0;
  5920. }
  5921. return result;
  5922. };
  5923. /**
  5924. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5925. */
  5926. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5927. var squared = amount * amount;
  5928. var cubed = amount * squared;
  5929. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5930. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5931. var part3 = (cubed - (2.0 * squared)) + amount;
  5932. var part4 = cubed - squared;
  5933. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5934. };
  5935. /**
  5936. * Returns a random float number between and min and max values
  5937. */
  5938. Scalar.RandomRange = function (min, max) {
  5939. if (min === max)
  5940. return min;
  5941. return ((Math.random() * (max - min)) + min);
  5942. };
  5943. /**
  5944. * This function returns percentage of a number in a given range.
  5945. *
  5946. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5947. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5948. */
  5949. Scalar.RangeToPercent = function (number, min, max) {
  5950. return ((number - min) / (max - min));
  5951. };
  5952. /**
  5953. * This function returns number that corresponds to the percentage in a given range.
  5954. *
  5955. * PercentToRange(0.34,0,100) will return 34.
  5956. */
  5957. Scalar.PercentToRange = function (percent, min, max) {
  5958. return ((max - min) * percent + min);
  5959. };
  5960. /**
  5961. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5962. * @param angle The angle to normalize in radian.
  5963. * @return The converted angle.
  5964. */
  5965. Scalar.NormalizeRadians = function (angle) {
  5966. // More precise but slower version kept for reference.
  5967. // angle = angle % Tools.TwoPi;
  5968. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5969. //if (angle > Math.PI) {
  5970. // angle -= Tools.TwoPi;
  5971. //}
  5972. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5973. return angle;
  5974. };
  5975. /**
  5976. * Two pi constants convenient for computation.
  5977. */
  5978. Scalar.TwoPi = Math.PI * 2;
  5979. return Scalar;
  5980. }());
  5981. BABYLON.Scalar = Scalar;
  5982. })(BABYLON || (BABYLON = {}));
  5983. //# sourceMappingURL=babylon.math.scalar.js.map
  5984. //# sourceMappingURL=babylon.mixins.js.map
  5985. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  5986. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  5987. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  5988. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  5989. //# sourceMappingURL=babylon.webgl2.js.map
  5990. var BABYLON;
  5991. (function (BABYLON) {
  5992. var __decoratorInitialStore = {};
  5993. var __mergedStore = {};
  5994. var _copySource = function (creationFunction, source, instanciate) {
  5995. var destination = creationFunction();
  5996. // Tags
  5997. if (BABYLON.Tags) {
  5998. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5999. }
  6000. var classStore = getMergedStore(destination);
  6001. // Properties
  6002. for (var property in classStore) {
  6003. var propertyDescriptor = classStore[property];
  6004. var sourceProperty = source[property];
  6005. var propertyType = propertyDescriptor.type;
  6006. if (sourceProperty !== undefined && sourceProperty !== null) {
  6007. switch (propertyType) {
  6008. case 0: // Value
  6009. case 6:// Mesh reference
  6010. destination[property] = sourceProperty;
  6011. break;
  6012. case 1:// Texture
  6013. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6014. break;
  6015. case 2: // Color3
  6016. case 3: // FresnelParameters
  6017. case 4: // Vector2
  6018. case 5: // Vector3
  6019. case 7: // Color Curves
  6020. case 10:// Quaternion
  6021. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6022. break;
  6023. }
  6024. }
  6025. }
  6026. return destination;
  6027. };
  6028. function getDirectStore(target) {
  6029. var classKey = target.getClassName();
  6030. if (!__decoratorInitialStore[classKey]) {
  6031. __decoratorInitialStore[classKey] = {};
  6032. }
  6033. return __decoratorInitialStore[classKey];
  6034. }
  6035. /**
  6036. * Return the list of properties flagged as serializable
  6037. * @param target: host object
  6038. */
  6039. function getMergedStore(target) {
  6040. var classKey = target.getClassName();
  6041. if (__mergedStore[classKey]) {
  6042. return __mergedStore[classKey];
  6043. }
  6044. __mergedStore[classKey] = {};
  6045. var store = __mergedStore[classKey];
  6046. var currentTarget = target;
  6047. var currentKey = classKey;
  6048. while (currentKey) {
  6049. var initialStore = __decoratorInitialStore[currentKey];
  6050. for (var property in initialStore) {
  6051. store[property] = initialStore[property];
  6052. }
  6053. var parent_1 = void 0;
  6054. var done = false;
  6055. do {
  6056. parent_1 = Object.getPrototypeOf(currentTarget);
  6057. if (!parent_1.getClassName) {
  6058. done = true;
  6059. break;
  6060. }
  6061. if (parent_1.getClassName() !== currentKey) {
  6062. break;
  6063. }
  6064. currentTarget = parent_1;
  6065. } while (parent_1);
  6066. if (done) {
  6067. break;
  6068. }
  6069. currentKey = parent_1.getClassName();
  6070. currentTarget = parent_1;
  6071. }
  6072. return store;
  6073. }
  6074. function generateSerializableMember(type, sourceName) {
  6075. return function (target, propertyKey) {
  6076. var classStore = getDirectStore(target);
  6077. if (!classStore[propertyKey]) {
  6078. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6079. }
  6080. };
  6081. }
  6082. function generateExpandMember(setCallback, targetKey) {
  6083. if (targetKey === void 0) { targetKey = null; }
  6084. return function (target, propertyKey) {
  6085. var key = targetKey || ("_" + propertyKey);
  6086. Object.defineProperty(target, propertyKey, {
  6087. get: function () {
  6088. return this[key];
  6089. },
  6090. set: function (value) {
  6091. if (this[key] === value) {
  6092. return;
  6093. }
  6094. this[key] = value;
  6095. target[setCallback].apply(this);
  6096. },
  6097. enumerable: true,
  6098. configurable: true
  6099. });
  6100. };
  6101. }
  6102. function expandToProperty(callback, targetKey) {
  6103. if (targetKey === void 0) { targetKey = null; }
  6104. return generateExpandMember(callback, targetKey);
  6105. }
  6106. BABYLON.expandToProperty = expandToProperty;
  6107. function serialize(sourceName) {
  6108. return generateSerializableMember(0, sourceName); // value member
  6109. }
  6110. BABYLON.serialize = serialize;
  6111. function serializeAsTexture(sourceName) {
  6112. return generateSerializableMember(1, sourceName); // texture member
  6113. }
  6114. BABYLON.serializeAsTexture = serializeAsTexture;
  6115. function serializeAsColor3(sourceName) {
  6116. return generateSerializableMember(2, sourceName); // color3 member
  6117. }
  6118. BABYLON.serializeAsColor3 = serializeAsColor3;
  6119. function serializeAsFresnelParameters(sourceName) {
  6120. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6121. }
  6122. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6123. function serializeAsVector2(sourceName) {
  6124. return generateSerializableMember(4, sourceName); // vector2 member
  6125. }
  6126. BABYLON.serializeAsVector2 = serializeAsVector2;
  6127. function serializeAsVector3(sourceName) {
  6128. return generateSerializableMember(5, sourceName); // vector3 member
  6129. }
  6130. BABYLON.serializeAsVector3 = serializeAsVector3;
  6131. function serializeAsMeshReference(sourceName) {
  6132. return generateSerializableMember(6, sourceName); // mesh reference member
  6133. }
  6134. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6135. function serializeAsColorCurves(sourceName) {
  6136. return generateSerializableMember(7, sourceName); // color curves
  6137. }
  6138. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6139. function serializeAsColor4(sourceName) {
  6140. return generateSerializableMember(8, sourceName); // color 4
  6141. }
  6142. BABYLON.serializeAsColor4 = serializeAsColor4;
  6143. function serializeAsImageProcessingConfiguration(sourceName) {
  6144. return generateSerializableMember(9, sourceName); // image processing
  6145. }
  6146. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6147. function serializeAsQuaternion(sourceName) {
  6148. return generateSerializableMember(10, sourceName); // quaternion member
  6149. }
  6150. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6151. var SerializationHelper = /** @class */ (function () {
  6152. function SerializationHelper() {
  6153. }
  6154. SerializationHelper.Serialize = function (entity, serializationObject) {
  6155. if (!serializationObject) {
  6156. serializationObject = {};
  6157. }
  6158. // Tags
  6159. if (BABYLON.Tags) {
  6160. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6161. }
  6162. var serializedProperties = getMergedStore(entity);
  6163. // Properties
  6164. for (var property in serializedProperties) {
  6165. var propertyDescriptor = serializedProperties[property];
  6166. var targetPropertyName = propertyDescriptor.sourceName || property;
  6167. var propertyType = propertyDescriptor.type;
  6168. var sourceProperty = entity[property];
  6169. if (sourceProperty !== undefined && sourceProperty !== null) {
  6170. switch (propertyType) {
  6171. case 0:// Value
  6172. serializationObject[targetPropertyName] = sourceProperty;
  6173. break;
  6174. case 1:// Texture
  6175. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6176. break;
  6177. case 2:// Color3
  6178. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6179. break;
  6180. case 3:// FresnelParameters
  6181. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6182. break;
  6183. case 4:// Vector2
  6184. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6185. break;
  6186. case 5:// Vector3
  6187. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6188. break;
  6189. case 6:// Mesh reference
  6190. serializationObject[targetPropertyName] = sourceProperty.id;
  6191. break;
  6192. case 7:// Color Curves
  6193. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6194. break;
  6195. case 8:// Color 4
  6196. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6197. break;
  6198. case 9:// Image Processing
  6199. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6200. break;
  6201. }
  6202. }
  6203. }
  6204. return serializationObject;
  6205. };
  6206. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6207. if (rootUrl === void 0) { rootUrl = null; }
  6208. var destination = creationFunction();
  6209. if (!rootUrl) {
  6210. rootUrl = "";
  6211. }
  6212. // Tags
  6213. if (BABYLON.Tags) {
  6214. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6215. }
  6216. var classStore = getMergedStore(destination);
  6217. // Properties
  6218. for (var property in classStore) {
  6219. var propertyDescriptor = classStore[property];
  6220. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6221. var propertyType = propertyDescriptor.type;
  6222. if (sourceProperty !== undefined && sourceProperty !== null) {
  6223. var dest = destination;
  6224. switch (propertyType) {
  6225. case 0:// Value
  6226. dest[property] = sourceProperty;
  6227. break;
  6228. case 1:// Texture
  6229. if (scene) {
  6230. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6231. }
  6232. break;
  6233. case 2:// Color3
  6234. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6235. break;
  6236. case 3:// FresnelParameters
  6237. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6238. break;
  6239. case 4:// Vector2
  6240. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6241. break;
  6242. case 5:// Vector3
  6243. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6244. break;
  6245. case 6:// Mesh reference
  6246. if (scene) {
  6247. dest[property] = scene.getLastMeshByID(sourceProperty);
  6248. }
  6249. break;
  6250. case 7:// Color Curves
  6251. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6252. break;
  6253. case 8:// Color 4
  6254. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6255. break;
  6256. case 9:// Image Processing
  6257. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6258. break;
  6259. }
  6260. }
  6261. }
  6262. return destination;
  6263. };
  6264. SerializationHelper.Clone = function (creationFunction, source) {
  6265. return _copySource(creationFunction, source, false);
  6266. };
  6267. SerializationHelper.Instanciate = function (creationFunction, source) {
  6268. return _copySource(creationFunction, source, true);
  6269. };
  6270. return SerializationHelper;
  6271. }());
  6272. BABYLON.SerializationHelper = SerializationHelper;
  6273. })(BABYLON || (BABYLON = {}));
  6274. //# sourceMappingURL=babylon.decorators.js.map
  6275. var BABYLON;
  6276. (function (BABYLON) {
  6277. /**
  6278. * A class serves as a medium between the observable and its observers
  6279. */
  6280. var EventState = /** @class */ (function () {
  6281. /**
  6282. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6283. */
  6284. function EventState(mask, skipNextObservers, target, currentTarget) {
  6285. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6286. this.initalize(mask, skipNextObservers, target, currentTarget);
  6287. }
  6288. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6289. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6290. this.mask = mask;
  6291. this.skipNextObservers = skipNextObservers;
  6292. this.target = target;
  6293. this.currentTarget = currentTarget;
  6294. return this;
  6295. };
  6296. return EventState;
  6297. }());
  6298. BABYLON.EventState = EventState;
  6299. /**
  6300. * Represent an Observer registered to a given Observable object.
  6301. */
  6302. var Observer = /** @class */ (function () {
  6303. function Observer(callback, mask, scope) {
  6304. if (scope === void 0) { scope = null; }
  6305. this.callback = callback;
  6306. this.mask = mask;
  6307. this.scope = scope;
  6308. }
  6309. return Observer;
  6310. }());
  6311. BABYLON.Observer = Observer;
  6312. /**
  6313. * Represent a list of observers registered to multiple Observables object.
  6314. */
  6315. var MultiObserver = /** @class */ (function () {
  6316. function MultiObserver() {
  6317. }
  6318. MultiObserver.prototype.dispose = function () {
  6319. if (this._observers && this._observables) {
  6320. for (var index = 0; index < this._observers.length; index++) {
  6321. this._observables[index].remove(this._observers[index]);
  6322. }
  6323. }
  6324. this._observers = null;
  6325. this._observables = null;
  6326. };
  6327. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6328. if (mask === void 0) { mask = -1; }
  6329. if (scope === void 0) { scope = null; }
  6330. var result = new MultiObserver();
  6331. result._observers = new Array();
  6332. result._observables = observables;
  6333. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6334. var observable = observables_1[_i];
  6335. var observer = observable.add(callback, mask, false, scope);
  6336. if (observer) {
  6337. result._observers.push(observer);
  6338. }
  6339. }
  6340. return result;
  6341. };
  6342. return MultiObserver;
  6343. }());
  6344. BABYLON.MultiObserver = MultiObserver;
  6345. /**
  6346. * The Observable class is a simple implementation of the Observable pattern.
  6347. * 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.
  6348. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6349. * 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).
  6350. * 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.
  6351. */
  6352. var Observable = /** @class */ (function () {
  6353. function Observable(onObserverAdded) {
  6354. this._observers = new Array();
  6355. this._eventState = new EventState(0);
  6356. if (onObserverAdded) {
  6357. this._onObserverAdded = onObserverAdded;
  6358. }
  6359. }
  6360. /**
  6361. * Create a new Observer with the specified callback
  6362. * @param callback the callback that will be executed for that Observer
  6363. * @param mask the mask used to filter observers
  6364. * @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.
  6365. * @param scope optional scope for the callback to be called from
  6366. */
  6367. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6368. if (mask === void 0) { mask = -1; }
  6369. if (insertFirst === void 0) { insertFirst = false; }
  6370. if (scope === void 0) { scope = null; }
  6371. if (!callback) {
  6372. return null;
  6373. }
  6374. var observer = new Observer(callback, mask, scope);
  6375. if (insertFirst) {
  6376. this._observers.unshift(observer);
  6377. }
  6378. else {
  6379. this._observers.push(observer);
  6380. }
  6381. if (this._onObserverAdded) {
  6382. this._onObserverAdded(observer);
  6383. }
  6384. return observer;
  6385. };
  6386. /**
  6387. * Remove an Observer from the Observable object
  6388. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6389. */
  6390. Observable.prototype.remove = function (observer) {
  6391. if (!observer) {
  6392. return false;
  6393. }
  6394. var index = this._observers.indexOf(observer);
  6395. if (index !== -1) {
  6396. this._observers.splice(index, 1);
  6397. return true;
  6398. }
  6399. return false;
  6400. };
  6401. /**
  6402. * Remove a callback from the Observable object
  6403. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6404. */
  6405. Observable.prototype.removeCallback = function (callback) {
  6406. for (var index = 0; index < this._observers.length; index++) {
  6407. if (this._observers[index].callback === callback) {
  6408. this._observers.splice(index, 1);
  6409. return true;
  6410. }
  6411. }
  6412. return false;
  6413. };
  6414. /**
  6415. * Notify all Observers by calling their respective callback with the given data
  6416. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6417. * @param eventData
  6418. * @param mask
  6419. */
  6420. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6421. if (mask === void 0) { mask = -1; }
  6422. if (!this._observers.length) {
  6423. return true;
  6424. }
  6425. var state = this._eventState;
  6426. state.mask = mask;
  6427. state.target = target;
  6428. state.currentTarget = currentTarget;
  6429. state.skipNextObservers = false;
  6430. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6431. var obs = _a[_i];
  6432. if (obs.mask & mask) {
  6433. if (obs.scope) {
  6434. obs.callback.apply(obs.scope, [eventData, state]);
  6435. }
  6436. else {
  6437. obs.callback(eventData, state);
  6438. }
  6439. }
  6440. if (state.skipNextObservers) {
  6441. return false;
  6442. }
  6443. }
  6444. return true;
  6445. };
  6446. /**
  6447. * Notify a specific observer
  6448. * @param eventData
  6449. * @param mask
  6450. */
  6451. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6452. if (mask === void 0) { mask = -1; }
  6453. var state = this._eventState;
  6454. state.mask = mask;
  6455. state.skipNextObservers = false;
  6456. observer.callback(eventData, state);
  6457. };
  6458. /**
  6459. * return true is the Observable has at least one Observer registered
  6460. */
  6461. Observable.prototype.hasObservers = function () {
  6462. return this._observers.length > 0;
  6463. };
  6464. /**
  6465. * Clear the list of observers
  6466. */
  6467. Observable.prototype.clear = function () {
  6468. this._observers = new Array();
  6469. this._onObserverAdded = null;
  6470. };
  6471. /**
  6472. * Clone the current observable
  6473. */
  6474. Observable.prototype.clone = function () {
  6475. var result = new Observable();
  6476. result._observers = this._observers.slice(0);
  6477. return result;
  6478. };
  6479. /**
  6480. * Does this observable handles observer registered with a given mask
  6481. * @param {number} trigger - the mask to be tested
  6482. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6483. **/
  6484. Observable.prototype.hasSpecificMask = function (mask) {
  6485. if (mask === void 0) { mask = -1; }
  6486. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6487. var obs = _a[_i];
  6488. if (obs.mask & mask || obs.mask === mask) {
  6489. return true;
  6490. }
  6491. }
  6492. return false;
  6493. };
  6494. return Observable;
  6495. }());
  6496. BABYLON.Observable = Observable;
  6497. })(BABYLON || (BABYLON = {}));
  6498. //# sourceMappingURL=babylon.observable.js.map
  6499. var BABYLON;
  6500. (function (BABYLON) {
  6501. var SmartArray = /** @class */ (function () {
  6502. function SmartArray(capacity) {
  6503. this.length = 0;
  6504. this.data = new Array(capacity);
  6505. this._id = SmartArray._GlobalId++;
  6506. }
  6507. SmartArray.prototype.push = function (value) {
  6508. this.data[this.length++] = value;
  6509. if (this.length > this.data.length) {
  6510. this.data.length *= 2;
  6511. }
  6512. };
  6513. SmartArray.prototype.forEach = function (func) {
  6514. for (var index = 0; index < this.length; index++) {
  6515. func(this.data[index]);
  6516. }
  6517. };
  6518. SmartArray.prototype.sort = function (compareFn) {
  6519. this.data.sort(compareFn);
  6520. };
  6521. SmartArray.prototype.reset = function () {
  6522. this.length = 0;
  6523. };
  6524. SmartArray.prototype.dispose = function () {
  6525. this.reset();
  6526. if (this.data) {
  6527. this.data.length = 0;
  6528. this.data = [];
  6529. }
  6530. };
  6531. SmartArray.prototype.concat = function (array) {
  6532. if (array.length === 0) {
  6533. return;
  6534. }
  6535. if (this.length + array.length > this.data.length) {
  6536. this.data.length = (this.length + array.length) * 2;
  6537. }
  6538. for (var index = 0; index < array.length; index++) {
  6539. this.data[this.length++] = (array.data || array)[index];
  6540. }
  6541. };
  6542. SmartArray.prototype.indexOf = function (value) {
  6543. var position = this.data.indexOf(value);
  6544. if (position >= this.length) {
  6545. return -1;
  6546. }
  6547. return position;
  6548. };
  6549. SmartArray.prototype.contains = function (value) {
  6550. return this.data.indexOf(value) !== -1;
  6551. };
  6552. // Statics
  6553. SmartArray._GlobalId = 0;
  6554. return SmartArray;
  6555. }());
  6556. BABYLON.SmartArray = SmartArray;
  6557. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6558. __extends(SmartArrayNoDuplicate, _super);
  6559. function SmartArrayNoDuplicate() {
  6560. var _this = _super !== null && _super.apply(this, arguments) || this;
  6561. _this._duplicateId = 0;
  6562. return _this;
  6563. }
  6564. SmartArrayNoDuplicate.prototype.push = function (value) {
  6565. _super.prototype.push.call(this, value);
  6566. if (!value.__smartArrayFlags) {
  6567. value.__smartArrayFlags = {};
  6568. }
  6569. value.__smartArrayFlags[this._id] = this._duplicateId;
  6570. };
  6571. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6572. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6573. return false;
  6574. }
  6575. this.push(value);
  6576. return true;
  6577. };
  6578. SmartArrayNoDuplicate.prototype.reset = function () {
  6579. _super.prototype.reset.call(this);
  6580. this._duplicateId++;
  6581. };
  6582. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6583. if (array.length === 0) {
  6584. return;
  6585. }
  6586. if (this.length + array.length > this.data.length) {
  6587. this.data.length = (this.length + array.length) * 2;
  6588. }
  6589. for (var index = 0; index < array.length; index++) {
  6590. var item = (array.data || array)[index];
  6591. this.pushNoDuplicate(item);
  6592. }
  6593. };
  6594. return SmartArrayNoDuplicate;
  6595. }(SmartArray));
  6596. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6597. })(BABYLON || (BABYLON = {}));
  6598. //# sourceMappingURL=babylon.smartArray.js.map
  6599. var BABYLON;
  6600. (function (BABYLON) {
  6601. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6602. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6603. var LoadFileError = /** @class */ (function (_super) {
  6604. __extends(LoadFileError, _super);
  6605. function LoadFileError(message, request) {
  6606. var _this = _super.call(this, message) || this;
  6607. _this.request = request;
  6608. _this.name = "LoadFileError";
  6609. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6610. return _this;
  6611. }
  6612. // Polyfill for Object.setPrototypeOf if necessary.
  6613. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6614. return LoadFileError;
  6615. }(Error));
  6616. BABYLON.LoadFileError = LoadFileError;
  6617. var RetryStrategy = /** @class */ (function () {
  6618. function RetryStrategy() {
  6619. }
  6620. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6621. if (maxRetries === void 0) { maxRetries = 3; }
  6622. if (baseInterval === void 0) { baseInterval = 500; }
  6623. return function (url, request, retryIndex) {
  6624. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6625. return -1;
  6626. }
  6627. return Math.pow(2, retryIndex) * baseInterval;
  6628. };
  6629. };
  6630. return RetryStrategy;
  6631. }());
  6632. BABYLON.RetryStrategy = RetryStrategy;
  6633. // Screenshots
  6634. var screenshotCanvas;
  6635. var cloneValue = function (source, destinationObject) {
  6636. if (!source)
  6637. return null;
  6638. if (source instanceof BABYLON.Mesh) {
  6639. return null;
  6640. }
  6641. if (source instanceof BABYLON.SubMesh) {
  6642. return source.clone(destinationObject);
  6643. }
  6644. else if (source.clone) {
  6645. return source.clone();
  6646. }
  6647. return null;
  6648. };
  6649. var Tools = /** @class */ (function () {
  6650. function Tools() {
  6651. }
  6652. /**
  6653. * Interpolates between a and b via alpha
  6654. * @param a The lower value (returned when alpha = 0)
  6655. * @param b The upper value (returned when alpha = 1)
  6656. * @param alpha The interpolation-factor
  6657. * @return The mixed value
  6658. */
  6659. Tools.Mix = function (a, b, alpha) {
  6660. return a * (1 - alpha) + b * alpha;
  6661. };
  6662. Tools.Instantiate = function (className) {
  6663. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6664. return Tools.RegisteredExternalClasses[className];
  6665. }
  6666. var arr = className.split(".");
  6667. var fn = (window || this);
  6668. for (var i = 0, len = arr.length; i < len; i++) {
  6669. fn = fn[arr[i]];
  6670. }
  6671. if (typeof fn !== "function") {
  6672. return null;
  6673. }
  6674. return fn;
  6675. };
  6676. Tools.SetImmediate = function (action) {
  6677. if (window.setImmediate) {
  6678. window.setImmediate(action);
  6679. }
  6680. else {
  6681. setTimeout(action, 1);
  6682. }
  6683. };
  6684. Tools.IsExponentOfTwo = function (value) {
  6685. var count = 1;
  6686. do {
  6687. count *= 2;
  6688. } while (count < value);
  6689. return count === value;
  6690. };
  6691. /**
  6692. * Find the next highest power of two.
  6693. * @param x Number to start search from.
  6694. * @return Next highest power of two.
  6695. */
  6696. Tools.CeilingPOT = function (x) {
  6697. x--;
  6698. x |= x >> 1;
  6699. x |= x >> 2;
  6700. x |= x >> 4;
  6701. x |= x >> 8;
  6702. x |= x >> 16;
  6703. x++;
  6704. return x;
  6705. };
  6706. /**
  6707. * Find the next lowest power of two.
  6708. * @param x Number to start search from.
  6709. * @return Next lowest power of two.
  6710. */
  6711. Tools.FloorPOT = function (x) {
  6712. x = x | (x >> 1);
  6713. x = x | (x >> 2);
  6714. x = x | (x >> 4);
  6715. x = x | (x >> 8);
  6716. x = x | (x >> 16);
  6717. return x - (x >> 1);
  6718. };
  6719. /**
  6720. * Find the nearest power of two.
  6721. * @param x Number to start search from.
  6722. * @return Next nearest power of two.
  6723. */
  6724. Tools.NearestPOT = function (x) {
  6725. var c = Tools.CeilingPOT(x);
  6726. var f = Tools.FloorPOT(x);
  6727. return (c - x) > (x - f) ? f : c;
  6728. };
  6729. Tools.GetExponentOfTwo = function (value, max, mode) {
  6730. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6731. var pot;
  6732. switch (mode) {
  6733. case BABYLON.Engine.SCALEMODE_FLOOR:
  6734. pot = Tools.FloorPOT(value);
  6735. break;
  6736. case BABYLON.Engine.SCALEMODE_NEAREST:
  6737. pot = Tools.NearestPOT(value);
  6738. break;
  6739. case BABYLON.Engine.SCALEMODE_CEILING:
  6740. default:
  6741. pot = Tools.CeilingPOT(value);
  6742. break;
  6743. }
  6744. return Math.min(pot, max);
  6745. };
  6746. Tools.GetFilename = function (path) {
  6747. var index = path.lastIndexOf("/");
  6748. if (index < 0)
  6749. return path;
  6750. return path.substring(index + 1);
  6751. };
  6752. Tools.GetFolderPath = function (uri) {
  6753. var index = uri.lastIndexOf("/");
  6754. if (index < 0)
  6755. return "";
  6756. return uri.substring(0, index + 1);
  6757. };
  6758. Tools.GetDOMTextContent = function (element) {
  6759. var result = "";
  6760. var child = element.firstChild;
  6761. while (child) {
  6762. if (child.nodeType === 3) {
  6763. result += child.textContent;
  6764. }
  6765. child = child.nextSibling;
  6766. }
  6767. return result;
  6768. };
  6769. Tools.ToDegrees = function (angle) {
  6770. return angle * 180 / Math.PI;
  6771. };
  6772. Tools.ToRadians = function (angle) {
  6773. return angle * Math.PI / 180;
  6774. };
  6775. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6776. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6777. var output = "";
  6778. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6779. var i = 0;
  6780. var bytes = new Uint8Array(buffer);
  6781. while (i < bytes.length) {
  6782. chr1 = bytes[i++];
  6783. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6784. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6785. enc1 = chr1 >> 2;
  6786. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6787. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6788. enc4 = chr3 & 63;
  6789. if (isNaN(chr2)) {
  6790. enc3 = enc4 = 64;
  6791. }
  6792. else if (isNaN(chr3)) {
  6793. enc4 = 64;
  6794. }
  6795. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6796. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6797. }
  6798. return "data:image/png;base64," + output;
  6799. };
  6800. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6801. if (bias === void 0) { bias = null; }
  6802. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6803. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6804. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6805. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6806. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6807. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6808. }
  6809. if (bias) {
  6810. minimum.x -= minimum.x * bias.x + bias.y;
  6811. minimum.y -= minimum.y * bias.x + bias.y;
  6812. minimum.z -= minimum.z * bias.x + bias.y;
  6813. maximum.x += maximum.x * bias.x + bias.y;
  6814. maximum.y += maximum.y * bias.x + bias.y;
  6815. maximum.z += maximum.z * bias.x + bias.y;
  6816. }
  6817. return {
  6818. minimum: minimum,
  6819. maximum: maximum
  6820. };
  6821. };
  6822. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6823. if (bias === void 0) { bias = null; }
  6824. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6825. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6826. if (!stride) {
  6827. stride = 3;
  6828. }
  6829. for (var index = start; index < start + count; index++) {
  6830. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6831. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6832. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6833. }
  6834. if (bias) {
  6835. minimum.x -= minimum.x * bias.x + bias.y;
  6836. minimum.y -= minimum.y * bias.x + bias.y;
  6837. minimum.z -= minimum.z * bias.x + bias.y;
  6838. maximum.x += maximum.x * bias.x + bias.y;
  6839. maximum.y += maximum.y * bias.x + bias.y;
  6840. maximum.z += maximum.z * bias.x + bias.y;
  6841. }
  6842. return {
  6843. minimum: minimum,
  6844. maximum: maximum
  6845. };
  6846. };
  6847. Tools.Vector2ArrayFeeder = function (array) {
  6848. return function (index) {
  6849. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6850. var length = isFloatArray ? array.length / 2 : array.length;
  6851. if (index >= length) {
  6852. return null;
  6853. }
  6854. if (isFloatArray) {
  6855. var fa = array;
  6856. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6857. }
  6858. var a = array;
  6859. return a[index];
  6860. };
  6861. };
  6862. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6863. if (bias === void 0) { bias = null; }
  6864. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6865. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6866. var i = 0;
  6867. var cur = feeder(i++);
  6868. while (cur) {
  6869. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6870. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6871. cur = feeder(i++);
  6872. }
  6873. if (bias) {
  6874. minimum.x -= minimum.x * bias.x + bias.y;
  6875. minimum.y -= minimum.y * bias.x + bias.y;
  6876. maximum.x += maximum.x * bias.x + bias.y;
  6877. maximum.y += maximum.y * bias.x + bias.y;
  6878. }
  6879. return {
  6880. minimum: minimum,
  6881. maximum: maximum
  6882. };
  6883. };
  6884. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6885. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6886. return null;
  6887. return Array.isArray(obj) ? obj : [obj];
  6888. };
  6889. // Misc.
  6890. Tools.GetPointerPrefix = function () {
  6891. var eventPrefix = "pointer";
  6892. // Check if pointer events are supported
  6893. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6894. eventPrefix = "mouse";
  6895. }
  6896. return eventPrefix;
  6897. };
  6898. /**
  6899. * @param func - the function to be called
  6900. * @param requester - the object that will request the next frame. Falls back to window.
  6901. */
  6902. Tools.QueueNewFrame = function (func, requester) {
  6903. if (!Tools.IsWindowObjectExist()) {
  6904. return setTimeout(func, 16);
  6905. }
  6906. if (!requester) {
  6907. requester = window;
  6908. }
  6909. if (requester.requestAnimationFrame) {
  6910. return requester.requestAnimationFrame(func);
  6911. }
  6912. else if (requester.msRequestAnimationFrame) {
  6913. return requester.msRequestAnimationFrame(func);
  6914. }
  6915. else if (requester.webkitRequestAnimationFrame) {
  6916. return requester.webkitRequestAnimationFrame(func);
  6917. }
  6918. else if (requester.mozRequestAnimationFrame) {
  6919. return requester.mozRequestAnimationFrame(func);
  6920. }
  6921. else if (requester.oRequestAnimationFrame) {
  6922. return requester.oRequestAnimationFrame(func);
  6923. }
  6924. else {
  6925. return window.setTimeout(func, 16);
  6926. }
  6927. };
  6928. Tools.RequestFullscreen = function (element) {
  6929. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6930. if (!requestFunction)
  6931. return;
  6932. requestFunction.call(element);
  6933. };
  6934. Tools.ExitFullscreen = function () {
  6935. if (document.exitFullscreen) {
  6936. document.exitFullscreen();
  6937. }
  6938. else if (document.mozCancelFullScreen) {
  6939. document.mozCancelFullScreen();
  6940. }
  6941. else if (document.webkitCancelFullScreen) {
  6942. document.webkitCancelFullScreen();
  6943. }
  6944. else if (document.msCancelFullScreen) {
  6945. document.msCancelFullScreen();
  6946. }
  6947. };
  6948. Tools.SetCorsBehavior = function (url, element) {
  6949. if (url && url.indexOf("data:") === 0) {
  6950. return;
  6951. }
  6952. if (Tools.CorsBehavior) {
  6953. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6954. element.crossOrigin = Tools.CorsBehavior;
  6955. }
  6956. else {
  6957. var result = Tools.CorsBehavior(url);
  6958. if (result) {
  6959. element.crossOrigin = result;
  6960. }
  6961. }
  6962. }
  6963. };
  6964. // External files
  6965. Tools.CleanUrl = function (url) {
  6966. url = url.replace(/#/mg, "%23");
  6967. return url;
  6968. };
  6969. Tools.LoadImage = function (url, onLoad, onError, database) {
  6970. if (url instanceof ArrayBuffer) {
  6971. url = Tools.EncodeArrayBufferTobase64(url);
  6972. }
  6973. url = Tools.CleanUrl(url);
  6974. url = Tools.PreprocessUrl(url);
  6975. var img = new Image();
  6976. Tools.SetCorsBehavior(url, img);
  6977. img.onload = function () {
  6978. onLoad(img);
  6979. };
  6980. img.onerror = function (err) {
  6981. Tools.Error("Error while trying to load image: " + url);
  6982. if (onError) {
  6983. onError("Error while trying to load image: " + url, err);
  6984. }
  6985. };
  6986. var noIndexedDB = function () {
  6987. img.src = url;
  6988. };
  6989. var loadFromIndexedDB = function () {
  6990. if (database) {
  6991. database.loadImageFromDB(url, img);
  6992. }
  6993. };
  6994. //ANY database to do!
  6995. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6996. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6997. }
  6998. else {
  6999. if (url.indexOf("file:") !== -1) {
  7000. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7001. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7002. try {
  7003. var blobURL;
  7004. try {
  7005. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7006. }
  7007. catch (ex) {
  7008. // Chrome doesn't support oneTimeOnly parameter
  7009. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7010. }
  7011. img.src = blobURL;
  7012. }
  7013. catch (e) {
  7014. img.src = "";
  7015. }
  7016. return img;
  7017. }
  7018. }
  7019. noIndexedDB();
  7020. }
  7021. return img;
  7022. };
  7023. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7024. url = Tools.CleanUrl(url);
  7025. url = Tools.PreprocessUrl(url);
  7026. // If file and file input are set
  7027. if (url.indexOf("file:") !== -1) {
  7028. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7029. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7030. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7031. }
  7032. }
  7033. var loadUrl = Tools.BaseUrl + url;
  7034. var aborted = false;
  7035. var fileRequest = {
  7036. onCompleteObservable: new BABYLON.Observable(),
  7037. abort: function () { return aborted = true; },
  7038. };
  7039. var requestFile = function () {
  7040. var request = new XMLHttpRequest();
  7041. var retryHandle = null;
  7042. fileRequest.abort = function () {
  7043. aborted = true;
  7044. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7045. request.abort();
  7046. }
  7047. if (retryHandle !== null) {
  7048. clearTimeout(retryHandle);
  7049. retryHandle = null;
  7050. }
  7051. };
  7052. var retryLoop = function (retryIndex) {
  7053. request.open('GET', loadUrl, true);
  7054. if (useArrayBuffer) {
  7055. request.responseType = "arraybuffer";
  7056. }
  7057. if (onProgress) {
  7058. request.addEventListener("progress", onProgress);
  7059. }
  7060. var onLoadEnd = function () {
  7061. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7062. };
  7063. request.addEventListener("loadend", onLoadEnd);
  7064. var onReadyStateChange = function () {
  7065. if (aborted) {
  7066. return;
  7067. }
  7068. // In case of undefined state in some browsers.
  7069. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7070. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7071. request.removeEventListener("readystatechange", onReadyStateChange);
  7072. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7073. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7074. return;
  7075. }
  7076. var retryStrategy = Tools.DefaultRetryStrategy;
  7077. if (retryStrategy) {
  7078. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7079. if (waitTime !== -1) {
  7080. // Prevent the request from completing for retry.
  7081. request.removeEventListener("loadend", onLoadEnd);
  7082. request = new XMLHttpRequest();
  7083. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7084. return;
  7085. }
  7086. }
  7087. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7088. if (onError) {
  7089. onError(request, e);
  7090. }
  7091. else {
  7092. throw e;
  7093. }
  7094. }
  7095. };
  7096. request.addEventListener("readystatechange", onReadyStateChange);
  7097. request.send();
  7098. };
  7099. retryLoop(0);
  7100. };
  7101. // Caching all files
  7102. if (database && database.enableSceneOffline) {
  7103. var noIndexedDB_1 = function () {
  7104. if (!aborted) {
  7105. requestFile();
  7106. }
  7107. };
  7108. var loadFromIndexedDB = function () {
  7109. // TODO: database needs to support aborting and should return a IFileRequest
  7110. if (aborted) {
  7111. return;
  7112. }
  7113. if (database) {
  7114. database.loadFileFromDB(url, function (data) {
  7115. if (!aborted) {
  7116. onSuccess(data);
  7117. }
  7118. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7119. }, onProgress ? function (event) {
  7120. if (!aborted) {
  7121. onProgress(event);
  7122. }
  7123. } : undefined, noIndexedDB_1, useArrayBuffer);
  7124. }
  7125. };
  7126. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7127. }
  7128. else {
  7129. requestFile();
  7130. }
  7131. return fileRequest;
  7132. };
  7133. /**
  7134. * Load a script (identified by an url). When the url returns, the
  7135. * content of this file is added into a new script element, attached to the DOM (body element)
  7136. */
  7137. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7138. var head = document.getElementsByTagName('head')[0];
  7139. var script = document.createElement('script');
  7140. script.type = 'text/javascript';
  7141. script.src = scriptUrl;
  7142. script.onload = function () {
  7143. if (onSuccess) {
  7144. onSuccess();
  7145. }
  7146. };
  7147. script.onerror = function (e) {
  7148. if (onError) {
  7149. onError("Unable to load script", e);
  7150. }
  7151. };
  7152. head.appendChild(script);
  7153. };
  7154. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7155. var reader = new FileReader();
  7156. var request = {
  7157. onCompleteObservable: new BABYLON.Observable(),
  7158. abort: function () { return reader.abort(); },
  7159. };
  7160. reader.onloadend = function (e) {
  7161. request.onCompleteObservable.notifyObservers(request);
  7162. };
  7163. reader.onload = function (e) {
  7164. //target doesn't have result from ts 1.3
  7165. callback(e.target['result']);
  7166. };
  7167. reader.onprogress = progressCallback;
  7168. reader.readAsDataURL(fileToLoad);
  7169. return request;
  7170. };
  7171. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7172. var reader = new FileReader();
  7173. var request = {
  7174. onCompleteObservable: new BABYLON.Observable(),
  7175. abort: function () { return reader.abort(); },
  7176. };
  7177. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7178. reader.onerror = function (e) {
  7179. Tools.Log("Error while reading file: " + fileToLoad.name);
  7180. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7181. };
  7182. reader.onload = function (e) {
  7183. //target doesn't have result from ts 1.3
  7184. callback(e.target['result']);
  7185. };
  7186. if (progressCallBack) {
  7187. reader.onprogress = progressCallBack;
  7188. }
  7189. if (!useArrayBuffer) {
  7190. // Asynchronous read
  7191. reader.readAsText(fileToLoad);
  7192. }
  7193. else {
  7194. reader.readAsArrayBuffer(fileToLoad);
  7195. }
  7196. return request;
  7197. };
  7198. //returns a downloadable url to a file content.
  7199. Tools.FileAsURL = function (content) {
  7200. var fileBlob = new Blob([content]);
  7201. var url = window.URL || window.webkitURL;
  7202. var link = url.createObjectURL(fileBlob);
  7203. return link;
  7204. };
  7205. // Misc.
  7206. Tools.Format = function (value, decimals) {
  7207. if (decimals === void 0) { decimals = 2; }
  7208. return value.toFixed(decimals);
  7209. };
  7210. Tools.CheckExtends = function (v, min, max) {
  7211. if (v.x < min.x)
  7212. min.x = v.x;
  7213. if (v.y < min.y)
  7214. min.y = v.y;
  7215. if (v.z < min.z)
  7216. min.z = v.z;
  7217. if (v.x > max.x)
  7218. max.x = v.x;
  7219. if (v.y > max.y)
  7220. max.y = v.y;
  7221. if (v.z > max.z)
  7222. max.z = v.z;
  7223. };
  7224. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7225. for (var prop in source) {
  7226. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7227. continue;
  7228. }
  7229. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7230. continue;
  7231. }
  7232. var sourceValue = source[prop];
  7233. var typeOfSourceValue = typeof sourceValue;
  7234. if (typeOfSourceValue === "function") {
  7235. continue;
  7236. }
  7237. if (typeOfSourceValue === "object") {
  7238. if (sourceValue instanceof Array) {
  7239. destination[prop] = [];
  7240. if (sourceValue.length > 0) {
  7241. if (typeof sourceValue[0] == "object") {
  7242. for (var index = 0; index < sourceValue.length; index++) {
  7243. var clonedValue = cloneValue(sourceValue[index], destination);
  7244. if (destination[prop].indexOf(clonedValue) === -1) {
  7245. destination[prop].push(clonedValue);
  7246. }
  7247. }
  7248. }
  7249. else {
  7250. destination[prop] = sourceValue.slice(0);
  7251. }
  7252. }
  7253. }
  7254. else {
  7255. destination[prop] = cloneValue(sourceValue, destination);
  7256. }
  7257. }
  7258. else {
  7259. destination[prop] = sourceValue;
  7260. }
  7261. }
  7262. };
  7263. Tools.IsEmpty = function (obj) {
  7264. for (var i in obj) {
  7265. if (obj.hasOwnProperty(i)) {
  7266. return false;
  7267. }
  7268. }
  7269. return true;
  7270. };
  7271. Tools.RegisterTopRootEvents = function (events) {
  7272. for (var index = 0; index < events.length; index++) {
  7273. var event = events[index];
  7274. window.addEventListener(event.name, event.handler, false);
  7275. try {
  7276. if (window.parent) {
  7277. window.parent.addEventListener(event.name, event.handler, false);
  7278. }
  7279. }
  7280. catch (e) {
  7281. // Silently fails...
  7282. }
  7283. }
  7284. };
  7285. Tools.UnregisterTopRootEvents = function (events) {
  7286. for (var index = 0; index < events.length; index++) {
  7287. var event = events[index];
  7288. window.removeEventListener(event.name, event.handler);
  7289. try {
  7290. if (window.parent) {
  7291. window.parent.removeEventListener(event.name, event.handler);
  7292. }
  7293. }
  7294. catch (e) {
  7295. // Silently fails...
  7296. }
  7297. }
  7298. };
  7299. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7300. if (mimeType === void 0) { mimeType = "image/png"; }
  7301. // Read the contents of the framebuffer
  7302. var numberOfChannelsByLine = width * 4;
  7303. var halfHeight = height / 2;
  7304. //Reading datas from WebGL
  7305. var data = engine.readPixels(0, 0, width, height);
  7306. //To flip image on Y axis.
  7307. for (var i = 0; i < halfHeight; i++) {
  7308. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7309. var currentCell = j + i * numberOfChannelsByLine;
  7310. var targetLine = height - i - 1;
  7311. var targetCell = j + targetLine * numberOfChannelsByLine;
  7312. var temp = data[currentCell];
  7313. data[currentCell] = data[targetCell];
  7314. data[targetCell] = temp;
  7315. }
  7316. }
  7317. // Create a 2D canvas to store the result
  7318. if (!screenshotCanvas) {
  7319. screenshotCanvas = document.createElement('canvas');
  7320. }
  7321. screenshotCanvas.width = width;
  7322. screenshotCanvas.height = height;
  7323. var context = screenshotCanvas.getContext('2d');
  7324. if (context) {
  7325. // Copy the pixels to a 2D canvas
  7326. var imageData = context.createImageData(width, height);
  7327. var castData = (imageData.data);
  7328. castData.set(data);
  7329. context.putImageData(imageData, 0, 0);
  7330. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7331. }
  7332. };
  7333. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7334. if (mimeType === void 0) { mimeType = "image/png"; }
  7335. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7336. if (successCallback) {
  7337. successCallback(base64Image);
  7338. }
  7339. else {
  7340. // We need HTMLCanvasElement.toBlob for HD screenshots
  7341. if (!screenshotCanvas.toBlob) {
  7342. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7343. screenshotCanvas.toBlob = function (callback, type, quality) {
  7344. var _this = this;
  7345. setTimeout(function () {
  7346. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7347. for (var i = 0; i < len; i++) {
  7348. arr[i] = binStr.charCodeAt(i);
  7349. }
  7350. callback(new Blob([arr], { type: type || 'image/png' }));
  7351. });
  7352. };
  7353. }
  7354. screenshotCanvas.toBlob(function (blob) {
  7355. var url = URL.createObjectURL(blob);
  7356. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7357. if (("download" in document.createElement("a"))) {
  7358. var a = window.document.createElement("a");
  7359. a.href = url;
  7360. if (fileName) {
  7361. a.setAttribute("download", fileName);
  7362. }
  7363. else {
  7364. var date = new Date();
  7365. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7366. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7367. }
  7368. window.document.body.appendChild(a);
  7369. a.addEventListener("click", function () {
  7370. if (a.parentElement) {
  7371. a.parentElement.removeChild(a);
  7372. }
  7373. });
  7374. a.click();
  7375. }
  7376. else {
  7377. var newWindow = window.open("");
  7378. if (!newWindow)
  7379. return;
  7380. var img = newWindow.document.createElement("img");
  7381. img.onload = function () {
  7382. // no longer need to read the blob so it's revoked
  7383. URL.revokeObjectURL(url);
  7384. };
  7385. img.src = url;
  7386. newWindow.document.body.appendChild(img);
  7387. }
  7388. });
  7389. }
  7390. };
  7391. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7392. if (mimeType === void 0) { mimeType = "image/png"; }
  7393. var width;
  7394. var height;
  7395. // If a precision value is specified
  7396. if (size.precision) {
  7397. width = Math.round(engine.getRenderWidth() * size.precision);
  7398. height = Math.round(width / engine.getAspectRatio(camera));
  7399. }
  7400. else if (size.width && size.height) {
  7401. width = size.width;
  7402. height = size.height;
  7403. }
  7404. else if (size.width && !size.height) {
  7405. width = size.width;
  7406. height = Math.round(width / engine.getAspectRatio(camera));
  7407. }
  7408. else if (size.height && !size.width) {
  7409. height = size.height;
  7410. width = Math.round(height * engine.getAspectRatio(camera));
  7411. }
  7412. else if (!isNaN(size)) {
  7413. height = size;
  7414. width = size;
  7415. }
  7416. else {
  7417. Tools.Error("Invalid 'size' parameter !");
  7418. return;
  7419. }
  7420. if (!screenshotCanvas) {
  7421. screenshotCanvas = document.createElement('canvas');
  7422. }
  7423. screenshotCanvas.width = width;
  7424. screenshotCanvas.height = height;
  7425. var renderContext = screenshotCanvas.getContext("2d");
  7426. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7427. var newWidth = width;
  7428. var newHeight = newWidth / ratio;
  7429. if (newHeight > height) {
  7430. newHeight = height;
  7431. newWidth = newHeight * ratio;
  7432. }
  7433. var offsetX = Math.max(0, width - newWidth) / 2;
  7434. var offsetY = Math.max(0, height - newHeight) / 2;
  7435. var renderingCanvas = engine.getRenderingCanvas();
  7436. if (renderContext && renderingCanvas) {
  7437. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7438. }
  7439. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7440. };
  7441. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7442. if (mimeType === void 0) { mimeType = "image/png"; }
  7443. if (samples === void 0) { samples = 1; }
  7444. if (antialiasing === void 0) { antialiasing = false; }
  7445. var width;
  7446. var height;
  7447. //If a precision value is specified
  7448. if (size.precision) {
  7449. width = Math.round(engine.getRenderWidth() * size.precision);
  7450. height = Math.round(width / engine.getAspectRatio(camera));
  7451. size = { width: width, height: height };
  7452. }
  7453. else if (size.width && size.height) {
  7454. width = size.width;
  7455. height = size.height;
  7456. }
  7457. else if (size.width && !size.height) {
  7458. width = size.width;
  7459. height = Math.round(width / engine.getAspectRatio(camera));
  7460. size = { width: width, height: height };
  7461. }
  7462. else if (size.height && !size.width) {
  7463. height = size.height;
  7464. width = Math.round(height * engine.getAspectRatio(camera));
  7465. size = { width: width, height: height };
  7466. }
  7467. else if (!isNaN(size)) {
  7468. height = size;
  7469. width = size;
  7470. }
  7471. else {
  7472. Tools.Error("Invalid 'size' parameter !");
  7473. return;
  7474. }
  7475. var scene = camera.getScene();
  7476. var previousCamera = null;
  7477. if (scene.activeCamera !== camera) {
  7478. previousCamera = scene.activeCamera;
  7479. scene.activeCamera = camera;
  7480. }
  7481. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7482. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7483. texture.renderList = null;
  7484. texture.samples = samples;
  7485. if (antialiasing) {
  7486. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7487. }
  7488. texture.onAfterRenderObservable.add(function () {
  7489. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7490. });
  7491. scene.incrementRenderId();
  7492. scene.resetCachedMaterial();
  7493. texture.render(true);
  7494. texture.dispose();
  7495. if (previousCamera) {
  7496. scene.activeCamera = previousCamera;
  7497. }
  7498. camera.getProjectionMatrix(true); // Force cache refresh;
  7499. };
  7500. // XHR response validator for local file scenario
  7501. Tools.ValidateXHRData = function (xhr, dataType) {
  7502. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7503. if (dataType === void 0) { dataType = 7; }
  7504. try {
  7505. if (dataType & 1) {
  7506. if (xhr.responseText && xhr.responseText.length > 0) {
  7507. return true;
  7508. }
  7509. else if (dataType === 1) {
  7510. return false;
  7511. }
  7512. }
  7513. if (dataType & 2) {
  7514. // Check header width and height since there is no "TGA" magic number
  7515. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7516. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7517. return true;
  7518. }
  7519. else if (dataType === 2) {
  7520. return false;
  7521. }
  7522. }
  7523. if (dataType & 4) {
  7524. // Check for the "DDS" magic number
  7525. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7526. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7527. return true;
  7528. }
  7529. else {
  7530. return false;
  7531. }
  7532. }
  7533. }
  7534. catch (e) {
  7535. // Global protection
  7536. }
  7537. return false;
  7538. };
  7539. /**
  7540. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7541. * Be aware Math.random() could cause collisions, but:
  7542. * "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"
  7543. */
  7544. Tools.RandomId = function () {
  7545. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7546. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7547. return v.toString(16);
  7548. });
  7549. };
  7550. Object.defineProperty(Tools, "NoneLogLevel", {
  7551. get: function () {
  7552. return Tools._NoneLogLevel;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(Tools, "MessageLogLevel", {
  7558. get: function () {
  7559. return Tools._MessageLogLevel;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(Tools, "WarningLogLevel", {
  7565. get: function () {
  7566. return Tools._WarningLogLevel;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. Object.defineProperty(Tools, "ErrorLogLevel", {
  7572. get: function () {
  7573. return Tools._ErrorLogLevel;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. Object.defineProperty(Tools, "AllLogLevel", {
  7579. get: function () {
  7580. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7581. },
  7582. enumerable: true,
  7583. configurable: true
  7584. });
  7585. Tools._AddLogEntry = function (entry) {
  7586. Tools._LogCache = entry + Tools._LogCache;
  7587. if (Tools.OnNewCacheEntry) {
  7588. Tools.OnNewCacheEntry(entry);
  7589. }
  7590. };
  7591. Tools._FormatMessage = function (message) {
  7592. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7593. var date = new Date();
  7594. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7595. };
  7596. Tools._LogDisabled = function (message) {
  7597. // nothing to do
  7598. };
  7599. Tools._LogEnabled = function (message) {
  7600. var formattedMessage = Tools._FormatMessage(message);
  7601. console.log("BJS - " + formattedMessage);
  7602. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7603. Tools._AddLogEntry(entry);
  7604. };
  7605. Tools._WarnDisabled = function (message) {
  7606. // nothing to do
  7607. };
  7608. Tools._WarnEnabled = function (message) {
  7609. var formattedMessage = Tools._FormatMessage(message);
  7610. console.warn("BJS - " + formattedMessage);
  7611. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7612. Tools._AddLogEntry(entry);
  7613. };
  7614. Tools._ErrorDisabled = function (message) {
  7615. // nothing to do
  7616. };
  7617. Tools._ErrorEnabled = function (message) {
  7618. Tools.errorsCount++;
  7619. var formattedMessage = Tools._FormatMessage(message);
  7620. console.error("BJS - " + formattedMessage);
  7621. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7622. Tools._AddLogEntry(entry);
  7623. };
  7624. Object.defineProperty(Tools, "LogCache", {
  7625. get: function () {
  7626. return Tools._LogCache;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Tools.ClearLogCache = function () {
  7632. Tools._LogCache = "";
  7633. Tools.errorsCount = 0;
  7634. };
  7635. Object.defineProperty(Tools, "LogLevels", {
  7636. set: function (level) {
  7637. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7638. Tools.Log = Tools._LogEnabled;
  7639. }
  7640. else {
  7641. Tools.Log = Tools._LogDisabled;
  7642. }
  7643. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7644. Tools.Warn = Tools._WarnEnabled;
  7645. }
  7646. else {
  7647. Tools.Warn = Tools._WarnDisabled;
  7648. }
  7649. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7650. Tools.Error = Tools._ErrorEnabled;
  7651. }
  7652. else {
  7653. Tools.Error = Tools._ErrorDisabled;
  7654. }
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Tools.IsWindowObjectExist = function () {
  7660. return (typeof window) !== "undefined";
  7661. };
  7662. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7663. get: function () {
  7664. return Tools._PerformanceNoneLogLevel;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7670. get: function () {
  7671. return Tools._PerformanceUserMarkLogLevel;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7677. get: function () {
  7678. return Tools._PerformanceConsoleLogLevel;
  7679. },
  7680. enumerable: true,
  7681. configurable: true
  7682. });
  7683. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7684. set: function (level) {
  7685. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7686. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7687. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7688. return;
  7689. }
  7690. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7691. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7692. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7693. return;
  7694. }
  7695. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7696. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7697. },
  7698. enumerable: true,
  7699. configurable: true
  7700. });
  7701. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7702. };
  7703. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7704. };
  7705. Tools._StartUserMark = function (counterName, condition) {
  7706. if (condition === void 0) { condition = true; }
  7707. if (!Tools._performance) {
  7708. if (!Tools.IsWindowObjectExist()) {
  7709. return;
  7710. }
  7711. Tools._performance = window.performance;
  7712. }
  7713. if (!condition || !Tools._performance.mark) {
  7714. return;
  7715. }
  7716. Tools._performance.mark(counterName + "-Begin");
  7717. };
  7718. Tools._EndUserMark = function (counterName, condition) {
  7719. if (condition === void 0) { condition = true; }
  7720. if (!condition || !Tools._performance.mark) {
  7721. return;
  7722. }
  7723. Tools._performance.mark(counterName + "-End");
  7724. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7725. };
  7726. Tools._StartPerformanceConsole = function (counterName, condition) {
  7727. if (condition === void 0) { condition = true; }
  7728. if (!condition) {
  7729. return;
  7730. }
  7731. Tools._StartUserMark(counterName, condition);
  7732. if (console.time) {
  7733. console.time(counterName);
  7734. }
  7735. };
  7736. Tools._EndPerformanceConsole = function (counterName, condition) {
  7737. if (condition === void 0) { condition = true; }
  7738. if (!condition) {
  7739. return;
  7740. }
  7741. Tools._EndUserMark(counterName, condition);
  7742. if (console.time) {
  7743. console.timeEnd(counterName);
  7744. }
  7745. };
  7746. Object.defineProperty(Tools, "Now", {
  7747. get: function () {
  7748. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7749. return window.performance.now();
  7750. }
  7751. return new Date().getTime();
  7752. },
  7753. enumerable: true,
  7754. configurable: true
  7755. });
  7756. /**
  7757. * This method will return the name of the class used to create the instance of the given object.
  7758. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7759. * @param object the object to get the class name from
  7760. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7761. */
  7762. Tools.GetClassName = function (object, isType) {
  7763. if (isType === void 0) { isType = false; }
  7764. var name = null;
  7765. if (!isType && object.getClassName) {
  7766. name = object.getClassName();
  7767. }
  7768. else {
  7769. if (object instanceof Object) {
  7770. var classObj = isType ? object : Object.getPrototypeOf(object);
  7771. name = classObj.constructor["__bjsclassName__"];
  7772. }
  7773. if (!name) {
  7774. name = typeof object;
  7775. }
  7776. }
  7777. return name;
  7778. };
  7779. Tools.First = function (array, predicate) {
  7780. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7781. var el = array_1[_i];
  7782. if (predicate(el)) {
  7783. return el;
  7784. }
  7785. }
  7786. return null;
  7787. };
  7788. /**
  7789. * This method will return the name of the full name of the class, including its owning module (if any).
  7790. * 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).
  7791. * @param object the object to get the class name from
  7792. * @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.
  7793. */
  7794. Tools.getFullClassName = function (object, isType) {
  7795. if (isType === void 0) { isType = false; }
  7796. var className = null;
  7797. var moduleName = null;
  7798. if (!isType && object.getClassName) {
  7799. className = object.getClassName();
  7800. }
  7801. else {
  7802. if (object instanceof Object) {
  7803. var classObj = isType ? object : Object.getPrototypeOf(object);
  7804. className = classObj.constructor["__bjsclassName__"];
  7805. moduleName = classObj.constructor["__bjsmoduleName__"];
  7806. }
  7807. if (!className) {
  7808. className = typeof object;
  7809. }
  7810. }
  7811. if (!className) {
  7812. return null;
  7813. }
  7814. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7815. };
  7816. /**
  7817. * 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.
  7818. * @param array
  7819. */
  7820. Tools.arrayOrStringFeeder = function (array) {
  7821. return function (index) {
  7822. if (index >= array.length) {
  7823. return null;
  7824. }
  7825. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7826. if (val && val.getHashCode) {
  7827. val = val.getHashCode();
  7828. }
  7829. if (typeof val === "string") {
  7830. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7831. }
  7832. return val;
  7833. };
  7834. };
  7835. /**
  7836. * Compute the hashCode of a stream of number
  7837. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7838. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7839. * @return the hash code computed
  7840. */
  7841. Tools.hashCodeFromStream = function (feeder) {
  7842. // Based from here: http://stackoverflow.com/a/7616484/802124
  7843. var hash = 0;
  7844. var index = 0;
  7845. var chr = feeder(index++);
  7846. while (chr != null) {
  7847. hash = ((hash << 5) - hash) + chr;
  7848. hash |= 0; // Convert to 32bit integer
  7849. chr = feeder(index++);
  7850. }
  7851. return hash;
  7852. };
  7853. Tools.BaseUrl = "";
  7854. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7855. /**
  7856. * Default behaviour for cors in the application.
  7857. * It can be a string if the expected behavior is identical in the entire app.
  7858. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7859. */
  7860. Tools.CorsBehavior = "anonymous";
  7861. Tools.UseFallbackTexture = true;
  7862. /**
  7863. * Use this object to register external classes like custom textures or material
  7864. * to allow the laoders to instantiate them
  7865. */
  7866. Tools.RegisteredExternalClasses = {};
  7867. // Used in case of a texture loading problem
  7868. 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";
  7869. Tools.PreprocessUrl = function (url) {
  7870. return url;
  7871. };
  7872. // Logs
  7873. Tools._NoneLogLevel = 0;
  7874. Tools._MessageLogLevel = 1;
  7875. Tools._WarningLogLevel = 2;
  7876. Tools._ErrorLogLevel = 4;
  7877. Tools._LogCache = "";
  7878. Tools.errorsCount = 0;
  7879. Tools.Log = Tools._LogEnabled;
  7880. Tools.Warn = Tools._WarnEnabled;
  7881. Tools.Error = Tools._ErrorEnabled;
  7882. // Performances
  7883. Tools._PerformanceNoneLogLevel = 0;
  7884. Tools._PerformanceUserMarkLogLevel = 1;
  7885. Tools._PerformanceConsoleLogLevel = 2;
  7886. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7887. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7888. return Tools;
  7889. }());
  7890. BABYLON.Tools = Tools;
  7891. /**
  7892. * This class is used to track a performance counter which is number based.
  7893. * The user has access to many properties which give statistics of different nature
  7894. *
  7895. * The implementer can track two kinds of Performance Counter: time and count
  7896. * 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.
  7897. * 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.
  7898. */
  7899. var PerfCounter = /** @class */ (function () {
  7900. function PerfCounter() {
  7901. this._startMonitoringTime = 0;
  7902. this._min = 0;
  7903. this._max = 0;
  7904. this._average = 0;
  7905. this._lastSecAverage = 0;
  7906. this._current = 0;
  7907. this._totalValueCount = 0;
  7908. this._totalAccumulated = 0;
  7909. this._lastSecAccumulated = 0;
  7910. this._lastSecTime = 0;
  7911. this._lastSecValueCount = 0;
  7912. }
  7913. Object.defineProperty(PerfCounter.prototype, "min", {
  7914. /**
  7915. * Returns the smallest value ever
  7916. */
  7917. get: function () {
  7918. return this._min;
  7919. },
  7920. enumerable: true,
  7921. configurable: true
  7922. });
  7923. Object.defineProperty(PerfCounter.prototype, "max", {
  7924. /**
  7925. * Returns the biggest value ever
  7926. */
  7927. get: function () {
  7928. return this._max;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. Object.defineProperty(PerfCounter.prototype, "average", {
  7934. /**
  7935. * Returns the average value since the performance counter is running
  7936. */
  7937. get: function () {
  7938. return this._average;
  7939. },
  7940. enumerable: true,
  7941. configurable: true
  7942. });
  7943. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7944. /**
  7945. * Returns the average value of the last second the counter was monitored
  7946. */
  7947. get: function () {
  7948. return this._lastSecAverage;
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. Object.defineProperty(PerfCounter.prototype, "current", {
  7954. /**
  7955. * Returns the current value
  7956. */
  7957. get: function () {
  7958. return this._current;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(PerfCounter.prototype, "total", {
  7964. get: function () {
  7965. return this._totalAccumulated;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(PerfCounter.prototype, "count", {
  7971. get: function () {
  7972. return this._totalValueCount;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. /**
  7978. * Call this method to start monitoring a new frame.
  7979. * 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.
  7980. */
  7981. PerfCounter.prototype.fetchNewFrame = function () {
  7982. this._totalValueCount++;
  7983. this._current = 0;
  7984. this._lastSecValueCount++;
  7985. };
  7986. /**
  7987. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7988. * @param newCount the count value to add to the monitored count
  7989. * @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.
  7990. */
  7991. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7992. if (!PerfCounter.Enabled) {
  7993. return;
  7994. }
  7995. this._current += newCount;
  7996. if (fetchResult) {
  7997. this._fetchResult();
  7998. }
  7999. };
  8000. /**
  8001. * Start monitoring this performance counter
  8002. */
  8003. PerfCounter.prototype.beginMonitoring = function () {
  8004. if (!PerfCounter.Enabled) {
  8005. return;
  8006. }
  8007. this._startMonitoringTime = Tools.Now;
  8008. };
  8009. /**
  8010. * Compute the time lapsed since the previous beginMonitoring() call.
  8011. * @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
  8012. */
  8013. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8014. if (newFrame === void 0) { newFrame = true; }
  8015. if (!PerfCounter.Enabled) {
  8016. return;
  8017. }
  8018. if (newFrame) {
  8019. this.fetchNewFrame();
  8020. }
  8021. var currentTime = Tools.Now;
  8022. this._current = currentTime - this._startMonitoringTime;
  8023. if (newFrame) {
  8024. this._fetchResult();
  8025. }
  8026. };
  8027. PerfCounter.prototype._fetchResult = function () {
  8028. this._totalAccumulated += this._current;
  8029. this._lastSecAccumulated += this._current;
  8030. // Min/Max update
  8031. this._min = Math.min(this._min, this._current);
  8032. this._max = Math.max(this._max, this._current);
  8033. this._average = this._totalAccumulated / this._totalValueCount;
  8034. // Reset last sec?
  8035. var now = Tools.Now;
  8036. if ((now - this._lastSecTime) > 1000) {
  8037. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8038. this._lastSecTime = now;
  8039. this._lastSecAccumulated = 0;
  8040. this._lastSecValueCount = 0;
  8041. }
  8042. };
  8043. PerfCounter.Enabled = true;
  8044. return PerfCounter;
  8045. }());
  8046. BABYLON.PerfCounter = PerfCounter;
  8047. /**
  8048. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8049. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8050. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8051. * @param name The name of the class, case should be preserved
  8052. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8053. */
  8054. function className(name, module) {
  8055. return function (target) {
  8056. target["__bjsclassName__"] = name;
  8057. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8058. };
  8059. }
  8060. BABYLON.className = className;
  8061. /**
  8062. * An implementation of a loop for asynchronous functions.
  8063. */
  8064. var AsyncLoop = /** @class */ (function () {
  8065. /**
  8066. * Constroctor.
  8067. * @param iterations the number of iterations.
  8068. * @param _fn the function to run each iteration
  8069. * @param _successCallback the callback that will be called upon succesful execution
  8070. * @param offset starting offset.
  8071. */
  8072. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8073. if (offset === void 0) { offset = 0; }
  8074. this.iterations = iterations;
  8075. this._fn = _fn;
  8076. this._successCallback = _successCallback;
  8077. this.index = offset - 1;
  8078. this._done = false;
  8079. }
  8080. /**
  8081. * Execute the next iteration. Must be called after the last iteration was finished.
  8082. */
  8083. AsyncLoop.prototype.executeNext = function () {
  8084. if (!this._done) {
  8085. if (this.index + 1 < this.iterations) {
  8086. ++this.index;
  8087. this._fn(this);
  8088. }
  8089. else {
  8090. this.breakLoop();
  8091. }
  8092. }
  8093. };
  8094. /**
  8095. * Break the loop and run the success callback.
  8096. */
  8097. AsyncLoop.prototype.breakLoop = function () {
  8098. this._done = true;
  8099. this._successCallback();
  8100. };
  8101. /**
  8102. * Helper function
  8103. */
  8104. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8105. if (offset === void 0) { offset = 0; }
  8106. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8107. loop.executeNext();
  8108. return loop;
  8109. };
  8110. /**
  8111. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8112. * @param iterations total number of iterations
  8113. * @param syncedIterations number of synchronous iterations in each async iteration.
  8114. * @param fn the function to call each iteration.
  8115. * @param callback a success call back that will be called when iterating stops.
  8116. * @param breakFunction a break condition (optional)
  8117. * @param timeout timeout settings for the setTimeout function. default - 0.
  8118. * @constructor
  8119. */
  8120. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8121. if (timeout === void 0) { timeout = 0; }
  8122. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8123. if (breakFunction && breakFunction())
  8124. loop.breakLoop();
  8125. else {
  8126. setTimeout(function () {
  8127. for (var i = 0; i < syncedIterations; ++i) {
  8128. var iteration = (loop.index * syncedIterations) + i;
  8129. if (iteration >= iterations)
  8130. break;
  8131. fn(iteration);
  8132. if (breakFunction && breakFunction()) {
  8133. loop.breakLoop();
  8134. break;
  8135. }
  8136. }
  8137. loop.executeNext();
  8138. }, timeout);
  8139. }
  8140. }, callback);
  8141. };
  8142. return AsyncLoop;
  8143. }());
  8144. BABYLON.AsyncLoop = AsyncLoop;
  8145. })(BABYLON || (BABYLON = {}));
  8146. //# sourceMappingURL=babylon.tools.js.map
  8147. var BABYLON;
  8148. (function (BABYLON) {
  8149. var _AlphaState = /** @class */ (function () {
  8150. /**
  8151. * Initializes the state.
  8152. */
  8153. function _AlphaState() {
  8154. this._isAlphaBlendDirty = false;
  8155. this._isBlendFunctionParametersDirty = false;
  8156. this._isBlendEquationParametersDirty = false;
  8157. this._isBlendConstantsDirty = false;
  8158. this._alphaBlend = false;
  8159. this._blendFunctionParameters = new Array(4);
  8160. this._blendEquationParameters = new Array(2);
  8161. this._blendConstants = new Array(4);
  8162. this.reset();
  8163. }
  8164. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8165. get: function () {
  8166. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8172. get: function () {
  8173. return this._alphaBlend;
  8174. },
  8175. set: function (value) {
  8176. if (this._alphaBlend === value) {
  8177. return;
  8178. }
  8179. this._alphaBlend = value;
  8180. this._isAlphaBlendDirty = true;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8186. if (this._blendConstants[0] === r &&
  8187. this._blendConstants[1] === g &&
  8188. this._blendConstants[2] === b &&
  8189. this._blendConstants[3] === a) {
  8190. return;
  8191. }
  8192. this._blendConstants[0] = r;
  8193. this._blendConstants[1] = g;
  8194. this._blendConstants[2] = b;
  8195. this._blendConstants[3] = a;
  8196. this._isBlendConstantsDirty = true;
  8197. };
  8198. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8199. if (this._blendFunctionParameters[0] === value0 &&
  8200. this._blendFunctionParameters[1] === value1 &&
  8201. this._blendFunctionParameters[2] === value2 &&
  8202. this._blendFunctionParameters[3] === value3) {
  8203. return;
  8204. }
  8205. this._blendFunctionParameters[0] = value0;
  8206. this._blendFunctionParameters[1] = value1;
  8207. this._blendFunctionParameters[2] = value2;
  8208. this._blendFunctionParameters[3] = value3;
  8209. this._isBlendFunctionParametersDirty = true;
  8210. };
  8211. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8212. if (this._blendEquationParameters[0] === rgb &&
  8213. this._blendEquationParameters[1] === alpha) {
  8214. return;
  8215. }
  8216. this._blendEquationParameters[0] = rgb;
  8217. this._blendEquationParameters[1] = alpha;
  8218. this._isBlendEquationParametersDirty = true;
  8219. };
  8220. _AlphaState.prototype.reset = function () {
  8221. this._alphaBlend = false;
  8222. this._blendFunctionParameters[0] = null;
  8223. this._blendFunctionParameters[1] = null;
  8224. this._blendFunctionParameters[2] = null;
  8225. this._blendFunctionParameters[3] = null;
  8226. this._blendEquationParameters[0] = null;
  8227. this._blendEquationParameters[1] = null;
  8228. this._blendConstants[0] = null;
  8229. this._blendConstants[1] = null;
  8230. this._blendConstants[2] = null;
  8231. this._blendConstants[3] = null;
  8232. this._isAlphaBlendDirty = true;
  8233. this._isBlendFunctionParametersDirty = false;
  8234. this._isBlendEquationParametersDirty = false;
  8235. this._isBlendConstantsDirty = false;
  8236. };
  8237. _AlphaState.prototype.apply = function (gl) {
  8238. if (!this.isDirty) {
  8239. return;
  8240. }
  8241. // Alpha blend
  8242. if (this._isAlphaBlendDirty) {
  8243. if (this._alphaBlend) {
  8244. gl.enable(gl.BLEND);
  8245. }
  8246. else {
  8247. gl.disable(gl.BLEND);
  8248. }
  8249. this._isAlphaBlendDirty = false;
  8250. }
  8251. // Alpha function
  8252. if (this._isBlendFunctionParametersDirty) {
  8253. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8254. this._isBlendFunctionParametersDirty = false;
  8255. }
  8256. // Alpha equation
  8257. if (this._isBlendEquationParametersDirty) {
  8258. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8259. this._isBlendEquationParametersDirty = false;
  8260. }
  8261. // Constants
  8262. if (this._isBlendConstantsDirty) {
  8263. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8264. this._isBlendConstantsDirty = false;
  8265. }
  8266. };
  8267. return _AlphaState;
  8268. }());
  8269. BABYLON._AlphaState = _AlphaState;
  8270. })(BABYLON || (BABYLON = {}));
  8271. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8272. var BABYLON;
  8273. (function (BABYLON) {
  8274. var _DepthCullingState = /** @class */ (function () {
  8275. /**
  8276. * Initializes the state.
  8277. */
  8278. function _DepthCullingState() {
  8279. this._isDepthTestDirty = false;
  8280. this._isDepthMaskDirty = false;
  8281. this._isDepthFuncDirty = false;
  8282. this._isCullFaceDirty = false;
  8283. this._isCullDirty = false;
  8284. this._isZOffsetDirty = false;
  8285. this._isFrontFaceDirty = false;
  8286. this.reset();
  8287. }
  8288. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8289. get: function () {
  8290. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8296. get: function () {
  8297. return this._zOffset;
  8298. },
  8299. set: function (value) {
  8300. if (this._zOffset === value) {
  8301. return;
  8302. }
  8303. this._zOffset = value;
  8304. this._isZOffsetDirty = true;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8310. get: function () {
  8311. return this._cullFace;
  8312. },
  8313. set: function (value) {
  8314. if (this._cullFace === value) {
  8315. return;
  8316. }
  8317. this._cullFace = value;
  8318. this._isCullFaceDirty = true;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8324. get: function () {
  8325. return this._cull;
  8326. },
  8327. set: function (value) {
  8328. if (this._cull === value) {
  8329. return;
  8330. }
  8331. this._cull = value;
  8332. this._isCullDirty = true;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8338. get: function () {
  8339. return this._depthFunc;
  8340. },
  8341. set: function (value) {
  8342. if (this._depthFunc === value) {
  8343. return;
  8344. }
  8345. this._depthFunc = value;
  8346. this._isDepthFuncDirty = true;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8352. get: function () {
  8353. return this._depthMask;
  8354. },
  8355. set: function (value) {
  8356. if (this._depthMask === value) {
  8357. return;
  8358. }
  8359. this._depthMask = value;
  8360. this._isDepthMaskDirty = true;
  8361. },
  8362. enumerable: true,
  8363. configurable: true
  8364. });
  8365. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8366. get: function () {
  8367. return this._depthTest;
  8368. },
  8369. set: function (value) {
  8370. if (this._depthTest === value) {
  8371. return;
  8372. }
  8373. this._depthTest = value;
  8374. this._isDepthTestDirty = true;
  8375. },
  8376. enumerable: true,
  8377. configurable: true
  8378. });
  8379. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8380. get: function () {
  8381. return this._frontFace;
  8382. },
  8383. set: function (value) {
  8384. if (this._frontFace === value) {
  8385. return;
  8386. }
  8387. this._frontFace = value;
  8388. this._isFrontFaceDirty = true;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. _DepthCullingState.prototype.reset = function () {
  8394. this._depthMask = true;
  8395. this._depthTest = true;
  8396. this._depthFunc = null;
  8397. this._cullFace = null;
  8398. this._cull = null;
  8399. this._zOffset = 0;
  8400. this._frontFace = null;
  8401. this._isDepthTestDirty = true;
  8402. this._isDepthMaskDirty = true;
  8403. this._isDepthFuncDirty = false;
  8404. this._isCullFaceDirty = false;
  8405. this._isCullDirty = false;
  8406. this._isZOffsetDirty = false;
  8407. this._isFrontFaceDirty = false;
  8408. };
  8409. _DepthCullingState.prototype.apply = function (gl) {
  8410. if (!this.isDirty) {
  8411. return;
  8412. }
  8413. // Cull
  8414. if (this._isCullDirty) {
  8415. if (this.cull) {
  8416. gl.enable(gl.CULL_FACE);
  8417. }
  8418. else {
  8419. gl.disable(gl.CULL_FACE);
  8420. }
  8421. this._isCullDirty = false;
  8422. }
  8423. // Cull face
  8424. if (this._isCullFaceDirty) {
  8425. gl.cullFace(this.cullFace);
  8426. this._isCullFaceDirty = false;
  8427. }
  8428. // Depth mask
  8429. if (this._isDepthMaskDirty) {
  8430. gl.depthMask(this.depthMask);
  8431. this._isDepthMaskDirty = false;
  8432. }
  8433. // Depth test
  8434. if (this._isDepthTestDirty) {
  8435. if (this.depthTest) {
  8436. gl.enable(gl.DEPTH_TEST);
  8437. }
  8438. else {
  8439. gl.disable(gl.DEPTH_TEST);
  8440. }
  8441. this._isDepthTestDirty = false;
  8442. }
  8443. // Depth func
  8444. if (this._isDepthFuncDirty) {
  8445. gl.depthFunc(this.depthFunc);
  8446. this._isDepthFuncDirty = false;
  8447. }
  8448. // zOffset
  8449. if (this._isZOffsetDirty) {
  8450. if (this.zOffset) {
  8451. gl.enable(gl.POLYGON_OFFSET_FILL);
  8452. gl.polygonOffset(this.zOffset, 0);
  8453. }
  8454. else {
  8455. gl.disable(gl.POLYGON_OFFSET_FILL);
  8456. }
  8457. this._isZOffsetDirty = false;
  8458. }
  8459. // Front face
  8460. if (this._isFrontFaceDirty) {
  8461. gl.frontFace(this.frontFace);
  8462. this._isFrontFaceDirty = false;
  8463. }
  8464. };
  8465. return _DepthCullingState;
  8466. }());
  8467. BABYLON._DepthCullingState = _DepthCullingState;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.depthCullingState.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var _StencilState = /** @class */ (function () {
  8473. function _StencilState() {
  8474. this._isStencilTestDirty = false;
  8475. this._isStencilMaskDirty = false;
  8476. this._isStencilFuncDirty = false;
  8477. this._isStencilOpDirty = false;
  8478. this.reset();
  8479. }
  8480. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8481. get: function () {
  8482. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8483. },
  8484. enumerable: true,
  8485. configurable: true
  8486. });
  8487. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8488. get: function () {
  8489. return this._stencilFunc;
  8490. },
  8491. set: function (value) {
  8492. if (this._stencilFunc === value) {
  8493. return;
  8494. }
  8495. this._stencilFunc = value;
  8496. this._isStencilFuncDirty = true;
  8497. },
  8498. enumerable: true,
  8499. configurable: true
  8500. });
  8501. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8502. get: function () {
  8503. return this._stencilFuncRef;
  8504. },
  8505. set: function (value) {
  8506. if (this._stencilFuncRef === value) {
  8507. return;
  8508. }
  8509. this._stencilFuncRef = value;
  8510. this._isStencilFuncDirty = true;
  8511. },
  8512. enumerable: true,
  8513. configurable: true
  8514. });
  8515. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8516. get: function () {
  8517. return this._stencilFuncMask;
  8518. },
  8519. set: function (value) {
  8520. if (this._stencilFuncMask === value) {
  8521. return;
  8522. }
  8523. this._stencilFuncMask = value;
  8524. this._isStencilFuncDirty = true;
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8530. get: function () {
  8531. return this._stencilOpStencilFail;
  8532. },
  8533. set: function (value) {
  8534. if (this._stencilOpStencilFail === value) {
  8535. return;
  8536. }
  8537. this._stencilOpStencilFail = value;
  8538. this._isStencilOpDirty = true;
  8539. },
  8540. enumerable: true,
  8541. configurable: true
  8542. });
  8543. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8544. get: function () {
  8545. return this._stencilOpDepthFail;
  8546. },
  8547. set: function (value) {
  8548. if (this._stencilOpDepthFail === value) {
  8549. return;
  8550. }
  8551. this._stencilOpDepthFail = value;
  8552. this._isStencilOpDirty = true;
  8553. },
  8554. enumerable: true,
  8555. configurable: true
  8556. });
  8557. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8558. get: function () {
  8559. return this._stencilOpStencilDepthPass;
  8560. },
  8561. set: function (value) {
  8562. if (this._stencilOpStencilDepthPass === value) {
  8563. return;
  8564. }
  8565. this._stencilOpStencilDepthPass = value;
  8566. this._isStencilOpDirty = true;
  8567. },
  8568. enumerable: true,
  8569. configurable: true
  8570. });
  8571. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8572. get: function () {
  8573. return this._stencilMask;
  8574. },
  8575. set: function (value) {
  8576. if (this._stencilMask === value) {
  8577. return;
  8578. }
  8579. this._stencilMask = value;
  8580. this._isStencilMaskDirty = true;
  8581. },
  8582. enumerable: true,
  8583. configurable: true
  8584. });
  8585. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8586. get: function () {
  8587. return this._stencilTest;
  8588. },
  8589. set: function (value) {
  8590. if (this._stencilTest === value) {
  8591. return;
  8592. }
  8593. this._stencilTest = value;
  8594. this._isStencilTestDirty = true;
  8595. },
  8596. enumerable: true,
  8597. configurable: true
  8598. });
  8599. _StencilState.prototype.reset = function () {
  8600. this._stencilTest = false;
  8601. this._stencilMask = 0xFF;
  8602. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8603. this._stencilFuncRef = 1;
  8604. this._stencilFuncMask = 0xFF;
  8605. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8606. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8607. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8608. this._isStencilTestDirty = true;
  8609. this._isStencilMaskDirty = true;
  8610. this._isStencilFuncDirty = true;
  8611. this._isStencilOpDirty = true;
  8612. };
  8613. _StencilState.prototype.apply = function (gl) {
  8614. if (!this.isDirty) {
  8615. return;
  8616. }
  8617. // Stencil test
  8618. if (this._isStencilTestDirty) {
  8619. if (this.stencilTest) {
  8620. gl.enable(gl.STENCIL_TEST);
  8621. }
  8622. else {
  8623. gl.disable(gl.STENCIL_TEST);
  8624. }
  8625. this._isStencilTestDirty = false;
  8626. }
  8627. // Stencil mask
  8628. if (this._isStencilMaskDirty) {
  8629. gl.stencilMask(this.stencilMask);
  8630. this._isStencilMaskDirty = false;
  8631. }
  8632. // Stencil func
  8633. if (this._isStencilFuncDirty) {
  8634. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8635. this._isStencilFuncDirty = false;
  8636. }
  8637. // Stencil op
  8638. if (this._isStencilOpDirty) {
  8639. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8640. this._isStencilOpDirty = false;
  8641. }
  8642. };
  8643. return _StencilState;
  8644. }());
  8645. BABYLON._StencilState = _StencilState;
  8646. })(BABYLON || (BABYLON = {}));
  8647. //# sourceMappingURL=babylon.stencilState.js.map
  8648. var BABYLON;
  8649. (function (BABYLON) {
  8650. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8651. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8652. };
  8653. var compileRawShader = function (gl, source, type) {
  8654. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8655. gl.shaderSource(shader, source);
  8656. gl.compileShader(shader);
  8657. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8658. var log = gl.getShaderInfoLog(shader);
  8659. if (log) {
  8660. throw new Error(log);
  8661. }
  8662. }
  8663. if (!shader) {
  8664. throw new Error("Something went wrong while compile the shader.");
  8665. }
  8666. return shader;
  8667. };
  8668. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8669. var magFilter = gl.NEAREST;
  8670. var minFilter = gl.NEAREST;
  8671. switch (samplingMode) {
  8672. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8673. magFilter = gl.LINEAR;
  8674. if (generateMipMaps) {
  8675. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8676. }
  8677. else {
  8678. minFilter = gl.LINEAR;
  8679. }
  8680. break;
  8681. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8682. magFilter = gl.LINEAR;
  8683. if (generateMipMaps) {
  8684. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8685. }
  8686. else {
  8687. minFilter = gl.LINEAR;
  8688. }
  8689. break;
  8690. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8691. magFilter = gl.NEAREST;
  8692. if (generateMipMaps) {
  8693. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8694. }
  8695. else {
  8696. minFilter = gl.NEAREST;
  8697. }
  8698. break;
  8699. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8700. magFilter = gl.NEAREST;
  8701. if (generateMipMaps) {
  8702. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8703. }
  8704. else {
  8705. minFilter = gl.NEAREST;
  8706. }
  8707. break;
  8708. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8709. magFilter = gl.NEAREST;
  8710. if (generateMipMaps) {
  8711. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8712. }
  8713. else {
  8714. minFilter = gl.LINEAR;
  8715. }
  8716. break;
  8717. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8718. magFilter = gl.NEAREST;
  8719. if (generateMipMaps) {
  8720. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8721. }
  8722. else {
  8723. minFilter = gl.LINEAR;
  8724. }
  8725. break;
  8726. case BABYLON.Texture.NEAREST_LINEAR:
  8727. magFilter = gl.NEAREST;
  8728. minFilter = gl.LINEAR;
  8729. break;
  8730. case BABYLON.Texture.NEAREST_NEAREST:
  8731. magFilter = gl.NEAREST;
  8732. minFilter = gl.NEAREST;
  8733. break;
  8734. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8735. magFilter = gl.LINEAR;
  8736. if (generateMipMaps) {
  8737. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8738. }
  8739. else {
  8740. minFilter = gl.NEAREST;
  8741. }
  8742. break;
  8743. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8744. magFilter = gl.LINEAR;
  8745. if (generateMipMaps) {
  8746. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8747. }
  8748. else {
  8749. minFilter = gl.NEAREST;
  8750. }
  8751. break;
  8752. case BABYLON.Texture.LINEAR_LINEAR:
  8753. magFilter = gl.LINEAR;
  8754. minFilter = gl.LINEAR;
  8755. break;
  8756. case BABYLON.Texture.LINEAR_NEAREST:
  8757. magFilter = gl.LINEAR;
  8758. minFilter = gl.NEAREST;
  8759. break;
  8760. }
  8761. return {
  8762. min: minFilter,
  8763. mag: magFilter
  8764. };
  8765. };
  8766. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8767. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8768. var img;
  8769. var onload = function () {
  8770. loadedImages[index] = img;
  8771. loadedImages._internalCount++;
  8772. if (scene) {
  8773. scene._removePendingData(img);
  8774. }
  8775. if (loadedImages._internalCount === 6) {
  8776. onfinish(loadedImages);
  8777. }
  8778. };
  8779. var onerror = function (message, exception) {
  8780. if (scene) {
  8781. scene._removePendingData(img);
  8782. }
  8783. if (onErrorCallBack) {
  8784. onErrorCallBack(message, exception);
  8785. }
  8786. };
  8787. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8788. if (scene) {
  8789. scene._addPendingData(img);
  8790. }
  8791. };
  8792. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8793. if (onError === void 0) { onError = null; }
  8794. var loadedImages = [];
  8795. loadedImages._internalCount = 0;
  8796. for (var index = 0; index < 6; index++) {
  8797. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8798. }
  8799. };
  8800. var BufferPointer = /** @class */ (function () {
  8801. function BufferPointer() {
  8802. }
  8803. return BufferPointer;
  8804. }());
  8805. var InstancingAttributeInfo = /** @class */ (function () {
  8806. function InstancingAttributeInfo() {
  8807. }
  8808. return InstancingAttributeInfo;
  8809. }());
  8810. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8811. /**
  8812. * Define options used to create a render target texture
  8813. */
  8814. var RenderTargetCreationOptions = /** @class */ (function () {
  8815. function RenderTargetCreationOptions() {
  8816. }
  8817. return RenderTargetCreationOptions;
  8818. }());
  8819. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8820. /**
  8821. * Regroup several parameters relative to the browser in use
  8822. */
  8823. var EngineCapabilities = /** @class */ (function () {
  8824. function EngineCapabilities() {
  8825. }
  8826. return EngineCapabilities;
  8827. }());
  8828. BABYLON.EngineCapabilities = EngineCapabilities;
  8829. /**
  8830. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8831. */
  8832. var Engine = /** @class */ (function () {
  8833. /**
  8834. * @constructor
  8835. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8836. * @param {boolean} [antialias] - enable antialias
  8837. * @param options - further options to be sent to the getContext function
  8838. */
  8839. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8840. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8841. var _this = this;
  8842. // Public members
  8843. this.forcePOTTextures = false;
  8844. this.isFullscreen = false;
  8845. this.isPointerLock = false;
  8846. this.cullBackFaces = true;
  8847. this.renderEvenInBackground = true;
  8848. this.preventCacheWipeBetweenFrames = false;
  8849. // To enable/disable IDB support and avoid XHR on .manifest
  8850. this.enableOfflineSupport = false;
  8851. this.scenes = new Array();
  8852. this.postProcesses = new Array();
  8853. // Observables
  8854. /**
  8855. * Observable event triggered each time the rendering canvas is resized
  8856. */
  8857. this.onResizeObservable = new BABYLON.Observable();
  8858. /**
  8859. * Observable event triggered each time the canvas loses focus
  8860. */
  8861. this.onCanvasBlurObservable = new BABYLON.Observable();
  8862. /**
  8863. * Observable event triggered each time the canvas gains focus
  8864. */
  8865. this.onCanvasFocusObservable = new BABYLON.Observable();
  8866. /**
  8867. * Observable event triggered each time the canvas receives pointerout event
  8868. */
  8869. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8870. /**
  8871. * Observable event triggered before each texture is initialized
  8872. */
  8873. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8874. //WebVR
  8875. this._vrDisplay = undefined;
  8876. this._vrSupported = false;
  8877. this._vrExclusivePointerMode = false;
  8878. // Uniform buffers list
  8879. this.disableUniformBuffers = false;
  8880. this._uniformBuffers = new Array();
  8881. // Observables
  8882. /**
  8883. * Observable raised when the engine begins a new frame
  8884. */
  8885. this.onBeginFrameObservable = new BABYLON.Observable();
  8886. /**
  8887. * Observable raised when the engine ends the current frame
  8888. */
  8889. this.onEndFrameObservable = new BABYLON.Observable();
  8890. /**
  8891. * Observable raised when the engine is about to compile a shader
  8892. */
  8893. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8894. /**
  8895. * Observable raised when the engine has jsut compiled a shader
  8896. */
  8897. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8898. this._windowIsBackground = false;
  8899. this._webGLVersion = 1.0;
  8900. this._badOS = false;
  8901. this._badDesktopOS = false;
  8902. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8903. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8904. this.onVRRequestPresentStart = new BABYLON.Observable();
  8905. this._colorWrite = true;
  8906. this._drawCalls = new BABYLON.PerfCounter();
  8907. this._textureCollisions = new BABYLON.PerfCounter();
  8908. this._renderingQueueLaunched = false;
  8909. this._activeRenderLoops = new Array();
  8910. // Deterministic lockstepMaxSteps
  8911. this._deterministicLockstep = false;
  8912. this._lockstepMaxSteps = 4;
  8913. // Lost context
  8914. this.onContextLostObservable = new BABYLON.Observable();
  8915. this.onContextRestoredObservable = new BABYLON.Observable();
  8916. this._contextWasLost = false;
  8917. this._doNotHandleContextLost = false;
  8918. // FPS
  8919. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8920. this._fps = 60;
  8921. this._deltaTime = 0;
  8922. /**
  8923. * Turn this value on if you want to pause FPS computation when in background
  8924. */
  8925. this.disablePerformanceMonitorInBackground = false;
  8926. // States
  8927. this._depthCullingState = new BABYLON._DepthCullingState();
  8928. this._stencilState = new BABYLON._StencilState();
  8929. this._alphaState = new BABYLON._AlphaState();
  8930. this._alphaMode = Engine.ALPHA_DISABLE;
  8931. // Cache
  8932. this._internalTexturesCache = new Array();
  8933. this._boundTexturesCache = {};
  8934. this._boundTexturesStack = new Array();
  8935. this._compiledEffects = {};
  8936. this._vertexAttribArraysEnabled = [];
  8937. this._uintIndicesCurrentlySet = false;
  8938. this._currentBoundBuffer = new Array();
  8939. this._currentBufferPointers = new Array();
  8940. this._currentInstanceLocations = new Array();
  8941. this._currentInstanceBuffers = new Array();
  8942. this._vaoRecordInProgress = false;
  8943. this._mustWipeVertexAttributes = false;
  8944. this._nextFreeTextureSlots = new Array();
  8945. this._activeRequests = new Array();
  8946. // Hardware supported Compressed Textures
  8947. this._texturesSupported = new Array();
  8948. this._onVRFullScreenTriggered = function () {
  8949. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8950. //get the old size before we change
  8951. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8952. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8953. //get the width and height, change the render size
  8954. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8955. _this.setHardwareScalingLevel(1);
  8956. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8957. }
  8958. else {
  8959. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8960. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8961. }
  8962. };
  8963. this._boundUniforms = {};
  8964. var canvas = null;
  8965. Engine.Instances.push(this);
  8966. if (!canvasOrContext) {
  8967. return;
  8968. }
  8969. options = options || {};
  8970. if (canvasOrContext.getContext) {
  8971. canvas = canvasOrContext;
  8972. this._renderingCanvas = canvas;
  8973. if (antialias != null) {
  8974. options.antialias = antialias;
  8975. }
  8976. if (options.deterministicLockstep === undefined) {
  8977. options.deterministicLockstep = false;
  8978. }
  8979. if (options.lockstepMaxSteps === undefined) {
  8980. options.lockstepMaxSteps = 4;
  8981. }
  8982. if (options.preserveDrawingBuffer === undefined) {
  8983. options.preserveDrawingBuffer = false;
  8984. }
  8985. if (options.audioEngine === undefined) {
  8986. options.audioEngine = true;
  8987. }
  8988. if (options.stencil === undefined) {
  8989. options.stencil = true;
  8990. }
  8991. this._deterministicLockstep = options.deterministicLockstep;
  8992. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8993. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8994. // Exceptions
  8995. if (navigator && navigator.userAgent) {
  8996. var ua = navigator.userAgent;
  8997. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  8998. var exception = _a[_i];
  8999. var key = exception.key;
  9000. var targets = exception.targets;
  9001. if (ua.indexOf(key) > -1) {
  9002. if (exception.capture && exception.captureConstraint) {
  9003. var capture = exception.capture;
  9004. var constraint = exception.captureConstraint;
  9005. var regex = new RegExp(capture);
  9006. var matches = regex.exec(ua);
  9007. if (matches && matches.length > 0) {
  9008. var capturedValue = parseInt(matches[matches.length - 1]);
  9009. if (capturedValue >= constraint) {
  9010. continue;
  9011. }
  9012. }
  9013. }
  9014. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9015. var target = targets_1[_b];
  9016. switch (target) {
  9017. case "uniformBuffer":
  9018. this.disableUniformBuffers = true;
  9019. break;
  9020. }
  9021. }
  9022. break;
  9023. }
  9024. }
  9025. }
  9026. // GL
  9027. if (!options.disableWebGL2Support) {
  9028. try {
  9029. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9030. if (this._gl) {
  9031. this._webGLVersion = 2.0;
  9032. }
  9033. }
  9034. catch (e) {
  9035. // Do nothing
  9036. }
  9037. }
  9038. if (!this._gl) {
  9039. if (!canvas) {
  9040. throw new Error("The provided canvas is null or undefined.");
  9041. }
  9042. try {
  9043. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9044. }
  9045. catch (e) {
  9046. throw new Error("WebGL not supported");
  9047. }
  9048. }
  9049. if (!this._gl) {
  9050. throw new Error("WebGL not supported");
  9051. }
  9052. this._onCanvasFocus = function () {
  9053. _this.onCanvasFocusObservable.notifyObservers(_this);
  9054. };
  9055. this._onCanvasBlur = function () {
  9056. _this.onCanvasBlurObservable.notifyObservers(_this);
  9057. };
  9058. canvas.addEventListener("focus", this._onCanvasFocus);
  9059. canvas.addEventListener("blur", this._onCanvasBlur);
  9060. this._onBlur = function () {
  9061. if (_this.disablePerformanceMonitorInBackground) {
  9062. _this._performanceMonitor.disable();
  9063. }
  9064. _this._windowIsBackground = true;
  9065. };
  9066. this._onFocus = function () {
  9067. if (_this.disablePerformanceMonitorInBackground) {
  9068. _this._performanceMonitor.enable();
  9069. }
  9070. _this._windowIsBackground = false;
  9071. };
  9072. this._onCanvasPointerOut = function () {
  9073. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9074. };
  9075. window.addEventListener("blur", this._onBlur);
  9076. window.addEventListener("focus", this._onFocus);
  9077. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9078. // Context lost
  9079. if (!this._doNotHandleContextLost) {
  9080. this._onContextLost = function (evt) {
  9081. evt.preventDefault();
  9082. _this._contextWasLost = true;
  9083. BABYLON.Tools.Warn("WebGL context lost.");
  9084. _this.onContextLostObservable.notifyObservers(_this);
  9085. };
  9086. this._onContextRestored = function (evt) {
  9087. // Adding a timeout to avoid race condition at browser level
  9088. setTimeout(function () {
  9089. // Rebuild gl context
  9090. _this._initGLContext();
  9091. // Rebuild effects
  9092. _this._rebuildEffects();
  9093. // Rebuild textures
  9094. _this._rebuildInternalTextures();
  9095. // Rebuild buffers
  9096. _this._rebuildBuffers();
  9097. // Cache
  9098. _this.wipeCaches(true);
  9099. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9100. _this.onContextRestoredObservable.notifyObservers(_this);
  9101. _this._contextWasLost = false;
  9102. }, 0);
  9103. };
  9104. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9105. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9106. }
  9107. }
  9108. else {
  9109. this._gl = canvasOrContext;
  9110. this._renderingCanvas = this._gl.canvas;
  9111. if (this._gl.renderbufferStorageMultisample) {
  9112. this._webGLVersion = 2.0;
  9113. }
  9114. options.stencil = this._gl.getContextAttributes().stencil;
  9115. }
  9116. // Viewport
  9117. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9118. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9119. this.resize();
  9120. this._isStencilEnable = options.stencil ? true : false;
  9121. this._initGLContext();
  9122. if (canvas) {
  9123. // Fullscreen
  9124. this._onFullscreenChange = function () {
  9125. if (document.fullscreen !== undefined) {
  9126. _this.isFullscreen = document.fullscreen;
  9127. }
  9128. else if (document.mozFullScreen !== undefined) {
  9129. _this.isFullscreen = document.mozFullScreen;
  9130. }
  9131. else if (document.webkitIsFullScreen !== undefined) {
  9132. _this.isFullscreen = document.webkitIsFullScreen;
  9133. }
  9134. else if (document.msIsFullScreen !== undefined) {
  9135. _this.isFullscreen = document.msIsFullScreen;
  9136. }
  9137. // Pointer lock
  9138. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9139. canvas.requestPointerLock = canvas.requestPointerLock ||
  9140. canvas.msRequestPointerLock ||
  9141. canvas.mozRequestPointerLock ||
  9142. canvas.webkitRequestPointerLock;
  9143. if (canvas.requestPointerLock) {
  9144. canvas.requestPointerLock();
  9145. }
  9146. }
  9147. };
  9148. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9149. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9150. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9151. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9152. // Pointer lock
  9153. this._onPointerLockChange = function () {
  9154. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9155. document.webkitPointerLockElement === canvas ||
  9156. document.msPointerLockElement === canvas ||
  9157. document.pointerLockElement === canvas);
  9158. };
  9159. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9160. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9161. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9162. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9163. this._onVRDisplayPointerRestricted = function () {
  9164. if (canvas) {
  9165. canvas.requestPointerLock();
  9166. }
  9167. };
  9168. this._onVRDisplayPointerUnrestricted = function () {
  9169. document.exitPointerLock();
  9170. };
  9171. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9172. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9173. }
  9174. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9175. Engine.audioEngine = new BABYLON.AudioEngine();
  9176. }
  9177. // Prepare buffer pointers
  9178. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9179. this._currentBufferPointers[i] = new BufferPointer();
  9180. }
  9181. // Load WebVR Devices
  9182. if (options.autoEnableWebVR) {
  9183. this.initWebVR();
  9184. }
  9185. // Detect if we are running on a faulty buggy OS.
  9186. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9187. // Detect if we are running on a faulty buggy desktop OS.
  9188. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9189. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9190. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9191. }
  9192. Object.defineProperty(Engine, "LastCreatedEngine", {
  9193. get: function () {
  9194. if (Engine.Instances.length === 0) {
  9195. return null;
  9196. }
  9197. return Engine.Instances[Engine.Instances.length - 1];
  9198. },
  9199. enumerable: true,
  9200. configurable: true
  9201. });
  9202. Object.defineProperty(Engine, "LastCreatedScene", {
  9203. get: function () {
  9204. var lastCreatedEngine = Engine.LastCreatedEngine;
  9205. if (!lastCreatedEngine) {
  9206. return null;
  9207. }
  9208. if (lastCreatedEngine.scenes.length === 0) {
  9209. return null;
  9210. }
  9211. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9212. },
  9213. enumerable: true,
  9214. configurable: true
  9215. });
  9216. /**
  9217. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9218. */
  9219. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9220. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9221. var engine = Engine.Instances[engineIndex];
  9222. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9223. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9224. }
  9225. }
  9226. };
  9227. Object.defineProperty(Engine, "NEVER", {
  9228. get: function () {
  9229. return Engine._NEVER;
  9230. },
  9231. enumerable: true,
  9232. configurable: true
  9233. });
  9234. Object.defineProperty(Engine, "ALWAYS", {
  9235. get: function () {
  9236. return Engine._ALWAYS;
  9237. },
  9238. enumerable: true,
  9239. configurable: true
  9240. });
  9241. Object.defineProperty(Engine, "LESS", {
  9242. get: function () {
  9243. return Engine._LESS;
  9244. },
  9245. enumerable: true,
  9246. configurable: true
  9247. });
  9248. Object.defineProperty(Engine, "EQUAL", {
  9249. get: function () {
  9250. return Engine._EQUAL;
  9251. },
  9252. enumerable: true,
  9253. configurable: true
  9254. });
  9255. Object.defineProperty(Engine, "LEQUAL", {
  9256. get: function () {
  9257. return Engine._LEQUAL;
  9258. },
  9259. enumerable: true,
  9260. configurable: true
  9261. });
  9262. Object.defineProperty(Engine, "GREATER", {
  9263. get: function () {
  9264. return Engine._GREATER;
  9265. },
  9266. enumerable: true,
  9267. configurable: true
  9268. });
  9269. Object.defineProperty(Engine, "GEQUAL", {
  9270. get: function () {
  9271. return Engine._GEQUAL;
  9272. },
  9273. enumerable: true,
  9274. configurable: true
  9275. });
  9276. Object.defineProperty(Engine, "NOTEQUAL", {
  9277. get: function () {
  9278. return Engine._NOTEQUAL;
  9279. },
  9280. enumerable: true,
  9281. configurable: true
  9282. });
  9283. Object.defineProperty(Engine, "KEEP", {
  9284. get: function () {
  9285. return Engine._KEEP;
  9286. },
  9287. enumerable: true,
  9288. configurable: true
  9289. });
  9290. Object.defineProperty(Engine, "REPLACE", {
  9291. get: function () {
  9292. return Engine._REPLACE;
  9293. },
  9294. enumerable: true,
  9295. configurable: true
  9296. });
  9297. Object.defineProperty(Engine, "INCR", {
  9298. get: function () {
  9299. return Engine._INCR;
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. Object.defineProperty(Engine, "DECR", {
  9305. get: function () {
  9306. return Engine._DECR;
  9307. },
  9308. enumerable: true,
  9309. configurable: true
  9310. });
  9311. Object.defineProperty(Engine, "INVERT", {
  9312. get: function () {
  9313. return Engine._INVERT;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Object.defineProperty(Engine, "INCR_WRAP", {
  9319. get: function () {
  9320. return Engine._INCR_WRAP;
  9321. },
  9322. enumerable: true,
  9323. configurable: true
  9324. });
  9325. Object.defineProperty(Engine, "DECR_WRAP", {
  9326. get: function () {
  9327. return Engine._DECR_WRAP;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9333. get: function () {
  9334. return Engine._ALPHA_DISABLE;
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9340. get: function () {
  9341. return Engine._ALPHA_ONEONE;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Object.defineProperty(Engine, "ALPHA_ADD", {
  9347. get: function () {
  9348. return Engine._ALPHA_ADD;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9354. get: function () {
  9355. return Engine._ALPHA_COMBINE;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9361. get: function () {
  9362. return Engine._ALPHA_SUBTRACT;
  9363. },
  9364. enumerable: true,
  9365. configurable: true
  9366. });
  9367. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9368. get: function () {
  9369. return Engine._ALPHA_MULTIPLY;
  9370. },
  9371. enumerable: true,
  9372. configurable: true
  9373. });
  9374. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9375. get: function () {
  9376. return Engine._ALPHA_MAXIMIZED;
  9377. },
  9378. enumerable: true,
  9379. configurable: true
  9380. });
  9381. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9382. get: function () {
  9383. return Engine._ALPHA_PREMULTIPLIED;
  9384. },
  9385. enumerable: true,
  9386. configurable: true
  9387. });
  9388. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9389. get: function () {
  9390. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9391. },
  9392. enumerable: true,
  9393. configurable: true
  9394. });
  9395. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9396. get: function () {
  9397. return Engine._ALPHA_INTERPOLATE;
  9398. },
  9399. enumerable: true,
  9400. configurable: true
  9401. });
  9402. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9403. get: function () {
  9404. return Engine._ALPHA_SCREENMODE;
  9405. },
  9406. enumerable: true,
  9407. configurable: true
  9408. });
  9409. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9410. get: function () {
  9411. return Engine._DELAYLOADSTATE_NONE;
  9412. },
  9413. enumerable: true,
  9414. configurable: true
  9415. });
  9416. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9417. get: function () {
  9418. return Engine._DELAYLOADSTATE_LOADED;
  9419. },
  9420. enumerable: true,
  9421. configurable: true
  9422. });
  9423. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9424. get: function () {
  9425. return Engine._DELAYLOADSTATE_LOADING;
  9426. },
  9427. enumerable: true,
  9428. configurable: true
  9429. });
  9430. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9431. get: function () {
  9432. return Engine._DELAYLOADSTATE_NOTLOADED;
  9433. },
  9434. enumerable: true,
  9435. configurable: true
  9436. });
  9437. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9438. get: function () {
  9439. return Engine._TEXTUREFORMAT_ALPHA;
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9445. get: function () {
  9446. return Engine._TEXTUREFORMAT_LUMINANCE;
  9447. },
  9448. enumerable: true,
  9449. configurable: true
  9450. });
  9451. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9452. get: function () {
  9453. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9454. },
  9455. enumerable: true,
  9456. configurable: true
  9457. });
  9458. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9459. get: function () {
  9460. return Engine._TEXTUREFORMAT_RGB;
  9461. },
  9462. enumerable: true,
  9463. configurable: true
  9464. });
  9465. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9466. get: function () {
  9467. return Engine._TEXTUREFORMAT_RGBA;
  9468. },
  9469. enumerable: true,
  9470. configurable: true
  9471. });
  9472. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9473. get: function () {
  9474. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9475. },
  9476. enumerable: true,
  9477. configurable: true
  9478. });
  9479. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9480. get: function () {
  9481. return Engine._TEXTURETYPE_FLOAT;
  9482. },
  9483. enumerable: true,
  9484. configurable: true
  9485. });
  9486. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9487. get: function () {
  9488. return Engine._TEXTURETYPE_HALF_FLOAT;
  9489. },
  9490. enumerable: true,
  9491. configurable: true
  9492. });
  9493. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9494. get: function () {
  9495. return Engine._SCALEMODE_FLOOR;
  9496. },
  9497. enumerable: true,
  9498. configurable: true
  9499. });
  9500. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9501. get: function () {
  9502. return Engine._SCALEMODE_NEAREST;
  9503. },
  9504. enumerable: true,
  9505. configurable: true
  9506. });
  9507. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9508. get: function () {
  9509. return Engine._SCALEMODE_CEILING;
  9510. },
  9511. enumerable: true,
  9512. configurable: true
  9513. });
  9514. Object.defineProperty(Engine, "Version", {
  9515. get: function () {
  9516. return "3.2.0-alpha2";
  9517. },
  9518. enumerable: true,
  9519. configurable: true
  9520. });
  9521. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9522. get: function () {
  9523. return this._vrExclusivePointerMode;
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9529. get: function () {
  9530. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9531. },
  9532. enumerable: true,
  9533. configurable: true
  9534. });
  9535. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9536. get: function () {
  9537. return this._webGLVersion < 2 || this.forcePOTTextures;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Object.defineProperty(Engine.prototype, "badOS", {
  9543. get: function () {
  9544. return this._badOS;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9550. get: function () {
  9551. return this._badDesktopOS;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9557. get: function () {
  9558. return this._performanceMonitor;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9564. get: function () {
  9565. return this._texturesSupported;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9571. get: function () {
  9572. return this._textureFormatInUse;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Engine.prototype, "currentViewport", {
  9578. get: function () {
  9579. return this._cachedViewport;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9585. // Empty texture
  9586. get: function () {
  9587. if (!this._emptyTexture) {
  9588. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9589. }
  9590. return this._emptyTexture;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9596. get: function () {
  9597. if (!this._emptyTexture3D) {
  9598. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9599. }
  9600. return this._emptyTexture3D;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9606. get: function () {
  9607. if (!this._emptyCubeTexture) {
  9608. var faceData = new Uint8Array(4);
  9609. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9610. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9611. }
  9612. return this._emptyCubeTexture;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Engine.prototype._rebuildInternalTextures = function () {
  9618. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9619. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9620. var internalTexture = currentState_1[_i];
  9621. internalTexture._rebuild();
  9622. }
  9623. };
  9624. Engine.prototype._rebuildEffects = function () {
  9625. for (var key in this._compiledEffects) {
  9626. var effect = this._compiledEffects[key];
  9627. effect._prepareEffect();
  9628. }
  9629. BABYLON.Effect.ResetCache();
  9630. };
  9631. Engine.prototype._rebuildBuffers = function () {
  9632. // Index / Vertex
  9633. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9634. var scene = _a[_i];
  9635. scene.resetCachedMaterial();
  9636. scene._rebuildGeometries();
  9637. scene._rebuildTextures();
  9638. }
  9639. // Uniforms
  9640. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9641. var uniformBuffer = _c[_b];
  9642. uniformBuffer._rebuild();
  9643. }
  9644. };
  9645. Engine.prototype._initGLContext = function () {
  9646. // Caps
  9647. this._caps = new EngineCapabilities();
  9648. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9649. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9650. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9651. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9652. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9653. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9654. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9655. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9656. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9657. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9658. // Infos
  9659. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9660. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9661. if (rendererInfo != null) {
  9662. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9663. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9664. }
  9665. if (!this._glVendor) {
  9666. this._glVendor = "Unknown vendor";
  9667. }
  9668. if (!this._glRenderer) {
  9669. this._glRenderer = "Unknown renderer";
  9670. }
  9671. // Constants
  9672. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9673. if (this._gl.RGBA16F !== 0x881A) {
  9674. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9675. }
  9676. if (this._gl.RGBA32F !== 0x8814) {
  9677. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9678. }
  9679. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9680. this._gl.DEPTH24_STENCIL8 = 35056;
  9681. }
  9682. // Extensions
  9683. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9684. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9685. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9686. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9687. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9688. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9689. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9690. 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');
  9691. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9692. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9693. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9694. this._caps.highPrecisionShaderSupported = true;
  9695. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9696. if (this._caps.timerQuery) {
  9697. if (this._webGLVersion === 1) {
  9698. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9699. }
  9700. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9701. }
  9702. // Checks if some of the format renders first to allow the use of webgl inspector.
  9703. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9704. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9705. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9706. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9707. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9708. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9709. if (this._webGLVersion > 1) {
  9710. this._gl.HALF_FLOAT_OES = 0x140B;
  9711. }
  9712. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9713. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9714. // Draw buffers
  9715. if (this._webGLVersion > 1) {
  9716. this._caps.drawBuffersExtension = true;
  9717. }
  9718. else {
  9719. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9720. if (drawBuffersExtension !== null) {
  9721. this._caps.drawBuffersExtension = true;
  9722. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9723. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9724. for (var i = 0; i < 16; i++) {
  9725. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9726. }
  9727. }
  9728. else {
  9729. this._caps.drawBuffersExtension = false;
  9730. }
  9731. }
  9732. // Depth Texture
  9733. if (this._webGLVersion > 1) {
  9734. this._caps.depthTextureExtension = true;
  9735. }
  9736. else {
  9737. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9738. if (depthTextureExtension != null) {
  9739. this._caps.depthTextureExtension = true;
  9740. }
  9741. }
  9742. // Vertex array object
  9743. if (this._webGLVersion > 1) {
  9744. this._caps.vertexArrayObject = true;
  9745. }
  9746. else {
  9747. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9748. if (vertexArrayObjectExtension != null) {
  9749. this._caps.vertexArrayObject = true;
  9750. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9751. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9752. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9753. }
  9754. else {
  9755. this._caps.vertexArrayObject = false;
  9756. }
  9757. }
  9758. // Instances count
  9759. if (this._webGLVersion > 1) {
  9760. this._caps.instancedArrays = true;
  9761. }
  9762. else {
  9763. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9764. if (instanceExtension != null) {
  9765. this._caps.instancedArrays = true;
  9766. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9767. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9768. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9769. }
  9770. else {
  9771. this._caps.instancedArrays = false;
  9772. }
  9773. }
  9774. // Intelligently add supported compressed formats in order to check for.
  9775. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9776. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9777. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9778. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9779. if (this._caps.astc)
  9780. this.texturesSupported.push('-astc.ktx');
  9781. if (this._caps.s3tc)
  9782. this.texturesSupported.push('-dxt.ktx');
  9783. if (this._caps.pvrtc)
  9784. this.texturesSupported.push('-pvrtc.ktx');
  9785. if (this._caps.etc2)
  9786. this.texturesSupported.push('-etc2.ktx');
  9787. if (this._caps.etc1)
  9788. this.texturesSupported.push('-etc1.ktx');
  9789. if (this._gl.getShaderPrecisionFormat) {
  9790. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9791. if (highp) {
  9792. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9793. }
  9794. }
  9795. // Depth buffer
  9796. this.setDepthBuffer(true);
  9797. this.setDepthFunctionToLessOrEqual();
  9798. this.setDepthWrite(true);
  9799. // Texture maps
  9800. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9801. this._nextFreeTextureSlots.push(slot);
  9802. }
  9803. };
  9804. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9805. get: function () {
  9806. return this._webGLVersion;
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9812. /**
  9813. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9814. */
  9815. get: function () {
  9816. return this._isStencilEnable;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Engine.prototype._prepareWorkingCanvas = function () {
  9822. if (this._workingCanvas) {
  9823. return;
  9824. }
  9825. this._workingCanvas = document.createElement("canvas");
  9826. var context = this._workingCanvas.getContext("2d");
  9827. if (context) {
  9828. this._workingContext = context;
  9829. }
  9830. };
  9831. Engine.prototype.resetTextureCache = function () {
  9832. for (var key in this._boundTexturesCache) {
  9833. var boundTexture = this._boundTexturesCache[key];
  9834. if (boundTexture) {
  9835. this._removeDesignatedSlot(boundTexture);
  9836. }
  9837. this._boundTexturesCache[key] = null;
  9838. }
  9839. this._nextFreeTextureSlots = [];
  9840. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9841. this._nextFreeTextureSlots.push(slot);
  9842. }
  9843. this._activeChannel = -1;
  9844. };
  9845. Engine.prototype.isDeterministicLockStep = function () {
  9846. return this._deterministicLockstep;
  9847. };
  9848. Engine.prototype.getLockstepMaxSteps = function () {
  9849. return this._lockstepMaxSteps;
  9850. };
  9851. Engine.prototype.getGlInfo = function () {
  9852. return {
  9853. vendor: this._glVendor,
  9854. renderer: this._glRenderer,
  9855. version: this._glVersion
  9856. };
  9857. };
  9858. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9859. if (useScreen === void 0) { useScreen = false; }
  9860. var viewport = camera.viewport;
  9861. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9862. };
  9863. Engine.prototype.getRenderWidth = function (useScreen) {
  9864. if (useScreen === void 0) { useScreen = false; }
  9865. if (!useScreen && this._currentRenderTarget) {
  9866. return this._currentRenderTarget.width;
  9867. }
  9868. return this._gl.drawingBufferWidth;
  9869. };
  9870. Engine.prototype.getRenderHeight = function (useScreen) {
  9871. if (useScreen === void 0) { useScreen = false; }
  9872. if (!useScreen && this._currentRenderTarget) {
  9873. return this._currentRenderTarget.height;
  9874. }
  9875. return this._gl.drawingBufferHeight;
  9876. };
  9877. Engine.prototype.getRenderingCanvas = function () {
  9878. return this._renderingCanvas;
  9879. };
  9880. Engine.prototype.getRenderingCanvasClientRect = function () {
  9881. if (!this._renderingCanvas) {
  9882. return null;
  9883. }
  9884. return this._renderingCanvas.getBoundingClientRect();
  9885. };
  9886. Engine.prototype.setHardwareScalingLevel = function (level) {
  9887. this._hardwareScalingLevel = level;
  9888. this.resize();
  9889. };
  9890. Engine.prototype.getHardwareScalingLevel = function () {
  9891. return this._hardwareScalingLevel;
  9892. };
  9893. Engine.prototype.getLoadedTexturesCache = function () {
  9894. return this._internalTexturesCache;
  9895. };
  9896. Engine.prototype.getCaps = function () {
  9897. return this._caps;
  9898. };
  9899. Object.defineProperty(Engine.prototype, "drawCalls", {
  9900. /** The number of draw calls submitted last frame */
  9901. get: function () {
  9902. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9903. return 0;
  9904. },
  9905. enumerable: true,
  9906. configurable: true
  9907. });
  9908. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9909. get: function () {
  9910. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9911. return null;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Engine.prototype.getDepthFunction = function () {
  9917. return this._depthCullingState.depthFunc;
  9918. };
  9919. Engine.prototype.setDepthFunction = function (depthFunc) {
  9920. this._depthCullingState.depthFunc = depthFunc;
  9921. };
  9922. Engine.prototype.setDepthFunctionToGreater = function () {
  9923. this._depthCullingState.depthFunc = this._gl.GREATER;
  9924. };
  9925. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9926. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9927. };
  9928. Engine.prototype.setDepthFunctionToLess = function () {
  9929. this._depthCullingState.depthFunc = this._gl.LESS;
  9930. };
  9931. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9932. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9933. };
  9934. Engine.prototype.getStencilBuffer = function () {
  9935. return this._stencilState.stencilTest;
  9936. };
  9937. Engine.prototype.setStencilBuffer = function (enable) {
  9938. this._stencilState.stencilTest = enable;
  9939. };
  9940. Engine.prototype.getStencilMask = function () {
  9941. return this._stencilState.stencilMask;
  9942. };
  9943. Engine.prototype.setStencilMask = function (mask) {
  9944. this._stencilState.stencilMask = mask;
  9945. };
  9946. Engine.prototype.getStencilFunction = function () {
  9947. return this._stencilState.stencilFunc;
  9948. };
  9949. Engine.prototype.getStencilFunctionReference = function () {
  9950. return this._stencilState.stencilFuncRef;
  9951. };
  9952. Engine.prototype.getStencilFunctionMask = function () {
  9953. return this._stencilState.stencilFuncMask;
  9954. };
  9955. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9956. this._stencilState.stencilFunc = stencilFunc;
  9957. };
  9958. Engine.prototype.setStencilFunctionReference = function (reference) {
  9959. this._stencilState.stencilFuncRef = reference;
  9960. };
  9961. Engine.prototype.setStencilFunctionMask = function (mask) {
  9962. this._stencilState.stencilFuncMask = mask;
  9963. };
  9964. Engine.prototype.getStencilOperationFail = function () {
  9965. return this._stencilState.stencilOpStencilFail;
  9966. };
  9967. Engine.prototype.getStencilOperationDepthFail = function () {
  9968. return this._stencilState.stencilOpDepthFail;
  9969. };
  9970. Engine.prototype.getStencilOperationPass = function () {
  9971. return this._stencilState.stencilOpStencilDepthPass;
  9972. };
  9973. Engine.prototype.setStencilOperationFail = function (operation) {
  9974. this._stencilState.stencilOpStencilFail = operation;
  9975. };
  9976. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9977. this._stencilState.stencilOpDepthFail = operation;
  9978. };
  9979. Engine.prototype.setStencilOperationPass = function (operation) {
  9980. this._stencilState.stencilOpStencilDepthPass = operation;
  9981. };
  9982. Engine.prototype.setDitheringState = function (value) {
  9983. if (value) {
  9984. this._gl.enable(this._gl.DITHER);
  9985. }
  9986. else {
  9987. this._gl.disable(this._gl.DITHER);
  9988. }
  9989. };
  9990. Engine.prototype.setRasterizerState = function (value) {
  9991. if (value) {
  9992. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9993. }
  9994. else {
  9995. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9996. }
  9997. };
  9998. /**
  9999. * stop executing a render loop function and remove it from the execution array
  10000. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10001. */
  10002. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10003. if (!renderFunction) {
  10004. this._activeRenderLoops = [];
  10005. return;
  10006. }
  10007. var index = this._activeRenderLoops.indexOf(renderFunction);
  10008. if (index >= 0) {
  10009. this._activeRenderLoops.splice(index, 1);
  10010. }
  10011. };
  10012. Engine.prototype._renderLoop = function () {
  10013. if (!this._contextWasLost) {
  10014. var shouldRender = true;
  10015. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10016. shouldRender = false;
  10017. }
  10018. if (shouldRender) {
  10019. // Start new frame
  10020. this.beginFrame();
  10021. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10022. var renderFunction = this._activeRenderLoops[index];
  10023. renderFunction();
  10024. }
  10025. // Present
  10026. this.endFrame();
  10027. }
  10028. }
  10029. if (this._activeRenderLoops.length > 0) {
  10030. // Register new frame
  10031. var requester = null;
  10032. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10033. requester = this._vrDisplay;
  10034. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10035. }
  10036. else {
  10037. this._renderingQueueLaunched = false;
  10038. }
  10039. };
  10040. /**
  10041. * Register and execute a render loop. The engine can have more than one render function.
  10042. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10043. * @example
  10044. * engine.runRenderLoop(function () {
  10045. * scene.render()
  10046. * })
  10047. */
  10048. Engine.prototype.runRenderLoop = function (renderFunction) {
  10049. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10050. return;
  10051. }
  10052. this._activeRenderLoops.push(renderFunction);
  10053. if (!this._renderingQueueLaunched) {
  10054. this._renderingQueueLaunched = true;
  10055. this._bindedRenderFunction = this._renderLoop.bind(this);
  10056. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10057. }
  10058. };
  10059. /**
  10060. * Toggle full screen mode.
  10061. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10062. * @param {any} options - an options object to be sent to the requestFullscreen function
  10063. */
  10064. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10065. if (this.isFullscreen) {
  10066. BABYLON.Tools.ExitFullscreen();
  10067. }
  10068. else {
  10069. this._pointerLockRequested = requestPointerLock;
  10070. if (this._renderingCanvas) {
  10071. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10072. }
  10073. }
  10074. };
  10075. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10076. if (stencil === void 0) { stencil = false; }
  10077. this.applyStates();
  10078. var mode = 0;
  10079. if (backBuffer && color) {
  10080. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10081. mode |= this._gl.COLOR_BUFFER_BIT;
  10082. }
  10083. if (depth) {
  10084. this._gl.clearDepth(1.0);
  10085. mode |= this._gl.DEPTH_BUFFER_BIT;
  10086. }
  10087. if (stencil) {
  10088. this._gl.clearStencil(0);
  10089. mode |= this._gl.STENCIL_BUFFER_BIT;
  10090. }
  10091. this._gl.clear(mode);
  10092. };
  10093. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10094. var gl = this._gl;
  10095. // Save state
  10096. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10097. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10098. // Change state
  10099. gl.enable(gl.SCISSOR_TEST);
  10100. gl.scissor(x, y, width, height);
  10101. // Clear
  10102. this.clear(clearColor, true, true, true);
  10103. // Restore state
  10104. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10105. if (curScissor === true) {
  10106. gl.enable(gl.SCISSOR_TEST);
  10107. }
  10108. else {
  10109. gl.disable(gl.SCISSOR_TEST);
  10110. }
  10111. };
  10112. /**
  10113. * Set the WebGL's viewport
  10114. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10115. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10116. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10117. */
  10118. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10119. var width = requiredWidth || this.getRenderWidth();
  10120. var height = requiredHeight || this.getRenderHeight();
  10121. var x = viewport.x || 0;
  10122. var y = viewport.y || 0;
  10123. this._cachedViewport = viewport;
  10124. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10125. };
  10126. /**
  10127. * Directly set the WebGL Viewport
  10128. * The x, y, width & height are directly passed to the WebGL call
  10129. * @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.
  10130. */
  10131. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10132. var currentViewport = this._cachedViewport;
  10133. this._cachedViewport = null;
  10134. this._gl.viewport(x, y, width, height);
  10135. return currentViewport;
  10136. };
  10137. Engine.prototype.beginFrame = function () {
  10138. this.onBeginFrameObservable.notifyObservers(this);
  10139. this._measureFps();
  10140. };
  10141. Engine.prototype.endFrame = function () {
  10142. //force a flush in case we are using a bad OS.
  10143. if (this._badOS) {
  10144. this.flushFramebuffer();
  10145. }
  10146. //submit frame to the vr device, if enabled
  10147. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10148. // TODO: We should only submit the frame if we read frameData successfully.
  10149. this._vrDisplay.submitFrame();
  10150. }
  10151. this.onEndFrameObservable.notifyObservers(this);
  10152. };
  10153. /**
  10154. * resize the view according to the canvas' size.
  10155. * @example
  10156. * window.addEventListener("resize", function () {
  10157. * engine.resize();
  10158. * });
  10159. */
  10160. Engine.prototype.resize = function () {
  10161. // We're not resizing the size of the canvas while in VR mode & presenting
  10162. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10163. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10164. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10165. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10166. }
  10167. };
  10168. /**
  10169. * force a specific size of the canvas
  10170. * @param {number} width - the new canvas' width
  10171. * @param {number} height - the new canvas' height
  10172. */
  10173. Engine.prototype.setSize = function (width, height) {
  10174. if (!this._renderingCanvas) {
  10175. return;
  10176. }
  10177. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10178. return;
  10179. }
  10180. this._renderingCanvas.width = width;
  10181. this._renderingCanvas.height = height;
  10182. for (var index = 0; index < this.scenes.length; index++) {
  10183. var scene = this.scenes[index];
  10184. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10185. var cam = scene.cameras[camIndex];
  10186. cam._currentRenderId = 0;
  10187. }
  10188. }
  10189. if (this.onResizeObservable.hasObservers) {
  10190. this.onResizeObservable.notifyObservers(this);
  10191. }
  10192. };
  10193. // WebVR functions
  10194. Engine.prototype.isVRDevicePresent = function () {
  10195. return !!this._vrDisplay;
  10196. };
  10197. Engine.prototype.getVRDevice = function () {
  10198. return this._vrDisplay;
  10199. };
  10200. Engine.prototype.initWebVR = function () {
  10201. var _this = this;
  10202. var notifyObservers = function () {
  10203. var eventArgs = {
  10204. vrDisplay: _this._vrDisplay,
  10205. vrSupported: _this._vrSupported
  10206. };
  10207. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10208. };
  10209. if (!this._onVrDisplayConnect) {
  10210. this._onVrDisplayConnect = function (event) {
  10211. _this._vrDisplay = event.display;
  10212. notifyObservers();
  10213. };
  10214. this._onVrDisplayDisconnect = function () {
  10215. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10216. _this._vrDisplay = undefined;
  10217. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10218. notifyObservers();
  10219. };
  10220. this._onVrDisplayPresentChange = function () {
  10221. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10222. };
  10223. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10224. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10225. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10226. }
  10227. this._getVRDisplays(notifyObservers);
  10228. return this.onVRDisplayChangedObservable;
  10229. };
  10230. Engine.prototype.enableVR = function () {
  10231. var _this = this;
  10232. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10233. var onResolved = function () {
  10234. _this.onVRRequestPresentComplete.notifyObservers(true);
  10235. _this._onVRFullScreenTriggered();
  10236. };
  10237. var onRejected = function () {
  10238. _this.onVRRequestPresentComplete.notifyObservers(false);
  10239. };
  10240. this.onVRRequestPresentStart.notifyObservers(this);
  10241. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10242. }
  10243. };
  10244. Engine.prototype.disableVR = function () {
  10245. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10246. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10247. }
  10248. };
  10249. Engine.prototype._getVRDisplays = function (callback) {
  10250. var _this = this;
  10251. var getWebVRDevices = function (devices) {
  10252. _this._vrSupported = true;
  10253. // note that devices may actually be an empty array. This is fine;
  10254. // we expect this._vrDisplay to be undefined in this case.
  10255. return _this._vrDisplay = devices[0];
  10256. };
  10257. if (navigator.getVRDisplays) {
  10258. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10259. // TODO: System CANNOT support WebVR, despite API presence.
  10260. _this._vrSupported = false;
  10261. callback();
  10262. });
  10263. }
  10264. else {
  10265. // TODO: Browser does not support WebVR
  10266. this._vrDisplay = undefined;
  10267. this._vrSupported = false;
  10268. callback();
  10269. }
  10270. };
  10271. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10272. if (this._currentRenderTarget) {
  10273. this.unBindFramebuffer(this._currentRenderTarget);
  10274. }
  10275. this._currentRenderTarget = texture;
  10276. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10277. var gl = this._gl;
  10278. if (texture.isCube) {
  10279. if (faceIndex === undefined) {
  10280. faceIndex = 0;
  10281. }
  10282. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10283. }
  10284. if (this._cachedViewport && !forceFullscreenViewport) {
  10285. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10286. }
  10287. else {
  10288. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10289. }
  10290. this.wipeCaches();
  10291. };
  10292. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10293. if (this._currentFramebuffer !== framebuffer) {
  10294. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10295. this._currentFramebuffer = framebuffer;
  10296. }
  10297. };
  10298. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10299. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10300. this._currentRenderTarget = null;
  10301. // If MSAA, we need to bitblt back to main texture
  10302. var gl = this._gl;
  10303. if (texture._MSAAFramebuffer) {
  10304. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10305. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10306. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10307. }
  10308. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10309. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10310. gl.generateMipmap(gl.TEXTURE_2D);
  10311. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10312. }
  10313. if (onBeforeUnbind) {
  10314. if (texture._MSAAFramebuffer) {
  10315. // Bind the correct framebuffer
  10316. this.bindUnboundFramebuffer(texture._framebuffer);
  10317. }
  10318. onBeforeUnbind();
  10319. }
  10320. this.bindUnboundFramebuffer(null);
  10321. };
  10322. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10323. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10324. this._currentRenderTarget = null;
  10325. // If MSAA, we need to bitblt back to main texture
  10326. var gl = this._gl;
  10327. if (textures[0]._MSAAFramebuffer) {
  10328. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10329. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10330. var attachments = textures[0]._attachments;
  10331. if (!attachments) {
  10332. attachments = new Array(textures.length);
  10333. textures[0]._attachments = attachments;
  10334. }
  10335. for (var i = 0; i < textures.length; i++) {
  10336. var texture = textures[i];
  10337. for (var j = 0; j < attachments.length; j++) {
  10338. attachments[j] = gl.NONE;
  10339. }
  10340. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10341. gl.readBuffer(attachments[i]);
  10342. gl.drawBuffers(attachments);
  10343. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10344. }
  10345. for (var i = 0; i < attachments.length; i++) {
  10346. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10347. }
  10348. gl.drawBuffers(attachments);
  10349. }
  10350. for (var i = 0; i < textures.length; i++) {
  10351. var texture = textures[i];
  10352. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10353. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10354. gl.generateMipmap(gl.TEXTURE_2D);
  10355. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10356. }
  10357. }
  10358. if (onBeforeUnbind) {
  10359. if (textures[0]._MSAAFramebuffer) {
  10360. // Bind the correct framebuffer
  10361. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10362. }
  10363. onBeforeUnbind();
  10364. }
  10365. this.bindUnboundFramebuffer(null);
  10366. };
  10367. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10368. if (texture.generateMipMaps) {
  10369. var gl = this._gl;
  10370. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10371. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10372. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10373. }
  10374. };
  10375. Engine.prototype.flushFramebuffer = function () {
  10376. this._gl.flush();
  10377. };
  10378. Engine.prototype.restoreDefaultFramebuffer = function () {
  10379. if (this._currentRenderTarget) {
  10380. this.unBindFramebuffer(this._currentRenderTarget);
  10381. }
  10382. else {
  10383. this.bindUnboundFramebuffer(null);
  10384. }
  10385. if (this._cachedViewport) {
  10386. this.setViewport(this._cachedViewport);
  10387. }
  10388. this.wipeCaches();
  10389. };
  10390. // UBOs
  10391. Engine.prototype.createUniformBuffer = function (elements) {
  10392. var ubo = this._gl.createBuffer();
  10393. if (!ubo) {
  10394. throw new Error("Unable to create uniform buffer");
  10395. }
  10396. this.bindUniformBuffer(ubo);
  10397. if (elements instanceof Float32Array) {
  10398. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10399. }
  10400. else {
  10401. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10402. }
  10403. this.bindUniformBuffer(null);
  10404. ubo.references = 1;
  10405. return ubo;
  10406. };
  10407. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10408. var ubo = this._gl.createBuffer();
  10409. if (!ubo) {
  10410. throw new Error("Unable to create dynamic uniform buffer");
  10411. }
  10412. this.bindUniformBuffer(ubo);
  10413. if (elements instanceof Float32Array) {
  10414. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10415. }
  10416. else {
  10417. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10418. }
  10419. this.bindUniformBuffer(null);
  10420. ubo.references = 1;
  10421. return ubo;
  10422. };
  10423. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10424. this.bindUniformBuffer(uniformBuffer);
  10425. if (offset === undefined) {
  10426. offset = 0;
  10427. }
  10428. if (count === undefined) {
  10429. if (elements instanceof Float32Array) {
  10430. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10431. }
  10432. else {
  10433. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10434. }
  10435. }
  10436. else {
  10437. if (elements instanceof Float32Array) {
  10438. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10439. }
  10440. else {
  10441. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10442. }
  10443. }
  10444. this.bindUniformBuffer(null);
  10445. };
  10446. // VBOs
  10447. Engine.prototype._resetVertexBufferBinding = function () {
  10448. this.bindArrayBuffer(null);
  10449. this._cachedVertexBuffers = null;
  10450. };
  10451. Engine.prototype.createVertexBuffer = function (vertices) {
  10452. var vbo = this._gl.createBuffer();
  10453. if (!vbo) {
  10454. throw new Error("Unable to create vertex buffer");
  10455. }
  10456. this.bindArrayBuffer(vbo);
  10457. if (vertices instanceof Float32Array) {
  10458. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10459. }
  10460. else {
  10461. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10462. }
  10463. this._resetVertexBufferBinding();
  10464. vbo.references = 1;
  10465. return vbo;
  10466. };
  10467. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10468. var vbo = this._gl.createBuffer();
  10469. if (!vbo) {
  10470. throw new Error("Unable to create dynamic vertex buffer");
  10471. }
  10472. this.bindArrayBuffer(vbo);
  10473. if (vertices instanceof Float32Array) {
  10474. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10475. }
  10476. else {
  10477. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10478. }
  10479. this._resetVertexBufferBinding();
  10480. vbo.references = 1;
  10481. return vbo;
  10482. };
  10483. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10484. if (offset === void 0) { offset = 0; }
  10485. // Force cache update
  10486. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10487. this.bindIndexBuffer(indexBuffer);
  10488. var arrayBuffer;
  10489. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10490. arrayBuffer = indices;
  10491. }
  10492. else {
  10493. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10494. }
  10495. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10496. this._resetIndexBufferBinding();
  10497. };
  10498. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10499. this.bindArrayBuffer(vertexBuffer);
  10500. if (offset === undefined) {
  10501. offset = 0;
  10502. }
  10503. if (count === undefined) {
  10504. if (vertices instanceof Float32Array) {
  10505. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10506. }
  10507. else {
  10508. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10509. }
  10510. }
  10511. else {
  10512. if (vertices instanceof Float32Array) {
  10513. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10514. }
  10515. else {
  10516. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10517. }
  10518. }
  10519. this._resetVertexBufferBinding();
  10520. };
  10521. Engine.prototype._resetIndexBufferBinding = function () {
  10522. this.bindIndexBuffer(null);
  10523. this._cachedIndexBuffer = null;
  10524. };
  10525. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10526. var vbo = this._gl.createBuffer();
  10527. if (!vbo) {
  10528. throw new Error("Unable to create index buffer");
  10529. }
  10530. this.bindIndexBuffer(vbo);
  10531. // Check for 32 bits indices
  10532. var arrayBuffer;
  10533. var need32Bits = false;
  10534. if (indices instanceof Uint16Array) {
  10535. arrayBuffer = indices;
  10536. }
  10537. else {
  10538. //check 32 bit support
  10539. if (this._caps.uintIndices) {
  10540. if (indices instanceof Uint32Array) {
  10541. arrayBuffer = indices;
  10542. need32Bits = true;
  10543. }
  10544. else {
  10545. //number[] or Int32Array, check if 32 bit is necessary
  10546. for (var index = 0; index < indices.length; index++) {
  10547. if (indices[index] > 65535) {
  10548. need32Bits = true;
  10549. break;
  10550. }
  10551. }
  10552. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10553. }
  10554. }
  10555. else {
  10556. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10557. arrayBuffer = new Uint16Array(indices);
  10558. }
  10559. }
  10560. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10561. this._resetIndexBufferBinding();
  10562. vbo.references = 1;
  10563. vbo.is32Bits = need32Bits;
  10564. return vbo;
  10565. };
  10566. Engine.prototype.bindArrayBuffer = function (buffer) {
  10567. if (!this._vaoRecordInProgress) {
  10568. this._unbindVertexArrayObject();
  10569. }
  10570. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10571. };
  10572. Engine.prototype.bindUniformBuffer = function (buffer) {
  10573. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10574. };
  10575. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10576. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10577. };
  10578. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10579. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10580. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10581. };
  10582. ;
  10583. Engine.prototype.bindIndexBuffer = function (buffer) {
  10584. if (!this._vaoRecordInProgress) {
  10585. this._unbindVertexArrayObject();
  10586. }
  10587. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10588. };
  10589. Engine.prototype.bindBuffer = function (buffer, target) {
  10590. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10591. this._gl.bindBuffer(target, buffer);
  10592. this._currentBoundBuffer[target] = buffer;
  10593. }
  10594. };
  10595. Engine.prototype.updateArrayBuffer = function (data) {
  10596. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10597. };
  10598. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10599. var pointer = this._currentBufferPointers[indx];
  10600. var changed = false;
  10601. if (!pointer.active) {
  10602. changed = true;
  10603. pointer.active = true;
  10604. pointer.index = indx;
  10605. pointer.size = size;
  10606. pointer.type = type;
  10607. pointer.normalized = normalized;
  10608. pointer.stride = stride;
  10609. pointer.offset = offset;
  10610. pointer.buffer = buffer;
  10611. }
  10612. else {
  10613. if (pointer.buffer !== buffer) {
  10614. pointer.buffer = buffer;
  10615. changed = true;
  10616. }
  10617. if (pointer.size !== size) {
  10618. pointer.size = size;
  10619. changed = true;
  10620. }
  10621. if (pointer.type !== type) {
  10622. pointer.type = type;
  10623. changed = true;
  10624. }
  10625. if (pointer.normalized !== normalized) {
  10626. pointer.normalized = normalized;
  10627. changed = true;
  10628. }
  10629. if (pointer.stride !== stride) {
  10630. pointer.stride = stride;
  10631. changed = true;
  10632. }
  10633. if (pointer.offset !== offset) {
  10634. pointer.offset = offset;
  10635. changed = true;
  10636. }
  10637. }
  10638. if (changed || this._vaoRecordInProgress) {
  10639. this.bindArrayBuffer(buffer);
  10640. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10641. }
  10642. };
  10643. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10644. if (indexBuffer == null) {
  10645. return;
  10646. }
  10647. if (this._cachedIndexBuffer !== indexBuffer) {
  10648. this._cachedIndexBuffer = indexBuffer;
  10649. this.bindIndexBuffer(indexBuffer);
  10650. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10651. }
  10652. };
  10653. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10654. var attributes = effect.getAttributesNames();
  10655. if (!this._vaoRecordInProgress) {
  10656. this._unbindVertexArrayObject();
  10657. }
  10658. this.unbindAllAttributes();
  10659. for (var index = 0; index < attributes.length; index++) {
  10660. var order = effect.getAttributeLocation(index);
  10661. if (order >= 0) {
  10662. var vertexBuffer = vertexBuffers[attributes[index]];
  10663. if (!vertexBuffer) {
  10664. continue;
  10665. }
  10666. this._gl.enableVertexAttribArray(order);
  10667. if (!this._vaoRecordInProgress) {
  10668. this._vertexAttribArraysEnabled[order] = true;
  10669. }
  10670. var buffer = vertexBuffer.getBuffer();
  10671. if (buffer) {
  10672. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10673. if (vertexBuffer.getIsInstanced()) {
  10674. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10675. if (!this._vaoRecordInProgress) {
  10676. this._currentInstanceLocations.push(order);
  10677. this._currentInstanceBuffers.push(buffer);
  10678. }
  10679. }
  10680. }
  10681. }
  10682. }
  10683. };
  10684. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10685. var vao = this._gl.createVertexArray();
  10686. this._vaoRecordInProgress = true;
  10687. this._gl.bindVertexArray(vao);
  10688. this._mustWipeVertexAttributes = true;
  10689. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10690. this.bindIndexBuffer(indexBuffer);
  10691. this._vaoRecordInProgress = false;
  10692. this._gl.bindVertexArray(null);
  10693. return vao;
  10694. };
  10695. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10696. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10697. this._cachedVertexArrayObject = vertexArrayObject;
  10698. this._gl.bindVertexArray(vertexArrayObject);
  10699. this._cachedVertexBuffers = null;
  10700. this._cachedIndexBuffer = null;
  10701. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10702. this._mustWipeVertexAttributes = true;
  10703. }
  10704. };
  10705. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10706. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10707. this._cachedVertexBuffers = vertexBuffer;
  10708. this._cachedEffectForVertexBuffers = effect;
  10709. var attributesCount = effect.getAttributesCount();
  10710. this._unbindVertexArrayObject();
  10711. this.unbindAllAttributes();
  10712. var offset = 0;
  10713. for (var index = 0; index < attributesCount; index++) {
  10714. if (index < vertexDeclaration.length) {
  10715. var order = effect.getAttributeLocation(index);
  10716. if (order >= 0) {
  10717. this._gl.enableVertexAttribArray(order);
  10718. this._vertexAttribArraysEnabled[order] = true;
  10719. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10720. }
  10721. offset += vertexDeclaration[index] * 4;
  10722. }
  10723. }
  10724. }
  10725. this._bindIndexBufferWithCache(indexBuffer);
  10726. };
  10727. Engine.prototype._unbindVertexArrayObject = function () {
  10728. if (!this._cachedVertexArrayObject) {
  10729. return;
  10730. }
  10731. this._cachedVertexArrayObject = null;
  10732. this._gl.bindVertexArray(null);
  10733. };
  10734. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10735. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10736. this._cachedVertexBuffers = vertexBuffers;
  10737. this._cachedEffectForVertexBuffers = effect;
  10738. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10739. }
  10740. this._bindIndexBufferWithCache(indexBuffer);
  10741. };
  10742. Engine.prototype.unbindInstanceAttributes = function () {
  10743. var boundBuffer;
  10744. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10745. var instancesBuffer = this._currentInstanceBuffers[i];
  10746. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10747. boundBuffer = instancesBuffer;
  10748. this.bindArrayBuffer(instancesBuffer);
  10749. }
  10750. var offsetLocation = this._currentInstanceLocations[i];
  10751. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10752. }
  10753. this._currentInstanceBuffers.length = 0;
  10754. this._currentInstanceLocations.length = 0;
  10755. };
  10756. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10757. this._gl.deleteVertexArray(vao);
  10758. };
  10759. Engine.prototype._releaseBuffer = function (buffer) {
  10760. buffer.references--;
  10761. if (buffer.references === 0) {
  10762. this._gl.deleteBuffer(buffer);
  10763. return true;
  10764. }
  10765. return false;
  10766. };
  10767. Engine.prototype.createInstancesBuffer = function (capacity) {
  10768. var buffer = this._gl.createBuffer();
  10769. if (!buffer) {
  10770. throw new Error("Unable to create instance buffer");
  10771. }
  10772. buffer.capacity = capacity;
  10773. this.bindArrayBuffer(buffer);
  10774. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10775. return buffer;
  10776. };
  10777. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10778. this._gl.deleteBuffer(buffer);
  10779. };
  10780. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10781. this.bindArrayBuffer(instancesBuffer);
  10782. if (data) {
  10783. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10784. }
  10785. if (offsetLocations[0].index !== undefined) {
  10786. var stride = 0;
  10787. for (var i = 0; i < offsetLocations.length; i++) {
  10788. var ai = offsetLocations[i];
  10789. stride += ai.attributeSize * 4;
  10790. }
  10791. for (var i = 0; i < offsetLocations.length; i++) {
  10792. var ai = offsetLocations[i];
  10793. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10794. this._gl.enableVertexAttribArray(ai.index);
  10795. this._vertexAttribArraysEnabled[ai.index] = true;
  10796. }
  10797. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10798. this._gl.vertexAttribDivisor(ai.index, 1);
  10799. this._currentInstanceLocations.push(ai.index);
  10800. this._currentInstanceBuffers.push(instancesBuffer);
  10801. }
  10802. }
  10803. else {
  10804. for (var index = 0; index < 4; index++) {
  10805. var offsetLocation = offsetLocations[index];
  10806. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10807. this._gl.enableVertexAttribArray(offsetLocation);
  10808. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10809. }
  10810. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10811. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10812. this._currentInstanceLocations.push(offsetLocation);
  10813. this._currentInstanceBuffers.push(instancesBuffer);
  10814. }
  10815. }
  10816. };
  10817. Engine.prototype.applyStates = function () {
  10818. this._depthCullingState.apply(this._gl);
  10819. this._stencilState.apply(this._gl);
  10820. this._alphaState.apply(this._gl);
  10821. };
  10822. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10823. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10824. };
  10825. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10826. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10827. };
  10828. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10829. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10830. };
  10831. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10832. // Apply states
  10833. this.applyStates();
  10834. this._drawCalls.addCount(1, false);
  10835. // Render
  10836. var drawMode = this.DrawMode(fillMode);
  10837. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10838. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10839. if (instancesCount) {
  10840. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10841. }
  10842. else {
  10843. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10844. }
  10845. };
  10846. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10847. // Apply states
  10848. this.applyStates();
  10849. this._drawCalls.addCount(1, false);
  10850. var drawMode = this.DrawMode(fillMode);
  10851. if (instancesCount) {
  10852. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10853. }
  10854. else {
  10855. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10856. }
  10857. };
  10858. Engine.prototype.DrawMode = function (fillMode) {
  10859. switch (fillMode) {
  10860. // Triangle views
  10861. case BABYLON.Material.TriangleFillMode:
  10862. return this._gl.TRIANGLES;
  10863. case BABYLON.Material.PointFillMode:
  10864. return this._gl.POINTS;
  10865. case BABYLON.Material.WireFrameFillMode:
  10866. return this._gl.LINES;
  10867. // Draw modes
  10868. case BABYLON.Material.PointListDrawMode:
  10869. return this._gl.POINTS;
  10870. case BABYLON.Material.LineListDrawMode:
  10871. return this._gl.LINES;
  10872. case BABYLON.Material.LineLoopDrawMode:
  10873. return this._gl.LINE_LOOP;
  10874. case BABYLON.Material.LineStripDrawMode:
  10875. return this._gl.LINE_STRIP;
  10876. case BABYLON.Material.TriangleStripDrawMode:
  10877. return this._gl.TRIANGLE_STRIP;
  10878. case BABYLON.Material.TriangleFanDrawMode:
  10879. return this._gl.TRIANGLE_FAN;
  10880. default:
  10881. return this._gl.TRIANGLES;
  10882. }
  10883. };
  10884. // Shaders
  10885. Engine.prototype._releaseEffect = function (effect) {
  10886. if (this._compiledEffects[effect._key]) {
  10887. delete this._compiledEffects[effect._key];
  10888. this._deleteProgram(effect.getProgram());
  10889. }
  10890. };
  10891. Engine.prototype._deleteProgram = function (program) {
  10892. if (program) {
  10893. program.__SPECTOR_rebuildProgram = null;
  10894. if (program.transformFeedback) {
  10895. this.deleteTransformFeedback(program.transformFeedback);
  10896. program.transformFeedback = null;
  10897. }
  10898. this._gl.deleteProgram(program);
  10899. }
  10900. };
  10901. /**
  10902. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10903. * @param samplers An array of string used to represent textures
  10904. */
  10905. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10906. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10907. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10908. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10909. if (this._compiledEffects[name]) {
  10910. var compiledEffect = this._compiledEffects[name];
  10911. if (onCompiled && compiledEffect.isReady()) {
  10912. onCompiled(compiledEffect);
  10913. }
  10914. return compiledEffect;
  10915. }
  10916. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10917. effect._key = name;
  10918. this._compiledEffects[name] = effect;
  10919. return effect;
  10920. };
  10921. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10922. if (uniformsNames === void 0) { uniformsNames = []; }
  10923. if (samplers === void 0) { samplers = []; }
  10924. if (defines === void 0) { defines = ""; }
  10925. return this.createEffect({
  10926. vertex: "particles",
  10927. fragmentElement: fragmentName
  10928. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10929. };
  10930. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10931. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10932. context = context || this._gl;
  10933. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10934. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10935. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10936. };
  10937. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10938. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10939. context = context || this._gl;
  10940. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10941. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10942. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10943. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10944. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10945. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10946. return program;
  10947. };
  10948. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10949. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10950. var shaderProgram = context.createProgram();
  10951. if (!shaderProgram) {
  10952. throw new Error("Unable to create program");
  10953. }
  10954. context.attachShader(shaderProgram, vertexShader);
  10955. context.attachShader(shaderProgram, fragmentShader);
  10956. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10957. var transformFeedback = this.createTransformFeedback();
  10958. this.bindTransformFeedback(transformFeedback);
  10959. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10960. shaderProgram.transformFeedback = transformFeedback;
  10961. }
  10962. context.linkProgram(shaderProgram);
  10963. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10964. this.bindTransformFeedback(null);
  10965. }
  10966. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10967. if (!linked) {
  10968. context.validateProgram(shaderProgram);
  10969. var error = context.getProgramInfoLog(shaderProgram);
  10970. if (error) {
  10971. throw new Error(error);
  10972. }
  10973. }
  10974. context.deleteShader(vertexShader);
  10975. context.deleteShader(fragmentShader);
  10976. return shaderProgram;
  10977. };
  10978. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10979. var results = new Array();
  10980. for (var index = 0; index < uniformsNames.length; index++) {
  10981. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10982. }
  10983. return results;
  10984. };
  10985. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10986. var results = [];
  10987. for (var index = 0; index < attributesNames.length; index++) {
  10988. try {
  10989. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10990. }
  10991. catch (e) {
  10992. results.push(-1);
  10993. }
  10994. }
  10995. return results;
  10996. };
  10997. Engine.prototype.enableEffect = function (effect) {
  10998. if (!effect) {
  10999. return;
  11000. }
  11001. // Use program
  11002. this.bindSamplers(effect);
  11003. this._currentEffect = effect;
  11004. if (effect.onBind) {
  11005. effect.onBind(effect);
  11006. }
  11007. effect.onBindObservable.notifyObservers(effect);
  11008. };
  11009. Engine.prototype.setIntArray = function (uniform, array) {
  11010. if (!uniform)
  11011. return;
  11012. this._gl.uniform1iv(uniform, array);
  11013. };
  11014. Engine.prototype.setIntArray2 = function (uniform, array) {
  11015. if (!uniform || array.length % 2 !== 0)
  11016. return;
  11017. this._gl.uniform2iv(uniform, array);
  11018. };
  11019. Engine.prototype.setIntArray3 = function (uniform, array) {
  11020. if (!uniform || array.length % 3 !== 0)
  11021. return;
  11022. this._gl.uniform3iv(uniform, array);
  11023. };
  11024. Engine.prototype.setIntArray4 = function (uniform, array) {
  11025. if (!uniform || array.length % 4 !== 0)
  11026. return;
  11027. this._gl.uniform4iv(uniform, array);
  11028. };
  11029. Engine.prototype.setFloatArray = function (uniform, array) {
  11030. if (!uniform)
  11031. return;
  11032. this._gl.uniform1fv(uniform, array);
  11033. };
  11034. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11035. if (!uniform || array.length % 2 !== 0)
  11036. return;
  11037. this._gl.uniform2fv(uniform, array);
  11038. };
  11039. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11040. if (!uniform || array.length % 3 !== 0)
  11041. return;
  11042. this._gl.uniform3fv(uniform, array);
  11043. };
  11044. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11045. if (!uniform || array.length % 4 !== 0)
  11046. return;
  11047. this._gl.uniform4fv(uniform, array);
  11048. };
  11049. Engine.prototype.setArray = function (uniform, array) {
  11050. if (!uniform)
  11051. return;
  11052. this._gl.uniform1fv(uniform, array);
  11053. };
  11054. Engine.prototype.setArray2 = function (uniform, array) {
  11055. if (!uniform || array.length % 2 !== 0)
  11056. return;
  11057. this._gl.uniform2fv(uniform, array);
  11058. };
  11059. Engine.prototype.setArray3 = function (uniform, array) {
  11060. if (!uniform || array.length % 3 !== 0)
  11061. return;
  11062. this._gl.uniform3fv(uniform, array);
  11063. };
  11064. Engine.prototype.setArray4 = function (uniform, array) {
  11065. if (!uniform || array.length % 4 !== 0)
  11066. return;
  11067. this._gl.uniform4fv(uniform, array);
  11068. };
  11069. Engine.prototype.setMatrices = function (uniform, matrices) {
  11070. if (!uniform)
  11071. return;
  11072. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11073. };
  11074. Engine.prototype.setMatrix = function (uniform, matrix) {
  11075. if (!uniform)
  11076. return;
  11077. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11078. };
  11079. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11080. if (!uniform)
  11081. return;
  11082. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11083. };
  11084. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11085. if (!uniform)
  11086. return;
  11087. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11088. };
  11089. Engine.prototype.setInt = function (uniform, value) {
  11090. if (!uniform)
  11091. return;
  11092. this._gl.uniform1i(uniform, value);
  11093. };
  11094. Engine.prototype.setFloat = function (uniform, value) {
  11095. if (!uniform)
  11096. return;
  11097. this._gl.uniform1f(uniform, value);
  11098. };
  11099. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11100. if (!uniform)
  11101. return;
  11102. this._gl.uniform2f(uniform, x, y);
  11103. };
  11104. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11105. if (!uniform)
  11106. return;
  11107. this._gl.uniform3f(uniform, x, y, z);
  11108. };
  11109. Engine.prototype.setBool = function (uniform, bool) {
  11110. if (!uniform)
  11111. return;
  11112. this._gl.uniform1i(uniform, bool);
  11113. };
  11114. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11115. if (!uniform)
  11116. return;
  11117. this._gl.uniform4f(uniform, x, y, z, w);
  11118. };
  11119. Engine.prototype.setColor3 = function (uniform, color3) {
  11120. if (!uniform)
  11121. return;
  11122. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11123. };
  11124. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11125. if (!uniform)
  11126. return;
  11127. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11128. };
  11129. // States
  11130. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11131. if (zOffset === void 0) { zOffset = 0; }
  11132. if (reverseSide === void 0) { reverseSide = false; }
  11133. // Culling
  11134. if (this._depthCullingState.cull !== culling || force) {
  11135. this._depthCullingState.cull = culling;
  11136. }
  11137. // Cull face
  11138. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11139. if (this._depthCullingState.cullFace !== cullFace || force) {
  11140. this._depthCullingState.cullFace = cullFace;
  11141. }
  11142. // Z offset
  11143. this.setZOffset(zOffset);
  11144. // Front face
  11145. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11146. if (this._depthCullingState.frontFace !== frontFace || force) {
  11147. this._depthCullingState.frontFace = frontFace;
  11148. }
  11149. };
  11150. Engine.prototype.setZOffset = function (value) {
  11151. this._depthCullingState.zOffset = value;
  11152. };
  11153. Engine.prototype.getZOffset = function () {
  11154. return this._depthCullingState.zOffset;
  11155. };
  11156. Engine.prototype.setDepthBuffer = function (enable) {
  11157. this._depthCullingState.depthTest = enable;
  11158. };
  11159. Engine.prototype.getDepthWrite = function () {
  11160. return this._depthCullingState.depthMask;
  11161. };
  11162. Engine.prototype.setDepthWrite = function (enable) {
  11163. this._depthCullingState.depthMask = enable;
  11164. };
  11165. Engine.prototype.setColorWrite = function (enable) {
  11166. this._gl.colorMask(enable, enable, enable, enable);
  11167. this._colorWrite = enable;
  11168. };
  11169. Engine.prototype.getColorWrite = function () {
  11170. return this._colorWrite;
  11171. };
  11172. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11173. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11174. };
  11175. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11176. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11177. if (this._alphaMode === mode) {
  11178. return;
  11179. }
  11180. switch (mode) {
  11181. case Engine.ALPHA_DISABLE:
  11182. this._alphaState.alphaBlend = false;
  11183. break;
  11184. case Engine.ALPHA_PREMULTIPLIED:
  11185. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11186. this._alphaState.alphaBlend = true;
  11187. break;
  11188. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11189. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11190. this._alphaState.alphaBlend = true;
  11191. break;
  11192. case Engine.ALPHA_COMBINE:
  11193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11194. this._alphaState.alphaBlend = true;
  11195. break;
  11196. case Engine.ALPHA_ONEONE:
  11197. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11198. this._alphaState.alphaBlend = true;
  11199. break;
  11200. case Engine.ALPHA_ADD:
  11201. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11202. this._alphaState.alphaBlend = true;
  11203. break;
  11204. case Engine.ALPHA_SUBTRACT:
  11205. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11206. this._alphaState.alphaBlend = true;
  11207. break;
  11208. case Engine.ALPHA_MULTIPLY:
  11209. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11210. this._alphaState.alphaBlend = true;
  11211. break;
  11212. case Engine.ALPHA_MAXIMIZED:
  11213. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11214. this._alphaState.alphaBlend = true;
  11215. break;
  11216. case Engine.ALPHA_INTERPOLATE:
  11217. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11218. this._alphaState.alphaBlend = true;
  11219. break;
  11220. case Engine.ALPHA_SCREENMODE:
  11221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11222. this._alphaState.alphaBlend = true;
  11223. break;
  11224. }
  11225. if (!noDepthWriteChange) {
  11226. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11227. }
  11228. this._alphaMode = mode;
  11229. };
  11230. Engine.prototype.getAlphaMode = function () {
  11231. return this._alphaMode;
  11232. };
  11233. Engine.prototype.setAlphaTesting = function (enable) {
  11234. this._alphaTest = enable;
  11235. };
  11236. Engine.prototype.getAlphaTesting = function () {
  11237. return !!this._alphaTest;
  11238. };
  11239. // Textures
  11240. Engine.prototype.wipeCaches = function (bruteForce) {
  11241. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11242. return;
  11243. }
  11244. this._currentEffect = null;
  11245. // 6/8/2017: deltakosh: Should not be required anymore.
  11246. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11247. if (bruteForce) {
  11248. this.resetTextureCache();
  11249. this._currentProgram = null;
  11250. this._stencilState.reset();
  11251. this._depthCullingState.reset();
  11252. this.setDepthFunctionToLessOrEqual();
  11253. this._alphaState.reset();
  11254. }
  11255. this._resetVertexBufferBinding();
  11256. this._cachedIndexBuffer = null;
  11257. this._cachedEffectForVertexBuffers = null;
  11258. this._unbindVertexArrayObject();
  11259. this.bindIndexBuffer(null);
  11260. };
  11261. /**
  11262. * Set the compressed texture format to use, based on the formats you have, and the formats
  11263. * supported by the hardware / browser.
  11264. *
  11265. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11266. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11267. * to API arguments needed to compressed textures. This puts the burden on the container
  11268. * generator to house the arcane code for determining these for current & future formats.
  11269. *
  11270. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11271. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11272. *
  11273. * Note: The result of this call is not taken into account when a texture is base64.
  11274. *
  11275. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11276. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11277. *
  11278. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11279. * @returns The extension selected.
  11280. */
  11281. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11282. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11283. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11284. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11285. return this._textureFormatInUse = this._texturesSupported[i];
  11286. }
  11287. }
  11288. }
  11289. // actively set format to nothing, to allow this to be called more than once
  11290. // and possibly fail the 2nd time
  11291. this._textureFormatInUse = null;
  11292. return null;
  11293. };
  11294. Engine.prototype._createTexture = function () {
  11295. var texture = this._gl.createTexture();
  11296. if (!texture) {
  11297. throw new Error("Unable to create texture");
  11298. }
  11299. return texture;
  11300. };
  11301. /**
  11302. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11303. * @param {string} urlArg- This contains one of the following:
  11304. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11305. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11306. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11307. *
  11308. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11309. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11310. * @param {Scene} scene- Needed for loading to the correct scene.
  11311. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11312. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11313. * @param {callback} onError- Optional callback to be called upon failure.
  11314. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11315. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11316. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11317. *
  11318. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11319. */
  11320. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11321. var _this = this;
  11322. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11323. if (onLoad === void 0) { onLoad = null; }
  11324. if (onError === void 0) { onError = null; }
  11325. if (buffer === void 0) { buffer = null; }
  11326. if (fallBack === void 0) { fallBack = null; }
  11327. if (format === void 0) { format = null; }
  11328. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11329. var fromData = url.substr(0, 5) === "data:";
  11330. var fromBlob = url.substr(0, 5) === "blob:";
  11331. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11332. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11333. // establish the file extension, if possible
  11334. var lastDot = url.lastIndexOf('.');
  11335. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11336. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11337. var isTGA = (extension === ".tga");
  11338. // determine if a ktx file should be substituted
  11339. var isKTX = false;
  11340. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11341. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11342. isKTX = true;
  11343. }
  11344. if (scene) {
  11345. scene._addPendingData(texture);
  11346. }
  11347. texture.url = url;
  11348. texture.generateMipMaps = !noMipmap;
  11349. texture.samplingMode = samplingMode;
  11350. texture.invertY = invertY;
  11351. if (!this._doNotHandleContextLost) {
  11352. // Keep a link to the buffer only if we plan to handle context lost
  11353. texture._buffer = buffer;
  11354. }
  11355. var onLoadObserver = null;
  11356. if (onLoad && !fallBack) {
  11357. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11358. }
  11359. if (!fallBack)
  11360. this._internalTexturesCache.push(texture);
  11361. var onerror = function (message, exception) {
  11362. if (scene) {
  11363. scene._removePendingData(texture);
  11364. }
  11365. if (onLoadObserver) {
  11366. texture.onLoadedObservable.remove(onLoadObserver);
  11367. }
  11368. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11369. if (isKTX) {
  11370. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11371. }
  11372. else if (BABYLON.Tools.UseFallbackTexture) {
  11373. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11374. }
  11375. if (onError) {
  11376. onError(message || "Unknown error", exception);
  11377. }
  11378. };
  11379. var callback = null;
  11380. // processing for non-image formats
  11381. if (isKTX || isTGA || isDDS) {
  11382. if (isKTX) {
  11383. callback = function (data) {
  11384. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11385. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11386. ktx.uploadLevels(_this._gl, !noMipmap);
  11387. return false;
  11388. }, samplingMode);
  11389. };
  11390. }
  11391. else if (isTGA) {
  11392. callback = function (arrayBuffer) {
  11393. var data = new Uint8Array(arrayBuffer);
  11394. var header = BABYLON.TGATools.GetTGAHeader(data);
  11395. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11396. BABYLON.TGATools.UploadContent(_this._gl, data);
  11397. return false;
  11398. }, samplingMode);
  11399. };
  11400. }
  11401. else if (isDDS) {
  11402. callback = function (data) {
  11403. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11404. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11405. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11406. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11407. return false;
  11408. }, samplingMode);
  11409. };
  11410. }
  11411. if (!buffer) {
  11412. this._loadFile(url, function (data) {
  11413. if (callback) {
  11414. callback(data);
  11415. }
  11416. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11417. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11418. });
  11419. }
  11420. else {
  11421. if (callback) {
  11422. callback(buffer);
  11423. }
  11424. }
  11425. // image format processing
  11426. }
  11427. else {
  11428. var onload = function (img) {
  11429. if (fromBlob && !_this._doNotHandleContextLost) {
  11430. // We need to store the image if we need to rebuild the texture
  11431. // in case of a webgl context lost
  11432. texture._buffer = img;
  11433. }
  11434. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11435. var gl = _this._gl;
  11436. var isPot = (img.width === potWidth && img.height === potHeight);
  11437. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11438. if (isPot) {
  11439. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11440. return false;
  11441. }
  11442. // Using shaders to rescale because canvas.drawImage is lossy
  11443. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11444. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11445. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11450. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11451. _this._releaseTexture(source);
  11452. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11453. continuationCallback();
  11454. });
  11455. return true;
  11456. }, samplingMode);
  11457. };
  11458. if (!fromData || isBase64)
  11459. if (buffer instanceof HTMLImageElement) {
  11460. onload(buffer);
  11461. }
  11462. else {
  11463. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11464. }
  11465. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11466. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11467. else
  11468. onload(buffer);
  11469. }
  11470. return texture;
  11471. };
  11472. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11473. var _this = this;
  11474. var rtt = this.createRenderTargetTexture({
  11475. width: destination.width,
  11476. height: destination.height,
  11477. }, {
  11478. generateMipMaps: false,
  11479. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11480. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11481. generateDepthBuffer: false,
  11482. generateStencilBuffer: false
  11483. });
  11484. if (!this._rescalePostProcess) {
  11485. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11486. }
  11487. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11488. _this._rescalePostProcess.onApply = function (effect) {
  11489. effect._bindTexture("textureSampler", source);
  11490. };
  11491. var hostingScene = scene;
  11492. if (!hostingScene) {
  11493. hostingScene = _this.scenes[_this.scenes.length - 1];
  11494. }
  11495. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11496. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11497. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11498. _this.unBindFramebuffer(rtt);
  11499. _this._releaseTexture(rtt);
  11500. if (onComplete) {
  11501. onComplete();
  11502. }
  11503. });
  11504. };
  11505. Engine.prototype._getInternalFormat = function (format) {
  11506. var internalFormat = this._gl.RGBA;
  11507. switch (format) {
  11508. case Engine.TEXTUREFORMAT_ALPHA:
  11509. internalFormat = this._gl.ALPHA;
  11510. break;
  11511. case Engine.TEXTUREFORMAT_LUMINANCE:
  11512. internalFormat = this._gl.LUMINANCE;
  11513. break;
  11514. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11515. internalFormat = this._gl.LUMINANCE_ALPHA;
  11516. break;
  11517. case Engine.TEXTUREFORMAT_RGB:
  11518. internalFormat = this._gl.RGB;
  11519. break;
  11520. case Engine.TEXTUREFORMAT_RGBA:
  11521. internalFormat = this._gl.RGBA;
  11522. break;
  11523. }
  11524. return internalFormat;
  11525. };
  11526. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11527. if (compression === void 0) { compression = null; }
  11528. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11529. if (!texture) {
  11530. return;
  11531. }
  11532. var internalFormat = this._getInternalFormat(format);
  11533. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11534. var textureType = this._getWebGLTextureType(type);
  11535. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11536. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11537. if (!this._doNotHandleContextLost) {
  11538. texture._bufferView = data;
  11539. texture.format = format;
  11540. texture.type = type;
  11541. texture.invertY = invertY;
  11542. texture._compression = compression;
  11543. }
  11544. if (texture.width % 4 !== 0) {
  11545. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11546. }
  11547. if (compression && data) {
  11548. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11549. }
  11550. else {
  11551. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11552. }
  11553. if (texture.generateMipMaps) {
  11554. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11555. }
  11556. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11557. // this.resetTextureCache();
  11558. texture.isReady = true;
  11559. };
  11560. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11561. if (compression === void 0) { compression = null; }
  11562. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11564. texture.baseWidth = width;
  11565. texture.baseHeight = height;
  11566. texture.width = width;
  11567. texture.height = height;
  11568. texture.format = format;
  11569. texture.generateMipMaps = generateMipMaps;
  11570. texture.samplingMode = samplingMode;
  11571. texture.invertY = invertY;
  11572. texture._compression = compression;
  11573. texture.type = type;
  11574. if (!this._doNotHandleContextLost) {
  11575. texture._bufferView = data;
  11576. }
  11577. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11578. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11579. // Filters
  11580. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11581. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11583. if (generateMipMaps) {
  11584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11585. }
  11586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11587. this._internalTexturesCache.push(texture);
  11588. return texture;
  11589. };
  11590. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11591. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11592. texture.baseWidth = width;
  11593. texture.baseHeight = height;
  11594. if (generateMipMaps) {
  11595. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11596. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11597. }
  11598. // this.resetTextureCache();
  11599. texture.width = width;
  11600. texture.height = height;
  11601. texture.isReady = false;
  11602. texture.generateMipMaps = generateMipMaps;
  11603. texture.samplingMode = samplingMode;
  11604. this.updateTextureSamplingMode(samplingMode, texture);
  11605. this._internalTexturesCache.push(texture);
  11606. return texture;
  11607. };
  11608. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11609. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11610. if (texture.isCube) {
  11611. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11613. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11614. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11615. }
  11616. else if (texture.is3D) {
  11617. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11618. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11619. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11620. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11621. }
  11622. else {
  11623. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11626. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11627. }
  11628. texture.samplingMode = samplingMode;
  11629. };
  11630. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11631. if (premulAlpha === void 0) { premulAlpha = false; }
  11632. if (!texture) {
  11633. return;
  11634. }
  11635. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11636. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11637. if (premulAlpha) {
  11638. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11639. }
  11640. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11641. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11642. if (texture.generateMipMaps) {
  11643. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11644. }
  11645. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11646. if (premulAlpha) {
  11647. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11648. }
  11649. texture.isReady = true;
  11650. };
  11651. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11652. if (!texture || texture._isDisabled) {
  11653. return;
  11654. }
  11655. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11656. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11657. try {
  11658. // Testing video texture support
  11659. if (this._videoTextureSupported === undefined) {
  11660. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11661. if (this._gl.getError() !== 0) {
  11662. this._videoTextureSupported = false;
  11663. }
  11664. else {
  11665. this._videoTextureSupported = true;
  11666. }
  11667. }
  11668. // Copy video through the current working canvas if video texture is not supported
  11669. if (!this._videoTextureSupported) {
  11670. if (!texture._workingCanvas) {
  11671. texture._workingCanvas = document.createElement("canvas");
  11672. var context = texture._workingCanvas.getContext("2d");
  11673. if (!context) {
  11674. throw new Error("Unable to get 2d context");
  11675. }
  11676. texture._workingContext = context;
  11677. texture._workingCanvas.width = texture.width;
  11678. texture._workingCanvas.height = texture.height;
  11679. }
  11680. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11681. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11682. }
  11683. else {
  11684. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11685. }
  11686. if (texture.generateMipMaps) {
  11687. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11688. }
  11689. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11690. // this.resetTextureCache();
  11691. texture.isReady = true;
  11692. }
  11693. catch (ex) {
  11694. // Something unexpected
  11695. // Let's disable the texture
  11696. texture._isDisabled = true;
  11697. }
  11698. };
  11699. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11700. var fullOptions = new RenderTargetCreationOptions();
  11701. if (options !== undefined && typeof options === "object") {
  11702. fullOptions.generateMipMaps = options.generateMipMaps;
  11703. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11704. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11705. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11706. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11707. }
  11708. else {
  11709. fullOptions.generateMipMaps = options;
  11710. fullOptions.generateDepthBuffer = true;
  11711. fullOptions.generateStencilBuffer = false;
  11712. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11713. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11714. }
  11715. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11716. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11717. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11718. }
  11719. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11720. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11721. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11722. }
  11723. var gl = this._gl;
  11724. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11725. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11726. var width = size.width || size;
  11727. var height = size.height || size;
  11728. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11729. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11730. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11731. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11732. }
  11733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11737. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11738. // Create the framebuffer
  11739. var framebuffer = gl.createFramebuffer();
  11740. this.bindUnboundFramebuffer(framebuffer);
  11741. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11742. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11743. if (fullOptions.generateMipMaps) {
  11744. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11745. }
  11746. // Unbind
  11747. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11748. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11749. this.bindUnboundFramebuffer(null);
  11750. texture._framebuffer = framebuffer;
  11751. texture.baseWidth = width;
  11752. texture.baseHeight = height;
  11753. texture.width = width;
  11754. texture.height = height;
  11755. texture.isReady = true;
  11756. texture.samples = 1;
  11757. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11758. texture.samplingMode = fullOptions.samplingMode;
  11759. texture.type = fullOptions.type;
  11760. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11761. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11762. // this.resetTextureCache();
  11763. this._internalTexturesCache.push(texture);
  11764. return texture;
  11765. };
  11766. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11767. var generateMipMaps = false;
  11768. var generateDepthBuffer = true;
  11769. var generateStencilBuffer = false;
  11770. var generateDepthTexture = false;
  11771. var textureCount = 1;
  11772. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11773. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11774. var types = [], samplingModes = [];
  11775. if (options !== undefined) {
  11776. generateMipMaps = options.generateMipMaps;
  11777. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11778. generateStencilBuffer = options.generateStencilBuffer;
  11779. generateDepthTexture = options.generateDepthTexture;
  11780. textureCount = options.textureCount || 1;
  11781. if (options.types) {
  11782. types = options.types;
  11783. }
  11784. if (options.samplingModes) {
  11785. samplingModes = options.samplingModes;
  11786. }
  11787. }
  11788. var gl = this._gl;
  11789. // Create the framebuffer
  11790. var framebuffer = gl.createFramebuffer();
  11791. this.bindUnboundFramebuffer(framebuffer);
  11792. var width = size.width || size;
  11793. var height = size.height || size;
  11794. var textures = [];
  11795. var attachments = [];
  11796. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11797. for (var i = 0; i < textureCount; i++) {
  11798. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11799. var type = types[i] || defaultType;
  11800. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11801. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11802. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11803. }
  11804. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11805. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11806. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11807. }
  11808. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11809. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11810. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11811. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11812. }
  11813. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11814. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11815. textures.push(texture);
  11816. attachments.push(attachment);
  11817. gl.activeTexture(gl["TEXTURE" + i]);
  11818. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11819. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11820. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11821. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11822. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11823. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11824. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11825. if (generateMipMaps) {
  11826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11827. }
  11828. // Unbind
  11829. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11830. texture._framebuffer = framebuffer;
  11831. texture._depthStencilBuffer = depthStencilBuffer;
  11832. texture.baseWidth = width;
  11833. texture.baseHeight = height;
  11834. texture.width = width;
  11835. texture.height = height;
  11836. texture.isReady = true;
  11837. texture.samples = 1;
  11838. texture.generateMipMaps = generateMipMaps;
  11839. texture.samplingMode = samplingMode;
  11840. texture.type = type;
  11841. texture._generateDepthBuffer = generateDepthBuffer;
  11842. texture._generateStencilBuffer = generateStencilBuffer;
  11843. texture._attachments = attachments;
  11844. this._internalTexturesCache.push(texture);
  11845. }
  11846. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11847. // Depth texture
  11848. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11849. gl.activeTexture(gl.TEXTURE0);
  11850. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11851. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11855. 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);
  11856. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11857. depthTexture._framebuffer = framebuffer;
  11858. depthTexture.baseWidth = width;
  11859. depthTexture.baseHeight = height;
  11860. depthTexture.width = width;
  11861. depthTexture.height = height;
  11862. depthTexture.isReady = true;
  11863. depthTexture.samples = 1;
  11864. depthTexture.generateMipMaps = generateMipMaps;
  11865. depthTexture.samplingMode = gl.NEAREST;
  11866. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11867. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11868. textures.push(depthTexture);
  11869. this._internalTexturesCache.push(depthTexture);
  11870. }
  11871. gl.drawBuffers(attachments);
  11872. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11873. this.bindUnboundFramebuffer(null);
  11874. this.resetTextureCache();
  11875. return textures;
  11876. };
  11877. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11878. if (samples === void 0) { samples = 1; }
  11879. var depthStencilBuffer = null;
  11880. var gl = this._gl;
  11881. // Create the depth/stencil buffer
  11882. if (generateStencilBuffer) {
  11883. depthStencilBuffer = gl.createRenderbuffer();
  11884. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11885. if (samples > 1) {
  11886. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11887. }
  11888. else {
  11889. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11890. }
  11891. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11892. }
  11893. else if (generateDepthBuffer) {
  11894. depthStencilBuffer = gl.createRenderbuffer();
  11895. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11896. if (samples > 1) {
  11897. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11898. }
  11899. else {
  11900. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11901. }
  11902. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11903. }
  11904. return depthStencilBuffer;
  11905. };
  11906. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11907. if (this.webGLVersion < 2 || !texture) {
  11908. return 1;
  11909. }
  11910. if (texture.samples === samples) {
  11911. return samples;
  11912. }
  11913. var gl = this._gl;
  11914. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11915. // Dispose previous render buffers
  11916. if (texture._depthStencilBuffer) {
  11917. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11918. texture._depthStencilBuffer = null;
  11919. }
  11920. if (texture._MSAAFramebuffer) {
  11921. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11922. texture._MSAAFramebuffer = null;
  11923. }
  11924. if (texture._MSAARenderBuffer) {
  11925. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11926. texture._MSAARenderBuffer = null;
  11927. }
  11928. if (samples > 1) {
  11929. var framebuffer = gl.createFramebuffer();
  11930. if (!framebuffer) {
  11931. throw new Error("Unable to create multi sampled framebuffer");
  11932. }
  11933. texture._MSAAFramebuffer = framebuffer;
  11934. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11935. var colorRenderbuffer = gl.createRenderbuffer();
  11936. if (!colorRenderbuffer) {
  11937. throw new Error("Unable to create multi sampled framebuffer");
  11938. }
  11939. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11940. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11942. texture._MSAARenderBuffer = colorRenderbuffer;
  11943. }
  11944. else {
  11945. this.bindUnboundFramebuffer(texture._framebuffer);
  11946. }
  11947. texture.samples = samples;
  11948. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11949. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11950. this.bindUnboundFramebuffer(null);
  11951. return samples;
  11952. };
  11953. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11954. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11955. return 1;
  11956. }
  11957. if (textures[0].samples === samples) {
  11958. return samples;
  11959. }
  11960. var gl = this._gl;
  11961. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11962. // Dispose previous render buffers
  11963. if (textures[0]._depthStencilBuffer) {
  11964. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11965. textures[0]._depthStencilBuffer = null;
  11966. }
  11967. if (textures[0]._MSAAFramebuffer) {
  11968. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11969. textures[0]._MSAAFramebuffer = null;
  11970. }
  11971. for (var i = 0; i < textures.length; i++) {
  11972. if (textures[i]._MSAARenderBuffer) {
  11973. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11974. textures[i]._MSAARenderBuffer = null;
  11975. }
  11976. }
  11977. if (samples > 1) {
  11978. var framebuffer = gl.createFramebuffer();
  11979. if (!framebuffer) {
  11980. throw new Error("Unable to create multi sampled framebuffer");
  11981. }
  11982. this.bindUnboundFramebuffer(framebuffer);
  11983. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  11984. var attachments = [];
  11985. for (var i = 0; i < textures.length; i++) {
  11986. var texture = textures[i];
  11987. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11988. var colorRenderbuffer = gl.createRenderbuffer();
  11989. if (!colorRenderbuffer) {
  11990. throw new Error("Unable to create multi sampled framebuffer");
  11991. }
  11992. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11993. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11994. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  11995. texture._MSAAFramebuffer = framebuffer;
  11996. texture._MSAARenderBuffer = colorRenderbuffer;
  11997. texture.samples = samples;
  11998. texture._depthStencilBuffer = depthStencilBuffer;
  11999. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12000. attachments.push(attachment);
  12001. }
  12002. gl.drawBuffers(attachments);
  12003. }
  12004. else {
  12005. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12006. }
  12007. this.bindUnboundFramebuffer(null);
  12008. return samples;
  12009. };
  12010. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12011. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12012. };
  12013. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12014. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12015. };
  12016. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12017. var gl = this._gl;
  12018. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12019. var generateMipMaps = true;
  12020. var generateDepthBuffer = true;
  12021. var generateStencilBuffer = false;
  12022. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12023. if (options !== undefined) {
  12024. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12025. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12026. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12027. if (options.samplingMode !== undefined) {
  12028. samplingMode = options.samplingMode;
  12029. }
  12030. }
  12031. texture.isCube = true;
  12032. texture.generateMipMaps = generateMipMaps;
  12033. texture.samples = 1;
  12034. texture.samplingMode = samplingMode;
  12035. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12036. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12037. for (var face = 0; face < 6; face++) {
  12038. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12039. }
  12040. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12044. // Create the framebuffer
  12045. var framebuffer = gl.createFramebuffer();
  12046. this.bindUnboundFramebuffer(framebuffer);
  12047. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12048. // Mipmaps
  12049. if (texture.generateMipMaps) {
  12050. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12051. }
  12052. // Unbind
  12053. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12054. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12055. this.bindUnboundFramebuffer(null);
  12056. texture._framebuffer = framebuffer;
  12057. texture.width = size;
  12058. texture.height = size;
  12059. texture.isReady = true;
  12060. //this.resetTextureCache();
  12061. this._internalTexturesCache.push(texture);
  12062. return texture;
  12063. };
  12064. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12065. var _this = this;
  12066. if (onLoad === void 0) { onLoad = null; }
  12067. if (onError === void 0) { onError = null; }
  12068. if (forcedExtension === void 0) { forcedExtension = null; }
  12069. var callback = function (loadData) {
  12070. if (!loadData) {
  12071. if (onLoad) {
  12072. onLoad(null);
  12073. }
  12074. return;
  12075. }
  12076. var texture = loadData.texture;
  12077. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12078. texture._lodGenerationScale = scale;
  12079. texture._lodGenerationOffset = offset;
  12080. if (_this._caps.textureLOD) {
  12081. // Do not add extra process if texture lod is supported.
  12082. if (onLoad) {
  12083. onLoad(texture);
  12084. }
  12085. return;
  12086. }
  12087. var mipSlices = 3;
  12088. var gl = _this._gl;
  12089. var width = loadData.width;
  12090. if (!width) {
  12091. return;
  12092. }
  12093. var textures = [];
  12094. for (var i = 0; i < mipSlices; i++) {
  12095. //compute LOD from even spacing in smoothness (matching shader calculation)
  12096. var smoothness = i / (mipSlices - 1);
  12097. var roughness = 1 - smoothness;
  12098. var minLODIndex = offset; // roughness = 0
  12099. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12100. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12101. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12102. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12103. glTextureFromLod.isCube = true;
  12104. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12105. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12109. if (loadData.isDDS) {
  12110. var info = loadData.info;
  12111. var data = loadData.data;
  12112. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12113. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12114. }
  12115. else {
  12116. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12117. }
  12118. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12119. // Wrap in a base texture for easy binding.
  12120. var lodTexture = new BABYLON.BaseTexture(scene);
  12121. lodTexture.isCube = true;
  12122. lodTexture._texture = glTextureFromLod;
  12123. glTextureFromLod.isReady = true;
  12124. textures.push(lodTexture);
  12125. }
  12126. texture._lodTextureHigh = textures[2];
  12127. texture._lodTextureMid = textures[1];
  12128. texture._lodTextureLow = textures[0];
  12129. if (onLoad) {
  12130. onLoad(texture);
  12131. }
  12132. };
  12133. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12134. };
  12135. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12136. var _this = this;
  12137. if (onLoad === void 0) { onLoad = null; }
  12138. if (onError === void 0) { onError = null; }
  12139. if (forcedExtension === void 0) { forcedExtension = null; }
  12140. var gl = this._gl;
  12141. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12142. texture.isCube = true;
  12143. texture.url = rootUrl;
  12144. texture.generateMipMaps = !noMipmap;
  12145. if (!this._doNotHandleContextLost) {
  12146. texture._extension = forcedExtension;
  12147. texture._files = files;
  12148. }
  12149. var isKTX = false;
  12150. var isDDS = false;
  12151. var lastDot = rootUrl.lastIndexOf('.');
  12152. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12153. if (this._textureFormatInUse) {
  12154. extension = this._textureFormatInUse;
  12155. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12156. isKTX = true;
  12157. }
  12158. else {
  12159. isDDS = (extension === ".dds");
  12160. }
  12161. var onerror = function (request, exception) {
  12162. if (onError && request) {
  12163. onError(request.status + " " + request.statusText, exception);
  12164. }
  12165. };
  12166. if (isKTX) {
  12167. this._loadFile(rootUrl, function (data) {
  12168. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12169. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12170. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12171. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12172. ktx.uploadLevels(_this._gl, !noMipmap);
  12173. _this.setCubeMapTextureParams(gl, loadMipmap);
  12174. texture.width = ktx.pixelWidth;
  12175. texture.height = ktx.pixelHeight;
  12176. texture.isReady = true;
  12177. }, undefined, undefined, true, onerror);
  12178. }
  12179. else if (isDDS) {
  12180. if (files && files.length === 6) {
  12181. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12182. var info;
  12183. var loadMipmap = false;
  12184. var width = 0;
  12185. for (var index = 0; index < imgs.length; index++) {
  12186. var data = imgs[index];
  12187. info = BABYLON.DDSTools.GetDDSInfo(data);
  12188. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12189. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12190. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12191. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12192. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12193. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12194. }
  12195. texture.width = info.width;
  12196. texture.height = info.height;
  12197. texture.type = info.textureType;
  12198. width = info.width;
  12199. }
  12200. _this.setCubeMapTextureParams(gl, loadMipmap);
  12201. texture.isReady = true;
  12202. if (onLoad) {
  12203. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12204. }
  12205. }, files, onError);
  12206. }
  12207. else {
  12208. this._loadFile(rootUrl, function (data) {
  12209. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12210. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12211. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12212. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12213. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12214. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12215. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12216. }
  12217. _this.setCubeMapTextureParams(gl, loadMipmap);
  12218. texture.width = info.width;
  12219. texture.height = info.height;
  12220. texture.isReady = true;
  12221. texture.type = info.textureType;
  12222. if (onLoad) {
  12223. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12224. }
  12225. }, undefined, undefined, true, onerror);
  12226. }
  12227. }
  12228. else {
  12229. if (!files) {
  12230. throw new Error("Cannot load cubemap because files were not defined");
  12231. }
  12232. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12233. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12234. var height = width;
  12235. _this._prepareWorkingCanvas();
  12236. if (!_this._workingCanvas || !_this._workingContext) {
  12237. return;
  12238. }
  12239. _this._workingCanvas.width = width;
  12240. _this._workingCanvas.height = height;
  12241. var faces = [
  12242. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12243. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12244. ];
  12245. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12246. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12247. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12248. for (var index = 0; index < faces.length; index++) {
  12249. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12250. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12251. }
  12252. if (!noMipmap) {
  12253. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12254. }
  12255. _this.setCubeMapTextureParams(gl, !noMipmap);
  12256. texture.width = width;
  12257. texture.height = height;
  12258. texture.isReady = true;
  12259. if (format) {
  12260. texture.format = format;
  12261. }
  12262. texture.onLoadedObservable.notifyObservers(texture);
  12263. texture.onLoadedObservable.clear();
  12264. if (onLoad) {
  12265. onLoad();
  12266. }
  12267. }, files, onError);
  12268. }
  12269. this._internalTexturesCache.push(texture);
  12270. return texture;
  12271. };
  12272. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12276. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12277. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12278. // this.resetTextureCache();
  12279. };
  12280. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12281. if (compression === void 0) { compression = null; }
  12282. if (level === void 0) { level = 0; }
  12283. texture._bufferViewArray = data;
  12284. texture.format = format;
  12285. texture.type = type;
  12286. texture.invertY = invertY;
  12287. texture._compression = compression;
  12288. var gl = this._gl;
  12289. var textureType = this._getWebGLTextureType(type);
  12290. var internalFormat = this._getInternalFormat(format);
  12291. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12292. var needConversion = false;
  12293. if (internalFormat === gl.RGB) {
  12294. internalFormat = gl.RGBA;
  12295. needConversion = true;
  12296. }
  12297. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12298. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12299. if (texture.width % 4 !== 0) {
  12300. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12301. }
  12302. // Data are known to be in +X +Y +Z -X -Y -Z
  12303. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12304. var faceData = data[faceIndex];
  12305. if (compression) {
  12306. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12307. }
  12308. else {
  12309. if (needConversion) {
  12310. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12311. }
  12312. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12313. }
  12314. }
  12315. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12316. if (isPot && texture.generateMipMaps && level === 0) {
  12317. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12318. }
  12319. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12320. // this.resetTextureCache();
  12321. texture.isReady = true;
  12322. };
  12323. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12324. if (compression === void 0) { compression = null; }
  12325. var gl = this._gl;
  12326. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12327. texture.isCube = true;
  12328. texture.generateMipMaps = generateMipMaps;
  12329. texture.format = format;
  12330. texture.type = type;
  12331. if (!this._doNotHandleContextLost) {
  12332. texture._bufferViewArray = data;
  12333. }
  12334. var textureType = this._getWebGLTextureType(type);
  12335. var internalFormat = this._getInternalFormat(format);
  12336. if (internalFormat === gl.RGB) {
  12337. internalFormat = gl.RGBA;
  12338. }
  12339. var width = size;
  12340. var height = width;
  12341. texture.width = width;
  12342. texture.height = height;
  12343. // Double check on POT to generate Mips.
  12344. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12345. if (!isPot) {
  12346. generateMipMaps = false;
  12347. }
  12348. // Upload data if needed. The texture won't be ready until then.
  12349. if (data) {
  12350. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12351. }
  12352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12353. // Filters
  12354. if (data && generateMipMaps) {
  12355. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12356. }
  12357. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12360. }
  12361. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12364. }
  12365. else {
  12366. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12369. }
  12370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12372. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12373. return texture;
  12374. };
  12375. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12376. var _this = this;
  12377. if (onLoad === void 0) { onLoad = null; }
  12378. if (onError === void 0) { onError = null; }
  12379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12380. if (invertY === void 0) { invertY = false; }
  12381. var gl = this._gl;
  12382. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12383. scene._addPendingData(texture);
  12384. texture.url = url;
  12385. this._internalTexturesCache.push(texture);
  12386. var onerror = function (request, exception) {
  12387. scene._removePendingData(texture);
  12388. if (onError && request) {
  12389. onError(request.status + " " + request.statusText, exception);
  12390. }
  12391. };
  12392. var internalCallback = function (data) {
  12393. var width = texture.width;
  12394. var faceDataArrays = callback(data);
  12395. if (!faceDataArrays) {
  12396. return;
  12397. }
  12398. if (mipmmapGenerator) {
  12399. var textureType = _this._getWebGLTextureType(type);
  12400. var internalFormat = _this._getInternalFormat(format);
  12401. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12402. var needConversion = false;
  12403. if (internalFormat === gl.RGB) {
  12404. internalFormat = gl.RGBA;
  12405. needConversion = true;
  12406. }
  12407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12409. var mipData = mipmmapGenerator(faceDataArrays);
  12410. for (var level = 0; level < mipData.length; level++) {
  12411. var mipSize = width >> level;
  12412. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12413. var mipFaceData = mipData[level][faceIndex];
  12414. if (needConversion) {
  12415. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12416. }
  12417. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12418. }
  12419. }
  12420. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12421. }
  12422. else {
  12423. texture.generateMipMaps = !noMipmap;
  12424. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12425. }
  12426. texture.isReady = true;
  12427. // this.resetTextureCache();
  12428. scene._removePendingData(texture);
  12429. if (onLoad) {
  12430. onLoad();
  12431. }
  12432. };
  12433. this._loadFile(url, function (data) {
  12434. internalCallback(data);
  12435. }, undefined, scene.database, true, onerror);
  12436. return texture;
  12437. };
  12438. ;
  12439. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12440. if (compression === void 0) { compression = null; }
  12441. var internalFormat = this._getInternalFormat(format);
  12442. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12443. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12444. if (!this._doNotHandleContextLost) {
  12445. texture._bufferView = data;
  12446. texture.format = format;
  12447. texture.invertY = invertY;
  12448. texture._compression = compression;
  12449. }
  12450. if (texture.width % 4 !== 0) {
  12451. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12452. }
  12453. if (compression && data) {
  12454. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12455. }
  12456. else {
  12457. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12458. }
  12459. if (texture.generateMipMaps) {
  12460. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12461. }
  12462. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12463. // this.resetTextureCache();
  12464. texture.isReady = true;
  12465. };
  12466. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12467. if (compression === void 0) { compression = null; }
  12468. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12469. texture.baseWidth = width;
  12470. texture.baseHeight = height;
  12471. texture.baseDepth = depth;
  12472. texture.width = width;
  12473. texture.height = height;
  12474. texture.depth = depth;
  12475. texture.format = format;
  12476. texture.generateMipMaps = generateMipMaps;
  12477. texture.samplingMode = samplingMode;
  12478. texture.is3D = true;
  12479. if (!this._doNotHandleContextLost) {
  12480. texture._bufferView = data;
  12481. }
  12482. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12483. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12484. // Filters
  12485. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12486. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12487. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12488. if (generateMipMaps) {
  12489. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12490. }
  12491. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12492. this._internalTexturesCache.push(texture);
  12493. return texture;
  12494. };
  12495. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12496. var gl = this._gl;
  12497. if (!gl) {
  12498. return;
  12499. }
  12500. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12503. if (!noMipmap && !isCompressed) {
  12504. gl.generateMipmap(gl.TEXTURE_2D);
  12505. }
  12506. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12507. // this.resetTextureCache();
  12508. if (scene) {
  12509. scene._removePendingData(texture);
  12510. }
  12511. texture.onLoadedObservable.notifyObservers(texture);
  12512. texture.onLoadedObservable.clear();
  12513. };
  12514. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12515. var _this = this;
  12516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12517. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12518. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12519. var gl = this._gl;
  12520. if (!gl) {
  12521. return;
  12522. }
  12523. if (!texture._webGLTexture) {
  12524. // this.resetTextureCache();
  12525. if (scene) {
  12526. scene._removePendingData(texture);
  12527. }
  12528. return;
  12529. }
  12530. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12531. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12532. texture.baseWidth = width;
  12533. texture.baseHeight = height;
  12534. texture.width = potWidth;
  12535. texture.height = potHeight;
  12536. texture.isReady = true;
  12537. if (processFunction(potWidth, potHeight, function () {
  12538. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12539. })) {
  12540. // Returning as texture needs extra async steps
  12541. return;
  12542. }
  12543. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12544. };
  12545. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12546. // Create new RGBA data container.
  12547. var rgbaData;
  12548. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12549. rgbaData = new Float32Array(width * height * 4);
  12550. }
  12551. else {
  12552. rgbaData = new Uint32Array(width * height * 4);
  12553. }
  12554. // Convert each pixel.
  12555. for (var x = 0; x < width; x++) {
  12556. for (var y = 0; y < height; y++) {
  12557. var index = (y * width + x) * 3;
  12558. var newIndex = (y * width + x) * 4;
  12559. // Map Old Value to new value.
  12560. rgbaData[newIndex + 0] = rgbData[index + 0];
  12561. rgbaData[newIndex + 1] = rgbData[index + 1];
  12562. rgbaData[newIndex + 2] = rgbData[index + 2];
  12563. // Add fully opaque alpha channel.
  12564. rgbaData[newIndex + 3] = 1;
  12565. }
  12566. }
  12567. return rgbaData;
  12568. };
  12569. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12570. var gl = this._gl;
  12571. if (texture._framebuffer) {
  12572. gl.deleteFramebuffer(texture._framebuffer);
  12573. texture._framebuffer = null;
  12574. }
  12575. if (texture._depthStencilBuffer) {
  12576. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12577. texture._depthStencilBuffer = null;
  12578. }
  12579. if (texture._MSAAFramebuffer) {
  12580. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12581. texture._MSAAFramebuffer = null;
  12582. }
  12583. if (texture._MSAARenderBuffer) {
  12584. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12585. texture._MSAARenderBuffer = null;
  12586. }
  12587. };
  12588. Engine.prototype._releaseTexture = function (texture) {
  12589. var gl = this._gl;
  12590. this._releaseFramebufferObjects(texture);
  12591. gl.deleteTexture(texture._webGLTexture);
  12592. // Unbind channels
  12593. this.unbindAllTextures();
  12594. var index = this._internalTexturesCache.indexOf(texture);
  12595. if (index !== -1) {
  12596. this._internalTexturesCache.splice(index, 1);
  12597. }
  12598. // Integrated fixed lod samplers.
  12599. if (texture._lodTextureHigh) {
  12600. texture._lodTextureHigh.dispose();
  12601. }
  12602. if (texture._lodTextureMid) {
  12603. texture._lodTextureMid.dispose();
  12604. }
  12605. if (texture._lodTextureLow) {
  12606. texture._lodTextureLow.dispose();
  12607. }
  12608. };
  12609. Engine.prototype.setProgram = function (program) {
  12610. if (this._currentProgram !== program) {
  12611. this._gl.useProgram(program);
  12612. this._currentProgram = program;
  12613. }
  12614. };
  12615. Engine.prototype.bindSamplers = function (effect) {
  12616. this.setProgram(effect.getProgram());
  12617. var samplers = effect.getSamplers();
  12618. for (var index = 0; index < samplers.length; index++) {
  12619. var uniform = effect.getUniform(samplers[index]);
  12620. if (uniform) {
  12621. this._boundUniforms[index] = uniform;
  12622. }
  12623. }
  12624. this._currentEffect = null;
  12625. };
  12626. Engine.prototype._activateTextureChannel = function (channel) {
  12627. if (this._activeChannel !== channel && channel > -1) {
  12628. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12629. this._activeChannel = channel;
  12630. }
  12631. };
  12632. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12633. var index = this._boundTexturesStack.indexOf(internalTexture);
  12634. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12635. this._boundTexturesStack.splice(index, 1);
  12636. this._boundTexturesStack.push(internalTexture);
  12637. }
  12638. };
  12639. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12640. var currentSlot = internalTexture._designatedSlot;
  12641. internalTexture._designatedSlot = -1;
  12642. var index = this._boundTexturesStack.indexOf(internalTexture);
  12643. if (index > -1) {
  12644. this._boundTexturesStack.splice(index, 1);
  12645. if (currentSlot > -1) {
  12646. this._boundTexturesCache[currentSlot] = null;
  12647. this._nextFreeTextureSlots.push(currentSlot);
  12648. }
  12649. }
  12650. return currentSlot;
  12651. };
  12652. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12653. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12654. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12655. var isTextureForRendering = texture && texture._initialSlot > -1;
  12656. if (currentTextureBound !== texture) {
  12657. if (currentTextureBound) {
  12658. this._removeDesignatedSlot(currentTextureBound);
  12659. }
  12660. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12661. if (this._activeChannel >= 0) {
  12662. this._boundTexturesCache[this._activeChannel] = texture;
  12663. if (isTextureForRendering) {
  12664. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12665. if (slotIndex > -1) {
  12666. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12667. }
  12668. this._boundTexturesStack.push(texture);
  12669. }
  12670. }
  12671. }
  12672. if (isTextureForRendering && this._activeChannel > -1) {
  12673. texture._designatedSlot = this._activeChannel;
  12674. if (!doNotBindUniformToTextureChannel) {
  12675. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12676. }
  12677. }
  12678. };
  12679. Engine.prototype._bindTexture = function (channel, texture) {
  12680. if (channel < 0) {
  12681. return;
  12682. }
  12683. if (texture) {
  12684. channel = this._getCorrectTextureChannel(channel, texture);
  12685. }
  12686. this._activateTextureChannel(channel);
  12687. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12688. };
  12689. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12690. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12691. };
  12692. Engine.prototype.unbindAllTextures = function () {
  12693. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  12694. this._activateTextureChannel(channel);
  12695. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12696. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12697. if (this.webGLVersion > 1) {
  12698. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12699. }
  12700. }
  12701. };
  12702. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12703. if (channel < 0) {
  12704. return;
  12705. }
  12706. if (uniform) {
  12707. this._boundUniforms[channel] = uniform;
  12708. }
  12709. this._setTexture(channel, texture);
  12710. };
  12711. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12712. if (!internalTexture) {
  12713. return -1;
  12714. }
  12715. internalTexture._initialSlot = channel;
  12716. if (channel !== internalTexture._designatedSlot) {
  12717. if (internalTexture._designatedSlot > -1) {
  12718. return internalTexture._designatedSlot;
  12719. }
  12720. else {
  12721. // No slot for this texture, let's pick a new one (if we find a free slot)
  12722. if (this._nextFreeTextureSlots.length) {
  12723. return this._nextFreeTextureSlots[0];
  12724. }
  12725. // We need to recycle the oldest bound texture, sorry.
  12726. this._textureCollisions.addCount(1, false);
  12727. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12728. }
  12729. }
  12730. return channel;
  12731. };
  12732. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12733. var uniform = this._boundUniforms[sourceSlot];
  12734. this._gl.uniform1i(uniform, destination);
  12735. };
  12736. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12737. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12738. // Not ready?
  12739. if (!texture) {
  12740. if (this._boundTexturesCache[channel] != null) {
  12741. this._activateTextureChannel(channel);
  12742. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12743. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12744. if (this.webGLVersion > 1) {
  12745. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12746. }
  12747. }
  12748. return false;
  12749. }
  12750. // Video
  12751. var alreadyActivated = false;
  12752. if (texture.video) {
  12753. this._activateTextureChannel(channel);
  12754. alreadyActivated = true;
  12755. texture.update();
  12756. }
  12757. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12758. texture.delayLoad();
  12759. return false;
  12760. }
  12761. var internalTexture;
  12762. if (texture.isReady()) {
  12763. internalTexture = texture.getInternalTexture();
  12764. }
  12765. else if (texture.isCube) {
  12766. internalTexture = this.emptyCubeTexture;
  12767. }
  12768. else if (texture.is3D) {
  12769. internalTexture = this.emptyTexture3D;
  12770. }
  12771. else {
  12772. internalTexture = this.emptyTexture;
  12773. }
  12774. if (!isPartOfTextureArray) {
  12775. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12776. }
  12777. if (this._boundTexturesCache[channel] === internalTexture) {
  12778. this._moveBoundTextureOnTop(internalTexture);
  12779. if (!isPartOfTextureArray) {
  12780. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12781. }
  12782. return false;
  12783. }
  12784. if (!alreadyActivated) {
  12785. this._activateTextureChannel(channel);
  12786. }
  12787. if (internalTexture && internalTexture.is3D) {
  12788. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12789. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12790. internalTexture._cachedWrapU = texture.wrapU;
  12791. switch (texture.wrapU) {
  12792. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12794. break;
  12795. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12797. break;
  12798. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12799. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12800. break;
  12801. }
  12802. }
  12803. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12804. internalTexture._cachedWrapV = texture.wrapV;
  12805. switch (texture.wrapV) {
  12806. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12808. break;
  12809. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12811. break;
  12812. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12814. break;
  12815. }
  12816. }
  12817. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12818. internalTexture._cachedWrapR = texture.wrapR;
  12819. switch (texture.wrapV) {
  12820. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12821. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12822. break;
  12823. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12825. break;
  12826. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12828. break;
  12829. }
  12830. }
  12831. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12832. }
  12833. else if (internalTexture && internalTexture.isCube) {
  12834. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12835. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12836. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12837. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12838. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12839. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12840. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12841. }
  12842. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12843. }
  12844. else {
  12845. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12846. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12847. internalTexture._cachedWrapU = texture.wrapU;
  12848. switch (texture.wrapU) {
  12849. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12851. break;
  12852. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12854. break;
  12855. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12856. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12857. break;
  12858. }
  12859. }
  12860. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12861. internalTexture._cachedWrapV = texture.wrapV;
  12862. switch (texture.wrapV) {
  12863. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12864. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12865. break;
  12866. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12868. break;
  12869. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12871. break;
  12872. }
  12873. }
  12874. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12875. }
  12876. return true;
  12877. };
  12878. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12879. if (channel < 0 || !uniform) {
  12880. return;
  12881. }
  12882. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12883. this._textureUnits = new Int32Array(textures.length);
  12884. }
  12885. for (var i = 0; i < textures.length; i++) {
  12886. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12887. }
  12888. this._gl.uniform1iv(uniform, this._textureUnits);
  12889. for (var index = 0; index < textures.length; index++) {
  12890. this._setTexture(this._textureUnits[index], textures[index], true);
  12891. }
  12892. };
  12893. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12894. var internalTexture = texture.getInternalTexture();
  12895. if (!internalTexture) {
  12896. return;
  12897. }
  12898. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12899. var value = texture.anisotropicFilteringLevel;
  12900. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12901. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12902. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12903. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12904. }
  12905. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12906. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12907. internalTexture._cachedAnisotropicFilteringLevel = value;
  12908. }
  12909. };
  12910. Engine.prototype.readPixels = function (x, y, width, height) {
  12911. var data = new Uint8Array(height * width * 4);
  12912. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12913. return data;
  12914. };
  12915. /**
  12916. * Add an externaly attached data from its key.
  12917. * This method call will fail and return false, if such key already exists.
  12918. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12919. * @param key the unique key that identifies the data
  12920. * @param data the data object to associate to the key for this Engine instance
  12921. * @return true if no such key were already present and the data was added successfully, false otherwise
  12922. */
  12923. Engine.prototype.addExternalData = function (key, data) {
  12924. if (!this._externalData) {
  12925. this._externalData = new BABYLON.StringDictionary();
  12926. }
  12927. return this._externalData.add(key, data);
  12928. };
  12929. /**
  12930. * Get an externaly attached data from its key
  12931. * @param key the unique key that identifies the data
  12932. * @return the associated data, if present (can be null), or undefined if not present
  12933. */
  12934. Engine.prototype.getExternalData = function (key) {
  12935. if (!this._externalData) {
  12936. this._externalData = new BABYLON.StringDictionary();
  12937. }
  12938. return this._externalData.get(key);
  12939. };
  12940. /**
  12941. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12942. * @param key the unique key that identifies the data
  12943. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12944. * @return the associated data, can be null if the factory returned null.
  12945. */
  12946. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12947. if (!this._externalData) {
  12948. this._externalData = new BABYLON.StringDictionary();
  12949. }
  12950. return this._externalData.getOrAddWithFactory(key, factory);
  12951. };
  12952. /**
  12953. * Remove an externaly attached data from the Engine instance
  12954. * @param key the unique key that identifies the data
  12955. * @return true if the data was successfully removed, false if it doesn't exist
  12956. */
  12957. Engine.prototype.removeExternalData = function (key) {
  12958. if (!this._externalData) {
  12959. this._externalData = new BABYLON.StringDictionary();
  12960. }
  12961. return this._externalData.remove(key);
  12962. };
  12963. Engine.prototype.unbindAllAttributes = function () {
  12964. if (this._mustWipeVertexAttributes) {
  12965. this._mustWipeVertexAttributes = false;
  12966. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12967. this._gl.disableVertexAttribArray(i);
  12968. this._vertexAttribArraysEnabled[i] = false;
  12969. this._currentBufferPointers[i].active = false;
  12970. }
  12971. return;
  12972. }
  12973. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12974. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12975. continue;
  12976. }
  12977. this._gl.disableVertexAttribArray(i);
  12978. this._vertexAttribArraysEnabled[i] = false;
  12979. this._currentBufferPointers[i].active = false;
  12980. }
  12981. };
  12982. Engine.prototype.releaseEffects = function () {
  12983. for (var name in this._compiledEffects) {
  12984. this._deleteProgram(this._compiledEffects[name]._program);
  12985. }
  12986. this._compiledEffects = {};
  12987. };
  12988. // Dispose
  12989. Engine.prototype.dispose = function () {
  12990. this.hideLoadingUI();
  12991. this.stopRenderLoop();
  12992. // Release postProcesses
  12993. while (this.postProcesses.length) {
  12994. this.postProcesses[0].dispose();
  12995. }
  12996. // Empty texture
  12997. if (this._emptyTexture) {
  12998. this._releaseTexture(this._emptyTexture);
  12999. this._emptyTexture = null;
  13000. }
  13001. if (this._emptyCubeTexture) {
  13002. this._releaseTexture(this._emptyCubeTexture);
  13003. this._emptyCubeTexture = null;
  13004. }
  13005. // Rescale PP
  13006. if (this._rescalePostProcess) {
  13007. this._rescalePostProcess.dispose();
  13008. }
  13009. // Release scenes
  13010. while (this.scenes.length) {
  13011. this.scenes[0].dispose();
  13012. }
  13013. // Release audio engine
  13014. if (Engine.audioEngine) {
  13015. Engine.audioEngine.dispose();
  13016. }
  13017. // Release effects
  13018. this.releaseEffects();
  13019. // Unbind
  13020. this.unbindAllAttributes();
  13021. if (this._dummyFramebuffer) {
  13022. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13023. }
  13024. //WebVR
  13025. this.disableVR();
  13026. // Events
  13027. if (BABYLON.Tools.IsWindowObjectExist()) {
  13028. window.removeEventListener("blur", this._onBlur);
  13029. window.removeEventListener("focus", this._onFocus);
  13030. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13031. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13032. if (this._renderingCanvas) {
  13033. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13034. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13035. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13036. if (!this._doNotHandleContextLost) {
  13037. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13038. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13039. }
  13040. }
  13041. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13042. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13043. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13044. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13045. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13046. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13047. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13048. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13049. if (this._onVrDisplayConnect) {
  13050. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13051. if (this._onVrDisplayDisconnect) {
  13052. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13053. }
  13054. if (this._onVrDisplayPresentChange) {
  13055. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13056. }
  13057. this._onVrDisplayConnect = null;
  13058. this._onVrDisplayDisconnect = null;
  13059. }
  13060. }
  13061. // Remove from Instances
  13062. var index = Engine.Instances.indexOf(this);
  13063. if (index >= 0) {
  13064. Engine.Instances.splice(index, 1);
  13065. }
  13066. this._workingCanvas = null;
  13067. this._workingContext = null;
  13068. this._currentBufferPointers = [];
  13069. this._renderingCanvas = null;
  13070. this._currentProgram = null;
  13071. this.onResizeObservable.clear();
  13072. this.onCanvasBlurObservable.clear();
  13073. this.onCanvasFocusObservable.clear();
  13074. this.onCanvasPointerOutObservable.clear();
  13075. this.onBeginFrameObservable.clear();
  13076. this.onEndFrameObservable.clear();
  13077. BABYLON.Effect.ResetCache();
  13078. // Abort active requests
  13079. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13080. var request = _a[_i];
  13081. request.abort();
  13082. }
  13083. };
  13084. // Loading screen
  13085. Engine.prototype.displayLoadingUI = function () {
  13086. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13087. return;
  13088. }
  13089. var loadingScreen = this.loadingScreen;
  13090. if (loadingScreen) {
  13091. loadingScreen.displayLoadingUI();
  13092. }
  13093. };
  13094. Engine.prototype.hideLoadingUI = function () {
  13095. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13096. return;
  13097. }
  13098. var loadingScreen = this.loadingScreen;
  13099. if (loadingScreen) {
  13100. loadingScreen.hideLoadingUI();
  13101. }
  13102. };
  13103. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13104. get: function () {
  13105. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13106. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13107. return this._loadingScreen;
  13108. },
  13109. set: function (loadingScreen) {
  13110. this._loadingScreen = loadingScreen;
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13116. set: function (text) {
  13117. this.loadingScreen.loadingUIText = text;
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13123. set: function (color) {
  13124. this.loadingScreen.loadingUIBackgroundColor = color;
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. Engine.prototype.attachContextLostEvent = function (callback) {
  13130. if (this._renderingCanvas) {
  13131. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13132. }
  13133. };
  13134. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13135. if (this._renderingCanvas) {
  13136. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13137. }
  13138. };
  13139. Engine.prototype.getVertexShaderSource = function (program) {
  13140. var shaders = this._gl.getAttachedShaders(program);
  13141. if (!shaders) {
  13142. return null;
  13143. }
  13144. return this._gl.getShaderSource(shaders[0]);
  13145. };
  13146. Engine.prototype.getFragmentShaderSource = function (program) {
  13147. var shaders = this._gl.getAttachedShaders(program);
  13148. if (!shaders) {
  13149. return null;
  13150. }
  13151. return this._gl.getShaderSource(shaders[1]);
  13152. };
  13153. Engine.prototype.getError = function () {
  13154. return this._gl.getError();
  13155. };
  13156. // FPS
  13157. Engine.prototype.getFps = function () {
  13158. return this._fps;
  13159. };
  13160. Engine.prototype.getDeltaTime = function () {
  13161. return this._deltaTime;
  13162. };
  13163. Engine.prototype._measureFps = function () {
  13164. this._performanceMonitor.sampleFrame();
  13165. this._fps = this._performanceMonitor.averageFPS;
  13166. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13167. };
  13168. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13169. if (faceIndex === void 0) { faceIndex = -1; }
  13170. var gl = this._gl;
  13171. if (!this._dummyFramebuffer) {
  13172. var dummy = gl.createFramebuffer();
  13173. if (!dummy) {
  13174. throw new Error("Unable to create dummy framebuffer");
  13175. }
  13176. this._dummyFramebuffer = dummy;
  13177. }
  13178. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13179. if (faceIndex > -1) {
  13180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13181. }
  13182. else {
  13183. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13184. }
  13185. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13186. var buffer;
  13187. switch (readType) {
  13188. case gl.UNSIGNED_BYTE:
  13189. buffer = new Uint8Array(4 * width * height);
  13190. readType = gl.UNSIGNED_BYTE;
  13191. break;
  13192. default:
  13193. buffer = new Float32Array(4 * width * height);
  13194. readType = gl.FLOAT;
  13195. break;
  13196. }
  13197. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13198. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13199. return buffer;
  13200. };
  13201. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13202. if (this._webGLVersion > 1) {
  13203. return this._caps.colorBufferFloat;
  13204. }
  13205. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13206. };
  13207. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13208. if (this._webGLVersion > 1) {
  13209. return this._caps.colorBufferFloat;
  13210. }
  13211. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13212. };
  13213. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13214. Engine.prototype._canRenderToFramebuffer = function (type) {
  13215. var gl = this._gl;
  13216. //clear existing errors
  13217. while (gl.getError() !== gl.NO_ERROR) { }
  13218. var successful = true;
  13219. var texture = gl.createTexture();
  13220. gl.bindTexture(gl.TEXTURE_2D, texture);
  13221. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13222. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13223. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13224. var fb = gl.createFramebuffer();
  13225. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13227. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13228. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13229. successful = successful && (gl.getError() === gl.NO_ERROR);
  13230. //try render by clearing frame buffer's color buffer
  13231. if (successful) {
  13232. gl.clear(gl.COLOR_BUFFER_BIT);
  13233. successful = successful && (gl.getError() === gl.NO_ERROR);
  13234. }
  13235. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13236. if (successful) {
  13237. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13238. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13239. var readFormat = gl.RGBA;
  13240. var readType = gl.UNSIGNED_BYTE;
  13241. var buffer = new Uint8Array(4);
  13242. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13243. successful = successful && (gl.getError() === gl.NO_ERROR);
  13244. }
  13245. //clean up
  13246. gl.deleteTexture(texture);
  13247. gl.deleteFramebuffer(fb);
  13248. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13249. //clear accumulated errors
  13250. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13251. return successful;
  13252. };
  13253. Engine.prototype._getWebGLTextureType = function (type) {
  13254. if (type === Engine.TEXTURETYPE_FLOAT) {
  13255. return this._gl.FLOAT;
  13256. }
  13257. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13258. // Add Half Float Constant.
  13259. return this._gl.HALF_FLOAT_OES;
  13260. }
  13261. return this._gl.UNSIGNED_BYTE;
  13262. };
  13263. ;
  13264. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13265. if (this._webGLVersion === 1) {
  13266. return this._gl.RGBA;
  13267. }
  13268. if (type === Engine.TEXTURETYPE_FLOAT) {
  13269. return this._gl.RGBA32F;
  13270. }
  13271. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13272. return this._gl.RGBA16F;
  13273. }
  13274. return this._gl.RGBA;
  13275. };
  13276. ;
  13277. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13278. if (type === Engine.TEXTURETYPE_FLOAT) {
  13279. return this._gl.RGBA32F;
  13280. }
  13281. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13282. return this._gl.RGBA16F;
  13283. }
  13284. return this._gl.RGBA8;
  13285. };
  13286. ;
  13287. Engine.prototype.createQuery = function () {
  13288. return this._gl.createQuery();
  13289. };
  13290. Engine.prototype.deleteQuery = function (query) {
  13291. this._gl.deleteQuery(query);
  13292. return this;
  13293. };
  13294. Engine.prototype.isQueryResultAvailable = function (query) {
  13295. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13296. };
  13297. Engine.prototype.getQueryResult = function (query) {
  13298. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13299. };
  13300. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13301. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13302. this._gl.beginQuery(glAlgorithm, query);
  13303. return this;
  13304. };
  13305. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13306. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13307. this._gl.endQuery(glAlgorithm);
  13308. return this;
  13309. };
  13310. /* Time queries */
  13311. Engine.prototype._createTimeQuery = function () {
  13312. var timerQuery = this._caps.timerQuery;
  13313. if (timerQuery.createQueryEXT) {
  13314. return timerQuery.createQueryEXT();
  13315. }
  13316. return this.createQuery();
  13317. };
  13318. Engine.prototype._deleteTimeQuery = function (query) {
  13319. var timerQuery = this._caps.timerQuery;
  13320. if (timerQuery.deleteQueryEXT) {
  13321. timerQuery.deleteQueryEXT(query);
  13322. return;
  13323. }
  13324. this.deleteQuery(query);
  13325. };
  13326. Engine.prototype._getTimeQueryResult = function (query) {
  13327. var timerQuery = this._caps.timerQuery;
  13328. if (timerQuery.getQueryObjectEXT) {
  13329. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13330. }
  13331. return this.getQueryResult(query);
  13332. };
  13333. Engine.prototype._getTimeQueryAvailability = function (query) {
  13334. var timerQuery = this._caps.timerQuery;
  13335. if (timerQuery.getQueryObjectEXT) {
  13336. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13337. }
  13338. return this.isQueryResultAvailable(query);
  13339. };
  13340. Engine.prototype.startTimeQuery = function () {
  13341. var timerQuery = this._caps.timerQuery;
  13342. if (!timerQuery) {
  13343. return null;
  13344. }
  13345. var token = new BABYLON._TimeToken();
  13346. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13347. if (this._caps.canUseTimestampForTimerQuery) {
  13348. token._startTimeQuery = this._createTimeQuery();
  13349. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13350. }
  13351. else {
  13352. if (this._currentNonTimestampToken) {
  13353. return this._currentNonTimestampToken;
  13354. }
  13355. token._timeElapsedQuery = this._createTimeQuery();
  13356. if (timerQuery.beginQueryEXT) {
  13357. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13358. }
  13359. else {
  13360. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13361. }
  13362. this._currentNonTimestampToken = token;
  13363. }
  13364. return token;
  13365. };
  13366. Engine.prototype.endTimeQuery = function (token) {
  13367. var timerQuery = this._caps.timerQuery;
  13368. if (!timerQuery || !token) {
  13369. return -1;
  13370. }
  13371. if (this._caps.canUseTimestampForTimerQuery) {
  13372. if (!token._startTimeQuery) {
  13373. return -1;
  13374. }
  13375. if (!token._endTimeQuery) {
  13376. token._endTimeQuery = this._createTimeQuery();
  13377. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13378. }
  13379. }
  13380. else if (!token._timeElapsedQueryEnded) {
  13381. if (!token._timeElapsedQuery) {
  13382. return -1;
  13383. }
  13384. if (timerQuery.endQueryEXT) {
  13385. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13386. }
  13387. else {
  13388. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13389. }
  13390. token._timeElapsedQueryEnded = true;
  13391. }
  13392. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13393. var available = false;
  13394. if (token._endTimeQuery) {
  13395. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13396. }
  13397. else if (token._timeElapsedQuery) {
  13398. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13399. }
  13400. if (available && !disjoint) {
  13401. var result = 0;
  13402. if (this._caps.canUseTimestampForTimerQuery) {
  13403. if (!token._startTimeQuery || !token._endTimeQuery) {
  13404. return -1;
  13405. }
  13406. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13407. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13408. result = timeEnd - timeStart;
  13409. this._deleteTimeQuery(token._startTimeQuery);
  13410. this._deleteTimeQuery(token._endTimeQuery);
  13411. token._startTimeQuery = null;
  13412. token._endTimeQuery = null;
  13413. }
  13414. else {
  13415. if (!token._timeElapsedQuery) {
  13416. return -1;
  13417. }
  13418. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13419. this._deleteTimeQuery(token._timeElapsedQuery);
  13420. token._timeElapsedQuery = null;
  13421. token._timeElapsedQueryEnded = false;
  13422. this._currentNonTimestampToken = null;
  13423. }
  13424. return result;
  13425. }
  13426. return -1;
  13427. };
  13428. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13429. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13430. };
  13431. // Transform feedback
  13432. Engine.prototype.createTransformFeedback = function () {
  13433. return this._gl.createTransformFeedback();
  13434. };
  13435. Engine.prototype.deleteTransformFeedback = function (value) {
  13436. this._gl.deleteTransformFeedback(value);
  13437. };
  13438. Engine.prototype.bindTransformFeedback = function (value) {
  13439. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13440. };
  13441. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13442. if (usePoints === void 0) { usePoints = true; }
  13443. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13444. };
  13445. Engine.prototype.endTransformFeedback = function () {
  13446. this._gl.endTransformFeedback();
  13447. };
  13448. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13449. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13450. };
  13451. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13452. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13453. };
  13454. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13455. var _this = this;
  13456. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13457. this._activeRequests.push(request);
  13458. request.onCompleteObservable.add(function (request) {
  13459. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13460. });
  13461. return request;
  13462. };
  13463. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13464. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13465. var onload = function (data) {
  13466. loadedFiles[index] = data;
  13467. loadedFiles._internalCount++;
  13468. if (loadedFiles._internalCount === 6) {
  13469. onfinish(loadedFiles);
  13470. }
  13471. };
  13472. var onerror = function (request, exception) {
  13473. if (onErrorCallBack && request) {
  13474. onErrorCallBack(request.status + " " + request.statusText, exception);
  13475. }
  13476. };
  13477. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13478. };
  13479. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13480. if (onError === void 0) { onError = null; }
  13481. var loadedFiles = [];
  13482. loadedFiles._internalCount = 0;
  13483. for (var index = 0; index < 6; index++) {
  13484. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13485. }
  13486. };
  13487. // Statics
  13488. Engine.isSupported = function () {
  13489. try {
  13490. var tempcanvas = document.createElement("canvas");
  13491. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13492. return gl != null && !!window.WebGLRenderingContext;
  13493. }
  13494. catch (e) {
  13495. return false;
  13496. }
  13497. };
  13498. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13499. Engine.ExceptionList = [
  13500. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13501. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  13502. ];
  13503. Engine.Instances = new Array();
  13504. // Const statics
  13505. Engine._ALPHA_DISABLE = 0;
  13506. Engine._ALPHA_ADD = 1;
  13507. Engine._ALPHA_COMBINE = 2;
  13508. Engine._ALPHA_SUBTRACT = 3;
  13509. Engine._ALPHA_MULTIPLY = 4;
  13510. Engine._ALPHA_MAXIMIZED = 5;
  13511. Engine._ALPHA_ONEONE = 6;
  13512. Engine._ALPHA_PREMULTIPLIED = 7;
  13513. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13514. Engine._ALPHA_INTERPOLATE = 9;
  13515. Engine._ALPHA_SCREENMODE = 10;
  13516. Engine._DELAYLOADSTATE_NONE = 0;
  13517. Engine._DELAYLOADSTATE_LOADED = 1;
  13518. Engine._DELAYLOADSTATE_LOADING = 2;
  13519. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13520. Engine._TEXTUREFORMAT_ALPHA = 0;
  13521. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13522. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13523. Engine._TEXTUREFORMAT_RGB = 4;
  13524. Engine._TEXTUREFORMAT_RGBA = 5;
  13525. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13526. Engine._TEXTURETYPE_FLOAT = 1;
  13527. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13528. // Depht or Stencil test Constants.
  13529. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13530. 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.
  13531. 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.
  13532. 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.
  13533. 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.
  13534. 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.
  13535. 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.
  13536. 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.
  13537. // Stencil Actions Constants.
  13538. Engine._KEEP = 0x1E00;
  13539. Engine._REPLACE = 0x1E01;
  13540. Engine._INCR = 0x1E02;
  13541. Engine._DECR = 0x1E03;
  13542. Engine._INVERT = 0x150A;
  13543. Engine._INCR_WRAP = 0x8507;
  13544. Engine._DECR_WRAP = 0x8508;
  13545. // Texture rescaling mode
  13546. Engine._SCALEMODE_FLOOR = 1;
  13547. Engine._SCALEMODE_NEAREST = 2;
  13548. Engine._SCALEMODE_CEILING = 3;
  13549. // Updatable statics so stick with vars here
  13550. Engine.CollisionsEpsilon = 0.001;
  13551. Engine.CodeRepository = "src/";
  13552. Engine.ShadersRepository = "src/Shaders/";
  13553. return Engine;
  13554. }());
  13555. BABYLON.Engine = Engine;
  13556. })(BABYLON || (BABYLON = {}));
  13557. //# sourceMappingURL=babylon.engine.js.map
  13558. var BABYLON;
  13559. (function (BABYLON) {
  13560. /**
  13561. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13562. */
  13563. var Node = /** @class */ (function () {
  13564. /**
  13565. * @constructor
  13566. * @param {string} name - the name and id to be given to this node
  13567. * @param {BABYLON.Scene} the scene this node will be added to
  13568. */
  13569. function Node(name, scene) {
  13570. if (scene === void 0) { scene = null; }
  13571. this.state = "";
  13572. this.metadata = null;
  13573. this.doNotSerialize = false;
  13574. this.animations = new Array();
  13575. this._ranges = {};
  13576. this._isEnabled = true;
  13577. this._isReady = true;
  13578. this._currentRenderId = -1;
  13579. this._parentRenderId = -1;
  13580. /**
  13581. * An event triggered when the mesh is disposed.
  13582. * @type {BABYLON.Observable}
  13583. */
  13584. this.onDisposeObservable = new BABYLON.Observable();
  13585. // Behaviors
  13586. this._behaviors = new Array();
  13587. this.name = name;
  13588. this.id = name;
  13589. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13590. this.uniqueId = this._scene.getUniqueId();
  13591. this._initCache();
  13592. }
  13593. Object.defineProperty(Node.prototype, "parent", {
  13594. get: function () {
  13595. return this._parentNode;
  13596. },
  13597. set: function (parent) {
  13598. if (this._parentNode === parent) {
  13599. return;
  13600. }
  13601. // Remove self from list of children of parent
  13602. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13603. var index = this._parentNode._children.indexOf(this);
  13604. if (index !== -1) {
  13605. this._parentNode._children.splice(index, 1);
  13606. }
  13607. }
  13608. // Store new parent
  13609. this._parentNode = parent;
  13610. // Add as child to new parent
  13611. if (this._parentNode) {
  13612. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13613. this._parentNode._children = new Array();
  13614. }
  13615. this._parentNode._children.push(this);
  13616. }
  13617. },
  13618. enumerable: true,
  13619. configurable: true
  13620. });
  13621. Node.prototype.getClassName = function () {
  13622. return "Node";
  13623. };
  13624. Object.defineProperty(Node.prototype, "onDispose", {
  13625. set: function (callback) {
  13626. if (this._onDisposeObserver) {
  13627. this.onDisposeObservable.remove(this._onDisposeObserver);
  13628. }
  13629. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. Node.prototype.getScene = function () {
  13635. return this._scene;
  13636. };
  13637. Node.prototype.getEngine = function () {
  13638. return this._scene.getEngine();
  13639. };
  13640. Node.prototype.addBehavior = function (behavior) {
  13641. var _this = this;
  13642. var index = this._behaviors.indexOf(behavior);
  13643. if (index !== -1) {
  13644. return this;
  13645. }
  13646. behavior.init();
  13647. if (this._scene.isLoading) {
  13648. // We defer the attach when the scene will be loaded
  13649. var observer = this._scene.onDataLoadedObservable.add(function () {
  13650. behavior.attach(_this);
  13651. setTimeout(function () {
  13652. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13653. _this._scene.onDataLoadedObservable.remove(observer);
  13654. }, 0);
  13655. });
  13656. }
  13657. else {
  13658. behavior.attach(this);
  13659. }
  13660. this._behaviors.push(behavior);
  13661. return this;
  13662. };
  13663. Node.prototype.removeBehavior = function (behavior) {
  13664. var index = this._behaviors.indexOf(behavior);
  13665. if (index === -1) {
  13666. return this;
  13667. }
  13668. this._behaviors[index].detach();
  13669. this._behaviors.splice(index, 1);
  13670. return this;
  13671. };
  13672. Object.defineProperty(Node.prototype, "behaviors", {
  13673. get: function () {
  13674. return this._behaviors;
  13675. },
  13676. enumerable: true,
  13677. configurable: true
  13678. });
  13679. Node.prototype.getBehaviorByName = function (name) {
  13680. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13681. var behavior = _a[_i];
  13682. if (behavior.name === name) {
  13683. return behavior;
  13684. }
  13685. }
  13686. return null;
  13687. };
  13688. // override it in derived class
  13689. Node.prototype.getWorldMatrix = function () {
  13690. return BABYLON.Matrix.Identity();
  13691. };
  13692. // override it in derived class if you add new variables to the cache
  13693. // and call the parent class method
  13694. Node.prototype._initCache = function () {
  13695. this._cache = {};
  13696. this._cache.parent = undefined;
  13697. };
  13698. Node.prototype.updateCache = function (force) {
  13699. if (!force && this.isSynchronized())
  13700. return;
  13701. this._cache.parent = this.parent;
  13702. this._updateCache();
  13703. };
  13704. // override it in derived class if you add new variables to the cache
  13705. // and call the parent class method if !ignoreParentClass
  13706. Node.prototype._updateCache = function (ignoreParentClass) {
  13707. };
  13708. // override it in derived class if you add new variables to the cache
  13709. Node.prototype._isSynchronized = function () {
  13710. return true;
  13711. };
  13712. Node.prototype._markSyncedWithParent = function () {
  13713. if (this.parent) {
  13714. this._parentRenderId = this.parent._currentRenderId;
  13715. }
  13716. };
  13717. Node.prototype.isSynchronizedWithParent = function () {
  13718. if (!this.parent) {
  13719. return true;
  13720. }
  13721. if (this._parentRenderId !== this.parent._currentRenderId) {
  13722. return false;
  13723. }
  13724. return this.parent.isSynchronized();
  13725. };
  13726. Node.prototype.isSynchronized = function (updateCache) {
  13727. var check = this.hasNewParent();
  13728. check = check || !this.isSynchronizedWithParent();
  13729. check = check || !this._isSynchronized();
  13730. if (updateCache)
  13731. this.updateCache(true);
  13732. return !check;
  13733. };
  13734. Node.prototype.hasNewParent = function (update) {
  13735. if (this._cache.parent === this.parent)
  13736. return false;
  13737. if (update)
  13738. this._cache.parent = this.parent;
  13739. return true;
  13740. };
  13741. /**
  13742. * Is this node ready to be used/rendered
  13743. * @return {boolean} is it ready
  13744. */
  13745. Node.prototype.isReady = function () {
  13746. return this._isReady;
  13747. };
  13748. /**
  13749. * Is this node enabled.
  13750. * 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.
  13751. * @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.
  13752. * @return {boolean} whether this node (and its parent) is enabled.
  13753. * @see setEnabled
  13754. */
  13755. Node.prototype.isEnabled = function (checkAncestors) {
  13756. if (checkAncestors === void 0) { checkAncestors = true; }
  13757. if (checkAncestors === false) {
  13758. return this._isEnabled;
  13759. }
  13760. if (this._isEnabled === false) {
  13761. return false;
  13762. }
  13763. if (this.parent !== undefined && this.parent !== null) {
  13764. return this.parent.isEnabled(checkAncestors);
  13765. }
  13766. return true;
  13767. };
  13768. /**
  13769. * Set the enabled state of this node.
  13770. * @param {boolean} value - the new enabled state
  13771. * @see isEnabled
  13772. */
  13773. Node.prototype.setEnabled = function (value) {
  13774. this._isEnabled = value;
  13775. };
  13776. /**
  13777. * Is this node a descendant of the given node.
  13778. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13779. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13780. * @see parent
  13781. */
  13782. Node.prototype.isDescendantOf = function (ancestor) {
  13783. if (this.parent) {
  13784. if (this.parent === ancestor) {
  13785. return true;
  13786. }
  13787. return this.parent.isDescendantOf(ancestor);
  13788. }
  13789. return false;
  13790. };
  13791. /**
  13792. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13793. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13794. * @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.
  13795. * @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.
  13796. */
  13797. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13798. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13799. if (!this._children) {
  13800. return;
  13801. }
  13802. for (var index = 0; index < this._children.length; index++) {
  13803. var item = this._children[index];
  13804. if (!predicate || predicate(item)) {
  13805. results.push(item);
  13806. }
  13807. if (!directDescendantsOnly) {
  13808. item._getDescendants(results, false, predicate);
  13809. }
  13810. }
  13811. };
  13812. /**
  13813. * Will return all nodes that have this node as ascendant.
  13814. * @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.
  13815. * @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.
  13816. * @return {BABYLON.Node[]} all children nodes of all types.
  13817. */
  13818. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13819. var results = new Array();
  13820. this._getDescendants(results, directDescendantsOnly, predicate);
  13821. return results;
  13822. };
  13823. /**
  13824. * Get all child-meshes of this node.
  13825. */
  13826. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13827. var results = [];
  13828. this._getDescendants(results, directDescendantsOnly, function (node) {
  13829. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13830. });
  13831. return results;
  13832. };
  13833. /**
  13834. * Get all child-transformNodes of this node.
  13835. */
  13836. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13837. var results = [];
  13838. this._getDescendants(results, directDescendantsOnly, function (node) {
  13839. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13840. });
  13841. return results;
  13842. };
  13843. /**
  13844. * Get all direct children of this node.
  13845. */
  13846. Node.prototype.getChildren = function (predicate) {
  13847. return this.getDescendants(true, predicate);
  13848. };
  13849. Node.prototype._setReady = function (state) {
  13850. if (state === this._isReady) {
  13851. return;
  13852. }
  13853. if (!state) {
  13854. this._isReady = false;
  13855. return;
  13856. }
  13857. this._isReady = true;
  13858. if (this.onReady) {
  13859. this.onReady(this);
  13860. }
  13861. };
  13862. Node.prototype.getAnimationByName = function (name) {
  13863. for (var i = 0; i < this.animations.length; i++) {
  13864. var animation = this.animations[i];
  13865. if (animation.name === name) {
  13866. return animation;
  13867. }
  13868. }
  13869. return null;
  13870. };
  13871. Node.prototype.createAnimationRange = function (name, from, to) {
  13872. // check name not already in use
  13873. if (!this._ranges[name]) {
  13874. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13875. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13876. if (this.animations[i]) {
  13877. this.animations[i].createRange(name, from, to);
  13878. }
  13879. }
  13880. }
  13881. };
  13882. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13883. if (deleteFrames === void 0) { deleteFrames = true; }
  13884. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13885. if (this.animations[i]) {
  13886. this.animations[i].deleteRange(name, deleteFrames);
  13887. }
  13888. }
  13889. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13890. };
  13891. Node.prototype.getAnimationRange = function (name) {
  13892. return this._ranges[name];
  13893. };
  13894. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13895. var range = this.getAnimationRange(name);
  13896. if (!range) {
  13897. return;
  13898. }
  13899. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13900. };
  13901. Node.prototype.serializeAnimationRanges = function () {
  13902. var serializationRanges = [];
  13903. for (var name in this._ranges) {
  13904. var localRange = this._ranges[name];
  13905. if (!localRange) {
  13906. continue;
  13907. }
  13908. var range = {};
  13909. range.name = name;
  13910. range.from = localRange.from;
  13911. range.to = localRange.to;
  13912. serializationRanges.push(range);
  13913. }
  13914. return serializationRanges;
  13915. };
  13916. // override it in derived class
  13917. Node.prototype.computeWorldMatrix = function (force) {
  13918. return BABYLON.Matrix.Identity();
  13919. };
  13920. Node.prototype.dispose = function () {
  13921. this.parent = null;
  13922. // Callback
  13923. this.onDisposeObservable.notifyObservers(this);
  13924. this.onDisposeObservable.clear();
  13925. // Behaviors
  13926. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13927. var behavior = _a[_i];
  13928. behavior.detach();
  13929. }
  13930. this._behaviors = [];
  13931. };
  13932. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13933. if (parsedNode.ranges) {
  13934. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13935. var data = parsedNode.ranges[index];
  13936. node.createAnimationRange(data.name, data.from, data.to);
  13937. }
  13938. }
  13939. };
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], Node.prototype, "name", void 0);
  13943. __decorate([
  13944. BABYLON.serialize()
  13945. ], Node.prototype, "id", void 0);
  13946. __decorate([
  13947. BABYLON.serialize()
  13948. ], Node.prototype, "uniqueId", void 0);
  13949. __decorate([
  13950. BABYLON.serialize()
  13951. ], Node.prototype, "state", void 0);
  13952. __decorate([
  13953. BABYLON.serialize()
  13954. ], Node.prototype, "metadata", void 0);
  13955. return Node;
  13956. }());
  13957. BABYLON.Node = Node;
  13958. })(BABYLON || (BABYLON = {}));
  13959. //# sourceMappingURL=babylon.node.js.map
  13960. var BABYLON;
  13961. (function (BABYLON) {
  13962. var BoundingSphere = /** @class */ (function () {
  13963. function BoundingSphere(minimum, maximum) {
  13964. this.minimum = minimum;
  13965. this.maximum = maximum;
  13966. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13967. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13968. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13969. this.radius = distance * 0.5;
  13970. this.centerWorld = BABYLON.Vector3.Zero();
  13971. this._update(BABYLON.Matrix.Identity());
  13972. }
  13973. // Methods
  13974. BoundingSphere.prototype._update = function (world) {
  13975. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13976. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13977. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13978. };
  13979. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13980. for (var i = 0; i < 6; i++) {
  13981. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  13982. return false;
  13983. }
  13984. return true;
  13985. };
  13986. BoundingSphere.prototype.intersectsPoint = function (point) {
  13987. var x = this.centerWorld.x - point.x;
  13988. var y = this.centerWorld.y - point.y;
  13989. var z = this.centerWorld.z - point.z;
  13990. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13991. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  13992. return false;
  13993. return true;
  13994. };
  13995. // Statics
  13996. BoundingSphere.Intersects = function (sphere0, sphere1) {
  13997. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  13998. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  13999. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14000. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14001. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14002. return false;
  14003. return true;
  14004. };
  14005. return BoundingSphere;
  14006. }());
  14007. BABYLON.BoundingSphere = BoundingSphere;
  14008. })(BABYLON || (BABYLON = {}));
  14009. //# sourceMappingURL=babylon.boundingSphere.js.map
  14010. var BABYLON;
  14011. (function (BABYLON) {
  14012. var BoundingBox = /** @class */ (function () {
  14013. function BoundingBox(minimum, maximum) {
  14014. this.minimum = minimum;
  14015. this.maximum = maximum;
  14016. this.vectors = new Array();
  14017. this.vectorsWorld = new Array();
  14018. // Bounding vectors
  14019. this.vectors.push(this.minimum.clone());
  14020. this.vectors.push(this.maximum.clone());
  14021. this.vectors.push(this.minimum.clone());
  14022. this.vectors[2].x = this.maximum.x;
  14023. this.vectors.push(this.minimum.clone());
  14024. this.vectors[3].y = this.maximum.y;
  14025. this.vectors.push(this.minimum.clone());
  14026. this.vectors[4].z = this.maximum.z;
  14027. this.vectors.push(this.maximum.clone());
  14028. this.vectors[5].z = this.minimum.z;
  14029. this.vectors.push(this.maximum.clone());
  14030. this.vectors[6].x = this.minimum.x;
  14031. this.vectors.push(this.maximum.clone());
  14032. this.vectors[7].y = this.minimum.y;
  14033. // OBB
  14034. this.center = this.maximum.add(this.minimum).scale(0.5);
  14035. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14036. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14037. // World
  14038. for (var index = 0; index < this.vectors.length; index++) {
  14039. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14040. }
  14041. this.minimumWorld = BABYLON.Vector3.Zero();
  14042. this.maximumWorld = BABYLON.Vector3.Zero();
  14043. this.centerWorld = BABYLON.Vector3.Zero();
  14044. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14045. this._update(BABYLON.Matrix.Identity());
  14046. }
  14047. // Methods
  14048. BoundingBox.prototype.getWorldMatrix = function () {
  14049. return this._worldMatrix;
  14050. };
  14051. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14052. this._worldMatrix.copyFrom(matrix);
  14053. return this;
  14054. };
  14055. BoundingBox.prototype._update = function (world) {
  14056. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14057. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14058. for (var index = 0; index < this.vectors.length; index++) {
  14059. var v = this.vectorsWorld[index];
  14060. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14061. if (v.x < this.minimumWorld.x)
  14062. this.minimumWorld.x = v.x;
  14063. if (v.y < this.minimumWorld.y)
  14064. this.minimumWorld.y = v.y;
  14065. if (v.z < this.minimumWorld.z)
  14066. this.minimumWorld.z = v.z;
  14067. if (v.x > this.maximumWorld.x)
  14068. this.maximumWorld.x = v.x;
  14069. if (v.y > this.maximumWorld.y)
  14070. this.maximumWorld.y = v.y;
  14071. if (v.z > this.maximumWorld.z)
  14072. this.maximumWorld.z = v.z;
  14073. }
  14074. // Extend
  14075. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14076. this.extendSizeWorld.scaleInPlace(0.5);
  14077. // OBB
  14078. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14079. this.centerWorld.scaleInPlace(0.5);
  14080. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14081. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14082. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14083. this._worldMatrix = world;
  14084. };
  14085. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14086. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14087. };
  14088. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14089. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14090. };
  14091. BoundingBox.prototype.intersectsPoint = function (point) {
  14092. var delta = -BABYLON.Epsilon;
  14093. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14094. return false;
  14095. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14096. return false;
  14097. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14098. return false;
  14099. return true;
  14100. };
  14101. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14102. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14103. };
  14104. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14105. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14106. return false;
  14107. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14108. return false;
  14109. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14110. return false;
  14111. return true;
  14112. };
  14113. // Statics
  14114. BoundingBox.Intersects = function (box0, box1) {
  14115. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14116. return false;
  14117. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14118. return false;
  14119. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14120. return false;
  14121. return true;
  14122. };
  14123. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14124. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14125. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14126. return (num <= (sphereRadius * sphereRadius));
  14127. };
  14128. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14129. for (var p = 0; p < 6; p++) {
  14130. for (var i = 0; i < 8; i++) {
  14131. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14132. return false;
  14133. }
  14134. }
  14135. }
  14136. return true;
  14137. };
  14138. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14139. for (var p = 0; p < 6; p++) {
  14140. var inCount = 8;
  14141. for (var i = 0; i < 8; i++) {
  14142. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14143. --inCount;
  14144. }
  14145. else {
  14146. break;
  14147. }
  14148. }
  14149. if (inCount === 0)
  14150. return false;
  14151. }
  14152. return true;
  14153. };
  14154. return BoundingBox;
  14155. }());
  14156. BABYLON.BoundingBox = BoundingBox;
  14157. })(BABYLON || (BABYLON = {}));
  14158. //# sourceMappingURL=babylon.boundingBox.js.map
  14159. var BABYLON;
  14160. (function (BABYLON) {
  14161. var computeBoxExtents = function (axis, box) {
  14162. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14163. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14164. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14165. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14166. var r = r0 + r1 + r2;
  14167. return {
  14168. min: p - r,
  14169. max: p + r
  14170. };
  14171. };
  14172. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14173. var axisOverlap = function (axis, box0, box1) {
  14174. var result0 = computeBoxExtents(axis, box0);
  14175. var result1 = computeBoxExtents(axis, box1);
  14176. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14177. };
  14178. var BoundingInfo = /** @class */ (function () {
  14179. function BoundingInfo(minimum, maximum) {
  14180. this.minimum = minimum;
  14181. this.maximum = maximum;
  14182. this._isLocked = false;
  14183. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14184. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14185. }
  14186. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14187. get: function () {
  14188. return this._isLocked;
  14189. },
  14190. set: function (value) {
  14191. this._isLocked = value;
  14192. },
  14193. enumerable: true,
  14194. configurable: true
  14195. });
  14196. // Methods
  14197. BoundingInfo.prototype.update = function (world) {
  14198. if (this._isLocked) {
  14199. return;
  14200. }
  14201. this.boundingBox._update(world);
  14202. this.boundingSphere._update(world);
  14203. };
  14204. /**
  14205. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14206. * @param center New center of the bounding info
  14207. * @param extend New extend of the bounding info
  14208. */
  14209. BoundingInfo.prototype.centerOn = function (center, extend) {
  14210. this.minimum = center.subtract(extend);
  14211. this.maximum = center.add(extend);
  14212. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14213. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14214. return this;
  14215. };
  14216. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14217. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14218. return false;
  14219. return this.boundingBox.isInFrustum(frustumPlanes);
  14220. };
  14221. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14222. /**
  14223. * Gets the world distance between the min and max points of the bounding box
  14224. */
  14225. get: function () {
  14226. var boundingBox = this.boundingBox;
  14227. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14228. return size.length();
  14229. },
  14230. enumerable: true,
  14231. configurable: true
  14232. });
  14233. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14234. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14235. };
  14236. BoundingInfo.prototype._checkCollision = function (collider) {
  14237. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14238. };
  14239. BoundingInfo.prototype.intersectsPoint = function (point) {
  14240. if (!this.boundingSphere.centerWorld) {
  14241. return false;
  14242. }
  14243. if (!this.boundingSphere.intersectsPoint(point)) {
  14244. return false;
  14245. }
  14246. if (!this.boundingBox.intersectsPoint(point)) {
  14247. return false;
  14248. }
  14249. return true;
  14250. };
  14251. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14252. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14253. return false;
  14254. }
  14255. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14256. return false;
  14257. }
  14258. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14259. return false;
  14260. }
  14261. if (!precise) {
  14262. return true;
  14263. }
  14264. var box0 = this.boundingBox;
  14265. var box1 = boundingInfo.boundingBox;
  14266. if (!axisOverlap(box0.directions[0], box0, box1))
  14267. return false;
  14268. if (!axisOverlap(box0.directions[1], box0, box1))
  14269. return false;
  14270. if (!axisOverlap(box0.directions[2], box0, box1))
  14271. return false;
  14272. if (!axisOverlap(box1.directions[0], box0, box1))
  14273. return false;
  14274. if (!axisOverlap(box1.directions[1], box0, box1))
  14275. return false;
  14276. if (!axisOverlap(box1.directions[2], box0, box1))
  14277. return false;
  14278. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14279. return false;
  14280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14281. return false;
  14282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14283. return false;
  14284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14285. return false;
  14286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14287. return false;
  14288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14289. return false;
  14290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14291. return false;
  14292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14293. return false;
  14294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14295. return false;
  14296. return true;
  14297. };
  14298. return BoundingInfo;
  14299. }());
  14300. BABYLON.BoundingInfo = BoundingInfo;
  14301. })(BABYLON || (BABYLON = {}));
  14302. //# sourceMappingURL=babylon.boundingInfo.js.map
  14303. var BABYLON;
  14304. (function (BABYLON) {
  14305. var TransformNode = /** @class */ (function (_super) {
  14306. __extends(TransformNode, _super);
  14307. function TransformNode(name, scene, isPure) {
  14308. if (scene === void 0) { scene = null; }
  14309. if (isPure === void 0) { isPure = true; }
  14310. var _this = _super.call(this, name, scene) || this;
  14311. // Properties
  14312. _this._rotation = BABYLON.Vector3.Zero();
  14313. _this._scaling = BABYLON.Vector3.One();
  14314. _this._isDirty = false;
  14315. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14316. _this.scalingDeterminant = 1;
  14317. _this.infiniteDistance = false;
  14318. _this.position = BABYLON.Vector3.Zero();
  14319. _this._localWorld = BABYLON.Matrix.Zero();
  14320. _this._worldMatrix = BABYLON.Matrix.Zero();
  14321. _this._worldMatrixDeterminant = 0;
  14322. _this._absolutePosition = BABYLON.Vector3.Zero();
  14323. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14324. _this._postMultiplyPivotMatrix = false;
  14325. _this._isWorldMatrixFrozen = false;
  14326. /**
  14327. * An event triggered after the world matrix is updated
  14328. * @type {BABYLON.Observable}
  14329. */
  14330. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14331. _this._nonUniformScaling = false;
  14332. if (isPure) {
  14333. _this.getScene().addTransformNode(_this);
  14334. }
  14335. return _this;
  14336. }
  14337. Object.defineProperty(TransformNode.prototype, "rotation", {
  14338. /**
  14339. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14340. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14341. * Default : (0.0, 0.0, 0.0)
  14342. */
  14343. get: function () {
  14344. return this._rotation;
  14345. },
  14346. set: function (newRotation) {
  14347. this._rotation = newRotation;
  14348. },
  14349. enumerable: true,
  14350. configurable: true
  14351. });
  14352. Object.defineProperty(TransformNode.prototype, "scaling", {
  14353. /**
  14354. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14355. * Default : (1.0, 1.0, 1.0)
  14356. */
  14357. get: function () {
  14358. return this._scaling;
  14359. },
  14360. /**
  14361. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14362. * Default : (1.0, 1.0, 1.0)
  14363. */
  14364. set: function (newScaling) {
  14365. this._scaling = newScaling;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14371. /**
  14372. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14373. * It's null by default.
  14374. * 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)
  14375. */
  14376. get: function () {
  14377. return this._rotationQuaternion;
  14378. },
  14379. set: function (quaternion) {
  14380. this._rotationQuaternion = quaternion;
  14381. //reset the rotation vector.
  14382. if (quaternion && this.rotation.length()) {
  14383. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14384. }
  14385. },
  14386. enumerable: true,
  14387. configurable: true
  14388. });
  14389. /**
  14390. * Returns the latest update of the World matrix
  14391. * Returns a Matrix.
  14392. */
  14393. TransformNode.prototype.getWorldMatrix = function () {
  14394. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14395. this.computeWorldMatrix();
  14396. }
  14397. return this._worldMatrix;
  14398. };
  14399. /**
  14400. * Returns the latest update of the World matrix determinant.
  14401. */
  14402. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14403. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14404. this.computeWorldMatrix();
  14405. }
  14406. return this._worldMatrixDeterminant;
  14407. };
  14408. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14409. /**
  14410. * Returns directly the latest state of the mesh World matrix.
  14411. * A Matrix is returned.
  14412. */
  14413. get: function () {
  14414. return this._worldMatrix;
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. /**
  14420. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14421. * Returns the AbstractMesh.
  14422. */
  14423. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14424. this._poseMatrix.copyFrom(matrix);
  14425. return this;
  14426. };
  14427. /**
  14428. * Returns the mesh Pose matrix.
  14429. * Returned object : Matrix
  14430. */
  14431. TransformNode.prototype.getPoseMatrix = function () {
  14432. return this._poseMatrix;
  14433. };
  14434. TransformNode.prototype._isSynchronized = function () {
  14435. if (this._isDirty) {
  14436. return false;
  14437. }
  14438. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14439. return false;
  14440. if (this._cache.pivotMatrixUpdated) {
  14441. return false;
  14442. }
  14443. if (this.infiniteDistance) {
  14444. return false;
  14445. }
  14446. if (!this._cache.position.equals(this.position))
  14447. return false;
  14448. if (this.rotationQuaternion) {
  14449. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14450. return false;
  14451. }
  14452. if (!this._cache.rotation.equals(this.rotation))
  14453. return false;
  14454. if (!this._cache.scaling.equals(this.scaling))
  14455. return false;
  14456. return true;
  14457. };
  14458. TransformNode.prototype._initCache = function () {
  14459. _super.prototype._initCache.call(this);
  14460. this._cache.localMatrixUpdated = false;
  14461. this._cache.position = BABYLON.Vector3.Zero();
  14462. this._cache.scaling = BABYLON.Vector3.Zero();
  14463. this._cache.rotation = BABYLON.Vector3.Zero();
  14464. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14465. this._cache.billboardMode = -1;
  14466. };
  14467. TransformNode.prototype.markAsDirty = function (property) {
  14468. if (property === "rotation") {
  14469. this.rotationQuaternion = null;
  14470. }
  14471. this._currentRenderId = Number.MAX_VALUE;
  14472. this._isDirty = true;
  14473. return this;
  14474. };
  14475. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14476. /**
  14477. * Returns the current mesh absolute position.
  14478. * Retuns a Vector3.
  14479. */
  14480. get: function () {
  14481. return this._absolutePosition;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. /**
  14487. * Sets a new pivot matrix to the mesh.
  14488. * Returns the AbstractMesh.
  14489. */
  14490. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14491. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14492. this._pivotMatrix = matrix.clone();
  14493. this._cache.pivotMatrixUpdated = true;
  14494. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14495. if (this._postMultiplyPivotMatrix) {
  14496. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14497. }
  14498. return this;
  14499. };
  14500. /**
  14501. * Returns the mesh pivot matrix.
  14502. * Default : Identity.
  14503. * A Matrix is returned.
  14504. */
  14505. TransformNode.prototype.getPivotMatrix = function () {
  14506. return this._pivotMatrix;
  14507. };
  14508. /**
  14509. * Prevents the World matrix to be computed any longer.
  14510. * Returns the AbstractMesh.
  14511. */
  14512. TransformNode.prototype.freezeWorldMatrix = function () {
  14513. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14514. this.computeWorldMatrix(true);
  14515. this._isWorldMatrixFrozen = true;
  14516. return this;
  14517. };
  14518. /**
  14519. * Allows back the World matrix computation.
  14520. * Returns the AbstractMesh.
  14521. */
  14522. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14523. this._isWorldMatrixFrozen = false;
  14524. this.computeWorldMatrix(true);
  14525. return this;
  14526. };
  14527. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14528. /**
  14529. * True if the World matrix has been frozen.
  14530. * Returns a boolean.
  14531. */
  14532. get: function () {
  14533. return this._isWorldMatrixFrozen;
  14534. },
  14535. enumerable: true,
  14536. configurable: true
  14537. });
  14538. /**
  14539. * Retuns the mesh absolute position in the World.
  14540. * Returns a Vector3.
  14541. */
  14542. TransformNode.prototype.getAbsolutePosition = function () {
  14543. this.computeWorldMatrix();
  14544. return this._absolutePosition;
  14545. };
  14546. /**
  14547. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14548. * Returns the AbstractMesh.
  14549. */
  14550. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14551. if (!absolutePosition) {
  14552. return this;
  14553. }
  14554. var absolutePositionX;
  14555. var absolutePositionY;
  14556. var absolutePositionZ;
  14557. if (absolutePosition.x === undefined) {
  14558. if (arguments.length < 3) {
  14559. return this;
  14560. }
  14561. absolutePositionX = arguments[0];
  14562. absolutePositionY = arguments[1];
  14563. absolutePositionZ = arguments[2];
  14564. }
  14565. else {
  14566. absolutePositionX = absolutePosition.x;
  14567. absolutePositionY = absolutePosition.y;
  14568. absolutePositionZ = absolutePosition.z;
  14569. }
  14570. if (this.parent) {
  14571. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14572. invertParentWorldMatrix.invert();
  14573. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14574. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14575. }
  14576. else {
  14577. this.position.x = absolutePositionX;
  14578. this.position.y = absolutePositionY;
  14579. this.position.z = absolutePositionZ;
  14580. }
  14581. return this;
  14582. };
  14583. /**
  14584. * Sets the mesh position in its local space.
  14585. * Returns the AbstractMesh.
  14586. */
  14587. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14588. this.computeWorldMatrix();
  14589. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14590. return this;
  14591. };
  14592. /**
  14593. * Returns the mesh position in the local space from the current World matrix values.
  14594. * Returns a new Vector3.
  14595. */
  14596. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14597. this.computeWorldMatrix();
  14598. var invLocalWorldMatrix = this._localWorld.clone();
  14599. invLocalWorldMatrix.invert();
  14600. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14601. };
  14602. /**
  14603. * Translates the mesh along the passed Vector3 in its local space.
  14604. * Returns the AbstractMesh.
  14605. */
  14606. TransformNode.prototype.locallyTranslate = function (vector3) {
  14607. this.computeWorldMatrix(true);
  14608. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14609. return this;
  14610. };
  14611. /**
  14612. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14613. * @param targetPoint the position (must be in same space as current mesh) to look at
  14614. * @param yawCor optional yaw (y-axis) correction in radians
  14615. * @param pitchCor optional pitch (x-axis) correction in radians
  14616. * @param rollCor optional roll (z-axis) correction in radians
  14617. * @param space the choosen space of the target
  14618. * @returns the TransformNode.
  14619. */
  14620. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14621. if (yawCor === void 0) { yawCor = 0; }
  14622. if (pitchCor === void 0) { pitchCor = 0; }
  14623. if (rollCor === void 0) { rollCor = 0; }
  14624. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14625. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14626. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14627. targetPoint.subtractToRef(pos, dv);
  14628. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14629. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14630. var pitch = Math.atan2(dv.y, len);
  14631. if (this.rotationQuaternion) {
  14632. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14633. }
  14634. else {
  14635. this.rotation.x = pitch + pitchCor;
  14636. this.rotation.y = yaw + yawCor;
  14637. this.rotation.z = rollCor;
  14638. }
  14639. return this;
  14640. };
  14641. /**
  14642. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14643. * This Vector3 is expressed in the World space.
  14644. */
  14645. TransformNode.prototype.getDirection = function (localAxis) {
  14646. var result = BABYLON.Vector3.Zero();
  14647. this.getDirectionToRef(localAxis, result);
  14648. return result;
  14649. };
  14650. /**
  14651. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14652. * localAxis is expressed in the mesh local space.
  14653. * result is computed in the Wordl space from the mesh World matrix.
  14654. * Returns the AbstractMesh.
  14655. */
  14656. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14657. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14658. return this;
  14659. };
  14660. TransformNode.prototype.setPivotPoint = function (point, space) {
  14661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14662. if (this.getScene().getRenderId() == 0) {
  14663. this.computeWorldMatrix(true);
  14664. }
  14665. var wm = this.getWorldMatrix();
  14666. if (space == BABYLON.Space.WORLD) {
  14667. var tmat = BABYLON.Tmp.Matrix[0];
  14668. wm.invertToRef(tmat);
  14669. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14670. }
  14671. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14672. this._pivotMatrix.m[12] = -point.x;
  14673. this._pivotMatrix.m[13] = -point.y;
  14674. this._pivotMatrix.m[14] = -point.z;
  14675. this._cache.pivotMatrixUpdated = true;
  14676. return this;
  14677. };
  14678. /**
  14679. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14680. */
  14681. TransformNode.prototype.getPivotPoint = function () {
  14682. var point = BABYLON.Vector3.Zero();
  14683. this.getPivotPointToRef(point);
  14684. return point;
  14685. };
  14686. /**
  14687. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14688. * Returns the AbstractMesh.
  14689. */
  14690. TransformNode.prototype.getPivotPointToRef = function (result) {
  14691. result.x = -this._pivotMatrix.m[12];
  14692. result.y = -this._pivotMatrix.m[13];
  14693. result.z = -this._pivotMatrix.m[14];
  14694. return this;
  14695. };
  14696. /**
  14697. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14698. */
  14699. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14700. var point = BABYLON.Vector3.Zero();
  14701. this.getAbsolutePivotPointToRef(point);
  14702. return point;
  14703. };
  14704. /**
  14705. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14706. * Returns the AbstractMesh.
  14707. */
  14708. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14709. result.x = this._pivotMatrix.m[12];
  14710. result.y = this._pivotMatrix.m[13];
  14711. result.z = this._pivotMatrix.m[14];
  14712. this.getPivotPointToRef(result);
  14713. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14714. return this;
  14715. };
  14716. /**
  14717. * Defines the passed node as the parent of the current node.
  14718. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14719. * Returns the TransformNode.
  14720. */
  14721. TransformNode.prototype.setParent = function (node) {
  14722. if (node === null) {
  14723. var rotation = BABYLON.Tmp.Quaternion[0];
  14724. var position = BABYLON.Tmp.Vector3[0];
  14725. var scale = BABYLON.Tmp.Vector3[1];
  14726. if (this.parent && this.parent.computeWorldMatrix) {
  14727. this.parent.computeWorldMatrix(true);
  14728. }
  14729. this.computeWorldMatrix(true);
  14730. this.getWorldMatrix().decompose(scale, rotation, position);
  14731. if (this.rotationQuaternion) {
  14732. this.rotationQuaternion.copyFrom(rotation);
  14733. }
  14734. else {
  14735. rotation.toEulerAnglesToRef(this.rotation);
  14736. }
  14737. this.scaling.x = scale.x;
  14738. this.scaling.y = scale.y;
  14739. this.scaling.z = scale.z;
  14740. this.position.x = position.x;
  14741. this.position.y = position.y;
  14742. this.position.z = position.z;
  14743. }
  14744. else {
  14745. var rotation = BABYLON.Tmp.Quaternion[0];
  14746. var position = BABYLON.Tmp.Vector3[0];
  14747. var scale = BABYLON.Tmp.Vector3[1];
  14748. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14749. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14750. this.computeWorldMatrix(true);
  14751. node.computeWorldMatrix(true);
  14752. node.getWorldMatrix().invertToRef(invParentMatrix);
  14753. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14754. diffMatrix.decompose(scale, rotation, position);
  14755. if (this.rotationQuaternion) {
  14756. this.rotationQuaternion.copyFrom(rotation);
  14757. }
  14758. else {
  14759. rotation.toEulerAnglesToRef(this.rotation);
  14760. }
  14761. this.position.x = position.x;
  14762. this.position.y = position.y;
  14763. this.position.z = position.z;
  14764. this.scaling.x = scale.x;
  14765. this.scaling.y = scale.y;
  14766. this.scaling.z = scale.z;
  14767. }
  14768. this.parent = node;
  14769. return this;
  14770. };
  14771. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14772. get: function () {
  14773. return this._nonUniformScaling;
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14779. if (this._nonUniformScaling === value) {
  14780. return false;
  14781. }
  14782. this._nonUniformScaling = true;
  14783. return true;
  14784. };
  14785. /**
  14786. * Attach the current TransformNode to another TransformNode associated with a bone
  14787. * @param bone Bone affecting the TransformNode
  14788. * @param affectedTransformNode TransformNode associated with the bone
  14789. */
  14790. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14791. this._transformToBoneReferal = affectedTransformNode;
  14792. this.parent = bone;
  14793. if (bone.getWorldMatrix().determinant() < 0) {
  14794. this.scalingDeterminant *= -1;
  14795. }
  14796. return this;
  14797. };
  14798. TransformNode.prototype.detachFromBone = function () {
  14799. if (!this.parent) {
  14800. return this;
  14801. }
  14802. if (this.parent.getWorldMatrix().determinant() < 0) {
  14803. this.scalingDeterminant *= -1;
  14804. }
  14805. this._transformToBoneReferal = null;
  14806. this.parent = null;
  14807. return this;
  14808. };
  14809. /**
  14810. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14811. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14812. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14813. * The passed axis is also normalized.
  14814. * Returns the AbstractMesh.
  14815. */
  14816. TransformNode.prototype.rotate = function (axis, amount, space) {
  14817. axis.normalize();
  14818. if (!this.rotationQuaternion) {
  14819. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14820. this.rotation = BABYLON.Vector3.Zero();
  14821. }
  14822. var rotationQuaternion;
  14823. if (!space || space === BABYLON.Space.LOCAL) {
  14824. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14825. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14826. }
  14827. else {
  14828. if (this.parent) {
  14829. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14830. invertParentWorldMatrix.invert();
  14831. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14832. }
  14833. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14834. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14835. }
  14836. return this;
  14837. };
  14838. /**
  14839. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14840. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14841. * The passed axis is also normalized.
  14842. * Returns the AbstractMesh.
  14843. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14844. */
  14845. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14846. axis.normalize();
  14847. if (!this.rotationQuaternion) {
  14848. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14849. this.rotation.copyFromFloats(0, 0, 0);
  14850. }
  14851. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14852. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14853. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14854. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14855. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14856. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14857. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14858. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14859. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14860. return this;
  14861. };
  14862. /**
  14863. * Translates the mesh along the axis vector for the passed distance in the given space.
  14864. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14865. * Returns the AbstractMesh.
  14866. */
  14867. TransformNode.prototype.translate = function (axis, distance, space) {
  14868. var displacementVector = axis.scale(distance);
  14869. if (!space || space === BABYLON.Space.LOCAL) {
  14870. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14871. this.setPositionWithLocalVector(tempV3);
  14872. }
  14873. else {
  14874. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14875. }
  14876. return this;
  14877. };
  14878. /**
  14879. * Adds a rotation step to the mesh current rotation.
  14880. * x, y, z are Euler angles expressed in radians.
  14881. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14882. * This means this rotation is made in the mesh local space only.
  14883. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14884. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14885. * ```javascript
  14886. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14887. * ```
  14888. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14889. * 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.
  14890. * Returns the AbstractMesh.
  14891. */
  14892. TransformNode.prototype.addRotation = function (x, y, z) {
  14893. var rotationQuaternion;
  14894. if (this.rotationQuaternion) {
  14895. rotationQuaternion = this.rotationQuaternion;
  14896. }
  14897. else {
  14898. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14899. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14900. }
  14901. var accumulation = BABYLON.Tmp.Quaternion[0];
  14902. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14903. rotationQuaternion.multiplyInPlace(accumulation);
  14904. if (!this.rotationQuaternion) {
  14905. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14906. }
  14907. return this;
  14908. };
  14909. /**
  14910. * Computes the mesh World matrix and returns it.
  14911. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14912. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14913. * If the parameter `force`is set to `true`, the actual computation is done.
  14914. * Returns the mesh World Matrix.
  14915. */
  14916. TransformNode.prototype.computeWorldMatrix = function (force) {
  14917. if (this._isWorldMatrixFrozen) {
  14918. return this._worldMatrix;
  14919. }
  14920. if (!force && this.isSynchronized(true)) {
  14921. return this._worldMatrix;
  14922. }
  14923. this._cache.position.copyFrom(this.position);
  14924. this._cache.scaling.copyFrom(this.scaling);
  14925. this._cache.pivotMatrixUpdated = false;
  14926. this._cache.billboardMode = this.billboardMode;
  14927. this._currentRenderId = this.getScene().getRenderId();
  14928. this._isDirty = false;
  14929. // Scaling
  14930. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14931. // Rotation
  14932. //rotate, if quaternion is set and rotation was used
  14933. if (this.rotationQuaternion) {
  14934. var len = this.rotation.length();
  14935. if (len) {
  14936. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14937. this.rotation.copyFromFloats(0, 0, 0);
  14938. }
  14939. }
  14940. if (this.rotationQuaternion) {
  14941. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14942. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14943. }
  14944. else {
  14945. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14946. this._cache.rotation.copyFrom(this.rotation);
  14947. }
  14948. // Translation
  14949. var camera = this.getScene().activeCamera;
  14950. if (this.infiniteDistance && !this.parent && camera) {
  14951. var cameraWorldMatrix = camera.getWorldMatrix();
  14952. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14953. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14954. }
  14955. else {
  14956. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14957. }
  14958. // Composing transformations
  14959. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14960. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14961. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14962. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14963. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14964. // Need to decompose each rotation here
  14965. var currentPosition = BABYLON.Tmp.Vector3[3];
  14966. if (this.parent && this.parent.getWorldMatrix) {
  14967. if (this._transformToBoneReferal) {
  14968. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14969. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14970. }
  14971. else {
  14972. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14973. }
  14974. }
  14975. else {
  14976. currentPosition.copyFrom(this.position);
  14977. }
  14978. currentPosition.subtractInPlace(camera.globalPosition);
  14979. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14980. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14981. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14982. }
  14983. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  14984. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14985. }
  14986. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  14987. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14988. }
  14989. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14990. }
  14991. else {
  14992. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14993. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14994. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14995. }
  14996. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14997. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14998. }
  14999. // Local world
  15000. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15001. // Parent
  15002. if (this.parent && this.parent.getWorldMatrix) {
  15003. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15004. if (this._transformToBoneReferal) {
  15005. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15006. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15007. }
  15008. else {
  15009. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15010. }
  15011. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15012. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15013. this._worldMatrix.copyFrom(this._localWorld);
  15014. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15015. }
  15016. else {
  15017. if (this._transformToBoneReferal) {
  15018. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15019. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15020. }
  15021. else {
  15022. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15023. }
  15024. }
  15025. this._markSyncedWithParent();
  15026. }
  15027. else {
  15028. this._worldMatrix.copyFrom(this._localWorld);
  15029. }
  15030. // Post multiply inverse of pivotMatrix
  15031. if (this._postMultiplyPivotMatrix) {
  15032. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15033. }
  15034. // Normal matrix
  15035. if (this.scaling.isNonUniform) {
  15036. this._updateNonUniformScalingState(true);
  15037. }
  15038. else if (this.parent && this.parent._nonUniformScaling) {
  15039. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15040. }
  15041. else {
  15042. this._updateNonUniformScalingState(false);
  15043. }
  15044. this._afterComputeWorldMatrix();
  15045. // Absolute position
  15046. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15047. // Callbacks
  15048. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15049. if (!this._poseMatrix) {
  15050. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15051. }
  15052. // Cache the determinant
  15053. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15054. return this._worldMatrix;
  15055. };
  15056. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15057. };
  15058. /**
  15059. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15060. * @param func: callback function to add
  15061. *
  15062. * Returns the TransformNode.
  15063. */
  15064. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15065. this.onAfterWorldMatrixUpdateObservable.add(func);
  15066. return this;
  15067. };
  15068. /**
  15069. * Removes a registered callback function.
  15070. * Returns the TransformNode.
  15071. */
  15072. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15073. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15074. return this;
  15075. };
  15076. /**
  15077. * Clone the current transform node
  15078. * Returns the new transform node
  15079. * @param name Name of the new clone
  15080. * @param newParent New parent for the clone
  15081. * @param doNotCloneChildren Do not clone children hierarchy
  15082. */
  15083. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15084. var _this = this;
  15085. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15086. result.name = name;
  15087. result.id = name;
  15088. if (newParent) {
  15089. result.parent = newParent;
  15090. }
  15091. if (!doNotCloneChildren) {
  15092. // Children
  15093. var directDescendants = this.getDescendants(true);
  15094. for (var index = 0; index < directDescendants.length; index++) {
  15095. var child = directDescendants[index];
  15096. if (child.clone) {
  15097. child.clone(name + "." + child.name, result);
  15098. }
  15099. }
  15100. }
  15101. return result;
  15102. };
  15103. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15104. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15105. serializationObject.type = this.getClassName();
  15106. // Parent
  15107. if (this.parent) {
  15108. serializationObject.parentId = this.parent.id;
  15109. }
  15110. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15111. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15112. }
  15113. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15114. serializationObject.isEnabled = this.isEnabled();
  15115. // Parent
  15116. if (this.parent) {
  15117. serializationObject.parentId = this.parent.id;
  15118. }
  15119. return serializationObject;
  15120. };
  15121. // Statics
  15122. /**
  15123. * Returns a new TransformNode object parsed from the source provided.
  15124. * The parameter `parsedMesh` is the source.
  15125. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15126. */
  15127. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15128. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15129. if (BABYLON.Tags) {
  15130. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15131. }
  15132. if (parsedTransformNode.localMatrix) {
  15133. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15134. }
  15135. else if (parsedTransformNode.pivotMatrix) {
  15136. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15137. }
  15138. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15139. // Parent
  15140. if (parsedTransformNode.parentId) {
  15141. transformNode._waitingParentId = parsedTransformNode.parentId;
  15142. }
  15143. return transformNode;
  15144. };
  15145. /**
  15146. * Disposes the TransformNode.
  15147. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15148. * Returns nothing.
  15149. */
  15150. TransformNode.prototype.dispose = function (doNotRecurse) {
  15151. // Animations
  15152. this.getScene().stopAnimation(this);
  15153. // Remove from scene
  15154. this.getScene().removeTransformNode(this);
  15155. this._cache = {};
  15156. if (!doNotRecurse) {
  15157. // Children
  15158. var objects = this.getDescendants(true);
  15159. for (var index = 0; index < objects.length; index++) {
  15160. objects[index].dispose();
  15161. }
  15162. }
  15163. else {
  15164. var childMeshes = this.getChildMeshes(true);
  15165. for (index = 0; index < childMeshes.length; index++) {
  15166. var child = childMeshes[index];
  15167. child.parent = null;
  15168. child.computeWorldMatrix(true);
  15169. }
  15170. }
  15171. this.onAfterWorldMatrixUpdateObservable.clear();
  15172. _super.prototype.dispose.call(this);
  15173. };
  15174. // Statics
  15175. TransformNode.BILLBOARDMODE_NONE = 0;
  15176. TransformNode.BILLBOARDMODE_X = 1;
  15177. TransformNode.BILLBOARDMODE_Y = 2;
  15178. TransformNode.BILLBOARDMODE_Z = 4;
  15179. TransformNode.BILLBOARDMODE_ALL = 7;
  15180. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15181. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15182. __decorate([
  15183. BABYLON.serializeAsVector3()
  15184. ], TransformNode.prototype, "_rotation", void 0);
  15185. __decorate([
  15186. BABYLON.serializeAsQuaternion()
  15187. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15188. __decorate([
  15189. BABYLON.serializeAsVector3()
  15190. ], TransformNode.prototype, "_scaling", void 0);
  15191. __decorate([
  15192. BABYLON.serialize()
  15193. ], TransformNode.prototype, "billboardMode", void 0);
  15194. __decorate([
  15195. BABYLON.serialize()
  15196. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15197. __decorate([
  15198. BABYLON.serialize()
  15199. ], TransformNode.prototype, "infiniteDistance", void 0);
  15200. __decorate([
  15201. BABYLON.serializeAsVector3()
  15202. ], TransformNode.prototype, "position", void 0);
  15203. return TransformNode;
  15204. }(BABYLON.Node));
  15205. BABYLON.TransformNode = TransformNode;
  15206. })(BABYLON || (BABYLON = {}));
  15207. //# sourceMappingURL=babylon.transformNode.js.map
  15208. var BABYLON;
  15209. (function (BABYLON) {
  15210. var AbstractMesh = /** @class */ (function (_super) {
  15211. __extends(AbstractMesh, _super);
  15212. // Constructor
  15213. function AbstractMesh(name, scene) {
  15214. if (scene === void 0) { scene = null; }
  15215. var _this = _super.call(this, name, scene, false) || this;
  15216. _this._facetNb = 0; // facet number
  15217. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15218. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15219. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15220. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15221. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15222. _this._subDiv = {
  15223. max: 1,
  15224. X: 1,
  15225. Y: 1,
  15226. Z: 1
  15227. };
  15228. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15229. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15230. // Events
  15231. /**
  15232. * An event triggered when this mesh collides with another one
  15233. * @type {BABYLON.Observable}
  15234. */
  15235. _this.onCollideObservable = new BABYLON.Observable();
  15236. /**
  15237. * An event triggered when the collision's position changes
  15238. * @type {BABYLON.Observable}
  15239. */
  15240. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15241. /**
  15242. * An event triggered when material is changed
  15243. * @type {BABYLON.Observable}
  15244. */
  15245. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15246. // Properties
  15247. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15248. /**
  15249. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15250. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15251. * or
  15252. * 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.
  15253. * for more info check WebGl documentations
  15254. */
  15255. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15256. /**
  15257. * 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:
  15258. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15259. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15260. * 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.
  15261. */
  15262. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15263. /**
  15264. * 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.
  15265. * The default value is -1 which means don't break the query and wait till the result.
  15266. */
  15267. _this.occlusionRetryCount = -1;
  15268. _this._occlusionInternalRetryCounter = 0;
  15269. _this._isOccluded = false;
  15270. _this._isOcclusionQueryInProgress = false;
  15271. _this.visibility = 1.0;
  15272. _this.alphaIndex = Number.MAX_VALUE;
  15273. _this.isVisible = true;
  15274. _this.isPickable = true;
  15275. _this.showBoundingBox = false;
  15276. _this.showSubMeshesBoundingBox = false;
  15277. _this.isBlocker = false;
  15278. _this.enablePointerMoveEvents = false;
  15279. _this.renderingGroupId = 0;
  15280. _this._receiveShadows = false;
  15281. _this.renderOutline = false;
  15282. _this.outlineColor = BABYLON.Color3.Red();
  15283. _this.outlineWidth = 0.02;
  15284. _this.renderOverlay = false;
  15285. _this.overlayColor = BABYLON.Color3.Red();
  15286. _this.overlayAlpha = 0.5;
  15287. _this._hasVertexAlpha = false;
  15288. _this._useVertexColors = true;
  15289. _this._computeBonesUsingShaders = true;
  15290. _this._numBoneInfluencers = 4;
  15291. _this._applyFog = true;
  15292. _this.useOctreeForRenderingSelection = true;
  15293. _this.useOctreeForPicking = true;
  15294. _this.useOctreeForCollisions = true;
  15295. _this._layerMask = 0x0FFFFFFF;
  15296. /**
  15297. * True if the mesh must be rendered in any case.
  15298. */
  15299. _this.alwaysSelectAsActiveMesh = false;
  15300. /**
  15301. * This scene's action manager
  15302. * @type {BABYLON.ActionManager}
  15303. */
  15304. _this.actionManager = null;
  15305. // Physics
  15306. _this.physicsImpostor = null;
  15307. // Collisions
  15308. _this._checkCollisions = false;
  15309. _this._collisionMask = -1;
  15310. _this._collisionGroup = -1;
  15311. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15312. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15313. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15314. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15315. // Edges
  15316. _this.edgesWidth = 1;
  15317. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15318. // Cache
  15319. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15320. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15321. _this._isDisposed = false;
  15322. _this._renderId = 0;
  15323. _this._intersectionsInProgress = new Array();
  15324. _this._unIndexed = false;
  15325. _this._lightSources = new Array();
  15326. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15327. if (collidedMesh === void 0) { collidedMesh = null; }
  15328. //TODO move this to the collision coordinator!
  15329. if (_this.getScene().workerCollisions)
  15330. newPosition.multiplyInPlace(_this._collider._radius);
  15331. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15332. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15333. _this.position.addInPlace(_this._diffPositionForCollisions);
  15334. }
  15335. if (collidedMesh) {
  15336. _this.onCollideObservable.notifyObservers(collidedMesh);
  15337. }
  15338. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15339. };
  15340. _this.getScene().addMesh(_this);
  15341. _this._resyncLightSources();
  15342. return _this;
  15343. }
  15344. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15345. get: function () {
  15346. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15347. },
  15348. enumerable: true,
  15349. configurable: true
  15350. });
  15351. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15352. get: function () {
  15353. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15354. },
  15355. enumerable: true,
  15356. configurable: true
  15357. });
  15358. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15359. get: function () {
  15360. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15361. },
  15362. enumerable: true,
  15363. configurable: true
  15364. });
  15365. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15366. get: function () {
  15367. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15368. },
  15369. enumerable: true,
  15370. configurable: true
  15371. });
  15372. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15373. get: function () {
  15374. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15375. },
  15376. enumerable: true,
  15377. configurable: true
  15378. });
  15379. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15380. /**
  15381. * Read-only : the number of facets in the mesh
  15382. */
  15383. get: function () {
  15384. return this._facetNb;
  15385. },
  15386. enumerable: true,
  15387. configurable: true
  15388. });
  15389. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15390. /**
  15391. * The number (integer) of subdivisions per axis in the partioning space
  15392. */
  15393. get: function () {
  15394. return this._partitioningSubdivisions;
  15395. },
  15396. set: function (nb) {
  15397. this._partitioningSubdivisions = nb;
  15398. },
  15399. enumerable: true,
  15400. configurable: true
  15401. });
  15402. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15403. /**
  15404. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15405. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15406. */
  15407. get: function () {
  15408. return this._partitioningBBoxRatio;
  15409. },
  15410. set: function (ratio) {
  15411. this._partitioningBBoxRatio = ratio;
  15412. },
  15413. enumerable: true,
  15414. configurable: true
  15415. });
  15416. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15417. /**
  15418. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15419. * Works only for updatable meshes.
  15420. * Doesn't work with multi-materials.
  15421. */
  15422. get: function () {
  15423. return this._facetDepthSort;
  15424. },
  15425. set: function (sort) {
  15426. this._facetDepthSort = sort;
  15427. },
  15428. enumerable: true,
  15429. configurable: true
  15430. });
  15431. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15432. /**
  15433. * The location (Vector3) where the facet depth sort must be computed from.
  15434. * By default, the active camera position.
  15435. * Used only when facet depth sort is enabled.
  15436. */
  15437. get: function () {
  15438. return this._facetDepthSortFrom;
  15439. },
  15440. set: function (location) {
  15441. this._facetDepthSortFrom = location;
  15442. },
  15443. enumerable: true,
  15444. configurable: true
  15445. });
  15446. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15447. /**
  15448. * Read-only boolean : is the feature facetData enabled ?
  15449. */
  15450. get: function () {
  15451. return this._facetDataEnabled;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15457. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15458. return false;
  15459. }
  15460. this._markSubMeshesAsMiscDirty();
  15461. return true;
  15462. };
  15463. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15464. set: function (callback) {
  15465. if (this._onCollideObserver) {
  15466. this.onCollideObservable.remove(this._onCollideObserver);
  15467. }
  15468. this._onCollideObserver = this.onCollideObservable.add(callback);
  15469. },
  15470. enumerable: true,
  15471. configurable: true
  15472. });
  15473. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15474. set: function (callback) {
  15475. if (this._onCollisionPositionChangeObserver) {
  15476. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15477. }
  15478. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15479. },
  15480. enumerable: true,
  15481. configurable: true
  15482. });
  15483. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15484. /**
  15485. * 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.
  15486. */
  15487. get: function () {
  15488. return this._isOccluded;
  15489. },
  15490. set: function (value) {
  15491. this._isOccluded = value;
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15497. /**
  15498. * Flag to check the progress status of the query
  15499. */
  15500. get: function () {
  15501. return this._isOcclusionQueryInProgress;
  15502. },
  15503. enumerable: true,
  15504. configurable: true
  15505. });
  15506. Object.defineProperty(AbstractMesh.prototype, "material", {
  15507. get: function () {
  15508. return this._material;
  15509. },
  15510. set: function (value) {
  15511. if (this._material === value) {
  15512. return;
  15513. }
  15514. this._material = value;
  15515. if (this.onMaterialChangedObservable.hasObservers) {
  15516. this.onMaterialChangedObservable.notifyObservers(this);
  15517. }
  15518. if (!this.subMeshes) {
  15519. return;
  15520. }
  15521. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15522. var subMesh = _a[_i];
  15523. subMesh.setEffect(null);
  15524. }
  15525. },
  15526. enumerable: true,
  15527. configurable: true
  15528. });
  15529. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15530. get: function () {
  15531. return this._receiveShadows;
  15532. },
  15533. set: function (value) {
  15534. if (this._receiveShadows === value) {
  15535. return;
  15536. }
  15537. this._receiveShadows = value;
  15538. this._markSubMeshesAsLightDirty();
  15539. },
  15540. enumerable: true,
  15541. configurable: true
  15542. });
  15543. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15544. get: function () {
  15545. return this._hasVertexAlpha;
  15546. },
  15547. set: function (value) {
  15548. if (this._hasVertexAlpha === value) {
  15549. return;
  15550. }
  15551. this._hasVertexAlpha = value;
  15552. this._markSubMeshesAsAttributesDirty();
  15553. },
  15554. enumerable: true,
  15555. configurable: true
  15556. });
  15557. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15558. get: function () {
  15559. return this._useVertexColors;
  15560. },
  15561. set: function (value) {
  15562. if (this._useVertexColors === value) {
  15563. return;
  15564. }
  15565. this._useVertexColors = value;
  15566. this._markSubMeshesAsAttributesDirty();
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15572. get: function () {
  15573. return this._computeBonesUsingShaders;
  15574. },
  15575. set: function (value) {
  15576. if (this._computeBonesUsingShaders === value) {
  15577. return;
  15578. }
  15579. this._computeBonesUsingShaders = value;
  15580. this._markSubMeshesAsAttributesDirty();
  15581. },
  15582. enumerable: true,
  15583. configurable: true
  15584. });
  15585. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15586. get: function () {
  15587. return this._numBoneInfluencers;
  15588. },
  15589. set: function (value) {
  15590. if (this._numBoneInfluencers === value) {
  15591. return;
  15592. }
  15593. this._numBoneInfluencers = value;
  15594. this._markSubMeshesAsAttributesDirty();
  15595. },
  15596. enumerable: true,
  15597. configurable: true
  15598. });
  15599. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15600. get: function () {
  15601. return this._applyFog;
  15602. },
  15603. set: function (value) {
  15604. if (this._applyFog === value) {
  15605. return;
  15606. }
  15607. this._applyFog = value;
  15608. this._markSubMeshesAsMiscDirty();
  15609. },
  15610. enumerable: true,
  15611. configurable: true
  15612. });
  15613. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15614. get: function () {
  15615. return this._layerMask;
  15616. },
  15617. set: function (value) {
  15618. if (value === this._layerMask) {
  15619. return;
  15620. }
  15621. this._layerMask = value;
  15622. this._resyncLightSources();
  15623. },
  15624. enumerable: true,
  15625. configurable: true
  15626. });
  15627. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15628. get: function () {
  15629. return this._collisionMask;
  15630. },
  15631. set: function (mask) {
  15632. this._collisionMask = !isNaN(mask) ? mask : -1;
  15633. },
  15634. enumerable: true,
  15635. configurable: true
  15636. });
  15637. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15638. get: function () {
  15639. return this._collisionGroup;
  15640. },
  15641. set: function (mask) {
  15642. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15643. },
  15644. enumerable: true,
  15645. configurable: true
  15646. });
  15647. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15648. get: function () {
  15649. return null;
  15650. },
  15651. enumerable: true,
  15652. configurable: true
  15653. });
  15654. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15655. get: function () {
  15656. return this._skeleton;
  15657. },
  15658. set: function (value) {
  15659. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15660. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15661. }
  15662. if (value && value.needInitialSkinMatrix) {
  15663. value._registerMeshWithPoseMatrix(this);
  15664. }
  15665. this._skeleton = value;
  15666. if (!this._skeleton) {
  15667. this._bonesTransformMatrices = null;
  15668. }
  15669. this._markSubMeshesAsAttributesDirty();
  15670. },
  15671. enumerable: true,
  15672. configurable: true
  15673. });
  15674. /**
  15675. * Boolean : true if the mesh has been disposed.
  15676. */
  15677. AbstractMesh.prototype.isDisposed = function () {
  15678. return this._isDisposed;
  15679. };
  15680. /**
  15681. * Returns the string "AbstractMesh"
  15682. */
  15683. AbstractMesh.prototype.getClassName = function () {
  15684. return "AbstractMesh";
  15685. };
  15686. /**
  15687. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15688. */
  15689. AbstractMesh.prototype.toString = function (fullDetails) {
  15690. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15691. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15692. if (this._skeleton) {
  15693. ret += ", skeleton: " + this._skeleton.name;
  15694. }
  15695. if (fullDetails) {
  15696. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15697. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15698. }
  15699. return ret;
  15700. };
  15701. AbstractMesh.prototype._rebuild = function () {
  15702. if (this._occlusionQuery) {
  15703. this._occlusionQuery = null;
  15704. }
  15705. if (this._edgesRenderer) {
  15706. this._edgesRenderer._rebuild();
  15707. }
  15708. if (!this.subMeshes) {
  15709. return;
  15710. }
  15711. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15712. var subMesh = _a[_i];
  15713. subMesh._rebuild();
  15714. }
  15715. };
  15716. AbstractMesh.prototype._resyncLightSources = function () {
  15717. this._lightSources.length = 0;
  15718. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15719. var light = _a[_i];
  15720. if (!light.isEnabled()) {
  15721. continue;
  15722. }
  15723. if (light.canAffectMesh(this)) {
  15724. this._lightSources.push(light);
  15725. }
  15726. }
  15727. this._markSubMeshesAsLightDirty();
  15728. };
  15729. AbstractMesh.prototype._resyncLighSource = function (light) {
  15730. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15731. var index = this._lightSources.indexOf(light);
  15732. if (index === -1) {
  15733. if (!isIn) {
  15734. return;
  15735. }
  15736. this._lightSources.push(light);
  15737. }
  15738. else {
  15739. if (isIn) {
  15740. return;
  15741. }
  15742. this._lightSources.splice(index, 1);
  15743. }
  15744. this._markSubMeshesAsLightDirty();
  15745. };
  15746. AbstractMesh.prototype._removeLightSource = function (light) {
  15747. var index = this._lightSources.indexOf(light);
  15748. if (index === -1) {
  15749. return;
  15750. }
  15751. this._lightSources.splice(index, 1);
  15752. };
  15753. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15754. if (!this.subMeshes) {
  15755. return;
  15756. }
  15757. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15758. var subMesh = _a[_i];
  15759. if (subMesh._materialDefines) {
  15760. func(subMesh._materialDefines);
  15761. }
  15762. }
  15763. };
  15764. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15765. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15766. };
  15767. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15768. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15769. };
  15770. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15771. if (!this.subMeshes) {
  15772. return;
  15773. }
  15774. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15775. var subMesh = _a[_i];
  15776. var material = subMesh.getMaterial();
  15777. if (material) {
  15778. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15779. }
  15780. }
  15781. };
  15782. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15783. /**
  15784. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15785. * Default : (1.0, 1.0, 1.0)
  15786. */
  15787. get: function () {
  15788. return this._scaling;
  15789. },
  15790. /**
  15791. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15792. * Default : (1.0, 1.0, 1.0)
  15793. */
  15794. set: function (newScaling) {
  15795. this._scaling = newScaling;
  15796. if (this.physicsImpostor) {
  15797. this.physicsImpostor.forceUpdate();
  15798. }
  15799. },
  15800. enumerable: true,
  15801. configurable: true
  15802. });
  15803. // Methods
  15804. /**
  15805. * Disables the mesh edger rendering mode.
  15806. * Returns the AbstractMesh.
  15807. */
  15808. AbstractMesh.prototype.disableEdgesRendering = function () {
  15809. if (this._edgesRenderer) {
  15810. this._edgesRenderer.dispose();
  15811. this._edgesRenderer = null;
  15812. }
  15813. return this;
  15814. };
  15815. /**
  15816. * Enables the edge rendering mode on the mesh.
  15817. * This mode makes the mesh edges visible.
  15818. * Returns the AbstractMesh.
  15819. */
  15820. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15821. if (epsilon === void 0) { epsilon = 0.95; }
  15822. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15823. this.disableEdgesRendering();
  15824. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15825. return this;
  15826. };
  15827. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15828. /**
  15829. * Returns true if the mesh is blocked. Used by the class Mesh.
  15830. * Returns the boolean `false` by default.
  15831. */
  15832. get: function () {
  15833. return false;
  15834. },
  15835. enumerable: true,
  15836. configurable: true
  15837. });
  15838. /**
  15839. * Returns the mesh itself by default, used by the class Mesh.
  15840. * Returned type : AbstractMesh
  15841. */
  15842. AbstractMesh.prototype.getLOD = function (camera) {
  15843. return this;
  15844. };
  15845. /**
  15846. * Returns 0 by default, used by the class Mesh.
  15847. * Returns an integer.
  15848. */
  15849. AbstractMesh.prototype.getTotalVertices = function () {
  15850. return 0;
  15851. };
  15852. /**
  15853. * Returns null by default, used by the class Mesh.
  15854. * Returned type : integer array
  15855. */
  15856. AbstractMesh.prototype.getIndices = function () {
  15857. return null;
  15858. };
  15859. /**
  15860. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15861. * Returned type : float array or Float32Array
  15862. */
  15863. AbstractMesh.prototype.getVerticesData = function (kind) {
  15864. return null;
  15865. };
  15866. /**
  15867. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15868. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15869. * The `data` are either a numeric array either a Float32Array.
  15870. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15871. * 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).
  15872. * Note that a new underlying VertexBuffer object is created each call.
  15873. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15874. *
  15875. * Possible `kind` values :
  15876. * - BABYLON.VertexBuffer.PositionKind
  15877. * - BABYLON.VertexBuffer.UVKind
  15878. * - BABYLON.VertexBuffer.UV2Kind
  15879. * - BABYLON.VertexBuffer.UV3Kind
  15880. * - BABYLON.VertexBuffer.UV4Kind
  15881. * - BABYLON.VertexBuffer.UV5Kind
  15882. * - BABYLON.VertexBuffer.UV6Kind
  15883. * - BABYLON.VertexBuffer.ColorKind
  15884. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15885. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15886. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15887. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15888. *
  15889. * Returns the Mesh.
  15890. */
  15891. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15892. return this;
  15893. };
  15894. /**
  15895. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15896. * If the mesh has no geometry, it is simply returned as it is.
  15897. * The `data` are either a numeric array either a Float32Array.
  15898. * No new underlying VertexBuffer object is created.
  15899. * 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.
  15900. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15901. *
  15902. * Possible `kind` values :
  15903. * - BABYLON.VertexBuffer.PositionKind
  15904. * - BABYLON.VertexBuffer.UVKind
  15905. * - BABYLON.VertexBuffer.UV2Kind
  15906. * - BABYLON.VertexBuffer.UV3Kind
  15907. * - BABYLON.VertexBuffer.UV4Kind
  15908. * - BABYLON.VertexBuffer.UV5Kind
  15909. * - BABYLON.VertexBuffer.UV6Kind
  15910. * - BABYLON.VertexBuffer.ColorKind
  15911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15915. *
  15916. * Returns the Mesh.
  15917. */
  15918. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15919. return this;
  15920. };
  15921. /**
  15922. * Sets the mesh indices.
  15923. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15924. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15925. * This method creates a new index buffer each call.
  15926. * Returns the Mesh.
  15927. */
  15928. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15929. return this;
  15930. };
  15931. /** Returns false by default, used by the class Mesh.
  15932. * Returns a boolean
  15933. */
  15934. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15935. return false;
  15936. };
  15937. /**
  15938. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15939. * Returns a BoundingInfo
  15940. */
  15941. AbstractMesh.prototype.getBoundingInfo = function () {
  15942. if (this._masterMesh) {
  15943. return this._masterMesh.getBoundingInfo();
  15944. }
  15945. if (!this._boundingInfo) {
  15946. // this._boundingInfo is being created here
  15947. this._updateBoundingInfo();
  15948. }
  15949. // cannot be null.
  15950. return this._boundingInfo;
  15951. };
  15952. /**
  15953. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15954. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15955. */
  15956. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15957. if (includeDescendants === void 0) { includeDescendants = true; }
  15958. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15959. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15960. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15961. if (maxDimension === 0) {
  15962. return this;
  15963. }
  15964. var scale = 1 / maxDimension;
  15965. this.scaling.scaleInPlace(scale);
  15966. return this;
  15967. };
  15968. /**
  15969. * Sets a mesh new object BoundingInfo.
  15970. * Returns the AbstractMesh.
  15971. */
  15972. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15973. this._boundingInfo = boundingInfo;
  15974. return this;
  15975. };
  15976. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15977. get: function () {
  15978. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. AbstractMesh.prototype._preActivate = function () {
  15984. };
  15985. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  15986. };
  15987. AbstractMesh.prototype._activate = function (renderId) {
  15988. this._renderId = renderId;
  15989. };
  15990. /**
  15991. * Returns the latest update of the World matrix
  15992. * Returns a Matrix.
  15993. */
  15994. AbstractMesh.prototype.getWorldMatrix = function () {
  15995. if (this._masterMesh) {
  15996. return this._masterMesh.getWorldMatrix();
  15997. }
  15998. return _super.prototype.getWorldMatrix.call(this);
  15999. };
  16000. /**
  16001. * Returns the latest update of the World matrix determinant.
  16002. */
  16003. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16004. if (this._masterMesh) {
  16005. return this._masterMesh._getWorldMatrixDeterminant();
  16006. }
  16007. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16008. };
  16009. // ================================== Point of View Movement =================================
  16010. /**
  16011. * Perform relative position change from the point of view of behind the front of the mesh.
  16012. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16013. * Supports definition of mesh facing forward or backward.
  16014. * @param {number} amountRight
  16015. * @param {number} amountUp
  16016. * @param {number} amountForward
  16017. *
  16018. * Returns the AbstractMesh.
  16019. */
  16020. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16021. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16022. return this;
  16023. };
  16024. /**
  16025. * Calculate relative position change from the point of view of behind the front of the mesh.
  16026. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16027. * Supports definition of mesh facing forward or backward.
  16028. * @param {number} amountRight
  16029. * @param {number} amountUp
  16030. * @param {number} amountForward
  16031. *
  16032. * Returns a new Vector3.
  16033. */
  16034. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16035. var rotMatrix = new BABYLON.Matrix();
  16036. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16037. rotQuaternion.toRotationMatrix(rotMatrix);
  16038. var translationDelta = BABYLON.Vector3.Zero();
  16039. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16040. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16041. return translationDelta;
  16042. };
  16043. // ================================== Point of View Rotation =================================
  16044. /**
  16045. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16046. * Supports definition of mesh facing forward or backward.
  16047. * @param {number} flipBack
  16048. * @param {number} twirlClockwise
  16049. * @param {number} tiltRight
  16050. *
  16051. * Returns the AbstractMesh.
  16052. */
  16053. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16054. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16055. return this;
  16056. };
  16057. /**
  16058. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16059. * Supports definition of mesh facing forward or backward.
  16060. * @param {number} flipBack
  16061. * @param {number} twirlClockwise
  16062. * @param {number} tiltRight
  16063. *
  16064. * Returns a new Vector3.
  16065. */
  16066. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16067. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16068. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16069. };
  16070. /**
  16071. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16072. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16073. */
  16074. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16075. if (includeDescendants === void 0) { includeDescendants = true; }
  16076. this.computeWorldMatrix(true);
  16077. var min;
  16078. var max;
  16079. var boundingInfo = this.getBoundingInfo();
  16080. if (!this.subMeshes) {
  16081. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16082. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16083. }
  16084. else {
  16085. min = boundingInfo.boundingBox.minimumWorld;
  16086. max = boundingInfo.boundingBox.maximumWorld;
  16087. }
  16088. if (includeDescendants) {
  16089. var descendants = this.getDescendants(false);
  16090. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16091. var descendant = descendants_1[_i];
  16092. var childMesh = descendant;
  16093. childMesh.computeWorldMatrix(true);
  16094. //make sure we have the needed params to get mix and max
  16095. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16096. continue;
  16097. }
  16098. var childBoundingInfo = childMesh.getBoundingInfo();
  16099. var boundingBox = childBoundingInfo.boundingBox;
  16100. var minBox = boundingBox.minimumWorld;
  16101. var maxBox = boundingBox.maximumWorld;
  16102. BABYLON.Tools.CheckExtends(minBox, min, max);
  16103. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16104. }
  16105. }
  16106. return {
  16107. min: min,
  16108. max: max
  16109. };
  16110. };
  16111. /**
  16112. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16113. * Returns the AbstractMesh.
  16114. */
  16115. AbstractMesh.prototype._updateBoundingInfo = function () {
  16116. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16117. this._boundingInfo.update(this.worldMatrixFromCache);
  16118. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16119. return this;
  16120. };
  16121. /**
  16122. * Update a mesh's children BoundingInfo objects only.
  16123. * Returns the AbstractMesh.
  16124. */
  16125. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16126. if (!this.subMeshes) {
  16127. return this;
  16128. }
  16129. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16130. var subMesh = this.subMeshes[subIndex];
  16131. if (!subMesh.IsGlobal) {
  16132. subMesh.updateBoundingInfo(matrix);
  16133. }
  16134. }
  16135. return this;
  16136. };
  16137. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16138. // Bounding info
  16139. this._updateBoundingInfo();
  16140. };
  16141. /**
  16142. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16143. * A mesh is in the frustum if its bounding box intersects the frustum.
  16144. * Boolean returned.
  16145. */
  16146. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16147. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16148. };
  16149. /**
  16150. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16151. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16152. * Boolean returned.
  16153. */
  16154. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16155. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16156. ;
  16157. };
  16158. /**
  16159. * True if the mesh intersects another mesh or a SolidParticle object.
  16160. * 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)
  16161. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16162. * Returns a boolean.
  16163. */
  16164. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16165. if (precise === void 0) { precise = false; }
  16166. if (!this._boundingInfo || !mesh._boundingInfo) {
  16167. return false;
  16168. }
  16169. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16170. return true;
  16171. }
  16172. if (includeDescendants) {
  16173. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16174. var child = _a[_i];
  16175. if (child.intersectsMesh(mesh, precise, true)) {
  16176. return true;
  16177. }
  16178. }
  16179. }
  16180. return false;
  16181. };
  16182. /**
  16183. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16184. * Returns a boolean.
  16185. */
  16186. AbstractMesh.prototype.intersectsPoint = function (point) {
  16187. if (!this._boundingInfo) {
  16188. return false;
  16189. }
  16190. return this._boundingInfo.intersectsPoint(point);
  16191. };
  16192. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16193. return this.physicsImpostor;
  16194. };
  16195. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16196. if (camera === void 0) { camera = null; }
  16197. if (!camera) {
  16198. camera = this.getScene().activeCamera;
  16199. }
  16200. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16201. };
  16202. /**
  16203. * Returns the distance from the mesh to the active camera.
  16204. * Returns a float.
  16205. */
  16206. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16207. if (camera === void 0) { camera = null; }
  16208. if (!camera) {
  16209. camera = this.getScene().activeCamera;
  16210. }
  16211. return this.absolutePosition.subtract(camera.position).length();
  16212. };
  16213. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16214. if (!this.physicsImpostor) {
  16215. return this;
  16216. }
  16217. this.physicsImpostor.applyImpulse(force, contactPoint);
  16218. return this;
  16219. };
  16220. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16221. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16222. return this;
  16223. }
  16224. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16225. mainPivot: pivot1,
  16226. connectedPivot: pivot2,
  16227. nativeParams: options
  16228. });
  16229. return this;
  16230. };
  16231. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16232. // Collisions
  16233. /**
  16234. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16235. * Default `false`.
  16236. */
  16237. get: function () {
  16238. return this._checkCollisions;
  16239. },
  16240. set: function (collisionEnabled) {
  16241. this._checkCollisions = collisionEnabled;
  16242. if (this.getScene().workerCollisions) {
  16243. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16244. }
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16250. /**
  16251. * Gets Collider object used to compute collisions (not physics)
  16252. */
  16253. get: function () {
  16254. return this._collider;
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16260. var globalPosition = this.getAbsolutePosition();
  16261. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16262. if (!this._collider) {
  16263. this._collider = new BABYLON.Collider();
  16264. }
  16265. this._collider._radius = this.ellipsoid;
  16266. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16267. return this;
  16268. };
  16269. // Submeshes octree
  16270. /**
  16271. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16272. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16273. * Returns an Octree of submeshes.
  16274. */
  16275. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16276. if (maxCapacity === void 0) { maxCapacity = 64; }
  16277. if (maxDepth === void 0) { maxDepth = 2; }
  16278. if (!this._submeshesOctree) {
  16279. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16280. }
  16281. this.computeWorldMatrix(true);
  16282. var boundingInfo = this.getBoundingInfo();
  16283. // Update octree
  16284. var bbox = boundingInfo.boundingBox;
  16285. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16286. return this._submeshesOctree;
  16287. };
  16288. // Collisions
  16289. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16290. this._generatePointsArray();
  16291. if (!this._positions) {
  16292. return this;
  16293. }
  16294. // Transformation
  16295. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16296. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16297. subMesh._lastColliderWorldVertices = [];
  16298. subMesh._trianglePlanes = [];
  16299. var start = subMesh.verticesStart;
  16300. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16301. for (var i = start; i < end; i++) {
  16302. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16303. }
  16304. }
  16305. // Collide
  16306. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16307. if (collider.collisionFound) {
  16308. collider.collidedMesh = this;
  16309. }
  16310. return this;
  16311. };
  16312. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16313. var subMeshes;
  16314. var len;
  16315. // Octrees
  16316. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16317. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16318. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16319. len = intersections.length;
  16320. subMeshes = intersections.data;
  16321. }
  16322. else {
  16323. subMeshes = this.subMeshes;
  16324. len = subMeshes.length;
  16325. }
  16326. for (var index = 0; index < len; index++) {
  16327. var subMesh = subMeshes[index];
  16328. // Bounding test
  16329. if (len > 1 && !subMesh._checkCollision(collider))
  16330. continue;
  16331. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16332. }
  16333. return this;
  16334. };
  16335. AbstractMesh.prototype._checkCollision = function (collider) {
  16336. // Bounding box test
  16337. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16338. return this;
  16339. // Transformation matrix
  16340. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16341. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16342. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16343. return this;
  16344. };
  16345. // Picking
  16346. AbstractMesh.prototype._generatePointsArray = function () {
  16347. return false;
  16348. };
  16349. /**
  16350. * Checks if the passed Ray intersects with the mesh.
  16351. * Returns an object PickingInfo.
  16352. */
  16353. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16354. var pickingInfo = new BABYLON.PickingInfo();
  16355. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16356. return pickingInfo;
  16357. }
  16358. if (!this._generatePointsArray()) {
  16359. return pickingInfo;
  16360. }
  16361. var intersectInfo = null;
  16362. // Octrees
  16363. var subMeshes;
  16364. var len;
  16365. if (this._submeshesOctree && this.useOctreeForPicking) {
  16366. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16367. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16368. len = intersections.length;
  16369. subMeshes = intersections.data;
  16370. }
  16371. else {
  16372. subMeshes = this.subMeshes;
  16373. len = subMeshes.length;
  16374. }
  16375. for (var index = 0; index < len; index++) {
  16376. var subMesh = subMeshes[index];
  16377. // Bounding test
  16378. if (len > 1 && !subMesh.canIntersects(ray))
  16379. continue;
  16380. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16381. if (currentIntersectInfo) {
  16382. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16383. intersectInfo = currentIntersectInfo;
  16384. intersectInfo.subMeshId = index;
  16385. if (fastCheck) {
  16386. break;
  16387. }
  16388. }
  16389. }
  16390. }
  16391. if (intersectInfo) {
  16392. // Get picked point
  16393. var world = this.getWorldMatrix();
  16394. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16395. var direction = ray.direction.clone();
  16396. direction = direction.scale(intersectInfo.distance);
  16397. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16398. var pickedPoint = worldOrigin.add(worldDirection);
  16399. // Return result
  16400. pickingInfo.hit = true;
  16401. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16402. pickingInfo.pickedPoint = pickedPoint;
  16403. pickingInfo.pickedMesh = this;
  16404. pickingInfo.bu = intersectInfo.bu || 0;
  16405. pickingInfo.bv = intersectInfo.bv || 0;
  16406. pickingInfo.faceId = intersectInfo.faceId;
  16407. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16408. return pickingInfo;
  16409. }
  16410. return pickingInfo;
  16411. };
  16412. /**
  16413. * Clones the mesh, used by the class Mesh.
  16414. * Just returns `null` for an AbstractMesh.
  16415. */
  16416. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16417. return null;
  16418. };
  16419. /**
  16420. * Disposes all the mesh submeshes.
  16421. * Returns the AbstractMesh.
  16422. */
  16423. AbstractMesh.prototype.releaseSubMeshes = function () {
  16424. if (this.subMeshes) {
  16425. while (this.subMeshes.length) {
  16426. this.subMeshes[0].dispose();
  16427. }
  16428. }
  16429. else {
  16430. this.subMeshes = new Array();
  16431. }
  16432. return this;
  16433. };
  16434. /**
  16435. * Disposes the AbstractMesh.
  16436. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16437. * Returns nothing.
  16438. */
  16439. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16440. var _this = this;
  16441. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16442. var index;
  16443. // Action manager
  16444. if (this.actionManager !== undefined && this.actionManager !== null) {
  16445. this.actionManager.dispose();
  16446. this.actionManager = null;
  16447. }
  16448. // Skeleton
  16449. this.skeleton = null;
  16450. // Physics
  16451. if (this.physicsImpostor) {
  16452. this.physicsImpostor.dispose();
  16453. }
  16454. // Intersections in progress
  16455. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16456. var other = this._intersectionsInProgress[index];
  16457. var pos = other._intersectionsInProgress.indexOf(this);
  16458. other._intersectionsInProgress.splice(pos, 1);
  16459. }
  16460. this._intersectionsInProgress = [];
  16461. // Lights
  16462. var lights = this.getScene().lights;
  16463. lights.forEach(function (light) {
  16464. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16465. if (meshIndex !== -1) {
  16466. light.includedOnlyMeshes.splice(meshIndex, 1);
  16467. }
  16468. meshIndex = light.excludedMeshes.indexOf(_this);
  16469. if (meshIndex !== -1) {
  16470. light.excludedMeshes.splice(meshIndex, 1);
  16471. }
  16472. // Shadow generators
  16473. var generator = light.getShadowGenerator();
  16474. if (generator) {
  16475. var shadowMap = generator.getShadowMap();
  16476. if (shadowMap && shadowMap.renderList) {
  16477. meshIndex = shadowMap.renderList.indexOf(_this);
  16478. if (meshIndex !== -1) {
  16479. shadowMap.renderList.splice(meshIndex, 1);
  16480. }
  16481. }
  16482. }
  16483. });
  16484. // Edges
  16485. if (this._edgesRenderer) {
  16486. this._edgesRenderer.dispose();
  16487. this._edgesRenderer = null;
  16488. }
  16489. // SubMeshes
  16490. if (this.getClassName() !== "InstancedMesh") {
  16491. this.releaseSubMeshes();
  16492. }
  16493. // Octree
  16494. var sceneOctree = this.getScene().selectionOctree;
  16495. if (sceneOctree !== undefined && sceneOctree !== null) {
  16496. var index = sceneOctree.dynamicContent.indexOf(this);
  16497. if (index !== -1) {
  16498. sceneOctree.dynamicContent.splice(index, 1);
  16499. }
  16500. }
  16501. // Query
  16502. var engine = this.getScene().getEngine();
  16503. if (this._occlusionQuery) {
  16504. this._isOcclusionQueryInProgress = false;
  16505. engine.deleteQuery(this._occlusionQuery);
  16506. this._occlusionQuery = null;
  16507. }
  16508. // Engine
  16509. engine.wipeCaches();
  16510. // Remove from scene
  16511. this.getScene().removeMesh(this);
  16512. if (disposeMaterialAndTextures) {
  16513. if (this.material) {
  16514. this.material.dispose(false, true);
  16515. }
  16516. }
  16517. if (!doNotRecurse) {
  16518. // Particles
  16519. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16520. if (this.getScene().particleSystems[index].emitter === this) {
  16521. this.getScene().particleSystems[index].dispose();
  16522. index--;
  16523. }
  16524. }
  16525. }
  16526. // facet data
  16527. if (this._facetDataEnabled) {
  16528. this.disableFacetData();
  16529. }
  16530. this.onAfterWorldMatrixUpdateObservable.clear();
  16531. this.onCollideObservable.clear();
  16532. this.onCollisionPositionChangeObservable.clear();
  16533. this._isDisposed = true;
  16534. _super.prototype.dispose.call(this, doNotRecurse);
  16535. };
  16536. /**
  16537. * Adds the passed mesh as a child to the current mesh.
  16538. * Returns the AbstractMesh.
  16539. */
  16540. AbstractMesh.prototype.addChild = function (mesh) {
  16541. mesh.setParent(this);
  16542. return this;
  16543. };
  16544. /**
  16545. * Removes the passed mesh from the current mesh children list.
  16546. * Returns the AbstractMesh.
  16547. */
  16548. AbstractMesh.prototype.removeChild = function (mesh) {
  16549. mesh.setParent(null);
  16550. return this;
  16551. };
  16552. // Facet data
  16553. /**
  16554. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16555. * Returns the AbstractMesh.
  16556. */
  16557. AbstractMesh.prototype._initFacetData = function () {
  16558. if (!this._facetNormals) {
  16559. this._facetNormals = new Array();
  16560. }
  16561. if (!this._facetPositions) {
  16562. this._facetPositions = new Array();
  16563. }
  16564. if (!this._facetPartitioning) {
  16565. this._facetPartitioning = new Array();
  16566. }
  16567. this._facetNb = (this.getIndices().length / 3) | 0;
  16568. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16569. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16570. for (var f = 0; f < this._facetNb; f++) {
  16571. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16572. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16573. }
  16574. this._facetDataEnabled = true;
  16575. return this;
  16576. };
  16577. /**
  16578. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16579. * This method can be called within the render loop.
  16580. * 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.
  16581. * Returns the AbstractMesh.
  16582. */
  16583. AbstractMesh.prototype.updateFacetData = function () {
  16584. if (!this._facetDataEnabled) {
  16585. this._initFacetData();
  16586. }
  16587. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16588. var indices = this.getIndices();
  16589. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16590. var bInfo = this.getBoundingInfo();
  16591. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16592. // init arrays, matrix and sort function on first call
  16593. this._facetDepthSortEnabled = true;
  16594. if (indices instanceof Uint16Array) {
  16595. this._depthSortedIndices = new Uint16Array(indices);
  16596. }
  16597. else if (indices instanceof Uint32Array) {
  16598. this._depthSortedIndices = new Uint32Array(indices);
  16599. }
  16600. else {
  16601. var needs32bits = false;
  16602. for (var i = 0; i < indices.length; i++) {
  16603. if (indices[i] > 65535) {
  16604. needs32bits = true;
  16605. break;
  16606. }
  16607. }
  16608. if (needs32bits) {
  16609. this._depthSortedIndices = new Uint32Array(indices);
  16610. }
  16611. else {
  16612. this._depthSortedIndices = new Uint16Array(indices);
  16613. }
  16614. }
  16615. this._facetDepthSortFunction = function (f1, f2) {
  16616. return (f2.sqDistance - f1.sqDistance);
  16617. };
  16618. if (!this._facetDepthSortFrom) {
  16619. var camera = this.getScene().activeCamera;
  16620. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16621. }
  16622. this._depthSortedFacets = [];
  16623. for (var f = 0; f < this._facetNb; f++) {
  16624. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16625. this._depthSortedFacets.push(depthSortedFacet);
  16626. }
  16627. this._invertedMatrix = BABYLON.Matrix.Identity();
  16628. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16629. }
  16630. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16631. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16632. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16633. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16634. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16635. this._subDiv.max = this._partitioningSubdivisions;
  16636. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16637. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16638. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16639. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16640. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16641. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16642. // set the parameters for ComputeNormals()
  16643. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16644. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16645. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16646. this._facetParameters.bInfo = bInfo;
  16647. this._facetParameters.bbSize = this._bbSize;
  16648. this._facetParameters.subDiv = this._subDiv;
  16649. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16650. this._facetParameters.depthSort = this._facetDepthSort;
  16651. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16652. this.computeWorldMatrix(true);
  16653. this._worldMatrix.invertToRef(this._invertedMatrix);
  16654. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16655. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16656. }
  16657. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16658. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16659. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16660. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16661. var l = (this._depthSortedIndices.length / 3) | 0;
  16662. for (var f = 0; f < l; f++) {
  16663. var sind = this._depthSortedFacets[f].ind;
  16664. this._depthSortedIndices[f * 3] = indices[sind];
  16665. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16666. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16667. }
  16668. this.updateIndices(this._depthSortedIndices);
  16669. }
  16670. return this;
  16671. };
  16672. /**
  16673. * Returns the facetLocalNormals array.
  16674. * The normals are expressed in the mesh local space.
  16675. */
  16676. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16677. if (!this._facetNormals) {
  16678. this.updateFacetData();
  16679. }
  16680. return this._facetNormals;
  16681. };
  16682. /**
  16683. * Returns the facetLocalPositions array.
  16684. * The facet positions are expressed in the mesh local space.
  16685. */
  16686. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16687. if (!this._facetPositions) {
  16688. this.updateFacetData();
  16689. }
  16690. return this._facetPositions;
  16691. };
  16692. /**
  16693. * Returns the facetLocalPartioning array.
  16694. */
  16695. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16696. if (!this._facetPartitioning) {
  16697. this.updateFacetData();
  16698. }
  16699. return this._facetPartitioning;
  16700. };
  16701. /**
  16702. * Returns the i-th facet position in the world system.
  16703. * This method allocates a new Vector3 per call.
  16704. */
  16705. AbstractMesh.prototype.getFacetPosition = function (i) {
  16706. var pos = BABYLON.Vector3.Zero();
  16707. this.getFacetPositionToRef(i, pos);
  16708. return pos;
  16709. };
  16710. /**
  16711. * Sets the reference Vector3 with the i-th facet position in the world system.
  16712. * Returns the AbstractMesh.
  16713. */
  16714. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16715. var localPos = (this.getFacetLocalPositions())[i];
  16716. var world = this.getWorldMatrix();
  16717. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16718. return this;
  16719. };
  16720. /**
  16721. * Returns the i-th facet normal in the world system.
  16722. * This method allocates a new Vector3 per call.
  16723. */
  16724. AbstractMesh.prototype.getFacetNormal = function (i) {
  16725. var norm = BABYLON.Vector3.Zero();
  16726. this.getFacetNormalToRef(i, norm);
  16727. return norm;
  16728. };
  16729. /**
  16730. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16731. * Returns the AbstractMesh.
  16732. */
  16733. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16734. var localNorm = (this.getFacetLocalNormals())[i];
  16735. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16736. return this;
  16737. };
  16738. /**
  16739. * 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).
  16740. */
  16741. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16742. var bInfo = this.getBoundingInfo();
  16743. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16744. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16745. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16746. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16747. return null;
  16748. }
  16749. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16750. };
  16751. /**
  16752. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16753. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16754. * 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.
  16755. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16756. * 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.
  16757. */
  16758. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16759. if (checkFace === void 0) { checkFace = false; }
  16760. if (facing === void 0) { facing = true; }
  16761. var world = this.getWorldMatrix();
  16762. var invMat = BABYLON.Tmp.Matrix[5];
  16763. world.invertToRef(invMat);
  16764. var invVect = BABYLON.Tmp.Vector3[8];
  16765. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16766. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16767. if (projected) {
  16768. // tranform the local computed projected vector to world coordinates
  16769. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16770. }
  16771. return closest;
  16772. };
  16773. /**
  16774. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16775. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16776. * 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.
  16777. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16778. * 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.
  16779. */
  16780. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16781. if (checkFace === void 0) { checkFace = false; }
  16782. if (facing === void 0) { facing = true; }
  16783. var closest = null;
  16784. var tmpx = 0.0;
  16785. var tmpy = 0.0;
  16786. var tmpz = 0.0;
  16787. var d = 0.0; // tmp dot facet normal * facet position
  16788. var t0 = 0.0;
  16789. var projx = 0.0;
  16790. var projy = 0.0;
  16791. var projz = 0.0;
  16792. // Get all the facets in the same partitioning block than (x, y, z)
  16793. var facetPositions = this.getFacetLocalPositions();
  16794. var facetNormals = this.getFacetLocalNormals();
  16795. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16796. if (!facetsInBlock) {
  16797. return null;
  16798. }
  16799. // Get the closest facet to (x, y, z)
  16800. var shortest = Number.MAX_VALUE; // init distance vars
  16801. var tmpDistance = shortest;
  16802. var fib; // current facet in the block
  16803. var norm; // current facet normal
  16804. var p0; // current facet barycenter position
  16805. // loop on all the facets in the current partitioning block
  16806. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16807. fib = facetsInBlock[idx];
  16808. norm = facetNormals[fib];
  16809. p0 = facetPositions[fib];
  16810. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16811. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16812. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16813. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16814. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16815. projx = x + norm.x * t0;
  16816. projy = y + norm.y * t0;
  16817. projz = z + norm.z * t0;
  16818. tmpx = projx - x;
  16819. tmpy = projy - y;
  16820. tmpz = projz - z;
  16821. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16822. if (tmpDistance < shortest) {
  16823. shortest = tmpDistance;
  16824. closest = fib;
  16825. if (projected) {
  16826. projected.x = projx;
  16827. projected.y = projy;
  16828. projected.z = projz;
  16829. }
  16830. }
  16831. }
  16832. }
  16833. return closest;
  16834. };
  16835. /**
  16836. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16837. */
  16838. AbstractMesh.prototype.getFacetDataParameters = function () {
  16839. return this._facetParameters;
  16840. };
  16841. /**
  16842. * Disables the feature FacetData and frees the related memory.
  16843. * Returns the AbstractMesh.
  16844. */
  16845. AbstractMesh.prototype.disableFacetData = function () {
  16846. if (this._facetDataEnabled) {
  16847. this._facetDataEnabled = false;
  16848. this._facetPositions = new Array();
  16849. this._facetNormals = new Array();
  16850. this._facetPartitioning = new Array();
  16851. this._facetParameters = null;
  16852. this._depthSortedIndices = new Uint32Array(0);
  16853. }
  16854. return this;
  16855. };
  16856. /**
  16857. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16858. * Returns the mesh.
  16859. */
  16860. AbstractMesh.prototype.updateIndices = function (indices) {
  16861. return this;
  16862. };
  16863. /**
  16864. * The mesh Geometry. Actually used by the Mesh object.
  16865. * Returns a blank geometry object.
  16866. */
  16867. /**
  16868. * Creates new normals data for the mesh.
  16869. * @param updatable.
  16870. */
  16871. AbstractMesh.prototype.createNormals = function (updatable) {
  16872. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16873. var indices = this.getIndices();
  16874. var normals;
  16875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16876. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16877. }
  16878. else {
  16879. normals = [];
  16880. }
  16881. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16882. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16883. };
  16884. /**
  16885. * Align the mesh with a normal.
  16886. * Returns the mesh.
  16887. */
  16888. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16889. if (!upDirection) {
  16890. upDirection = BABYLON.Axis.Y;
  16891. }
  16892. var axisX = BABYLON.Tmp.Vector3[0];
  16893. var axisZ = BABYLON.Tmp.Vector3[1];
  16894. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16895. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16896. if (this.rotationQuaternion) {
  16897. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16898. }
  16899. else {
  16900. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16901. }
  16902. return this;
  16903. };
  16904. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16905. var engine = this.getEngine();
  16906. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16907. this._isOccluded = false;
  16908. return;
  16909. }
  16910. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16911. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16912. if (isOcclusionQueryAvailable) {
  16913. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16914. this._isOcclusionQueryInProgress = false;
  16915. this._occlusionInternalRetryCounter = 0;
  16916. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16917. }
  16918. else {
  16919. this._occlusionInternalRetryCounter++;
  16920. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16921. this._isOcclusionQueryInProgress = false;
  16922. this._occlusionInternalRetryCounter = 0;
  16923. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16924. // if strict continue the last state of the object.
  16925. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16926. }
  16927. else {
  16928. return;
  16929. }
  16930. }
  16931. }
  16932. var scene = this.getScene();
  16933. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16934. if (!this._occlusionQuery) {
  16935. this._occlusionQuery = engine.createQuery();
  16936. }
  16937. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16938. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16939. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16940. this._isOcclusionQueryInProgress = true;
  16941. };
  16942. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16943. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16944. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16945. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16946. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16947. return AbstractMesh;
  16948. }(BABYLON.TransformNode));
  16949. BABYLON.AbstractMesh = AbstractMesh;
  16950. })(BABYLON || (BABYLON = {}));
  16951. //# sourceMappingURL=babylon.abstractMesh.js.map
  16952. var BABYLON;
  16953. (function (BABYLON) {
  16954. var Light = /** @class */ (function (_super) {
  16955. __extends(Light, _super);
  16956. /**
  16957. * Creates a Light object in the scene.
  16958. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16959. */
  16960. function Light(name, scene) {
  16961. var _this = _super.call(this, name, scene) || this;
  16962. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16963. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16964. _this.intensity = 1.0;
  16965. _this.range = Number.MAX_VALUE;
  16966. /**
  16967. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16968. * of light.
  16969. */
  16970. _this._photometricScale = 1.0;
  16971. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16972. _this._radius = 0.00001;
  16973. _this.renderPriority = 0;
  16974. /**
  16975. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16976. * the current shadow generator.
  16977. */
  16978. _this.shadowEnabled = true;
  16979. _this._excludeWithLayerMask = 0;
  16980. _this._includeOnlyWithLayerMask = 0;
  16981. _this._lightmapMode = 0;
  16982. _this._excludedMeshesIds = new Array();
  16983. _this._includedOnlyMeshesIds = new Array();
  16984. _this.getScene().addLight(_this);
  16985. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  16986. _this._buildUniformLayout();
  16987. _this.includedOnlyMeshes = new Array();
  16988. _this.excludedMeshes = new Array();
  16989. _this._resyncMeshes();
  16990. return _this;
  16991. }
  16992. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  16993. /**
  16994. * If every light affecting the material is in this lightmapMode,
  16995. * material.lightmapTexture adds or multiplies
  16996. * (depends on material.useLightmapAsShadowmap)
  16997. * after every other light calculations.
  16998. */
  16999. get: function () {
  17000. return Light._LIGHTMAP_DEFAULT;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17006. /**
  17007. * material.lightmapTexture as only diffuse lighting from this light
  17008. * adds pnly specular lighting from this light
  17009. * adds dynamic shadows
  17010. */
  17011. get: function () {
  17012. return Light._LIGHTMAP_SPECULAR;
  17013. },
  17014. enumerable: true,
  17015. configurable: true
  17016. });
  17017. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17018. /**
  17019. * material.lightmapTexture as only lighting
  17020. * no light calculation from this light
  17021. * only adds dynamic shadows from this light
  17022. */
  17023. get: function () {
  17024. return Light._LIGHTMAP_SHADOWSONLY;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17030. /**
  17031. * Each light type uses the default quantity according to its type:
  17032. * point/spot lights use luminous intensity
  17033. * directional lights use illuminance
  17034. */
  17035. get: function () {
  17036. return Light._INTENSITYMODE_AUTOMATIC;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17042. /**
  17043. * lumen (lm)
  17044. */
  17045. get: function () {
  17046. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17052. /**
  17053. * candela (lm/sr)
  17054. */
  17055. get: function () {
  17056. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17062. /**
  17063. * lux (lm/m^2)
  17064. */
  17065. get: function () {
  17066. return Light._INTENSITYMODE_ILLUMINANCE;
  17067. },
  17068. enumerable: true,
  17069. configurable: true
  17070. });
  17071. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17072. /**
  17073. * nit (cd/m^2)
  17074. */
  17075. get: function () {
  17076. return Light._INTENSITYMODE_LUMINANCE;
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17082. /**
  17083. * Light type const id of the point light.
  17084. */
  17085. get: function () {
  17086. return Light._LIGHTTYPEID_POINTLIGHT;
  17087. },
  17088. enumerable: true,
  17089. configurable: true
  17090. });
  17091. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17092. /**
  17093. * Light type const id of the directional light.
  17094. */
  17095. get: function () {
  17096. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17102. /**
  17103. * Light type const id of the spot light.
  17104. */
  17105. get: function () {
  17106. return Light._LIGHTTYPEID_SPOTLIGHT;
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17112. /**
  17113. * Light type const id of the hemispheric light.
  17114. */
  17115. get: function () {
  17116. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. Object.defineProperty(Light.prototype, "intensityMode", {
  17122. /**
  17123. * Gets the photometric scale used to interpret the intensity.
  17124. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17125. */
  17126. get: function () {
  17127. return this._intensityMode;
  17128. },
  17129. /**
  17130. * Sets the photometric scale used to interpret the intensity.
  17131. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17132. */
  17133. set: function (value) {
  17134. this._intensityMode = value;
  17135. this._computePhotometricScale();
  17136. },
  17137. enumerable: true,
  17138. configurable: true
  17139. });
  17140. ;
  17141. ;
  17142. Object.defineProperty(Light.prototype, "radius", {
  17143. /**
  17144. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17145. */
  17146. get: function () {
  17147. return this._radius;
  17148. },
  17149. /**
  17150. * sets the light radius used by PBR Materials to simulate soft area lights.
  17151. */
  17152. set: function (value) {
  17153. this._radius = value;
  17154. this._computePhotometricScale();
  17155. },
  17156. enumerable: true,
  17157. configurable: true
  17158. });
  17159. ;
  17160. ;
  17161. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17162. get: function () {
  17163. return this._includedOnlyMeshes;
  17164. },
  17165. set: function (value) {
  17166. this._includedOnlyMeshes = value;
  17167. this._hookArrayForIncludedOnly(value);
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17173. get: function () {
  17174. return this._excludedMeshes;
  17175. },
  17176. set: function (value) {
  17177. this._excludedMeshes = value;
  17178. this._hookArrayForExcluded(value);
  17179. },
  17180. enumerable: true,
  17181. configurable: true
  17182. });
  17183. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17184. get: function () {
  17185. return this._excludeWithLayerMask;
  17186. },
  17187. set: function (value) {
  17188. this._excludeWithLayerMask = value;
  17189. this._resyncMeshes();
  17190. },
  17191. enumerable: true,
  17192. configurable: true
  17193. });
  17194. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17195. get: function () {
  17196. return this._includeOnlyWithLayerMask;
  17197. },
  17198. set: function (value) {
  17199. this._includeOnlyWithLayerMask = value;
  17200. this._resyncMeshes();
  17201. },
  17202. enumerable: true,
  17203. configurable: true
  17204. });
  17205. Object.defineProperty(Light.prototype, "lightmapMode", {
  17206. get: function () {
  17207. return this._lightmapMode;
  17208. },
  17209. set: function (value) {
  17210. if (this._lightmapMode === value) {
  17211. return;
  17212. }
  17213. this._lightmapMode = value;
  17214. this._markMeshesAsLightDirty();
  17215. },
  17216. enumerable: true,
  17217. configurable: true
  17218. });
  17219. Light.prototype._buildUniformLayout = function () {
  17220. // Overridden
  17221. };
  17222. /**
  17223. * Returns the string "Light".
  17224. */
  17225. Light.prototype.getClassName = function () {
  17226. return "Light";
  17227. };
  17228. /**
  17229. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17230. */
  17231. Light.prototype.toString = function (fullDetails) {
  17232. var ret = "Name: " + this.name;
  17233. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17234. if (this.animations) {
  17235. for (var i = 0; i < this.animations.length; i++) {
  17236. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17237. }
  17238. }
  17239. if (fullDetails) {
  17240. }
  17241. return ret;
  17242. };
  17243. /**
  17244. * Set the enabled state of this node.
  17245. * @param {boolean} value - the new enabled state
  17246. * @see isEnabled
  17247. */
  17248. Light.prototype.setEnabled = function (value) {
  17249. _super.prototype.setEnabled.call(this, value);
  17250. this._resyncMeshes();
  17251. };
  17252. /**
  17253. * Returns the Light associated shadow generator.
  17254. */
  17255. Light.prototype.getShadowGenerator = function () {
  17256. return this._shadowGenerator;
  17257. };
  17258. /**
  17259. * Returns a Vector3, the absolute light position in the World.
  17260. */
  17261. Light.prototype.getAbsolutePosition = function () {
  17262. return BABYLON.Vector3.Zero();
  17263. };
  17264. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17265. };
  17266. Light.prototype._getWorldMatrix = function () {
  17267. return BABYLON.Matrix.Identity();
  17268. };
  17269. /**
  17270. * Boolean : True if the light will affect the passed mesh.
  17271. */
  17272. Light.prototype.canAffectMesh = function (mesh) {
  17273. if (!mesh) {
  17274. return true;
  17275. }
  17276. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17277. return false;
  17278. }
  17279. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17280. return false;
  17281. }
  17282. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17283. return false;
  17284. }
  17285. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17286. return false;
  17287. }
  17288. return true;
  17289. };
  17290. /**
  17291. * Returns the light World matrix.
  17292. */
  17293. Light.prototype.getWorldMatrix = function () {
  17294. this._currentRenderId = this.getScene().getRenderId();
  17295. var worldMatrix = this._getWorldMatrix();
  17296. if (this.parent && this.parent.getWorldMatrix) {
  17297. if (!this._parentedWorldMatrix) {
  17298. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17299. }
  17300. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17301. this._markSyncedWithParent();
  17302. return this._parentedWorldMatrix;
  17303. }
  17304. return worldMatrix;
  17305. };
  17306. /**
  17307. * Sort function to order lights for rendering.
  17308. * @param a First Light object to compare to second.
  17309. * @param b Second Light object to compare first.
  17310. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17311. */
  17312. Light.compareLightsPriority = function (a, b) {
  17313. //shadow-casting lights have priority over non-shadow-casting lights
  17314. //the renderPrioirty is a secondary sort criterion
  17315. if (a.shadowEnabled !== b.shadowEnabled) {
  17316. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17317. }
  17318. return b.renderPriority - a.renderPriority;
  17319. };
  17320. /**
  17321. * Disposes the light.
  17322. */
  17323. Light.prototype.dispose = function () {
  17324. if (this._shadowGenerator) {
  17325. this._shadowGenerator.dispose();
  17326. this._shadowGenerator = null;
  17327. }
  17328. // Animations
  17329. this.getScene().stopAnimation(this);
  17330. this._uniformBuffer.dispose();
  17331. // Remove from scene
  17332. this.getScene().removeLight(this);
  17333. _super.prototype.dispose.call(this);
  17334. };
  17335. /**
  17336. * Returns the light type ID (integer).
  17337. */
  17338. Light.prototype.getTypeID = function () {
  17339. return 0;
  17340. };
  17341. /**
  17342. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17343. */
  17344. Light.prototype.getScaledIntensity = function () {
  17345. return this._photometricScale * this.intensity;
  17346. };
  17347. /**
  17348. * Returns a new Light object, named "name", from the current one.
  17349. */
  17350. Light.prototype.clone = function (name) {
  17351. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17352. if (!constructor) {
  17353. return null;
  17354. }
  17355. return BABYLON.SerializationHelper.Clone(constructor, this);
  17356. };
  17357. /**
  17358. * Serializes the current light into a Serialization object.
  17359. * Returns the serialized object.
  17360. */
  17361. Light.prototype.serialize = function () {
  17362. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17363. // Type
  17364. serializationObject.type = this.getTypeID();
  17365. // Parent
  17366. if (this.parent) {
  17367. serializationObject.parentId = this.parent.id;
  17368. }
  17369. // Inclusion / exclusions
  17370. if (this.excludedMeshes.length > 0) {
  17371. serializationObject.excludedMeshesIds = [];
  17372. this.excludedMeshes.forEach(function (mesh) {
  17373. serializationObject.excludedMeshesIds.push(mesh.id);
  17374. });
  17375. }
  17376. if (this.includedOnlyMeshes.length > 0) {
  17377. serializationObject.includedOnlyMeshesIds = [];
  17378. this.includedOnlyMeshes.forEach(function (mesh) {
  17379. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17380. });
  17381. }
  17382. // Animations
  17383. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17384. serializationObject.ranges = this.serializeAnimationRanges();
  17385. return serializationObject;
  17386. };
  17387. /**
  17388. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17389. * This new light is named "name" and added to the passed scene.
  17390. */
  17391. Light.GetConstructorFromName = function (type, name, scene) {
  17392. switch (type) {
  17393. case 0:
  17394. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17395. case 1:
  17396. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17397. case 2:
  17398. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17399. case 3:
  17400. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17401. }
  17402. return null;
  17403. };
  17404. /**
  17405. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17406. */
  17407. Light.Parse = function (parsedLight, scene) {
  17408. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17409. if (!constructor) {
  17410. return null;
  17411. }
  17412. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17413. // Inclusion / exclusions
  17414. if (parsedLight.excludedMeshesIds) {
  17415. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17416. }
  17417. if (parsedLight.includedOnlyMeshesIds) {
  17418. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17419. }
  17420. // Parent
  17421. if (parsedLight.parentId) {
  17422. light._waitingParentId = parsedLight.parentId;
  17423. }
  17424. // Animations
  17425. if (parsedLight.animations) {
  17426. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17427. var parsedAnimation = parsedLight.animations[animationIndex];
  17428. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17429. }
  17430. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17431. }
  17432. if (parsedLight.autoAnimate) {
  17433. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17434. }
  17435. return light;
  17436. };
  17437. Light.prototype._hookArrayForExcluded = function (array) {
  17438. var _this = this;
  17439. var oldPush = array.push;
  17440. array.push = function () {
  17441. var items = [];
  17442. for (var _i = 0; _i < arguments.length; _i++) {
  17443. items[_i] = arguments[_i];
  17444. }
  17445. var result = oldPush.apply(array, items);
  17446. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17447. var item = items_1[_a];
  17448. item._resyncLighSource(_this);
  17449. }
  17450. return result;
  17451. };
  17452. var oldSplice = array.splice;
  17453. array.splice = function (index, deleteCount) {
  17454. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17455. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17456. var item = deleted_1[_i];
  17457. item._resyncLighSource(_this);
  17458. }
  17459. return deleted;
  17460. };
  17461. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17462. var item = array_1[_i];
  17463. item._resyncLighSource(this);
  17464. }
  17465. };
  17466. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17467. var _this = this;
  17468. var oldPush = array.push;
  17469. array.push = function () {
  17470. var items = [];
  17471. for (var _i = 0; _i < arguments.length; _i++) {
  17472. items[_i] = arguments[_i];
  17473. }
  17474. var result = oldPush.apply(array, items);
  17475. _this._resyncMeshes();
  17476. return result;
  17477. };
  17478. var oldSplice = array.splice;
  17479. array.splice = function (index, deleteCount) {
  17480. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17481. _this._resyncMeshes();
  17482. return deleted;
  17483. };
  17484. this._resyncMeshes();
  17485. };
  17486. Light.prototype._resyncMeshes = function () {
  17487. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17488. var mesh = _a[_i];
  17489. mesh._resyncLighSource(this);
  17490. }
  17491. };
  17492. Light.prototype._markMeshesAsLightDirty = function () {
  17493. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17494. var mesh = _a[_i];
  17495. if (mesh._lightSources.indexOf(this) !== -1) {
  17496. mesh._markSubMeshesAsLightDirty();
  17497. }
  17498. }
  17499. };
  17500. /**
  17501. * Recomputes the cached photometric scale if needed.
  17502. */
  17503. Light.prototype._computePhotometricScale = function () {
  17504. this._photometricScale = this._getPhotometricScale();
  17505. this.getScene().resetCachedMaterial();
  17506. };
  17507. /**
  17508. * Returns the Photometric Scale according to the light type and intensity mode.
  17509. */
  17510. Light.prototype._getPhotometricScale = function () {
  17511. var photometricScale = 0.0;
  17512. var lightTypeID = this.getTypeID();
  17513. //get photometric mode
  17514. var photometricMode = this.intensityMode;
  17515. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17516. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17517. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17518. }
  17519. else {
  17520. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17521. }
  17522. }
  17523. //compute photometric scale
  17524. switch (lightTypeID) {
  17525. case Light.LIGHTTYPEID_POINTLIGHT:
  17526. case Light.LIGHTTYPEID_SPOTLIGHT:
  17527. switch (photometricMode) {
  17528. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17529. photometricScale = 1.0 / (4.0 * Math.PI);
  17530. break;
  17531. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17532. photometricScale = 1.0;
  17533. break;
  17534. case Light.INTENSITYMODE_LUMINANCE:
  17535. photometricScale = this.radius * this.radius;
  17536. break;
  17537. }
  17538. break;
  17539. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17540. switch (photometricMode) {
  17541. case Light.INTENSITYMODE_ILLUMINANCE:
  17542. photometricScale = 1.0;
  17543. break;
  17544. case Light.INTENSITYMODE_LUMINANCE:
  17545. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17546. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17547. var apexAngleRadians = this.radius;
  17548. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17549. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17550. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17551. photometricScale = solidAngle;
  17552. break;
  17553. }
  17554. break;
  17555. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17556. // No fall off in hemisperic light.
  17557. photometricScale = 1.0;
  17558. break;
  17559. }
  17560. return photometricScale;
  17561. };
  17562. Light.prototype._reorderLightsInScene = function () {
  17563. var scene = this.getScene();
  17564. if (this._renderPriority != 0) {
  17565. scene.requireLightSorting = true;
  17566. }
  17567. this.getScene().sortLightsByPriority();
  17568. };
  17569. //lightmapMode Consts
  17570. Light._LIGHTMAP_DEFAULT = 0;
  17571. Light._LIGHTMAP_SPECULAR = 1;
  17572. Light._LIGHTMAP_SHADOWSONLY = 2;
  17573. // Intensity Mode Consts
  17574. Light._INTENSITYMODE_AUTOMATIC = 0;
  17575. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17576. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17577. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17578. Light._INTENSITYMODE_LUMINANCE = 4;
  17579. // Light types ids const.
  17580. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17581. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17582. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17583. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17584. __decorate([
  17585. BABYLON.serializeAsColor3()
  17586. ], Light.prototype, "diffuse", void 0);
  17587. __decorate([
  17588. BABYLON.serializeAsColor3()
  17589. ], Light.prototype, "specular", void 0);
  17590. __decorate([
  17591. BABYLON.serialize()
  17592. ], Light.prototype, "intensity", void 0);
  17593. __decorate([
  17594. BABYLON.serialize()
  17595. ], Light.prototype, "range", void 0);
  17596. __decorate([
  17597. BABYLON.serialize()
  17598. ], Light.prototype, "intensityMode", null);
  17599. __decorate([
  17600. BABYLON.serialize()
  17601. ], Light.prototype, "radius", null);
  17602. __decorate([
  17603. BABYLON.serialize()
  17604. ], Light.prototype, "_renderPriority", void 0);
  17605. __decorate([
  17606. BABYLON.expandToProperty("_reorderLightsInScene")
  17607. ], Light.prototype, "renderPriority", void 0);
  17608. __decorate([
  17609. BABYLON.serialize()
  17610. ], Light.prototype, "shadowEnabled", void 0);
  17611. __decorate([
  17612. BABYLON.serialize("excludeWithLayerMask")
  17613. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17614. __decorate([
  17615. BABYLON.serialize("includeOnlyWithLayerMask")
  17616. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17617. __decorate([
  17618. BABYLON.serialize("lightmapMode")
  17619. ], Light.prototype, "_lightmapMode", void 0);
  17620. return Light;
  17621. }(BABYLON.Node));
  17622. BABYLON.Light = Light;
  17623. })(BABYLON || (BABYLON = {}));
  17624. //# sourceMappingURL=babylon.light.js.map
  17625. var BABYLON;
  17626. (function (BABYLON) {
  17627. var Camera = /** @class */ (function (_super) {
  17628. __extends(Camera, _super);
  17629. function Camera(name, position, scene) {
  17630. var _this = _super.call(this, name, scene) || this;
  17631. _this.upVector = BABYLON.Vector3.Up();
  17632. _this.orthoLeft = null;
  17633. _this.orthoRight = null;
  17634. _this.orthoBottom = null;
  17635. _this.orthoTop = null;
  17636. _this.fov = 0.8;
  17637. _this.minZ = 1;
  17638. _this.maxZ = 10000.0;
  17639. _this.inertia = 0.9;
  17640. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17641. _this.isIntermediate = false;
  17642. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17643. _this.layerMask = 0x0FFFFFFF;
  17644. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17645. // Camera rig members
  17646. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17647. _this._rigCameras = new Array();
  17648. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17649. _this._skipRendering = false;
  17650. _this.customRenderTargets = new Array();
  17651. // Observables
  17652. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17653. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17654. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17655. _this.onRestoreStateObservable = new BABYLON.Observable();
  17656. // Cache
  17657. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17658. _this._projectionMatrix = new BABYLON.Matrix();
  17659. _this._doNotComputeProjectionMatrix = false;
  17660. _this._postProcesses = new Array();
  17661. _this._transformMatrix = BABYLON.Matrix.Zero();
  17662. _this._activeMeshes = new BABYLON.SmartArray(256);
  17663. _this._globalPosition = BABYLON.Vector3.Zero();
  17664. _this._refreshFrustumPlanes = true;
  17665. _this.getScene().addCamera(_this);
  17666. if (!_this.getScene().activeCamera) {
  17667. _this.getScene().activeCamera = _this;
  17668. }
  17669. _this.position = position;
  17670. return _this;
  17671. }
  17672. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17673. get: function () {
  17674. return Camera._PERSPECTIVE_CAMERA;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17680. get: function () {
  17681. return Camera._ORTHOGRAPHIC_CAMERA;
  17682. },
  17683. enumerable: true,
  17684. configurable: true
  17685. });
  17686. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17687. get: function () {
  17688. return Camera._FOVMODE_VERTICAL_FIXED;
  17689. },
  17690. enumerable: true,
  17691. configurable: true
  17692. });
  17693. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17694. get: function () {
  17695. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17701. get: function () {
  17702. return Camera._RIG_MODE_NONE;
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17708. get: function () {
  17709. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17715. get: function () {
  17716. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17722. get: function () {
  17723. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17729. get: function () {
  17730. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17736. get: function () {
  17737. return Camera._RIG_MODE_VR;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17743. get: function () {
  17744. return Camera._RIG_MODE_WEBVR;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. /**
  17750. * Store current camera state (fov, position, etc..)
  17751. */
  17752. Camera.prototype.storeState = function () {
  17753. this._stateStored = true;
  17754. this._storedFov = this.fov;
  17755. return this;
  17756. };
  17757. /**
  17758. * Restores the camera state values if it has been stored. You must call storeState() first
  17759. */
  17760. Camera.prototype._restoreStateValues = function () {
  17761. if (!this._stateStored) {
  17762. return false;
  17763. }
  17764. this.fov = this._storedFov;
  17765. return true;
  17766. };
  17767. /**
  17768. * Restored camera state. You must call storeState() first
  17769. */
  17770. Camera.prototype.restoreState = function () {
  17771. if (this._restoreStateValues()) {
  17772. this.onRestoreStateObservable.notifyObservers(this);
  17773. return true;
  17774. }
  17775. return false;
  17776. };
  17777. Camera.prototype.getClassName = function () {
  17778. return "Camera";
  17779. };
  17780. /**
  17781. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17782. */
  17783. Camera.prototype.toString = function (fullDetails) {
  17784. var ret = "Name: " + this.name;
  17785. ret += ", type: " + this.getClassName();
  17786. if (this.animations) {
  17787. for (var i = 0; i < this.animations.length; i++) {
  17788. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17789. }
  17790. }
  17791. if (fullDetails) {
  17792. }
  17793. return ret;
  17794. };
  17795. Object.defineProperty(Camera.prototype, "globalPosition", {
  17796. get: function () {
  17797. return this._globalPosition;
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Camera.prototype.getActiveMeshes = function () {
  17803. return this._activeMeshes;
  17804. };
  17805. Camera.prototype.isActiveMesh = function (mesh) {
  17806. return (this._activeMeshes.indexOf(mesh) !== -1);
  17807. };
  17808. //Cache
  17809. Camera.prototype._initCache = function () {
  17810. _super.prototype._initCache.call(this);
  17811. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17812. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17813. this._cache.mode = undefined;
  17814. this._cache.minZ = undefined;
  17815. this._cache.maxZ = undefined;
  17816. this._cache.fov = undefined;
  17817. this._cache.fovMode = undefined;
  17818. this._cache.aspectRatio = undefined;
  17819. this._cache.orthoLeft = undefined;
  17820. this._cache.orthoRight = undefined;
  17821. this._cache.orthoBottom = undefined;
  17822. this._cache.orthoTop = undefined;
  17823. this._cache.renderWidth = undefined;
  17824. this._cache.renderHeight = undefined;
  17825. };
  17826. Camera.prototype._updateCache = function (ignoreParentClass) {
  17827. if (!ignoreParentClass) {
  17828. _super.prototype._updateCache.call(this);
  17829. }
  17830. this._cache.position.copyFrom(this.position);
  17831. this._cache.upVector.copyFrom(this.upVector);
  17832. };
  17833. // Synchronized
  17834. Camera.prototype._isSynchronized = function () {
  17835. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17836. };
  17837. Camera.prototype._isSynchronizedViewMatrix = function () {
  17838. if (!_super.prototype._isSynchronized.call(this))
  17839. return false;
  17840. return this._cache.position.equals(this.position)
  17841. && this._cache.upVector.equals(this.upVector)
  17842. && this.isSynchronizedWithParent();
  17843. };
  17844. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17845. var check = this._cache.mode === this.mode
  17846. && this._cache.minZ === this.minZ
  17847. && this._cache.maxZ === this.maxZ;
  17848. if (!check) {
  17849. return false;
  17850. }
  17851. var engine = this.getEngine();
  17852. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17853. check = this._cache.fov === this.fov
  17854. && this._cache.fovMode === this.fovMode
  17855. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17856. }
  17857. else {
  17858. check = this._cache.orthoLeft === this.orthoLeft
  17859. && this._cache.orthoRight === this.orthoRight
  17860. && this._cache.orthoBottom === this.orthoBottom
  17861. && this._cache.orthoTop === this.orthoTop
  17862. && this._cache.renderWidth === engine.getRenderWidth()
  17863. && this._cache.renderHeight === engine.getRenderHeight();
  17864. }
  17865. return check;
  17866. };
  17867. // Controls
  17868. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17869. };
  17870. Camera.prototype.detachControl = function (element) {
  17871. };
  17872. Camera.prototype.update = function () {
  17873. this._checkInputs();
  17874. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17875. this._updateRigCameras();
  17876. }
  17877. };
  17878. Camera.prototype._checkInputs = function () {
  17879. this.onAfterCheckInputsObservable.notifyObservers(this);
  17880. };
  17881. Object.defineProperty(Camera.prototype, "rigCameras", {
  17882. get: function () {
  17883. return this._rigCameras;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17889. get: function () {
  17890. return this._rigPostProcess;
  17891. },
  17892. enumerable: true,
  17893. configurable: true
  17894. });
  17895. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17896. // invalidate framebuffer
  17897. if (this._postProcesses.length > 0) {
  17898. this._postProcesses[0].markTextureDirty();
  17899. }
  17900. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17901. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17902. var cam = this._rigCameras[i];
  17903. var rigPostProcess = cam._rigPostProcess;
  17904. // for VR rig, there does not have to be a post process
  17905. if (rigPostProcess) {
  17906. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17907. if (isPass) {
  17908. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17909. cam.isIntermediate = this._postProcesses.length === 0;
  17910. }
  17911. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17912. rigPostProcess.markTextureDirty();
  17913. }
  17914. else {
  17915. cam._postProcesses = this._postProcesses.slice(0);
  17916. }
  17917. }
  17918. };
  17919. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17920. if (insertAt === void 0) { insertAt = null; }
  17921. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17922. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17923. return 0;
  17924. }
  17925. if (insertAt == null || insertAt < 0) {
  17926. this._postProcesses.push(postProcess);
  17927. }
  17928. else {
  17929. this._postProcesses.splice(insertAt, 0, postProcess);
  17930. }
  17931. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17932. return this._postProcesses.indexOf(postProcess);
  17933. };
  17934. Camera.prototype.detachPostProcess = function (postProcess) {
  17935. var idx = this._postProcesses.indexOf(postProcess);
  17936. if (idx !== -1) {
  17937. this._postProcesses.splice(idx, 1);
  17938. }
  17939. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17940. };
  17941. Camera.prototype.getWorldMatrix = function () {
  17942. if (!this._worldMatrix) {
  17943. this._worldMatrix = BABYLON.Matrix.Identity();
  17944. }
  17945. var viewMatrix = this.getViewMatrix();
  17946. viewMatrix.invertToRef(this._worldMatrix);
  17947. return this._worldMatrix;
  17948. };
  17949. Camera.prototype._getViewMatrix = function () {
  17950. return BABYLON.Matrix.Identity();
  17951. };
  17952. Camera.prototype.getViewMatrix = function (force) {
  17953. if (!force && this._isSynchronizedViewMatrix()) {
  17954. return this._computedViewMatrix;
  17955. }
  17956. this.updateCache();
  17957. this._computedViewMatrix = this._getViewMatrix();
  17958. this._currentRenderId = this.getScene().getRenderId();
  17959. this._refreshFrustumPlanes = true;
  17960. if (!this.parent || !this.parent.getWorldMatrix) {
  17961. this._globalPosition.copyFrom(this.position);
  17962. }
  17963. else {
  17964. if (!this._worldMatrix) {
  17965. this._worldMatrix = BABYLON.Matrix.Identity();
  17966. }
  17967. this._computedViewMatrix.invertToRef(this._worldMatrix);
  17968. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  17969. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  17970. this._computedViewMatrix.invert();
  17971. this._markSyncedWithParent();
  17972. }
  17973. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  17974. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  17975. }
  17976. this.onViewMatrixChangedObservable.notifyObservers(this);
  17977. return this._computedViewMatrix;
  17978. };
  17979. Camera.prototype.freezeProjectionMatrix = function (projection) {
  17980. this._doNotComputeProjectionMatrix = true;
  17981. if (projection !== undefined) {
  17982. this._projectionMatrix = projection;
  17983. }
  17984. };
  17985. ;
  17986. Camera.prototype.unfreezeProjectionMatrix = function () {
  17987. this._doNotComputeProjectionMatrix = false;
  17988. };
  17989. ;
  17990. Camera.prototype.getProjectionMatrix = function (force) {
  17991. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  17992. return this._projectionMatrix;
  17993. }
  17994. // Cache
  17995. this._cache.mode = this.mode;
  17996. this._cache.minZ = this.minZ;
  17997. this._cache.maxZ = this.maxZ;
  17998. // Matrix
  17999. this._refreshFrustumPlanes = true;
  18000. var engine = this.getEngine();
  18001. var scene = this.getScene();
  18002. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18003. this._cache.fov = this.fov;
  18004. this._cache.fovMode = this.fovMode;
  18005. this._cache.aspectRatio = engine.getAspectRatio(this);
  18006. if (this.minZ <= 0) {
  18007. this.minZ = 0.1;
  18008. }
  18009. if (scene.useRightHandedSystem) {
  18010. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18011. }
  18012. else {
  18013. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18014. }
  18015. }
  18016. else {
  18017. var halfWidth = engine.getRenderWidth() / 2.0;
  18018. var halfHeight = engine.getRenderHeight() / 2.0;
  18019. if (scene.useRightHandedSystem) {
  18020. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18021. }
  18022. else {
  18023. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18024. }
  18025. this._cache.orthoLeft = this.orthoLeft;
  18026. this._cache.orthoRight = this.orthoRight;
  18027. this._cache.orthoBottom = this.orthoBottom;
  18028. this._cache.orthoTop = this.orthoTop;
  18029. this._cache.renderWidth = engine.getRenderWidth();
  18030. this._cache.renderHeight = engine.getRenderHeight();
  18031. }
  18032. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18033. return this._projectionMatrix;
  18034. };
  18035. Camera.prototype.getTranformationMatrix = function () {
  18036. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18037. return this._transformMatrix;
  18038. };
  18039. Camera.prototype.updateFrustumPlanes = function () {
  18040. if (!this._refreshFrustumPlanes) {
  18041. return;
  18042. }
  18043. this.getTranformationMatrix();
  18044. if (!this._frustumPlanes) {
  18045. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18046. }
  18047. else {
  18048. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18049. }
  18050. this._refreshFrustumPlanes = false;
  18051. };
  18052. Camera.prototype.isInFrustum = function (target) {
  18053. this.updateFrustumPlanes();
  18054. return target.isInFrustum(this._frustumPlanes);
  18055. };
  18056. Camera.prototype.isCompletelyInFrustum = function (target) {
  18057. this.updateFrustumPlanes();
  18058. return target.isCompletelyInFrustum(this._frustumPlanes);
  18059. };
  18060. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18061. if (length === void 0) { length = 100; }
  18062. if (!transform) {
  18063. transform = this.getWorldMatrix();
  18064. }
  18065. if (!origin) {
  18066. origin = this.position;
  18067. }
  18068. var forward = new BABYLON.Vector3(0, 0, 1);
  18069. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18070. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18071. return new BABYLON.Ray(origin, direction, length);
  18072. };
  18073. Camera.prototype.dispose = function () {
  18074. // Observables
  18075. this.onViewMatrixChangedObservable.clear();
  18076. this.onProjectionMatrixChangedObservable.clear();
  18077. this.onAfterCheckInputsObservable.clear();
  18078. this.onRestoreStateObservable.clear();
  18079. // Inputs
  18080. if (this.inputs) {
  18081. this.inputs.clear();
  18082. }
  18083. // Animations
  18084. this.getScene().stopAnimation(this);
  18085. // Remove from scene
  18086. this.getScene().removeCamera(this);
  18087. while (this._rigCameras.length > 0) {
  18088. var camera = this._rigCameras.pop();
  18089. if (camera) {
  18090. camera.dispose();
  18091. }
  18092. }
  18093. // Postprocesses
  18094. if (this._rigPostProcess) {
  18095. this._rigPostProcess.dispose(this);
  18096. this._rigPostProcess = null;
  18097. this._postProcesses = [];
  18098. }
  18099. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18100. this._rigPostProcess = null;
  18101. this._postProcesses = [];
  18102. }
  18103. else {
  18104. var i = this._postProcesses.length;
  18105. while (--i >= 0) {
  18106. this._postProcesses[i].dispose(this);
  18107. }
  18108. }
  18109. // Render targets
  18110. var i = this.customRenderTargets.length;
  18111. while (--i >= 0) {
  18112. this.customRenderTargets[i].dispose();
  18113. }
  18114. this.customRenderTargets = [];
  18115. // Active Meshes
  18116. this._activeMeshes.dispose();
  18117. _super.prototype.dispose.call(this);
  18118. };
  18119. Object.defineProperty(Camera.prototype, "leftCamera", {
  18120. // ---- Camera rigs section ----
  18121. get: function () {
  18122. if (this._rigCameras.length < 1) {
  18123. return null;
  18124. }
  18125. return this._rigCameras[0];
  18126. },
  18127. enumerable: true,
  18128. configurable: true
  18129. });
  18130. Object.defineProperty(Camera.prototype, "rightCamera", {
  18131. get: function () {
  18132. if (this._rigCameras.length < 2) {
  18133. return null;
  18134. }
  18135. return this._rigCameras[1];
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Camera.prototype.getLeftTarget = function () {
  18141. if (this._rigCameras.length < 1) {
  18142. return null;
  18143. }
  18144. return this._rigCameras[0].getTarget();
  18145. };
  18146. Camera.prototype.getRightTarget = function () {
  18147. if (this._rigCameras.length < 2) {
  18148. return null;
  18149. }
  18150. return this._rigCameras[1].getTarget();
  18151. };
  18152. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18153. if (this.cameraRigMode === mode) {
  18154. return;
  18155. }
  18156. while (this._rigCameras.length > 0) {
  18157. var camera = this._rigCameras.pop();
  18158. if (camera) {
  18159. camera.dispose();
  18160. }
  18161. }
  18162. this.cameraRigMode = mode;
  18163. this._cameraRigParams = {};
  18164. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18165. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18166. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18167. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18168. // create the rig cameras, unless none
  18169. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18170. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18171. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18172. if (leftCamera && rightCamera) {
  18173. this._rigCameras.push(leftCamera);
  18174. this._rigCameras.push(rightCamera);
  18175. }
  18176. }
  18177. switch (this.cameraRigMode) {
  18178. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18179. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18180. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18181. break;
  18182. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18183. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18184. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18185. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18186. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18187. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18188. break;
  18189. case Camera.RIG_MODE_VR:
  18190. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18191. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18192. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18193. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18194. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18195. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18196. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18197. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18198. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18199. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18200. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18201. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18202. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18203. if (metrics.compensateDistortion) {
  18204. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18205. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18206. }
  18207. break;
  18208. case Camera.RIG_MODE_WEBVR:
  18209. if (rigParams.vrDisplay) {
  18210. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18211. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18212. //Left eye
  18213. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18214. this._rigCameras[0].setCameraRigParameter("left", true);
  18215. //leaving this for future reference
  18216. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18217. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18218. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18219. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18220. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18221. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18222. this._rigCameras[0].parent = this;
  18223. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18224. //Right eye
  18225. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18226. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18227. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18228. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18229. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18230. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18231. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18232. this._rigCameras[1].parent = this;
  18233. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18234. if (Camera.UseAlternateWebVRRendering) {
  18235. this._rigCameras[1]._skipRendering = true;
  18236. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18237. }
  18238. }
  18239. break;
  18240. }
  18241. this._cascadePostProcessesToRigCams();
  18242. this.update();
  18243. };
  18244. Camera.prototype._getVRProjectionMatrix = function () {
  18245. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18246. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18247. return this._projectionMatrix;
  18248. };
  18249. Camera.prototype._updateCameraRotationMatrix = function () {
  18250. //Here for WebVR
  18251. };
  18252. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18253. //Here for WebVR
  18254. };
  18255. /**
  18256. * This function MUST be overwritten by the different WebVR cameras available.
  18257. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18258. */
  18259. Camera.prototype._getWebVRProjectionMatrix = function () {
  18260. return BABYLON.Matrix.Identity();
  18261. };
  18262. /**
  18263. * This function MUST be overwritten by the different WebVR cameras available.
  18264. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18265. */
  18266. Camera.prototype._getWebVRViewMatrix = function () {
  18267. return BABYLON.Matrix.Identity();
  18268. };
  18269. Camera.prototype.setCameraRigParameter = function (name, value) {
  18270. if (!this._cameraRigParams) {
  18271. this._cameraRigParams = {};
  18272. }
  18273. this._cameraRigParams[name] = value;
  18274. //provisionnally:
  18275. if (name === "interaxialDistance") {
  18276. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18277. }
  18278. };
  18279. /**
  18280. * needs to be overridden by children so sub has required properties to be copied
  18281. */
  18282. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18283. return null;
  18284. };
  18285. /**
  18286. * May need to be overridden by children
  18287. */
  18288. Camera.prototype._updateRigCameras = function () {
  18289. for (var i = 0; i < this._rigCameras.length; i++) {
  18290. this._rigCameras[i].minZ = this.minZ;
  18291. this._rigCameras[i].maxZ = this.maxZ;
  18292. this._rigCameras[i].fov = this.fov;
  18293. }
  18294. // only update viewport when ANAGLYPH
  18295. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18296. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18297. }
  18298. };
  18299. Camera.prototype._setupInputs = function () {
  18300. };
  18301. Camera.prototype.serialize = function () {
  18302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18303. // Type
  18304. serializationObject.type = this.getClassName();
  18305. // Parent
  18306. if (this.parent) {
  18307. serializationObject.parentId = this.parent.id;
  18308. }
  18309. if (this.inputs) {
  18310. this.inputs.serialize(serializationObject);
  18311. }
  18312. // Animations
  18313. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18314. serializationObject.ranges = this.serializeAnimationRanges();
  18315. return serializationObject;
  18316. };
  18317. Camera.prototype.clone = function (name) {
  18318. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18319. };
  18320. Camera.prototype.getDirection = function (localAxis) {
  18321. var result = BABYLON.Vector3.Zero();
  18322. this.getDirectionToRef(localAxis, result);
  18323. return result;
  18324. };
  18325. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18326. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18327. };
  18328. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18329. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18330. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18331. switch (type) {
  18332. case "ArcRotateCamera":
  18333. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18334. case "DeviceOrientationCamera":
  18335. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18336. case "FollowCamera":
  18337. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18338. case "ArcFollowCamera":
  18339. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18340. case "GamepadCamera":
  18341. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18342. case "TouchCamera":
  18343. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18344. case "VirtualJoysticksCamera":
  18345. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18346. case "WebVRFreeCamera":
  18347. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18348. case "WebVRGamepadCamera":
  18349. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18350. case "VRDeviceOrientationFreeCamera":
  18351. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18352. case "VRDeviceOrientationGamepadCamera":
  18353. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18354. case "AnaglyphArcRotateCamera":
  18355. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18356. case "AnaglyphFreeCamera":
  18357. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18358. case "AnaglyphGamepadCamera":
  18359. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18360. case "AnaglyphUniversalCamera":
  18361. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18362. case "StereoscopicArcRotateCamera":
  18363. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18364. case "StereoscopicFreeCamera":
  18365. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18366. case "StereoscopicGamepadCamera":
  18367. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18368. case "StereoscopicUniversalCamera":
  18369. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18370. case "FreeCamera":// Forcing Universal here
  18371. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18372. default:// Universal Camera is the default value
  18373. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18374. }
  18375. };
  18376. Camera.prototype.computeWorldMatrix = function () {
  18377. return this.getWorldMatrix();
  18378. };
  18379. Camera.Parse = function (parsedCamera, scene) {
  18380. var type = parsedCamera.type;
  18381. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18382. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18383. // Parent
  18384. if (parsedCamera.parentId) {
  18385. camera._waitingParentId = parsedCamera.parentId;
  18386. }
  18387. //If camera has an input manager, let it parse inputs settings
  18388. if (camera.inputs) {
  18389. camera.inputs.parse(parsedCamera);
  18390. camera._setupInputs();
  18391. }
  18392. if (camera.setPosition) {
  18393. camera.position.copyFromFloats(0, 0, 0);
  18394. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18395. }
  18396. // Target
  18397. if (parsedCamera.target) {
  18398. if (camera.setTarget) {
  18399. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18400. }
  18401. }
  18402. // Apply 3d rig, when found
  18403. if (parsedCamera.cameraRigMode) {
  18404. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18405. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18406. }
  18407. // Animations
  18408. if (parsedCamera.animations) {
  18409. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18410. var parsedAnimation = parsedCamera.animations[animationIndex];
  18411. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18412. }
  18413. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18414. }
  18415. if (parsedCamera.autoAnimate) {
  18416. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18417. }
  18418. return camera;
  18419. };
  18420. // Statics
  18421. Camera._PERSPECTIVE_CAMERA = 0;
  18422. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18423. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18424. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18425. Camera._RIG_MODE_NONE = 0;
  18426. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18427. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18428. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18429. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18430. Camera._RIG_MODE_VR = 20;
  18431. Camera._RIG_MODE_WEBVR = 21;
  18432. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18433. Camera.UseAlternateWebVRRendering = false;
  18434. __decorate([
  18435. BABYLON.serializeAsVector3()
  18436. ], Camera.prototype, "position", void 0);
  18437. __decorate([
  18438. BABYLON.serializeAsVector3()
  18439. ], Camera.prototype, "upVector", void 0);
  18440. __decorate([
  18441. BABYLON.serialize()
  18442. ], Camera.prototype, "orthoLeft", void 0);
  18443. __decorate([
  18444. BABYLON.serialize()
  18445. ], Camera.prototype, "orthoRight", void 0);
  18446. __decorate([
  18447. BABYLON.serialize()
  18448. ], Camera.prototype, "orthoBottom", void 0);
  18449. __decorate([
  18450. BABYLON.serialize()
  18451. ], Camera.prototype, "orthoTop", void 0);
  18452. __decorate([
  18453. BABYLON.serialize()
  18454. ], Camera.prototype, "fov", void 0);
  18455. __decorate([
  18456. BABYLON.serialize()
  18457. ], Camera.prototype, "minZ", void 0);
  18458. __decorate([
  18459. BABYLON.serialize()
  18460. ], Camera.prototype, "maxZ", void 0);
  18461. __decorate([
  18462. BABYLON.serialize()
  18463. ], Camera.prototype, "inertia", void 0);
  18464. __decorate([
  18465. BABYLON.serialize()
  18466. ], Camera.prototype, "mode", void 0);
  18467. __decorate([
  18468. BABYLON.serialize()
  18469. ], Camera.prototype, "layerMask", void 0);
  18470. __decorate([
  18471. BABYLON.serialize()
  18472. ], Camera.prototype, "fovMode", void 0);
  18473. __decorate([
  18474. BABYLON.serialize()
  18475. ], Camera.prototype, "cameraRigMode", void 0);
  18476. __decorate([
  18477. BABYLON.serialize()
  18478. ], Camera.prototype, "interaxialDistance", void 0);
  18479. __decorate([
  18480. BABYLON.serialize()
  18481. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18482. return Camera;
  18483. }(BABYLON.Node));
  18484. BABYLON.Camera = Camera;
  18485. })(BABYLON || (BABYLON = {}));
  18486. //# sourceMappingURL=babylon.camera.js.map
  18487. var BABYLON;
  18488. (function (BABYLON) {
  18489. var RenderingManager = /** @class */ (function () {
  18490. function RenderingManager(scene) {
  18491. this._renderingGroups = new Array();
  18492. this._autoClearDepthStencil = {};
  18493. this._customOpaqueSortCompareFn = {};
  18494. this._customAlphaTestSortCompareFn = {};
  18495. this._customTransparentSortCompareFn = {};
  18496. this._renderinGroupInfo = null;
  18497. this._scene = scene;
  18498. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18499. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18500. }
  18501. }
  18502. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18503. if (depth === void 0) { depth = true; }
  18504. if (stencil === void 0) { stencil = true; }
  18505. if (this._depthStencilBufferAlreadyCleaned) {
  18506. return;
  18507. }
  18508. this._scene.getEngine().clear(null, false, depth, stencil);
  18509. this._depthStencilBufferAlreadyCleaned = true;
  18510. };
  18511. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18512. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18513. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18514. var info = null;
  18515. if (observable) {
  18516. if (!this._renderinGroupInfo) {
  18517. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18518. }
  18519. info = this._renderinGroupInfo;
  18520. info.scene = this._scene;
  18521. info.camera = this._scene.activeCamera;
  18522. }
  18523. // Dispatch sprites
  18524. if (renderSprites) {
  18525. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18526. var manager = this._scene.spriteManagers[index];
  18527. this.dispatchSprites(manager);
  18528. }
  18529. }
  18530. // Render
  18531. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18532. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18533. var renderingGroup = this._renderingGroups[index];
  18534. if (!renderingGroup && !observable)
  18535. continue;
  18536. var renderingGroupMask = 0;
  18537. // Fire PRECLEAR stage
  18538. if (observable && info) {
  18539. renderingGroupMask = Math.pow(2, index);
  18540. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18541. info.renderingGroupId = index;
  18542. observable.notifyObservers(info, renderingGroupMask);
  18543. }
  18544. // Clear depth/stencil if needed
  18545. if (RenderingManager.AUTOCLEAR) {
  18546. var autoClear = this._autoClearDepthStencil[index];
  18547. if (autoClear && autoClear.autoClear) {
  18548. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18549. }
  18550. }
  18551. if (observable && info) {
  18552. // Fire PREOPAQUE stage
  18553. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18554. observable.notifyObservers(info, renderingGroupMask);
  18555. // Fire PRETRANSPARENT stage
  18556. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18557. observable.notifyObservers(info, renderingGroupMask);
  18558. }
  18559. if (renderingGroup)
  18560. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18561. // Fire POSTTRANSPARENT stage
  18562. if (observable && info) {
  18563. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18564. observable.notifyObservers(info, renderingGroupMask);
  18565. }
  18566. }
  18567. };
  18568. RenderingManager.prototype.reset = function () {
  18569. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18570. var renderingGroup = this._renderingGroups[index];
  18571. if (renderingGroup) {
  18572. renderingGroup.prepare();
  18573. }
  18574. }
  18575. };
  18576. RenderingManager.prototype.dispose = function () {
  18577. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18578. var renderingGroup = this._renderingGroups[index];
  18579. if (renderingGroup) {
  18580. renderingGroup.dispose();
  18581. }
  18582. }
  18583. this._renderingGroups.length = 0;
  18584. };
  18585. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18586. if (this._renderingGroups[renderingGroupId] === undefined) {
  18587. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18588. }
  18589. };
  18590. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18591. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18592. this._prepareRenderingGroup(renderingGroupId);
  18593. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18594. };
  18595. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18596. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18597. this._prepareRenderingGroup(renderingGroupId);
  18598. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18599. };
  18600. /**
  18601. * @param subMesh The submesh to dispatch
  18602. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18603. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18604. */
  18605. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18606. if (mesh === undefined) {
  18607. mesh = subMesh.getMesh();
  18608. }
  18609. var renderingGroupId = mesh.renderingGroupId || 0;
  18610. this._prepareRenderingGroup(renderingGroupId);
  18611. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18612. };
  18613. /**
  18614. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18615. * This allowed control for front to back rendering or reversly depending of the special needs.
  18616. *
  18617. * @param renderingGroupId The rendering group id corresponding to its index
  18618. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18619. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18620. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18621. */
  18622. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18623. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18624. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18625. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18626. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18627. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18628. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18629. if (this._renderingGroups[renderingGroupId]) {
  18630. var group = this._renderingGroups[renderingGroupId];
  18631. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18632. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18633. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18634. }
  18635. };
  18636. /**
  18637. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18638. *
  18639. * @param renderingGroupId The rendering group id corresponding to its index
  18640. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18641. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18642. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18643. */
  18644. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18645. if (depth === void 0) { depth = true; }
  18646. if (stencil === void 0) { stencil = true; }
  18647. this._autoClearDepthStencil[renderingGroupId] = {
  18648. autoClear: autoClearDepthStencil,
  18649. depth: depth,
  18650. stencil: stencil
  18651. };
  18652. };
  18653. /**
  18654. * The max id used for rendering groups (not included)
  18655. */
  18656. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18657. /**
  18658. * The min id used for rendering groups (included)
  18659. */
  18660. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18661. /**
  18662. * Used to globally prevent autoclearing scenes.
  18663. */
  18664. RenderingManager.AUTOCLEAR = true;
  18665. return RenderingManager;
  18666. }());
  18667. BABYLON.RenderingManager = RenderingManager;
  18668. })(BABYLON || (BABYLON = {}));
  18669. //# sourceMappingURL=babylon.renderingManager.js.map
  18670. var BABYLON;
  18671. (function (BABYLON) {
  18672. var RenderingGroup = /** @class */ (function () {
  18673. /**
  18674. * Creates a new rendering group.
  18675. * @param index The rendering group index
  18676. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18677. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18678. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18679. */
  18680. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18681. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18682. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18683. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18684. this.index = index;
  18685. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18686. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18687. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18688. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18689. this._particleSystems = new BABYLON.SmartArray(256);
  18690. this._spriteManagers = new BABYLON.SmartArray(256);
  18691. this._edgesRenderers = new BABYLON.SmartArray(16);
  18692. this._scene = scene;
  18693. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18694. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18695. this.transparentSortCompareFn = transparentSortCompareFn;
  18696. }
  18697. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18698. /**
  18699. * Set the opaque sort comparison function.
  18700. * If null the sub meshes will be render in the order they were created
  18701. */
  18702. set: function (value) {
  18703. this._opaqueSortCompareFn = value;
  18704. if (value) {
  18705. this._renderOpaque = this.renderOpaqueSorted;
  18706. }
  18707. else {
  18708. this._renderOpaque = RenderingGroup.renderUnsorted;
  18709. }
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18715. /**
  18716. * Set the alpha test sort comparison function.
  18717. * If null the sub meshes will be render in the order they were created
  18718. */
  18719. set: function (value) {
  18720. this._alphaTestSortCompareFn = value;
  18721. if (value) {
  18722. this._renderAlphaTest = this.renderAlphaTestSorted;
  18723. }
  18724. else {
  18725. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18726. }
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18732. /**
  18733. * Set the transparent sort comparison function.
  18734. * If null the sub meshes will be render in the order they were created
  18735. */
  18736. set: function (value) {
  18737. if (value) {
  18738. this._transparentSortCompareFn = value;
  18739. }
  18740. else {
  18741. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18742. }
  18743. this._renderTransparent = this.renderTransparentSorted;
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. /**
  18749. * Render all the sub meshes contained in the group.
  18750. * @param customRenderFunction Used to override the default render behaviour of the group.
  18751. * @returns true if rendered some submeshes.
  18752. */
  18753. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18754. if (customRenderFunction) {
  18755. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18756. return;
  18757. }
  18758. var engine = this._scene.getEngine();
  18759. // Depth only
  18760. if (this._depthOnlySubMeshes.length !== 0) {
  18761. engine.setAlphaTesting(true);
  18762. engine.setColorWrite(false);
  18763. this._renderAlphaTest(this._depthOnlySubMeshes);
  18764. engine.setAlphaTesting(false);
  18765. engine.setColorWrite(true);
  18766. }
  18767. // Opaque
  18768. if (this._opaqueSubMeshes.length !== 0) {
  18769. this._renderOpaque(this._opaqueSubMeshes);
  18770. }
  18771. // Alpha test
  18772. if (this._alphaTestSubMeshes.length !== 0) {
  18773. engine.setAlphaTesting(true);
  18774. this._renderAlphaTest(this._alphaTestSubMeshes);
  18775. engine.setAlphaTesting(false);
  18776. }
  18777. var stencilState = engine.getStencilBuffer();
  18778. engine.setStencilBuffer(false);
  18779. // Sprites
  18780. if (renderSprites) {
  18781. this._renderSprites();
  18782. }
  18783. // Particles
  18784. if (renderParticles) {
  18785. this._renderParticles(activeMeshes);
  18786. }
  18787. if (this.onBeforeTransparentRendering) {
  18788. this.onBeforeTransparentRendering();
  18789. }
  18790. // Transparent
  18791. if (this._transparentSubMeshes.length !== 0) {
  18792. this._renderTransparent(this._transparentSubMeshes);
  18793. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18794. }
  18795. // Set back stencil to false in case it changes before the edge renderer.
  18796. engine.setStencilBuffer(false);
  18797. // Edges
  18798. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18799. this._edgesRenderers.data[edgesRendererIndex].render();
  18800. }
  18801. // Restore Stencil state.
  18802. engine.setStencilBuffer(stencilState);
  18803. };
  18804. /**
  18805. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18806. * @param subMeshes The submeshes to render
  18807. */
  18808. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18809. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18810. };
  18811. /**
  18812. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18813. * @param subMeshes The submeshes to render
  18814. */
  18815. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18816. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18817. };
  18818. /**
  18819. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18820. * @param subMeshes The submeshes to render
  18821. */
  18822. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18823. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18824. };
  18825. /**
  18826. * Renders the submeshes in a specified order.
  18827. * @param subMeshes The submeshes to sort before render
  18828. * @param sortCompareFn The comparison function use to sort
  18829. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18830. * @param transparent Specifies to activate blending if true
  18831. */
  18832. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18833. var subIndex = 0;
  18834. var subMesh;
  18835. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18836. for (; subIndex < subMeshes.length; subIndex++) {
  18837. subMesh = subMeshes.data[subIndex];
  18838. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18839. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18840. }
  18841. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18842. if (sortCompareFn) {
  18843. sortedArray.sort(sortCompareFn);
  18844. }
  18845. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18846. subMesh = sortedArray[subIndex];
  18847. if (transparent) {
  18848. var material = subMesh.getMaterial();
  18849. if (material && material.needDepthPrePass) {
  18850. var engine = material.getScene().getEngine();
  18851. engine.setColorWrite(false);
  18852. engine.setAlphaTesting(true);
  18853. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18854. subMesh.render(false);
  18855. engine.setAlphaTesting(false);
  18856. engine.setColorWrite(true);
  18857. }
  18858. }
  18859. subMesh.render(transparent);
  18860. }
  18861. };
  18862. /**
  18863. * Renders the submeshes in the order they were dispatched (no sort applied).
  18864. * @param subMeshes The submeshes to render
  18865. */
  18866. RenderingGroup.renderUnsorted = function (subMeshes) {
  18867. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18868. var submesh = subMeshes.data[subIndex];
  18869. submesh.render(false);
  18870. }
  18871. };
  18872. /**
  18873. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18874. * are rendered back to front if in the same alpha index.
  18875. *
  18876. * @param a The first submesh
  18877. * @param b The second submesh
  18878. * @returns The result of the comparison
  18879. */
  18880. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18881. // Alpha index first
  18882. if (a._alphaIndex > b._alphaIndex) {
  18883. return 1;
  18884. }
  18885. if (a._alphaIndex < b._alphaIndex) {
  18886. return -1;
  18887. }
  18888. // Then distance to camera
  18889. return RenderingGroup.backToFrontSortCompare(a, b);
  18890. };
  18891. /**
  18892. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18893. * are rendered back to front.
  18894. *
  18895. * @param a The first submesh
  18896. * @param b The second submesh
  18897. * @returns The result of the comparison
  18898. */
  18899. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18900. // Then distance to camera
  18901. if (a._distanceToCamera < b._distanceToCamera) {
  18902. return 1;
  18903. }
  18904. if (a._distanceToCamera > b._distanceToCamera) {
  18905. return -1;
  18906. }
  18907. return 0;
  18908. };
  18909. /**
  18910. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18911. * are rendered front to back (prevent overdraw).
  18912. *
  18913. * @param a The first submesh
  18914. * @param b The second submesh
  18915. * @returns The result of the comparison
  18916. */
  18917. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18918. // Then distance to camera
  18919. if (a._distanceToCamera < b._distanceToCamera) {
  18920. return -1;
  18921. }
  18922. if (a._distanceToCamera > b._distanceToCamera) {
  18923. return 1;
  18924. }
  18925. return 0;
  18926. };
  18927. /**
  18928. * Resets the different lists of submeshes to prepare a new frame.
  18929. */
  18930. RenderingGroup.prototype.prepare = function () {
  18931. this._opaqueSubMeshes.reset();
  18932. this._transparentSubMeshes.reset();
  18933. this._alphaTestSubMeshes.reset();
  18934. this._depthOnlySubMeshes.reset();
  18935. this._particleSystems.reset();
  18936. this._spriteManagers.reset();
  18937. this._edgesRenderers.reset();
  18938. };
  18939. RenderingGroup.prototype.dispose = function () {
  18940. this._opaqueSubMeshes.dispose();
  18941. this._transparentSubMeshes.dispose();
  18942. this._alphaTestSubMeshes.dispose();
  18943. this._depthOnlySubMeshes.dispose();
  18944. this._particleSystems.dispose();
  18945. this._spriteManagers.dispose();
  18946. this._edgesRenderers.dispose();
  18947. };
  18948. /**
  18949. * Inserts the submesh in its correct queue depending on its material.
  18950. * @param subMesh The submesh to dispatch
  18951. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18952. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18953. */
  18954. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18955. // Get mesh and materials if not provided
  18956. if (mesh === undefined) {
  18957. mesh = subMesh.getMesh();
  18958. }
  18959. if (material === undefined) {
  18960. material = subMesh.getMaterial();
  18961. }
  18962. if (material === null || material === undefined) {
  18963. return;
  18964. }
  18965. if (material.needAlphaBlendingForMesh(mesh)) {
  18966. this._transparentSubMeshes.push(subMesh);
  18967. }
  18968. else if (material.needAlphaTesting()) {
  18969. if (material.needDepthPrePass) {
  18970. this._depthOnlySubMeshes.push(subMesh);
  18971. }
  18972. this._alphaTestSubMeshes.push(subMesh);
  18973. }
  18974. else {
  18975. if (material.needDepthPrePass) {
  18976. this._depthOnlySubMeshes.push(subMesh);
  18977. }
  18978. this._opaqueSubMeshes.push(subMesh); // Opaque
  18979. }
  18980. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  18981. this._edgesRenderers.push(mesh._edgesRenderer);
  18982. }
  18983. };
  18984. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18985. this._spriteManagers.push(spriteManager);
  18986. };
  18987. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18988. this._particleSystems.push(particleSystem);
  18989. };
  18990. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18991. if (this._particleSystems.length === 0) {
  18992. return;
  18993. }
  18994. // Particles
  18995. var activeCamera = this._scene.activeCamera;
  18996. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  18997. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18998. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18999. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19000. continue;
  19001. }
  19002. var emitter = particleSystem.emitter;
  19003. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19004. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19005. }
  19006. }
  19007. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19008. };
  19009. RenderingGroup.prototype._renderSprites = function () {
  19010. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19011. return;
  19012. }
  19013. // Sprites
  19014. var activeCamera = this._scene.activeCamera;
  19015. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19016. for (var id = 0; id < this._spriteManagers.length; id++) {
  19017. var spriteManager = this._spriteManagers.data[id];
  19018. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19019. spriteManager.render();
  19020. }
  19021. }
  19022. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19023. };
  19024. return RenderingGroup;
  19025. }());
  19026. BABYLON.RenderingGroup = RenderingGroup;
  19027. })(BABYLON || (BABYLON = {}));
  19028. //# sourceMappingURL=babylon.renderingGroup.js.map
  19029. var BABYLON;
  19030. (function (BABYLON) {
  19031. var ClickInfo = /** @class */ (function () {
  19032. function ClickInfo() {
  19033. this._singleClick = false;
  19034. this._doubleClick = false;
  19035. this._hasSwiped = false;
  19036. this._ignore = false;
  19037. }
  19038. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19039. get: function () {
  19040. return this._singleClick;
  19041. },
  19042. set: function (b) {
  19043. this._singleClick = b;
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19049. get: function () {
  19050. return this._doubleClick;
  19051. },
  19052. set: function (b) {
  19053. this._doubleClick = b;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19059. get: function () {
  19060. return this._hasSwiped;
  19061. },
  19062. set: function (b) {
  19063. this._hasSwiped = b;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19069. get: function () {
  19070. return this._ignore;
  19071. },
  19072. set: function (b) {
  19073. this._ignore = b;
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. return ClickInfo;
  19079. }());
  19080. /**
  19081. * This class is used by the onRenderingGroupObservable
  19082. */
  19083. var RenderingGroupInfo = /** @class */ (function () {
  19084. function RenderingGroupInfo() {
  19085. }
  19086. /**
  19087. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19088. * This stage will be fired no matter what
  19089. */
  19090. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19091. /**
  19092. * Called before opaque object are rendered.
  19093. * This stage will be fired only if there's 3D Opaque content to render
  19094. */
  19095. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19096. /**
  19097. * Called after the opaque objects are rendered and before the transparent ones
  19098. * This stage will be fired only if there's 3D transparent content to render
  19099. */
  19100. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19101. /**
  19102. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19103. * This stage will be fired no matter what
  19104. */
  19105. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19106. return RenderingGroupInfo;
  19107. }());
  19108. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19109. /**
  19110. * Represents a scene to be rendered by the engine.
  19111. * @see http://doc.babylonjs.com/page.php?p=21911
  19112. */
  19113. var Scene = /** @class */ (function () {
  19114. /**
  19115. * @constructor
  19116. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19117. */
  19118. function Scene(engine) {
  19119. // Members
  19120. this.autoClear = true;
  19121. this.autoClearDepthAndStencil = true;
  19122. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19123. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19124. this.forceWireframe = false;
  19125. this._forcePointsCloud = false;
  19126. this.forceShowBoundingBoxes = false;
  19127. this.animationsEnabled = true;
  19128. this.useConstantAnimationDeltaTime = false;
  19129. this.constantlyUpdateMeshUnderPointer = false;
  19130. this.hoverCursor = "pointer";
  19131. this.defaultCursor = "";
  19132. /**
  19133. * This is used to call preventDefault() on pointer down
  19134. * in order to block unwanted artifacts like system double clicks
  19135. */
  19136. this.preventDefaultOnPointerDown = true;
  19137. // Metadata
  19138. this.metadata = null;
  19139. /**
  19140. * An event triggered when the scene is disposed.
  19141. * @type {BABYLON.Observable}
  19142. */
  19143. this.onDisposeObservable = new BABYLON.Observable();
  19144. /**
  19145. * An event triggered before rendering the scene (right after animations and physics)
  19146. * @type {BABYLON.Observable}
  19147. */
  19148. this.onBeforeRenderObservable = new BABYLON.Observable();
  19149. /**
  19150. * An event triggered after rendering the scene
  19151. * @type {BABYLON.Observable}
  19152. */
  19153. this.onAfterRenderObservable = new BABYLON.Observable();
  19154. /**
  19155. * An event triggered before animating the scene
  19156. * @type {BABYLON.Observable}
  19157. */
  19158. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19159. /**
  19160. * An event triggered after animations processing
  19161. * @type {BABYLON.Observable}
  19162. */
  19163. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19164. /**
  19165. * An event triggered before draw calls are ready to be sent
  19166. * @type {BABYLON.Observable}
  19167. */
  19168. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19169. /**
  19170. * An event triggered after draw calls have been sent
  19171. * @type {BABYLON.Observable}
  19172. */
  19173. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19174. /**
  19175. * An event triggered when physic simulation is about to be run
  19176. * @type {BABYLON.Observable}
  19177. */
  19178. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19179. /**
  19180. * An event triggered when physic simulation has been done
  19181. * @type {BABYLON.Observable}
  19182. */
  19183. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19184. /**
  19185. * An event triggered when the scene is ready
  19186. * @type {BABYLON.Observable}
  19187. */
  19188. this.onReadyObservable = new BABYLON.Observable();
  19189. /**
  19190. * An event triggered before rendering a camera
  19191. * @type {BABYLON.Observable}
  19192. */
  19193. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19194. /**
  19195. * An event triggered after rendering a camera
  19196. * @type {BABYLON.Observable}
  19197. */
  19198. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19199. /**
  19200. * An event triggered when active meshes evaluation is about to start
  19201. * @type {BABYLON.Observable}
  19202. */
  19203. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19204. /**
  19205. * An event triggered when active meshes evaluation is done
  19206. * @type {BABYLON.Observable}
  19207. */
  19208. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19209. /**
  19210. * An event triggered when particles rendering is about to start
  19211. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19212. * @type {BABYLON.Observable}
  19213. */
  19214. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19215. /**
  19216. * An event triggered when particles rendering is done
  19217. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19218. * @type {BABYLON.Observable}
  19219. */
  19220. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19221. /**
  19222. * An event triggered when sprites rendering is about to start
  19223. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19224. * @type {BABYLON.Observable}
  19225. */
  19226. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19227. /**
  19228. * An event triggered when sprites rendering is done
  19229. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19230. * @type {BABYLON.Observable}
  19231. */
  19232. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19233. /**
  19234. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19235. * @type {BABYLON.Observable}
  19236. */
  19237. this.onDataLoadedObservable = new BABYLON.Observable();
  19238. /**
  19239. * An event triggered when a camera is created
  19240. * @type {BABYLON.Observable}
  19241. */
  19242. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when a camera is removed
  19245. * @type {BABYLON.Observable}
  19246. */
  19247. this.onCameraRemovedObservable = new BABYLON.Observable();
  19248. /**
  19249. * An event triggered when a light is created
  19250. * @type {BABYLON.Observable}
  19251. */
  19252. this.onNewLightAddedObservable = new BABYLON.Observable();
  19253. /**
  19254. * An event triggered when a light is removed
  19255. * @type {BABYLON.Observable}
  19256. */
  19257. this.onLightRemovedObservable = new BABYLON.Observable();
  19258. /**
  19259. * An event triggered when a geometry is created
  19260. * @type {BABYLON.Observable}
  19261. */
  19262. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19263. /**
  19264. * An event triggered when a geometry is removed
  19265. * @type {BABYLON.Observable}
  19266. */
  19267. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19268. /**
  19269. * An event triggered when a transform node is created
  19270. * @type {BABYLON.Observable}
  19271. */
  19272. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19273. /**
  19274. * An event triggered when a transform node is removed
  19275. * @type {BABYLON.Observable}
  19276. */
  19277. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when a mesh is created
  19280. * @type {BABYLON.Observable}
  19281. */
  19282. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19283. /**
  19284. * An event triggered when a mesh is removed
  19285. * @type {BABYLON.Observable}
  19286. */
  19287. this.onMeshRemovedObservable = new BABYLON.Observable();
  19288. /**
  19289. * An event triggered when render targets are about to be rendered
  19290. * Can happen multiple times per frame.
  19291. * @type {BABYLON.Observable}
  19292. */
  19293. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19294. /**
  19295. * An event triggered when render targets were rendered.
  19296. * Can happen multiple times per frame.
  19297. * @type {BABYLON.Observable}
  19298. */
  19299. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19300. /**
  19301. * An event triggered before calculating deterministic simulation step
  19302. * @type {BABYLON.Observable}
  19303. */
  19304. this.onBeforeStepObservable = new BABYLON.Observable();
  19305. /**
  19306. * An event triggered after calculating deterministic simulation step
  19307. * @type {BABYLON.Observable}
  19308. */
  19309. this.onAfterStepObservable = new BABYLON.Observable();
  19310. /**
  19311. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19312. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19313. * 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)
  19314. */
  19315. this.onRenderingGroupObservable = new BABYLON.Observable();
  19316. // Animations
  19317. this.animations = [];
  19318. /**
  19319. * 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).
  19320. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19321. */
  19322. this.onPrePointerObservable = new BABYLON.Observable();
  19323. /**
  19324. * Observable event triggered each time an input event is received from the rendering canvas
  19325. */
  19326. this.onPointerObservable = new BABYLON.Observable();
  19327. this._meshPickProceed = false;
  19328. this._currentPickResult = null;
  19329. this._previousPickResult = null;
  19330. this._totalPointersPressed = 0;
  19331. this._doubleClickOccured = false;
  19332. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19333. this.cameraToUseForPointers = null;
  19334. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19335. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19336. this._startingPointerTime = 0;
  19337. this._previousStartingPointerTime = 0;
  19338. // Deterministic lockstep
  19339. this._timeAccumulator = 0;
  19340. this._currentStepId = 0;
  19341. this._currentInternalStep = 0;
  19342. // Keyboard
  19343. /**
  19344. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19345. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19346. */
  19347. this.onPreKeyboardObservable = new BABYLON.Observable();
  19348. /**
  19349. * Observable event triggered each time an keyboard event is received from the hosting window
  19350. */
  19351. this.onKeyboardObservable = new BABYLON.Observable();
  19352. // Coordinate system
  19353. /**
  19354. * use right-handed coordinate system on this scene.
  19355. * @type {boolean}
  19356. */
  19357. this._useRightHandedSystem = false;
  19358. // Fog
  19359. this._fogEnabled = true;
  19360. this._fogMode = Scene.FOGMODE_NONE;
  19361. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19362. this.fogDensity = 0.1;
  19363. this.fogStart = 0;
  19364. this.fogEnd = 1000.0;
  19365. // Lights
  19366. /**
  19367. * is shadow enabled on this scene.
  19368. * @type {boolean}
  19369. */
  19370. this._shadowsEnabled = true;
  19371. /**
  19372. * is light enabled on this scene.
  19373. * @type {boolean}
  19374. */
  19375. this._lightsEnabled = true;
  19376. /**
  19377. * All of the lights added to this scene.
  19378. * @see BABYLON.Light
  19379. * @type {BABYLON.Light[]}
  19380. */
  19381. this.lights = new Array();
  19382. // Cameras
  19383. /** All of the cameras added to this scene. */
  19384. this.cameras = new Array();
  19385. /** All of the active cameras added to this scene. */
  19386. this.activeCameras = new Array();
  19387. // Meshes
  19388. /**
  19389. * All of the tranform nodes added to this scene.
  19390. * @see BABYLON.TransformNode
  19391. * @type {BABYLON.TransformNode[]}
  19392. */
  19393. this.transformNodes = new Array();
  19394. /**
  19395. * All of the (abstract) meshes added to this scene.
  19396. * @see BABYLON.AbstractMesh
  19397. * @type {BABYLON.AbstractMesh[]}
  19398. */
  19399. this.meshes = new Array();
  19400. /**
  19401. * All of the animation groups added to this scene.
  19402. * @see BABYLON.AnimationGroup
  19403. * @type {BABYLON.AnimationGroup[]}
  19404. */
  19405. this.animationGroups = new Array();
  19406. // Geometries
  19407. this._geometries = new Array();
  19408. this.materials = new Array();
  19409. this.multiMaterials = new Array();
  19410. // Textures
  19411. this._texturesEnabled = true;
  19412. this.textures = new Array();
  19413. // Particles
  19414. this.particlesEnabled = true;
  19415. this.particleSystems = new Array();
  19416. // Sprites
  19417. this.spritesEnabled = true;
  19418. this.spriteManagers = new Array();
  19419. // Layers
  19420. this.layers = new Array();
  19421. this.highlightLayers = new Array();
  19422. // Skeletons
  19423. this._skeletonsEnabled = true;
  19424. this.skeletons = new Array();
  19425. // Morph targets
  19426. this.morphTargetManagers = new Array();
  19427. // Lens flares
  19428. this.lensFlaresEnabled = true;
  19429. this.lensFlareSystems = new Array();
  19430. // Collisions
  19431. this.collisionsEnabled = true;
  19432. /** Defines the gravity applied to this scene */
  19433. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19434. // Postprocesses
  19435. this.postProcesses = new Array();
  19436. this.postProcessesEnabled = true;
  19437. // Customs render targets
  19438. this.renderTargetsEnabled = true;
  19439. this.dumpNextRenderTargets = false;
  19440. this.customRenderTargets = new Array();
  19441. // Imported meshes
  19442. this.importedMeshesFiles = new Array();
  19443. // Probes
  19444. this.probesEnabled = true;
  19445. this.reflectionProbes = new Array();
  19446. this._actionManagers = new Array();
  19447. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19448. // Procedural textures
  19449. this.proceduralTexturesEnabled = true;
  19450. this._proceduralTextures = new Array();
  19451. this.soundTracks = new Array();
  19452. this._audioEnabled = true;
  19453. this._headphone = false;
  19454. // Performance counters
  19455. this._totalVertices = new BABYLON.PerfCounter();
  19456. this._activeIndices = new BABYLON.PerfCounter();
  19457. this._activeParticles = new BABYLON.PerfCounter();
  19458. this._activeBones = new BABYLON.PerfCounter();
  19459. this._animationTime = 0;
  19460. this.animationTimeScale = 1;
  19461. this._renderId = 0;
  19462. this._executeWhenReadyTimeoutId = -1;
  19463. this._intermediateRendering = false;
  19464. this._viewUpdateFlag = -1;
  19465. this._projectionUpdateFlag = -1;
  19466. this._alternateViewUpdateFlag = -1;
  19467. this._alternateProjectionUpdateFlag = -1;
  19468. this._toBeDisposed = new BABYLON.SmartArray(256);
  19469. this._activeRequests = new Array();
  19470. this._pendingData = new Array();
  19471. this._isDisposed = false;
  19472. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19473. this._activeMeshes = new BABYLON.SmartArray(256);
  19474. this._processedMaterials = new BABYLON.SmartArray(256);
  19475. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19476. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19477. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19478. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19479. this._activeAnimatables = new Array();
  19480. this._transformMatrix = BABYLON.Matrix.Zero();
  19481. this._useAlternateCameraConfiguration = false;
  19482. this._alternateRendering = false;
  19483. this.requireLightSorting = false;
  19484. this._activeMeshesFrozen = false;
  19485. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19486. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19487. this._engine.scenes.push(this);
  19488. this._uid = null;
  19489. this._renderingManager = new BABYLON.RenderingManager(this);
  19490. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19491. if (BABYLON.OutlineRenderer) {
  19492. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19493. }
  19494. if (BABYLON.Tools.IsWindowObjectExist()) {
  19495. this.attachControl();
  19496. }
  19497. //simplification queue
  19498. if (BABYLON.SimplificationQueue) {
  19499. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19500. }
  19501. //collision coordinator initialization. For now legacy per default.
  19502. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19503. // Uniform Buffer
  19504. this._createUbo();
  19505. // Default Image processing definition.
  19506. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19507. }
  19508. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19509. /** The fog is deactivated */
  19510. get: function () {
  19511. return Scene._FOGMODE_NONE;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19517. /** The fog density is following an exponential function */
  19518. get: function () {
  19519. return Scene._FOGMODE_EXP;
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19525. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19526. get: function () {
  19527. return Scene._FOGMODE_EXP2;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19533. /** The fog density is following a linear function. */
  19534. get: function () {
  19535. return Scene._FOGMODE_LINEAR;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19541. /**
  19542. * Texture used in all pbr material as the reflection texture.
  19543. * As in the majority of the scene they are the same (exception for multi room and so on),
  19544. * this is easier to reference from here than from all the materials.
  19545. */
  19546. get: function () {
  19547. return this._environmentTexture;
  19548. },
  19549. /**
  19550. * Texture used in all pbr material as the reflection texture.
  19551. * As in the majority of the scene they are the same (exception for multi room and so on),
  19552. * this is easier to set here than in all the materials.
  19553. */
  19554. set: function (value) {
  19555. if (this._environmentTexture === value) {
  19556. return;
  19557. }
  19558. this._environmentTexture = value;
  19559. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19560. },
  19561. enumerable: true,
  19562. configurable: true
  19563. });
  19564. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19565. /**
  19566. * Default image processing configuration used either in the rendering
  19567. * Forward main pass or through the imageProcessingPostProcess if present.
  19568. * As in the majority of the scene they are the same (exception for multi camera),
  19569. * this is easier to reference from here than from all the materials and post process.
  19570. *
  19571. * No setter as we it is a shared configuration, you can set the values instead.
  19572. */
  19573. get: function () {
  19574. return this._imageProcessingConfiguration;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19580. get: function () {
  19581. return this._forcePointsCloud;
  19582. },
  19583. set: function (value) {
  19584. if (this._forcePointsCloud === value) {
  19585. return;
  19586. }
  19587. this._forcePointsCloud = value;
  19588. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(Scene.prototype, "onDispose", {
  19594. /** A function to be executed when this scene is disposed. */
  19595. set: function (callback) {
  19596. if (this._onDisposeObserver) {
  19597. this.onDisposeObservable.remove(this._onDisposeObserver);
  19598. }
  19599. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(Scene.prototype, "beforeRender", {
  19605. /** A function to be executed before rendering this scene */
  19606. set: function (callback) {
  19607. if (this._onBeforeRenderObserver) {
  19608. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19609. }
  19610. if (callback) {
  19611. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19612. }
  19613. },
  19614. enumerable: true,
  19615. configurable: true
  19616. });
  19617. Object.defineProperty(Scene.prototype, "afterRender", {
  19618. /** A function to be executed after rendering this scene */
  19619. set: function (callback) {
  19620. if (this._onAfterRenderObserver) {
  19621. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19622. }
  19623. if (callback) {
  19624. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19625. }
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19631. set: function (callback) {
  19632. if (this._onBeforeCameraRenderObserver) {
  19633. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19634. }
  19635. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19641. set: function (callback) {
  19642. if (this._onAfterCameraRenderObserver) {
  19643. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19644. }
  19645. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19651. get: function () {
  19652. if (!this._gamepadManager) {
  19653. this._gamepadManager = new BABYLON.GamepadManager(this);
  19654. }
  19655. return this._gamepadManager;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19661. get: function () {
  19662. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19668. get: function () {
  19669. return this._useRightHandedSystem;
  19670. },
  19671. set: function (value) {
  19672. if (this._useRightHandedSystem === value) {
  19673. return;
  19674. }
  19675. this._useRightHandedSystem = value;
  19676. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19677. },
  19678. enumerable: true,
  19679. configurable: true
  19680. });
  19681. Scene.prototype.setStepId = function (newStepId) {
  19682. this._currentStepId = newStepId;
  19683. };
  19684. ;
  19685. Scene.prototype.getStepId = function () {
  19686. return this._currentStepId;
  19687. };
  19688. ;
  19689. Scene.prototype.getInternalStep = function () {
  19690. return this._currentInternalStep;
  19691. };
  19692. ;
  19693. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19694. get: function () {
  19695. return this._fogEnabled;
  19696. },
  19697. /**
  19698. * is fog enabled on this scene.
  19699. */
  19700. set: function (value) {
  19701. if (this._fogEnabled === value) {
  19702. return;
  19703. }
  19704. this._fogEnabled = value;
  19705. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19706. },
  19707. enumerable: true,
  19708. configurable: true
  19709. });
  19710. Object.defineProperty(Scene.prototype, "fogMode", {
  19711. get: function () {
  19712. return this._fogMode;
  19713. },
  19714. set: function (value) {
  19715. if (this._fogMode === value) {
  19716. return;
  19717. }
  19718. this._fogMode = value;
  19719. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19725. get: function () {
  19726. return this._shadowsEnabled;
  19727. },
  19728. set: function (value) {
  19729. if (this._shadowsEnabled === value) {
  19730. return;
  19731. }
  19732. this._shadowsEnabled = value;
  19733. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19739. get: function () {
  19740. return this._lightsEnabled;
  19741. },
  19742. set: function (value) {
  19743. if (this._lightsEnabled === value) {
  19744. return;
  19745. }
  19746. this._lightsEnabled = value;
  19747. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19753. /** The default material used on meshes when no material is affected */
  19754. get: function () {
  19755. if (!this._defaultMaterial) {
  19756. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19757. }
  19758. return this._defaultMaterial;
  19759. },
  19760. /** The default material used on meshes when no material is affected */
  19761. set: function (value) {
  19762. this._defaultMaterial = value;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19768. get: function () {
  19769. return this._texturesEnabled;
  19770. },
  19771. set: function (value) {
  19772. if (this._texturesEnabled === value) {
  19773. return;
  19774. }
  19775. this._texturesEnabled = value;
  19776. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19782. get: function () {
  19783. return this._skeletonsEnabled;
  19784. },
  19785. set: function (value) {
  19786. if (this._skeletonsEnabled === value) {
  19787. return;
  19788. }
  19789. this._skeletonsEnabled = value;
  19790. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19796. get: function () {
  19797. if (!this._postProcessRenderPipelineManager) {
  19798. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19799. }
  19800. return this._postProcessRenderPipelineManager;
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19806. get: function () {
  19807. if (!this._mainSoundTrack) {
  19808. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19809. }
  19810. return this._mainSoundTrack;
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19816. get: function () {
  19817. return this._alternateRendering;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19823. get: function () {
  19824. return this._frustumPlanes;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. Object.defineProperty(Scene.prototype, "debugLayer", {
  19830. // Properties
  19831. get: function () {
  19832. if (!this._debugLayer) {
  19833. this._debugLayer = new BABYLON.DebugLayer(this);
  19834. }
  19835. return this._debugLayer;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19841. get: function () {
  19842. return this._workerCollisions;
  19843. },
  19844. set: function (enabled) {
  19845. if (!BABYLON.CollisionCoordinatorLegacy) {
  19846. return;
  19847. }
  19848. enabled = (enabled && !!Worker);
  19849. this._workerCollisions = enabled;
  19850. if (this.collisionCoordinator) {
  19851. this.collisionCoordinator.destroy();
  19852. }
  19853. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19854. this.collisionCoordinator.init(this);
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19860. get: function () {
  19861. return this._selectionOctree;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19867. /**
  19868. * The mesh that is currently under the pointer.
  19869. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19870. */
  19871. get: function () {
  19872. return this._pointerOverMesh;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(Scene.prototype, "pointerX", {
  19878. /**
  19879. * Current on-screen X position of the pointer
  19880. * @return {number} X position of the pointer
  19881. */
  19882. get: function () {
  19883. return this._pointerX;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(Scene.prototype, "pointerY", {
  19889. /**
  19890. * Current on-screen Y position of the pointer
  19891. * @return {number} Y position of the pointer
  19892. */
  19893. get: function () {
  19894. return this._pointerY;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Scene.prototype.getCachedMaterial = function () {
  19900. return this._cachedMaterial;
  19901. };
  19902. Scene.prototype.getCachedEffect = function () {
  19903. return this._cachedEffect;
  19904. };
  19905. Scene.prototype.getCachedVisibility = function () {
  19906. return this._cachedVisibility;
  19907. };
  19908. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19909. if (visibility === void 0) { visibility = 1; }
  19910. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19911. };
  19912. Scene.prototype.getBoundingBoxRenderer = function () {
  19913. if (!this._boundingBoxRenderer) {
  19914. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19915. }
  19916. return this._boundingBoxRenderer;
  19917. };
  19918. Scene.prototype.getOutlineRenderer = function () {
  19919. return this._outlineRenderer;
  19920. };
  19921. Scene.prototype.getEngine = function () {
  19922. return this._engine;
  19923. };
  19924. Scene.prototype.getTotalVertices = function () {
  19925. return this._totalVertices.current;
  19926. };
  19927. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19928. get: function () {
  19929. return this._totalVertices;
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Scene.prototype.getActiveIndices = function () {
  19935. return this._activeIndices.current;
  19936. };
  19937. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19938. get: function () {
  19939. return this._activeIndices;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Scene.prototype.getActiveParticles = function () {
  19945. return this._activeParticles.current;
  19946. };
  19947. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19948. get: function () {
  19949. return this._activeParticles;
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Scene.prototype.getActiveBones = function () {
  19955. return this._activeBones.current;
  19956. };
  19957. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19958. get: function () {
  19959. return this._activeBones;
  19960. },
  19961. enumerable: true,
  19962. configurable: true
  19963. });
  19964. // Stats
  19965. Scene.prototype.getInterFramePerfCounter = function () {
  19966. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19967. return 0;
  19968. };
  19969. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  19970. get: function () {
  19971. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19972. return null;
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Scene.prototype.getLastFrameDuration = function () {
  19978. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  19979. return 0;
  19980. };
  19981. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19982. get: function () {
  19983. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19984. return null;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19990. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  19991. return 0;
  19992. };
  19993. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19994. get: function () {
  19995. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19996. return null;
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Scene.prototype.getActiveMeshes = function () {
  20002. return this._activeMeshes;
  20003. };
  20004. Scene.prototype.getRenderTargetsDuration = function () {
  20005. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20006. return 0;
  20007. };
  20008. Scene.prototype.getRenderDuration = function () {
  20009. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20010. return 0;
  20011. };
  20012. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20013. get: function () {
  20014. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20015. return null;
  20016. },
  20017. enumerable: true,
  20018. configurable: true
  20019. });
  20020. Scene.prototype.getParticlesDuration = function () {
  20021. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20022. return 0;
  20023. };
  20024. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20025. get: function () {
  20026. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20027. return null;
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Scene.prototype.getSpritesDuration = function () {
  20033. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20034. return 0;
  20035. };
  20036. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20037. get: function () {
  20038. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20039. return null;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Scene.prototype.getAnimationRatio = function () {
  20045. return this._animationRatio;
  20046. };
  20047. Scene.prototype.getRenderId = function () {
  20048. return this._renderId;
  20049. };
  20050. Scene.prototype.incrementRenderId = function () {
  20051. this._renderId++;
  20052. };
  20053. Scene.prototype._updatePointerPosition = function (evt) {
  20054. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20055. if (!canvasRect) {
  20056. return;
  20057. }
  20058. this._pointerX = evt.clientX - canvasRect.left;
  20059. this._pointerY = evt.clientY - canvasRect.top;
  20060. this._unTranslatedPointerX = this._pointerX;
  20061. this._unTranslatedPointerY = this._pointerY;
  20062. };
  20063. Scene.prototype._createUbo = function () {
  20064. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20065. this._sceneUbo.addUniform("viewProjection", 16);
  20066. this._sceneUbo.addUniform("view", 16);
  20067. };
  20068. Scene.prototype._createAlternateUbo = function () {
  20069. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20070. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20071. this._alternateSceneUbo.addUniform("view", 16);
  20072. };
  20073. // Pointers handling
  20074. /**
  20075. * Use this method to simulate a pointer move on a mesh
  20076. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20077. */
  20078. Scene.prototype.simulatePointerMove = function (pickResult) {
  20079. var evt = new PointerEvent("pointermove");
  20080. return this._processPointerMove(pickResult, evt);
  20081. };
  20082. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20083. var canvas = this._engine.getRenderingCanvas();
  20084. if (!canvas) {
  20085. return this;
  20086. }
  20087. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20088. this.setPointerOverSprite(null);
  20089. this.setPointerOverMesh(pickResult.pickedMesh);
  20090. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20091. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20092. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20093. }
  20094. else {
  20095. canvas.style.cursor = this.hoverCursor;
  20096. }
  20097. }
  20098. else {
  20099. canvas.style.cursor = this.defaultCursor;
  20100. }
  20101. }
  20102. else {
  20103. this.setPointerOverMesh(null);
  20104. // Sprites
  20105. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20106. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20107. this.setPointerOverSprite(pickResult.pickedSprite);
  20108. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20109. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20110. }
  20111. else {
  20112. canvas.style.cursor = this.hoverCursor;
  20113. }
  20114. }
  20115. else {
  20116. this.setPointerOverSprite(null);
  20117. // Restore pointer
  20118. canvas.style.cursor = this.defaultCursor;
  20119. }
  20120. }
  20121. if (pickResult) {
  20122. if (this.onPointerMove) {
  20123. this.onPointerMove(evt, pickResult);
  20124. }
  20125. if (this.onPointerObservable.hasObservers()) {
  20126. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20127. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20128. this.onPointerObservable.notifyObservers(pi, type);
  20129. }
  20130. }
  20131. return this;
  20132. };
  20133. /**
  20134. * Use this method to simulate a pointer down on a mesh
  20135. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20136. */
  20137. Scene.prototype.simulatePointerDown = function (pickResult) {
  20138. var evt = new PointerEvent("pointerdown");
  20139. return this._processPointerDown(pickResult, evt);
  20140. };
  20141. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20142. var _this = this;
  20143. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20144. this._pickedDownMesh = pickResult.pickedMesh;
  20145. var actionManager = pickResult.pickedMesh.actionManager;
  20146. if (actionManager) {
  20147. if (actionManager.hasPickTriggers) {
  20148. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20149. switch (evt.button) {
  20150. case 0:
  20151. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20152. break;
  20153. case 1:
  20154. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20155. break;
  20156. case 2:
  20157. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20158. break;
  20159. }
  20160. }
  20161. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20162. window.setTimeout(function () {
  20163. 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);
  20164. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20165. if (_this._totalPointersPressed !== 0 &&
  20166. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20167. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20168. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20169. _this._startingPointerTime = 0;
  20170. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20171. }
  20172. }
  20173. }, Scene.LongPressDelay);
  20174. }
  20175. }
  20176. }
  20177. if (pickResult) {
  20178. if (this.onPointerDown) {
  20179. this.onPointerDown(evt, pickResult);
  20180. }
  20181. if (this.onPointerObservable.hasObservers()) {
  20182. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20183. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20184. this.onPointerObservable.notifyObservers(pi, type);
  20185. }
  20186. }
  20187. return this;
  20188. };
  20189. /**
  20190. * Use this method to simulate a pointer up on a mesh
  20191. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20192. */
  20193. Scene.prototype.simulatePointerUp = function (pickResult) {
  20194. var evt = new PointerEvent("pointerup");
  20195. var clickInfo = new ClickInfo();
  20196. clickInfo.singleClick = true;
  20197. clickInfo.ignore = true;
  20198. return this._processPointerUp(pickResult, evt, clickInfo);
  20199. };
  20200. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20201. if (pickResult && pickResult && pickResult.pickedMesh) {
  20202. this._pickedUpMesh = pickResult.pickedMesh;
  20203. if (this._pickedDownMesh === this._pickedUpMesh) {
  20204. if (this.onPointerPick) {
  20205. this.onPointerPick(evt, pickResult);
  20206. }
  20207. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20208. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20209. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20210. this.onPointerObservable.notifyObservers(pi, type);
  20211. }
  20212. }
  20213. if (pickResult.pickedMesh.actionManager) {
  20214. if (clickInfo.ignore) {
  20215. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20216. }
  20217. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20218. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20219. }
  20220. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20221. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20222. }
  20223. }
  20224. }
  20225. if (this._pickedDownMesh &&
  20226. this._pickedDownMesh.actionManager &&
  20227. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20228. this._pickedDownMesh !== this._pickedUpMesh) {
  20229. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20230. }
  20231. if (this.onPointerUp) {
  20232. this.onPointerUp(evt, pickResult);
  20233. }
  20234. if (this.onPointerObservable.hasObservers()) {
  20235. if (!clickInfo.ignore) {
  20236. if (!clickInfo.hasSwiped) {
  20237. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20238. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20239. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20240. this.onPointerObservable.notifyObservers(pi, type);
  20241. }
  20242. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20243. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20244. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20245. this.onPointerObservable.notifyObservers(pi, type);
  20246. }
  20247. }
  20248. }
  20249. else {
  20250. var type = BABYLON.PointerEventTypes.POINTERUP;
  20251. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20252. this.onPointerObservable.notifyObservers(pi, type);
  20253. }
  20254. }
  20255. return this;
  20256. };
  20257. /**
  20258. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20259. * @param attachUp defines if you want to attach events to pointerup
  20260. * @param attachDown defines if you want to attach events to pointerdown
  20261. * @param attachMove defines if you want to attach events to pointermove
  20262. */
  20263. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20264. var _this = this;
  20265. if (attachUp === void 0) { attachUp = true; }
  20266. if (attachDown === void 0) { attachDown = true; }
  20267. if (attachMove === void 0) { attachMove = true; }
  20268. this._initActionManager = function (act, clickInfo) {
  20269. if (!_this._meshPickProceed) {
  20270. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20271. _this._currentPickResult = pickResult;
  20272. if (pickResult) {
  20273. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20274. }
  20275. _this._meshPickProceed = true;
  20276. }
  20277. return act;
  20278. };
  20279. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20280. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20281. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20282. btn !== _this._previousButtonPressed) {
  20283. _this._doubleClickOccured = false;
  20284. clickInfo.singleClick = true;
  20285. clickInfo.ignore = false;
  20286. cb(clickInfo, _this._currentPickResult);
  20287. }
  20288. };
  20289. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20290. var clickInfo = new ClickInfo();
  20291. _this._currentPickResult = null;
  20292. var act = null;
  20293. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20294. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20295. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20296. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20297. act = _this._initActionManager(act, clickInfo);
  20298. if (act)
  20299. checkPicking = act.hasPickTriggers;
  20300. }
  20301. if (checkPicking) {
  20302. var btn = evt.button;
  20303. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20304. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20305. if (!clickInfo.hasSwiped) {
  20306. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20307. if (!checkSingleClickImmediately) {
  20308. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20309. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20310. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20311. act = _this._initActionManager(act, clickInfo);
  20312. if (act)
  20313. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20314. }
  20315. }
  20316. if (checkSingleClickImmediately) {
  20317. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20318. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20319. btn !== _this._previousButtonPressed) {
  20320. clickInfo.singleClick = true;
  20321. cb(clickInfo, _this._currentPickResult);
  20322. }
  20323. }
  20324. else {
  20325. // wait that no double click has been raised during the double click delay
  20326. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20327. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20328. }
  20329. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20330. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20331. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20332. act = _this._initActionManager(act, clickInfo);
  20333. if (act)
  20334. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20335. }
  20336. if (checkDoubleClick) {
  20337. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20338. if (btn === _this._previousButtonPressed &&
  20339. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20340. !_this._doubleClickOccured) {
  20341. // pointer has not moved for 2 clicks, it's a double click
  20342. if (!clickInfo.hasSwiped &&
  20343. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20344. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20345. _this._previousStartingPointerTime = 0;
  20346. _this._doubleClickOccured = true;
  20347. clickInfo.doubleClick = true;
  20348. clickInfo.ignore = false;
  20349. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20350. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20351. }
  20352. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20353. cb(clickInfo, _this._currentPickResult);
  20354. }
  20355. else {
  20356. _this._doubleClickOccured = false;
  20357. _this._previousStartingPointerTime = _this._startingPointerTime;
  20358. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20359. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20360. _this._previousButtonPressed = btn;
  20361. if (Scene.ExclusiveDoubleClickMode) {
  20362. if (_this._previousDelayedSimpleClickTimeout) {
  20363. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20364. }
  20365. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20366. cb(clickInfo, _this._previousPickResult);
  20367. }
  20368. else {
  20369. cb(clickInfo, _this._currentPickResult);
  20370. }
  20371. }
  20372. }
  20373. else {
  20374. _this._doubleClickOccured = false;
  20375. _this._previousStartingPointerTime = _this._startingPointerTime;
  20376. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20377. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20378. _this._previousButtonPressed = btn;
  20379. }
  20380. }
  20381. }
  20382. }
  20383. clickInfo.ignore = true;
  20384. cb(clickInfo, _this._currentPickResult);
  20385. };
  20386. this._spritePredicate = function (sprite) {
  20387. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20388. };
  20389. this._onPointerMove = function (evt) {
  20390. _this._updatePointerPosition(evt);
  20391. // PreObservable support
  20392. if (_this.onPrePointerObservable.hasObservers()) {
  20393. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20394. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20395. _this.onPrePointerObservable.notifyObservers(pi, type);
  20396. if (pi.skipOnPointerObservable) {
  20397. return;
  20398. }
  20399. }
  20400. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20401. return;
  20402. }
  20403. if (!_this.pointerMovePredicate) {
  20404. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20405. }
  20406. // Meshes
  20407. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20408. _this._processPointerMove(pickResult, evt);
  20409. };
  20410. this._onPointerDown = function (evt) {
  20411. _this._totalPointersPressed++;
  20412. _this._pickedDownMesh = null;
  20413. _this._meshPickProceed = false;
  20414. _this._updatePointerPosition(evt);
  20415. if (_this.preventDefaultOnPointerDown && canvas) {
  20416. evt.preventDefault();
  20417. canvas.focus();
  20418. }
  20419. // PreObservable support
  20420. if (_this.onPrePointerObservable.hasObservers()) {
  20421. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20422. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20423. _this.onPrePointerObservable.notifyObservers(pi, type);
  20424. if (pi.skipOnPointerObservable) {
  20425. return;
  20426. }
  20427. }
  20428. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20429. return;
  20430. }
  20431. _this._startingPointerPosition.x = _this._pointerX;
  20432. _this._startingPointerPosition.y = _this._pointerY;
  20433. _this._startingPointerTime = new Date().getTime();
  20434. if (!_this.pointerDownPredicate) {
  20435. _this.pointerDownPredicate = function (mesh) {
  20436. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20437. };
  20438. }
  20439. // Meshes
  20440. _this._pickedDownMesh = null;
  20441. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20442. _this._processPointerDown(pickResult, evt);
  20443. // Sprites
  20444. _this._pickedDownSprite = null;
  20445. if (_this.spriteManagers.length > 0) {
  20446. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20447. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20448. if (pickResult.pickedSprite.actionManager) {
  20449. _this._pickedDownSprite = pickResult.pickedSprite;
  20450. switch (evt.button) {
  20451. case 0:
  20452. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20453. break;
  20454. case 1:
  20455. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20456. break;
  20457. case 2:
  20458. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20459. break;
  20460. }
  20461. if (pickResult.pickedSprite.actionManager) {
  20462. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20463. }
  20464. }
  20465. }
  20466. }
  20467. };
  20468. this._onPointerUp = function (evt) {
  20469. if (_this._totalPointersPressed === 0) {
  20470. return; // So we need to test it the pointer down was pressed before.
  20471. }
  20472. _this._totalPointersPressed--;
  20473. _this._pickedUpMesh = null;
  20474. _this._meshPickProceed = false;
  20475. _this._updatePointerPosition(evt);
  20476. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20477. // PreObservable support
  20478. if (_this.onPrePointerObservable.hasObservers()) {
  20479. if (!clickInfo.ignore) {
  20480. if (!clickInfo.hasSwiped) {
  20481. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20482. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20483. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20484. _this.onPrePointerObservable.notifyObservers(pi, type);
  20485. if (pi.skipOnPointerObservable) {
  20486. return;
  20487. }
  20488. }
  20489. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20490. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20491. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20492. _this.onPrePointerObservable.notifyObservers(pi, type);
  20493. if (pi.skipOnPointerObservable) {
  20494. return;
  20495. }
  20496. }
  20497. }
  20498. }
  20499. else {
  20500. var type = BABYLON.PointerEventTypes.POINTERUP;
  20501. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20502. _this.onPrePointerObservable.notifyObservers(pi, type);
  20503. if (pi.skipOnPointerObservable) {
  20504. return;
  20505. }
  20506. }
  20507. }
  20508. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20509. return;
  20510. }
  20511. if (!_this.pointerUpPredicate) {
  20512. _this.pointerUpPredicate = function (mesh) {
  20513. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20514. };
  20515. }
  20516. // Meshes
  20517. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20518. _this._initActionManager(null, clickInfo);
  20519. }
  20520. if (!pickResult) {
  20521. pickResult = _this._currentPickResult;
  20522. }
  20523. _this._processPointerUp(pickResult, evt, clickInfo);
  20524. // Sprites
  20525. if (_this.spriteManagers.length > 0) {
  20526. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20527. if (spritePickResult) {
  20528. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20529. if (spritePickResult.pickedSprite.actionManager) {
  20530. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20531. if (spritePickResult.pickedSprite.actionManager) {
  20532. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20533. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20534. }
  20535. }
  20536. }
  20537. }
  20538. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20539. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20540. }
  20541. }
  20542. }
  20543. _this._previousPickResult = _this._currentPickResult;
  20544. });
  20545. };
  20546. this._onKeyDown = function (evt) {
  20547. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20548. if (_this.onPreKeyboardObservable.hasObservers()) {
  20549. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20550. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20551. if (pi.skipOnPointerObservable) {
  20552. return;
  20553. }
  20554. }
  20555. if (_this.onKeyboardObservable.hasObservers()) {
  20556. var pi = new BABYLON.KeyboardInfo(type, evt);
  20557. _this.onKeyboardObservable.notifyObservers(pi, type);
  20558. }
  20559. if (_this.actionManager) {
  20560. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20561. }
  20562. };
  20563. this._onKeyUp = function (evt) {
  20564. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20565. if (_this.onPreKeyboardObservable.hasObservers()) {
  20566. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20567. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20568. if (pi.skipOnPointerObservable) {
  20569. return;
  20570. }
  20571. }
  20572. if (_this.onKeyboardObservable.hasObservers()) {
  20573. var pi = new BABYLON.KeyboardInfo(type, evt);
  20574. _this.onKeyboardObservable.notifyObservers(pi, type);
  20575. }
  20576. if (_this.actionManager) {
  20577. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20578. }
  20579. };
  20580. var engine = this.getEngine();
  20581. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20582. if (!canvas) {
  20583. return;
  20584. }
  20585. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20586. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20587. });
  20588. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20589. if (!canvas) {
  20590. return;
  20591. }
  20592. canvas.removeEventListener("keydown", _this._onKeyDown);
  20593. canvas.removeEventListener("keyup", _this._onKeyUp);
  20594. });
  20595. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20596. var canvas = this._engine.getRenderingCanvas();
  20597. if (!canvas) {
  20598. return;
  20599. }
  20600. if (attachMove) {
  20601. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20602. // Wheel
  20603. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20604. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20605. }
  20606. if (attachDown) {
  20607. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20608. }
  20609. if (attachUp) {
  20610. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20611. }
  20612. canvas.tabIndex = 1;
  20613. };
  20614. Scene.prototype.detachControl = function () {
  20615. var engine = this.getEngine();
  20616. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20617. var canvas = engine.getRenderingCanvas();
  20618. if (!canvas) {
  20619. return;
  20620. }
  20621. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20622. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20623. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20624. if (this._onCanvasBlurObserver) {
  20625. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20626. }
  20627. if (this._onCanvasFocusObserver) {
  20628. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20629. }
  20630. // Wheel
  20631. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20632. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20633. // Keyboard
  20634. canvas.removeEventListener("keydown", this._onKeyDown);
  20635. canvas.removeEventListener("keyup", this._onKeyUp);
  20636. // Observables
  20637. this.onKeyboardObservable.clear();
  20638. this.onPreKeyboardObservable.clear();
  20639. this.onPointerObservable.clear();
  20640. this.onPrePointerObservable.clear();
  20641. };
  20642. // Ready
  20643. Scene.prototype.isReady = function () {
  20644. if (this._isDisposed) {
  20645. return false;
  20646. }
  20647. if (this._pendingData.length > 0) {
  20648. return false;
  20649. }
  20650. var index;
  20651. // Geometries
  20652. for (index = 0; index < this._geometries.length; index++) {
  20653. var geometry = this._geometries[index];
  20654. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20655. return false;
  20656. }
  20657. }
  20658. // Meshes
  20659. for (index = 0; index < this.meshes.length; index++) {
  20660. var mesh = this.meshes[index];
  20661. if (!mesh.isEnabled()) {
  20662. continue;
  20663. }
  20664. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20665. continue;
  20666. }
  20667. if (!mesh.isReady()) {
  20668. return false;
  20669. }
  20670. var mat = mesh.material;
  20671. if (mat) {
  20672. if (!mat.isReady(mesh)) {
  20673. return false;
  20674. }
  20675. }
  20676. }
  20677. return true;
  20678. };
  20679. Scene.prototype.resetCachedMaterial = function () {
  20680. this._cachedMaterial = null;
  20681. this._cachedEffect = null;
  20682. this._cachedVisibility = null;
  20683. };
  20684. Scene.prototype.registerBeforeRender = function (func) {
  20685. this.onBeforeRenderObservable.add(func);
  20686. };
  20687. Scene.prototype.unregisterBeforeRender = function (func) {
  20688. this.onBeforeRenderObservable.removeCallback(func);
  20689. };
  20690. Scene.prototype.registerAfterRender = function (func) {
  20691. this.onAfterRenderObservable.add(func);
  20692. };
  20693. Scene.prototype.unregisterAfterRender = function (func) {
  20694. this.onAfterRenderObservable.removeCallback(func);
  20695. };
  20696. Scene.prototype._addPendingData = function (data) {
  20697. this._pendingData.push(data);
  20698. };
  20699. Scene.prototype._removePendingData = function (data) {
  20700. var wasLoading = this.isLoading;
  20701. var index = this._pendingData.indexOf(data);
  20702. if (index !== -1) {
  20703. this._pendingData.splice(index, 1);
  20704. }
  20705. if (wasLoading && !this.isLoading) {
  20706. this.onDataLoadedObservable.notifyObservers(this);
  20707. }
  20708. };
  20709. Scene.prototype.getWaitingItemsCount = function () {
  20710. return this._pendingData.length;
  20711. };
  20712. Object.defineProperty(Scene.prototype, "isLoading", {
  20713. get: function () {
  20714. return this._pendingData.length > 0;
  20715. },
  20716. enumerable: true,
  20717. configurable: true
  20718. });
  20719. /**
  20720. * Registers a function to be executed when the scene is ready.
  20721. * @param {Function} func - the function to be executed.
  20722. */
  20723. Scene.prototype.executeWhenReady = function (func) {
  20724. var _this = this;
  20725. this.onReadyObservable.add(func);
  20726. if (this._executeWhenReadyTimeoutId !== -1) {
  20727. return;
  20728. }
  20729. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20730. _this._checkIsReady();
  20731. }, 150);
  20732. };
  20733. Scene.prototype._checkIsReady = function () {
  20734. var _this = this;
  20735. if (this.isReady()) {
  20736. this.onReadyObservable.notifyObservers(this);
  20737. this.onReadyObservable.clear();
  20738. this._executeWhenReadyTimeoutId = -1;
  20739. return;
  20740. }
  20741. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20742. _this._checkIsReady();
  20743. }, 150);
  20744. };
  20745. // Animations
  20746. /**
  20747. * Will start the animation sequence of a given target
  20748. * @param target - the target
  20749. * @param {number} from - from which frame should animation start
  20750. * @param {number} to - till which frame should animation run.
  20751. * @param {boolean} [loop] - should the animation loop
  20752. * @param {number} [speedRatio] - the speed in which to run the animation
  20753. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20754. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20755. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20756. * See BABYLON.Animatable
  20757. */
  20758. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20759. if (speedRatio === void 0) { speedRatio = 1.0; }
  20760. if (from > to && speedRatio > 0) {
  20761. speedRatio *= -1;
  20762. }
  20763. this.stopAnimation(target);
  20764. if (!animatable) {
  20765. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20766. }
  20767. // Local animations
  20768. if (target.animations) {
  20769. animatable.appendAnimations(target, target.animations);
  20770. }
  20771. // Children animations
  20772. if (target.getAnimatables) {
  20773. var animatables = target.getAnimatables();
  20774. for (var index = 0; index < animatables.length; index++) {
  20775. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20776. }
  20777. }
  20778. animatable.reset();
  20779. return animatable;
  20780. };
  20781. /**
  20782. * Begin a new animation on a given node
  20783. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20784. * @param {BABYLON.Animation[]} defines the list of animations to start
  20785. * @param {number} from defines the initial value
  20786. * @param {number} to defines the final value
  20787. * @param {boolean} loop defines if you want animation to loop (off by default)
  20788. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20789. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20790. * @returns the list of created animatables
  20791. */
  20792. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20793. if (speedRatio === undefined) {
  20794. speedRatio = 1.0;
  20795. }
  20796. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20797. return animatable;
  20798. };
  20799. /**
  20800. * Begin a new animation on a given node and its hierarchy
  20801. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20802. * @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.
  20803. * @param {BABYLON.Animation[]} defines the list of animations to start
  20804. * @param {number} from defines the initial value
  20805. * @param {number} to defines the final value
  20806. * @param {boolean} loop defines if you want animation to loop (off by default)
  20807. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20808. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20809. * @returns the list of animatables created for all nodes
  20810. */
  20811. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20812. var children = target.getDescendants(directDescendantsOnly);
  20813. var result = [];
  20814. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20815. var child = children_1[_i];
  20816. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20817. }
  20818. return result;
  20819. };
  20820. Scene.prototype.getAnimatableByTarget = function (target) {
  20821. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20822. if (this._activeAnimatables[index].target === target) {
  20823. return this._activeAnimatables[index];
  20824. }
  20825. }
  20826. return null;
  20827. };
  20828. Object.defineProperty(Scene.prototype, "animatables", {
  20829. get: function () {
  20830. return this._activeAnimatables;
  20831. },
  20832. enumerable: true,
  20833. configurable: true
  20834. });
  20835. /**
  20836. * Will stop the animation of the given target
  20837. * @param target - the target
  20838. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20839. * @see beginAnimation
  20840. */
  20841. Scene.prototype.stopAnimation = function (target, animationName) {
  20842. var animatable = this.getAnimatableByTarget(target);
  20843. if (animatable) {
  20844. animatable.stop(animationName);
  20845. }
  20846. };
  20847. /**
  20848. * Stops and removes all animations that have been applied to the scene
  20849. */
  20850. Scene.prototype.stopAllAnimations = function () {
  20851. if (this._activeAnimatables) {
  20852. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20853. this._activeAnimatables[i].stop();
  20854. }
  20855. this._activeAnimatables = [];
  20856. }
  20857. };
  20858. Scene.prototype._animate = function () {
  20859. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20860. return;
  20861. }
  20862. // Getting time
  20863. var now = BABYLON.Tools.Now;
  20864. if (!this._animationTimeLast) {
  20865. if (this._pendingData.length > 0) {
  20866. return;
  20867. }
  20868. this._animationTimeLast = now;
  20869. }
  20870. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20871. this._animationTime += deltaTime;
  20872. this._animationTimeLast = now;
  20873. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20874. this._activeAnimatables[index]._animate(this._animationTime);
  20875. }
  20876. };
  20877. // Matrix
  20878. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20879. this._useAlternateCameraConfiguration = active;
  20880. };
  20881. Scene.prototype.getViewMatrix = function () {
  20882. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20883. };
  20884. Scene.prototype.getProjectionMatrix = function () {
  20885. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20886. };
  20887. Scene.prototype.getTransformMatrix = function () {
  20888. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20889. };
  20890. Scene.prototype.setTransformMatrix = function (view, projection) {
  20891. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20892. return;
  20893. }
  20894. this._viewUpdateFlag = view.updateFlag;
  20895. this._projectionUpdateFlag = projection.updateFlag;
  20896. this._viewMatrix = view;
  20897. this._projectionMatrix = projection;
  20898. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20899. // Update frustum
  20900. if (!this._frustumPlanes) {
  20901. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20902. }
  20903. else {
  20904. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20905. }
  20906. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20907. var otherCamera = this.activeCamera._alternateCamera;
  20908. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20909. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20910. }
  20911. if (this._sceneUbo.useUbo) {
  20912. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20913. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20914. this._sceneUbo.update();
  20915. }
  20916. };
  20917. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20918. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20919. return;
  20920. }
  20921. this._alternateViewUpdateFlag = view.updateFlag;
  20922. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20923. this._alternateViewMatrix = view;
  20924. this._alternateProjectionMatrix = projection;
  20925. if (!this._alternateTransformMatrix) {
  20926. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20927. }
  20928. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20929. if (!this._alternateSceneUbo) {
  20930. this._createAlternateUbo();
  20931. }
  20932. if (this._alternateSceneUbo.useUbo) {
  20933. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  20934. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  20935. this._alternateSceneUbo.update();
  20936. }
  20937. };
  20938. Scene.prototype.getSceneUniformBuffer = function () {
  20939. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  20940. };
  20941. // Methods
  20942. Scene.prototype.getUniqueId = function () {
  20943. var result = Scene._uniqueIdCounter;
  20944. Scene._uniqueIdCounter++;
  20945. return result;
  20946. };
  20947. Scene.prototype.addMesh = function (newMesh) {
  20948. this.meshes.push(newMesh);
  20949. //notify the collision coordinator
  20950. if (this.collisionCoordinator) {
  20951. this.collisionCoordinator.onMeshAdded(newMesh);
  20952. }
  20953. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20954. };
  20955. Scene.prototype.removeMesh = function (toRemove) {
  20956. var index = this.meshes.indexOf(toRemove);
  20957. if (index !== -1) {
  20958. // Remove from the scene if mesh found
  20959. this.meshes.splice(index, 1);
  20960. }
  20961. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20962. return index;
  20963. };
  20964. Scene.prototype.addTransformNode = function (newTransformNode) {
  20965. this.transformNodes.push(newTransformNode);
  20966. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  20967. };
  20968. Scene.prototype.removeTransformNode = function (toRemove) {
  20969. var index = this.transformNodes.indexOf(toRemove);
  20970. if (index !== -1) {
  20971. // Remove from the scene if found
  20972. this.transformNodes.splice(index, 1);
  20973. }
  20974. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  20975. return index;
  20976. };
  20977. Scene.prototype.removeSkeleton = function (toRemove) {
  20978. var index = this.skeletons.indexOf(toRemove);
  20979. if (index !== -1) {
  20980. // Remove from the scene if found
  20981. this.skeletons.splice(index, 1);
  20982. }
  20983. return index;
  20984. };
  20985. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  20986. var index = this.morphTargetManagers.indexOf(toRemove);
  20987. if (index !== -1) {
  20988. // Remove from the scene if found
  20989. this.morphTargetManagers.splice(index, 1);
  20990. }
  20991. return index;
  20992. };
  20993. Scene.prototype.removeLight = function (toRemove) {
  20994. var index = this.lights.indexOf(toRemove);
  20995. if (index !== -1) {
  20996. // Remove from meshes
  20997. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  20998. var mesh = _a[_i];
  20999. mesh._removeLightSource(toRemove);
  21000. }
  21001. // Remove from the scene if mesh found
  21002. this.lights.splice(index, 1);
  21003. this.sortLightsByPriority();
  21004. }
  21005. this.onLightRemovedObservable.notifyObservers(toRemove);
  21006. return index;
  21007. };
  21008. Scene.prototype.removeCamera = function (toRemove) {
  21009. var index = this.cameras.indexOf(toRemove);
  21010. if (index !== -1) {
  21011. // Remove from the scene if mesh found
  21012. this.cameras.splice(index, 1);
  21013. }
  21014. // Remove from activeCameras
  21015. var index2 = this.activeCameras.indexOf(toRemove);
  21016. if (index2 !== -1) {
  21017. // Remove from the scene if mesh found
  21018. this.activeCameras.splice(index2, 1);
  21019. }
  21020. // Reset the activeCamera
  21021. if (this.activeCamera === toRemove) {
  21022. if (this.cameras.length > 0) {
  21023. this.activeCamera = this.cameras[0];
  21024. }
  21025. else {
  21026. this.activeCamera = null;
  21027. }
  21028. }
  21029. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21030. return index;
  21031. };
  21032. Scene.prototype.addLight = function (newLight) {
  21033. this.lights.push(newLight);
  21034. this.sortLightsByPriority();
  21035. // Add light to all meshes (To support if the light is removed and then readded)
  21036. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21037. var mesh = _a[_i];
  21038. if (mesh._lightSources.indexOf(newLight) === -1) {
  21039. mesh._lightSources.push(newLight);
  21040. mesh._resyncLightSources();
  21041. }
  21042. }
  21043. this.onNewLightAddedObservable.notifyObservers(newLight);
  21044. };
  21045. Scene.prototype.sortLightsByPriority = function () {
  21046. if (this.requireLightSorting) {
  21047. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21048. }
  21049. };
  21050. Scene.prototype.addCamera = function (newCamera) {
  21051. this.cameras.push(newCamera);
  21052. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21053. };
  21054. /**
  21055. * Switch active camera
  21056. * @param {Camera} newCamera - new active camera
  21057. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21058. */
  21059. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21060. if (attachControl === void 0) { attachControl = true; }
  21061. var canvas = this._engine.getRenderingCanvas();
  21062. if (!canvas) {
  21063. return;
  21064. }
  21065. if (this.activeCamera) {
  21066. this.activeCamera.detachControl(canvas);
  21067. }
  21068. this.activeCamera = newCamera;
  21069. if (attachControl) {
  21070. newCamera.attachControl(canvas);
  21071. }
  21072. };
  21073. /**
  21074. * sets the active camera of the scene using its ID
  21075. * @param {string} id - the camera's ID
  21076. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21077. * @see activeCamera
  21078. */
  21079. Scene.prototype.setActiveCameraByID = function (id) {
  21080. var camera = this.getCameraByID(id);
  21081. if (camera) {
  21082. this.activeCamera = camera;
  21083. return camera;
  21084. }
  21085. return null;
  21086. };
  21087. /**
  21088. * sets the active camera of the scene using its name
  21089. * @param {string} name - the camera's name
  21090. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21091. * @see activeCamera
  21092. */
  21093. Scene.prototype.setActiveCameraByName = function (name) {
  21094. var camera = this.getCameraByName(name);
  21095. if (camera) {
  21096. this.activeCamera = camera;
  21097. return camera;
  21098. }
  21099. return null;
  21100. };
  21101. /**
  21102. * get an animation group using its name
  21103. * @param {string} the material's name
  21104. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21105. */
  21106. Scene.prototype.getAnimationGroupByName = function (name) {
  21107. for (var index = 0; index < this.animationGroups.length; index++) {
  21108. if (this.animationGroups[index].name === name) {
  21109. return this.animationGroups[index];
  21110. }
  21111. }
  21112. return null;
  21113. };
  21114. /**
  21115. * get a material using its id
  21116. * @param {string} the material's ID
  21117. * @return {BABYLON.Material|null} the material or null if none found.
  21118. */
  21119. Scene.prototype.getMaterialByID = function (id) {
  21120. for (var index = 0; index < this.materials.length; index++) {
  21121. if (this.materials[index].id === id) {
  21122. return this.materials[index];
  21123. }
  21124. }
  21125. return null;
  21126. };
  21127. /**
  21128. * get a material using its name
  21129. * @param {string} the material's name
  21130. * @return {BABYLON.Material|null} the material or null if none found.
  21131. */
  21132. Scene.prototype.getMaterialByName = function (name) {
  21133. for (var index = 0; index < this.materials.length; index++) {
  21134. if (this.materials[index].name === name) {
  21135. return this.materials[index];
  21136. }
  21137. }
  21138. return null;
  21139. };
  21140. Scene.prototype.getLensFlareSystemByName = function (name) {
  21141. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21142. if (this.lensFlareSystems[index].name === name) {
  21143. return this.lensFlareSystems[index];
  21144. }
  21145. }
  21146. return null;
  21147. };
  21148. Scene.prototype.getLensFlareSystemByID = function (id) {
  21149. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21150. if (this.lensFlareSystems[index].id === id) {
  21151. return this.lensFlareSystems[index];
  21152. }
  21153. }
  21154. return null;
  21155. };
  21156. Scene.prototype.getCameraByID = function (id) {
  21157. for (var index = 0; index < this.cameras.length; index++) {
  21158. if (this.cameras[index].id === id) {
  21159. return this.cameras[index];
  21160. }
  21161. }
  21162. return null;
  21163. };
  21164. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21165. for (var index = 0; index < this.cameras.length; index++) {
  21166. if (this.cameras[index].uniqueId === uniqueId) {
  21167. return this.cameras[index];
  21168. }
  21169. }
  21170. return null;
  21171. };
  21172. /**
  21173. * get a camera using its name
  21174. * @param {string} the camera's name
  21175. * @return {BABYLON.Camera|null} the camera or null if none found.
  21176. */
  21177. Scene.prototype.getCameraByName = function (name) {
  21178. for (var index = 0; index < this.cameras.length; index++) {
  21179. if (this.cameras[index].name === name) {
  21180. return this.cameras[index];
  21181. }
  21182. }
  21183. return null;
  21184. };
  21185. /**
  21186. * get a bone using its id
  21187. * @param {string} the bone's id
  21188. * @return {BABYLON.Bone|null} the bone or null if not found
  21189. */
  21190. Scene.prototype.getBoneByID = function (id) {
  21191. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21192. var skeleton = this.skeletons[skeletonIndex];
  21193. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21194. if (skeleton.bones[boneIndex].id === id) {
  21195. return skeleton.bones[boneIndex];
  21196. }
  21197. }
  21198. }
  21199. return null;
  21200. };
  21201. /**
  21202. * get a bone using its id
  21203. * @param {string} the bone's name
  21204. * @return {BABYLON.Bone|null} the bone or null if not found
  21205. */
  21206. Scene.prototype.getBoneByName = function (name) {
  21207. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21208. var skeleton = this.skeletons[skeletonIndex];
  21209. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21210. if (skeleton.bones[boneIndex].name === name) {
  21211. return skeleton.bones[boneIndex];
  21212. }
  21213. }
  21214. }
  21215. return null;
  21216. };
  21217. /**
  21218. * get a light node using its name
  21219. * @param {string} the light's name
  21220. * @return {BABYLON.Light|null} the light or null if none found.
  21221. */
  21222. Scene.prototype.getLightByName = function (name) {
  21223. for (var index = 0; index < this.lights.length; index++) {
  21224. if (this.lights[index].name === name) {
  21225. return this.lights[index];
  21226. }
  21227. }
  21228. return null;
  21229. };
  21230. /**
  21231. * get a light node using its ID
  21232. * @param {string} the light's id
  21233. * @return {BABYLON.Light|null} the light or null if none found.
  21234. */
  21235. Scene.prototype.getLightByID = function (id) {
  21236. for (var index = 0; index < this.lights.length; index++) {
  21237. if (this.lights[index].id === id) {
  21238. return this.lights[index];
  21239. }
  21240. }
  21241. return null;
  21242. };
  21243. /**
  21244. * get a light node using its scene-generated unique ID
  21245. * @param {number} the light's unique id
  21246. * @return {BABYLON.Light|null} the light or null if none found.
  21247. */
  21248. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21249. for (var index = 0; index < this.lights.length; index++) {
  21250. if (this.lights[index].uniqueId === uniqueId) {
  21251. return this.lights[index];
  21252. }
  21253. }
  21254. return null;
  21255. };
  21256. /**
  21257. * get a particle system by id
  21258. * @param id {number} the particle system id
  21259. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21260. */
  21261. Scene.prototype.getParticleSystemByID = function (id) {
  21262. for (var index = 0; index < this.particleSystems.length; index++) {
  21263. if (this.particleSystems[index].id === id) {
  21264. return this.particleSystems[index];
  21265. }
  21266. }
  21267. return null;
  21268. };
  21269. /**
  21270. * get a geometry using its ID
  21271. * @param {string} the geometry's id
  21272. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21273. */
  21274. Scene.prototype.getGeometryByID = function (id) {
  21275. for (var index = 0; index < this._geometries.length; index++) {
  21276. if (this._geometries[index].id === id) {
  21277. return this._geometries[index];
  21278. }
  21279. }
  21280. return null;
  21281. };
  21282. /**
  21283. * add a new geometry to this scene.
  21284. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21285. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21286. * @return {boolean} was the geometry added or not
  21287. */
  21288. Scene.prototype.pushGeometry = function (geometry, force) {
  21289. if (!force && this.getGeometryByID(geometry.id)) {
  21290. return false;
  21291. }
  21292. this._geometries.push(geometry);
  21293. //notify the collision coordinator
  21294. if (this.collisionCoordinator) {
  21295. this.collisionCoordinator.onGeometryAdded(geometry);
  21296. }
  21297. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21298. return true;
  21299. };
  21300. /**
  21301. * Removes an existing geometry
  21302. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21303. * @return {boolean} was the geometry removed or not
  21304. */
  21305. Scene.prototype.removeGeometry = function (geometry) {
  21306. var index = this._geometries.indexOf(geometry);
  21307. if (index > -1) {
  21308. this._geometries.splice(index, 1);
  21309. //notify the collision coordinator
  21310. if (this.collisionCoordinator) {
  21311. this.collisionCoordinator.onGeometryDeleted(geometry);
  21312. }
  21313. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21314. return true;
  21315. }
  21316. return false;
  21317. };
  21318. Scene.prototype.getGeometries = function () {
  21319. return this._geometries;
  21320. };
  21321. /**
  21322. * Get the first added mesh found of a given ID
  21323. * @param {string} id - the id to search for
  21324. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21325. */
  21326. Scene.prototype.getMeshByID = function (id) {
  21327. for (var index = 0; index < this.meshes.length; index++) {
  21328. if (this.meshes[index].id === id) {
  21329. return this.meshes[index];
  21330. }
  21331. }
  21332. return null;
  21333. };
  21334. Scene.prototype.getMeshesByID = function (id) {
  21335. return this.meshes.filter(function (m) {
  21336. return m.id === id;
  21337. });
  21338. };
  21339. /**
  21340. * Get the first added transform node found of a given ID
  21341. * @param {string} id - the id to search for
  21342. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21343. */
  21344. Scene.prototype.getTransformNodeByID = function (id) {
  21345. for (var index = 0; index < this.transformNodes.length; index++) {
  21346. if (this.transformNodes[index].id === id) {
  21347. return this.transformNodes[index];
  21348. }
  21349. }
  21350. return null;
  21351. };
  21352. Scene.prototype.getTransformNodesByID = function (id) {
  21353. return this.transformNodes.filter(function (m) {
  21354. return m.id === id;
  21355. });
  21356. };
  21357. /**
  21358. * Get a mesh with its auto-generated unique id
  21359. * @param {number} uniqueId - the unique id to search for
  21360. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21361. */
  21362. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21363. for (var index = 0; index < this.meshes.length; index++) {
  21364. if (this.meshes[index].uniqueId === uniqueId) {
  21365. return this.meshes[index];
  21366. }
  21367. }
  21368. return null;
  21369. };
  21370. /**
  21371. * Get a the last added mesh found of a given ID
  21372. * @param {string} id - the id to search for
  21373. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21374. */
  21375. Scene.prototype.getLastMeshByID = function (id) {
  21376. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21377. if (this.meshes[index].id === id) {
  21378. return this.meshes[index];
  21379. }
  21380. }
  21381. return null;
  21382. };
  21383. /**
  21384. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21385. * @param {string} id - the id to search for
  21386. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21387. */
  21388. Scene.prototype.getLastEntryByID = function (id) {
  21389. var index;
  21390. for (index = this.meshes.length - 1; index >= 0; index--) {
  21391. if (this.meshes[index].id === id) {
  21392. return this.meshes[index];
  21393. }
  21394. }
  21395. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21396. if (this.transformNodes[index].id === id) {
  21397. return this.transformNodes[index];
  21398. }
  21399. }
  21400. for (index = this.cameras.length - 1; index >= 0; index--) {
  21401. if (this.cameras[index].id === id) {
  21402. return this.cameras[index];
  21403. }
  21404. }
  21405. for (index = this.lights.length - 1; index >= 0; index--) {
  21406. if (this.lights[index].id === id) {
  21407. return this.lights[index];
  21408. }
  21409. }
  21410. return null;
  21411. };
  21412. Scene.prototype.getNodeByID = function (id) {
  21413. var mesh = this.getMeshByID(id);
  21414. if (mesh) {
  21415. return mesh;
  21416. }
  21417. var light = this.getLightByID(id);
  21418. if (light) {
  21419. return light;
  21420. }
  21421. var camera = this.getCameraByID(id);
  21422. if (camera) {
  21423. return camera;
  21424. }
  21425. var bone = this.getBoneByID(id);
  21426. return bone;
  21427. };
  21428. Scene.prototype.getNodeByName = function (name) {
  21429. var mesh = this.getMeshByName(name);
  21430. if (mesh) {
  21431. return mesh;
  21432. }
  21433. var light = this.getLightByName(name);
  21434. if (light) {
  21435. return light;
  21436. }
  21437. var camera = this.getCameraByName(name);
  21438. if (camera) {
  21439. return camera;
  21440. }
  21441. var bone = this.getBoneByName(name);
  21442. return bone;
  21443. };
  21444. Scene.prototype.getMeshByName = function (name) {
  21445. for (var index = 0; index < this.meshes.length; index++) {
  21446. if (this.meshes[index].name === name) {
  21447. return this.meshes[index];
  21448. }
  21449. }
  21450. return null;
  21451. };
  21452. Scene.prototype.getTransformNodeByName = function (name) {
  21453. for (var index = 0; index < this.transformNodes.length; index++) {
  21454. if (this.transformNodes[index].name === name) {
  21455. return this.transformNodes[index];
  21456. }
  21457. }
  21458. return null;
  21459. };
  21460. Scene.prototype.getSoundByName = function (name) {
  21461. var index;
  21462. if (BABYLON.AudioEngine) {
  21463. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21464. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21465. return this.mainSoundTrack.soundCollection[index];
  21466. }
  21467. }
  21468. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21469. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21470. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21471. return this.soundTracks[sdIndex].soundCollection[index];
  21472. }
  21473. }
  21474. }
  21475. }
  21476. return null;
  21477. };
  21478. Scene.prototype.getLastSkeletonByID = function (id) {
  21479. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21480. if (this.skeletons[index].id === id) {
  21481. return this.skeletons[index];
  21482. }
  21483. }
  21484. return null;
  21485. };
  21486. Scene.prototype.getSkeletonById = function (id) {
  21487. for (var index = 0; index < this.skeletons.length; index++) {
  21488. if (this.skeletons[index].id === id) {
  21489. return this.skeletons[index];
  21490. }
  21491. }
  21492. return null;
  21493. };
  21494. Scene.prototype.getSkeletonByName = function (name) {
  21495. for (var index = 0; index < this.skeletons.length; index++) {
  21496. if (this.skeletons[index].name === name) {
  21497. return this.skeletons[index];
  21498. }
  21499. }
  21500. return null;
  21501. };
  21502. Scene.prototype.getMorphTargetManagerById = function (id) {
  21503. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21504. if (this.morphTargetManagers[index].uniqueId === id) {
  21505. return this.morphTargetManagers[index];
  21506. }
  21507. }
  21508. return null;
  21509. };
  21510. Scene.prototype.isActiveMesh = function (mesh) {
  21511. return (this._activeMeshes.indexOf(mesh) !== -1);
  21512. };
  21513. /**
  21514. * Return a the first highlight layer of the scene with a given name.
  21515. * @param name The name of the highlight layer to look for.
  21516. * @return The highlight layer if found otherwise null.
  21517. */
  21518. Scene.prototype.getHighlightLayerByName = function (name) {
  21519. for (var index = 0; index < this.highlightLayers.length; index++) {
  21520. if (this.highlightLayers[index].name === name) {
  21521. return this.highlightLayers[index];
  21522. }
  21523. }
  21524. return null;
  21525. };
  21526. Object.defineProperty(Scene.prototype, "uid", {
  21527. /**
  21528. * Return a unique id as a string which can serve as an identifier for the scene
  21529. */
  21530. get: function () {
  21531. if (!this._uid) {
  21532. this._uid = BABYLON.Tools.RandomId();
  21533. }
  21534. return this._uid;
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. /**
  21540. * Add an externaly attached data from its key.
  21541. * This method call will fail and return false, if such key already exists.
  21542. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21543. * @param key the unique key that identifies the data
  21544. * @param data the data object to associate to the key for this Engine instance
  21545. * @return true if no such key were already present and the data was added successfully, false otherwise
  21546. */
  21547. Scene.prototype.addExternalData = function (key, data) {
  21548. if (!this._externalData) {
  21549. this._externalData = new BABYLON.StringDictionary();
  21550. }
  21551. return this._externalData.add(key, data);
  21552. };
  21553. /**
  21554. * Get an externaly attached data from its key
  21555. * @param key the unique key that identifies the data
  21556. * @return the associated data, if present (can be null), or undefined if not present
  21557. */
  21558. Scene.prototype.getExternalData = function (key) {
  21559. if (!this._externalData) {
  21560. return null;
  21561. }
  21562. return this._externalData.get(key);
  21563. };
  21564. /**
  21565. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21566. * @param key the unique key that identifies the data
  21567. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21568. * @return the associated data, can be null if the factory returned null.
  21569. */
  21570. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21571. if (!this._externalData) {
  21572. this._externalData = new BABYLON.StringDictionary();
  21573. }
  21574. return this._externalData.getOrAddWithFactory(key, factory);
  21575. };
  21576. /**
  21577. * Remove an externaly attached data from the Engine instance
  21578. * @param key the unique key that identifies the data
  21579. * @return true if the data was successfully removed, false if it doesn't exist
  21580. */
  21581. Scene.prototype.removeExternalData = function (key) {
  21582. return this._externalData.remove(key);
  21583. };
  21584. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21585. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21586. if (mesh.showSubMeshesBoundingBox) {
  21587. var boundingInfo = subMesh.getBoundingInfo();
  21588. if (boundingInfo !== null && boundingInfo !== undefined) {
  21589. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21590. }
  21591. }
  21592. var material = subMesh.getMaterial();
  21593. if (material !== null && material !== undefined) {
  21594. // Render targets
  21595. if (material.getRenderTargetTextures !== undefined) {
  21596. if (this._processedMaterials.indexOf(material) === -1) {
  21597. this._processedMaterials.push(material);
  21598. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21599. }
  21600. }
  21601. // Dispatch
  21602. this._activeIndices.addCount(subMesh.indexCount, false);
  21603. this._renderingManager.dispatch(subMesh, mesh, material);
  21604. }
  21605. }
  21606. };
  21607. Scene.prototype._isInIntermediateRendering = function () {
  21608. return this._intermediateRendering;
  21609. };
  21610. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21611. this._activeMeshCandidateProvider = provider;
  21612. };
  21613. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21614. return this._activeMeshCandidateProvider;
  21615. };
  21616. /**
  21617. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21618. */
  21619. Scene.prototype.freezeActiveMeshes = function () {
  21620. this._evaluateActiveMeshes();
  21621. this._activeMeshesFrozen = true;
  21622. return this;
  21623. };
  21624. /**
  21625. * Use this function to restart evaluating active meshes on every frame
  21626. */
  21627. Scene.prototype.unfreezeActiveMeshes = function () {
  21628. this._activeMeshesFrozen = false;
  21629. return this;
  21630. };
  21631. Scene.prototype._evaluateActiveMeshes = function () {
  21632. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21633. return;
  21634. }
  21635. if (!this.activeCamera) {
  21636. return;
  21637. }
  21638. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21639. this.activeCamera._activeMeshes.reset();
  21640. this._activeMeshes.reset();
  21641. this._renderingManager.reset();
  21642. this._processedMaterials.reset();
  21643. this._activeParticleSystems.reset();
  21644. this._activeSkeletons.reset();
  21645. this._softwareSkinnedMeshes.reset();
  21646. if (this._boundingBoxRenderer) {
  21647. this._boundingBoxRenderer.reset();
  21648. }
  21649. // Meshes
  21650. var meshes;
  21651. var len;
  21652. var checkIsEnabled = true;
  21653. // Determine mesh candidates
  21654. if (this._activeMeshCandidateProvider !== undefined) {
  21655. // Use _activeMeshCandidateProvider
  21656. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21657. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21658. if (meshes !== undefined) {
  21659. len = meshes.length;
  21660. }
  21661. else {
  21662. len = 0;
  21663. }
  21664. }
  21665. else if (this._selectionOctree !== undefined) {
  21666. // Octree
  21667. var selection = this._selectionOctree.select(this._frustumPlanes);
  21668. meshes = selection.data;
  21669. len = selection.length;
  21670. }
  21671. else {
  21672. // Full scene traversal
  21673. len = this.meshes.length;
  21674. meshes = this.meshes;
  21675. }
  21676. // Check each mesh
  21677. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21678. mesh = meshes[meshIndex];
  21679. if (mesh.isBlocked) {
  21680. continue;
  21681. }
  21682. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21683. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21684. continue;
  21685. }
  21686. mesh.computeWorldMatrix();
  21687. // Intersections
  21688. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21689. this._meshesForIntersections.pushNoDuplicate(mesh);
  21690. }
  21691. // Switch to current LOD
  21692. meshLOD = mesh.getLOD(this.activeCamera);
  21693. if (meshLOD === undefined || meshLOD === null) {
  21694. continue;
  21695. }
  21696. mesh._preActivate();
  21697. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21698. this._activeMeshes.push(mesh);
  21699. this.activeCamera._activeMeshes.push(mesh);
  21700. mesh._activate(this._renderId);
  21701. if (meshLOD !== mesh) {
  21702. meshLOD._activate(this._renderId);
  21703. }
  21704. this._activeMesh(mesh, meshLOD);
  21705. }
  21706. }
  21707. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21708. // Particle systems
  21709. if (this.particlesEnabled) {
  21710. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21711. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21712. var particleSystem = this.particleSystems[particleIndex];
  21713. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21714. continue;
  21715. }
  21716. var emitter = particleSystem.emitter;
  21717. if (!emitter.position || emitter.isEnabled()) {
  21718. this._activeParticleSystems.push(particleSystem);
  21719. particleSystem.animate();
  21720. this._renderingManager.dispatchParticles(particleSystem);
  21721. }
  21722. }
  21723. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21724. }
  21725. };
  21726. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21727. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21728. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21729. mesh.skeleton.prepare();
  21730. }
  21731. if (!mesh.computeBonesUsingShaders) {
  21732. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21733. }
  21734. }
  21735. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21736. var boundingInfo = sourceMesh.getBoundingInfo();
  21737. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21738. }
  21739. if (mesh !== undefined && mesh !== null
  21740. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21741. // Submeshes Octrees
  21742. var len;
  21743. var subMeshes;
  21744. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21745. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21746. len = intersections.length;
  21747. subMeshes = intersections.data;
  21748. }
  21749. else {
  21750. subMeshes = mesh.subMeshes;
  21751. len = subMeshes.length;
  21752. }
  21753. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21754. subMesh = subMeshes[subIndex];
  21755. this._evaluateSubMesh(subMesh, mesh);
  21756. }
  21757. }
  21758. };
  21759. Scene.prototype.updateTransformMatrix = function (force) {
  21760. if (!this.activeCamera) {
  21761. return;
  21762. }
  21763. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21764. };
  21765. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21766. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21767. };
  21768. Scene.prototype._renderForCamera = function (camera) {
  21769. if (camera && camera._skipRendering) {
  21770. return;
  21771. }
  21772. var engine = this._engine;
  21773. this.activeCamera = camera;
  21774. if (!this.activeCamera)
  21775. throw new Error("Active camera not set");
  21776. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21777. // Viewport
  21778. engine.setViewport(this.activeCamera.viewport);
  21779. // Camera
  21780. this.resetCachedMaterial();
  21781. this._renderId++;
  21782. this.activeCamera.update();
  21783. this.updateTransformMatrix();
  21784. if (camera._alternateCamera) {
  21785. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21786. this._alternateRendering = true;
  21787. }
  21788. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21789. // Meshes
  21790. this._evaluateActiveMeshes();
  21791. // Software skinning
  21792. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21793. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21794. mesh.applySkeleton(mesh.skeleton);
  21795. }
  21796. // Render targets
  21797. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21798. var needsRestoreFrameBuffer = false;
  21799. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21800. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21801. }
  21802. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21803. this._intermediateRendering = true;
  21804. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21805. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21806. var renderTarget = this._renderTargets.data[renderIndex];
  21807. if (renderTarget._shouldRender()) {
  21808. this._renderId++;
  21809. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21810. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21811. }
  21812. }
  21813. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21814. this._intermediateRendering = false;
  21815. this._renderId++;
  21816. needsRestoreFrameBuffer = true; // Restore back buffer
  21817. }
  21818. // Render HighlightLayer Texture
  21819. var stencilState = this._engine.getStencilBuffer();
  21820. var renderhighlights = false;
  21821. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21822. this._intermediateRendering = true;
  21823. for (var i = 0; i < this.highlightLayers.length; i++) {
  21824. var highlightLayer = this.highlightLayers[i];
  21825. if (highlightLayer.shouldRender() &&
  21826. (!highlightLayer.camera ||
  21827. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21828. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21829. renderhighlights = true;
  21830. var renderTarget = highlightLayer._mainTexture;
  21831. if (renderTarget._shouldRender()) {
  21832. this._renderId++;
  21833. renderTarget.render(false, false);
  21834. needsRestoreFrameBuffer = true;
  21835. }
  21836. }
  21837. }
  21838. this._intermediateRendering = false;
  21839. this._renderId++;
  21840. }
  21841. if (needsRestoreFrameBuffer) {
  21842. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21843. }
  21844. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21845. // Prepare Frame
  21846. this.postProcessManager._prepareFrame();
  21847. // Backgrounds
  21848. var layerIndex;
  21849. var layer;
  21850. if (this.layers.length) {
  21851. engine.setDepthBuffer(false);
  21852. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21853. layer = this.layers[layerIndex];
  21854. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21855. layer.render();
  21856. }
  21857. }
  21858. engine.setDepthBuffer(true);
  21859. }
  21860. // Activate HighlightLayer stencil
  21861. if (renderhighlights) {
  21862. this._engine.setStencilBuffer(true);
  21863. }
  21864. // Render
  21865. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21866. this._renderingManager.render(null, null, true, true);
  21867. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21868. // Restore HighlightLayer stencil
  21869. if (renderhighlights) {
  21870. this._engine.setStencilBuffer(stencilState);
  21871. }
  21872. // Bounding boxes
  21873. if (this._boundingBoxRenderer) {
  21874. this._boundingBoxRenderer.render();
  21875. }
  21876. // Lens flares
  21877. if (this.lensFlaresEnabled) {
  21878. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21879. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21880. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21881. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21882. lensFlareSystem.render();
  21883. }
  21884. }
  21885. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21886. }
  21887. // Foregrounds
  21888. if (this.layers.length) {
  21889. engine.setDepthBuffer(false);
  21890. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21891. layer = this.layers[layerIndex];
  21892. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21893. layer.render();
  21894. }
  21895. }
  21896. engine.setDepthBuffer(true);
  21897. }
  21898. // Highlight Layer
  21899. if (renderhighlights) {
  21900. engine.setDepthBuffer(false);
  21901. for (var i = 0; i < this.highlightLayers.length; i++) {
  21902. if (this.highlightLayers[i].shouldRender()) {
  21903. this.highlightLayers[i].render();
  21904. }
  21905. }
  21906. engine.setDepthBuffer(true);
  21907. }
  21908. // Finalize frame
  21909. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21910. // Reset some special arrays
  21911. this._renderTargets.reset();
  21912. this._alternateRendering = false;
  21913. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21914. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21915. };
  21916. Scene.prototype._processSubCameras = function (camera) {
  21917. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21918. this._renderForCamera(camera);
  21919. return;
  21920. }
  21921. // Update camera
  21922. if (this.activeCamera) {
  21923. this.activeCamera.update();
  21924. }
  21925. // rig cameras
  21926. for (var index = 0; index < camera._rigCameras.length; index++) {
  21927. this._renderForCamera(camera._rigCameras[index]);
  21928. }
  21929. this.activeCamera = camera;
  21930. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21931. };
  21932. Scene.prototype._checkIntersections = function () {
  21933. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21934. var sourceMesh = this._meshesForIntersections.data[index];
  21935. if (!sourceMesh.actionManager) {
  21936. continue;
  21937. }
  21938. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21939. var action = sourceMesh.actionManager.actions[actionIndex];
  21940. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21941. var parameters = action.getTriggerParameter();
  21942. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21943. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21944. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21945. if (areIntersecting && currentIntersectionInProgress === -1) {
  21946. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21947. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21948. sourceMesh._intersectionsInProgress.push(otherMesh);
  21949. }
  21950. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21951. sourceMesh._intersectionsInProgress.push(otherMesh);
  21952. }
  21953. }
  21954. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21955. //They intersected, and now they don't.
  21956. //is this trigger an exit trigger? execute an event.
  21957. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21958. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21959. }
  21960. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21961. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21962. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21963. }
  21964. }
  21965. }
  21966. }
  21967. }
  21968. };
  21969. Scene.prototype.render = function () {
  21970. if (this.isDisposed) {
  21971. return;
  21972. }
  21973. this._activeParticles.fetchNewFrame();
  21974. this._totalVertices.fetchNewFrame();
  21975. this._activeIndices.fetchNewFrame();
  21976. this._activeBones.fetchNewFrame();
  21977. this._meshesForIntersections.reset();
  21978. this.resetCachedMaterial();
  21979. this.onBeforeAnimationsObservable.notifyObservers(this);
  21980. // Actions
  21981. if (this.actionManager) {
  21982. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  21983. }
  21984. //Simplification Queue
  21985. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21986. this.simplificationQueue.executeNext();
  21987. }
  21988. if (this._engine.isDeterministicLockStep()) {
  21989. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  21990. var defaultFPS = (60.0 / 1000.0);
  21991. var defaultFrameTime = 1000 / 60; // frame time in MS
  21992. if (this._physicsEngine) {
  21993. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  21994. }
  21995. var stepsTaken = 0;
  21996. var maxSubSteps = this._engine.getLockstepMaxSteps();
  21997. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  21998. internalSteps = Math.min(internalSteps, maxSubSteps);
  21999. do {
  22000. this.onBeforeStepObservable.notifyObservers(this);
  22001. // Animations
  22002. this._animationRatio = defaultFrameTime * defaultFPS;
  22003. this._animate();
  22004. this.onAfterAnimationsObservable.notifyObservers(this);
  22005. // Physics
  22006. if (this._physicsEngine) {
  22007. this.onBeforePhysicsObservable.notifyObservers(this);
  22008. this._physicsEngine._step(defaultFrameTime / 1000);
  22009. this.onAfterPhysicsObservable.notifyObservers(this);
  22010. }
  22011. this.onAfterStepObservable.notifyObservers(this);
  22012. this._currentStepId++;
  22013. stepsTaken++;
  22014. deltaTime -= defaultFrameTime;
  22015. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22016. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22017. }
  22018. else {
  22019. // Animations
  22020. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22021. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22022. this._animate();
  22023. this.onAfterAnimationsObservable.notifyObservers(this);
  22024. // Physics
  22025. if (this._physicsEngine) {
  22026. this.onBeforePhysicsObservable.notifyObservers(this);
  22027. this._physicsEngine._step(deltaTime / 1000.0);
  22028. this.onAfterPhysicsObservable.notifyObservers(this);
  22029. }
  22030. }
  22031. // update gamepad manager
  22032. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22033. this._gamepadManager._checkGamepadsStatus();
  22034. }
  22035. // Before render
  22036. this.onBeforeRenderObservable.notifyObservers(this);
  22037. // Customs render targets
  22038. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22039. var engine = this.getEngine();
  22040. var currentActiveCamera = this.activeCamera;
  22041. if (this.renderTargetsEnabled) {
  22042. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22043. this._intermediateRendering = true;
  22044. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22045. var renderTarget = this.customRenderTargets[customIndex];
  22046. if (renderTarget._shouldRender()) {
  22047. this._renderId++;
  22048. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22049. if (!this.activeCamera)
  22050. throw new Error("Active camera not set");
  22051. // Viewport
  22052. engine.setViewport(this.activeCamera.viewport);
  22053. // Camera
  22054. this.updateTransformMatrix();
  22055. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22056. }
  22057. }
  22058. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22059. this._intermediateRendering = false;
  22060. this._renderId++;
  22061. }
  22062. // Restore back buffer
  22063. if (this.customRenderTargets.length > 0) {
  22064. engine.restoreDefaultFramebuffer();
  22065. }
  22066. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22067. this.activeCamera = currentActiveCamera;
  22068. // Procedural textures
  22069. if (this.proceduralTexturesEnabled) {
  22070. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22071. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22072. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22073. if (proceduralTexture._shouldRender()) {
  22074. proceduralTexture.render();
  22075. }
  22076. }
  22077. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22078. }
  22079. // Clear
  22080. if (this.autoClearDepthAndStencil || this.autoClear) {
  22081. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22082. }
  22083. // Shadows
  22084. if (this.shadowsEnabled) {
  22085. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22086. var light = this.lights[lightIndex];
  22087. var shadowGenerator = light.getShadowGenerator();
  22088. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22089. var shadowMap = (shadowGenerator.getShadowMap());
  22090. if (this.textures.indexOf(shadowMap) !== -1) {
  22091. this._renderTargets.push(shadowMap);
  22092. }
  22093. }
  22094. }
  22095. }
  22096. // Depth renderer
  22097. if (this._depthRenderer) {
  22098. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22099. }
  22100. // Geometry renderer
  22101. if (this._geometryBufferRenderer) {
  22102. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22103. }
  22104. // RenderPipeline
  22105. if (this._postProcessRenderPipelineManager) {
  22106. this._postProcessRenderPipelineManager.update();
  22107. }
  22108. // Multi-cameras?
  22109. if (this.activeCameras.length > 0) {
  22110. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22111. if (cameraIndex > 0) {
  22112. this._engine.clear(null, false, true, true);
  22113. }
  22114. this._processSubCameras(this.activeCameras[cameraIndex]);
  22115. }
  22116. }
  22117. else {
  22118. if (!this.activeCamera) {
  22119. throw new Error("No camera defined");
  22120. }
  22121. this._processSubCameras(this.activeCamera);
  22122. }
  22123. // Intersection checks
  22124. this._checkIntersections();
  22125. // Update the audio listener attached to the camera
  22126. if (BABYLON.AudioEngine) {
  22127. this._updateAudioParameters();
  22128. }
  22129. // After render
  22130. if (this.afterRender) {
  22131. this.afterRender();
  22132. }
  22133. this.onAfterRenderObservable.notifyObservers(this);
  22134. // Cleaning
  22135. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22136. var data = this._toBeDisposed.data[index];
  22137. if (data) {
  22138. data.dispose();
  22139. }
  22140. this._toBeDisposed[index] = null;
  22141. }
  22142. this._toBeDisposed.reset();
  22143. if (this.dumpNextRenderTargets) {
  22144. this.dumpNextRenderTargets = false;
  22145. }
  22146. this._activeBones.addCount(0, true);
  22147. this._activeIndices.addCount(0, true);
  22148. this._activeParticles.addCount(0, true);
  22149. };
  22150. Scene.prototype._updateAudioParameters = function () {
  22151. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22152. return;
  22153. }
  22154. var listeningCamera;
  22155. var audioEngine = BABYLON.Engine.audioEngine;
  22156. if (this.activeCameras.length > 0) {
  22157. listeningCamera = this.activeCameras[0];
  22158. }
  22159. else {
  22160. listeningCamera = this.activeCamera;
  22161. }
  22162. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22163. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22164. // for VR cameras
  22165. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22166. listeningCamera = listeningCamera.rigCameras[0];
  22167. }
  22168. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22169. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22170. cameraDirection.normalize();
  22171. // To avoid some errors on GearVR
  22172. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22173. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22174. }
  22175. var i;
  22176. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22177. var sound = this.mainSoundTrack.soundCollection[i];
  22178. if (sound.useCustomAttenuation) {
  22179. sound.updateDistanceFromListener();
  22180. }
  22181. }
  22182. for (i = 0; i < this.soundTracks.length; i++) {
  22183. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22184. sound = this.soundTracks[i].soundCollection[j];
  22185. if (sound.useCustomAttenuation) {
  22186. sound.updateDistanceFromListener();
  22187. }
  22188. }
  22189. }
  22190. }
  22191. };
  22192. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22193. // Audio
  22194. get: function () {
  22195. return this._audioEnabled;
  22196. },
  22197. set: function (value) {
  22198. this._audioEnabled = value;
  22199. if (BABYLON.AudioEngine) {
  22200. if (this._audioEnabled) {
  22201. this._enableAudio();
  22202. }
  22203. else {
  22204. this._disableAudio();
  22205. }
  22206. }
  22207. },
  22208. enumerable: true,
  22209. configurable: true
  22210. });
  22211. Scene.prototype._disableAudio = function () {
  22212. var i;
  22213. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22214. this.mainSoundTrack.soundCollection[i].pause();
  22215. }
  22216. for (i = 0; i < this.soundTracks.length; i++) {
  22217. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22218. this.soundTracks[i].soundCollection[j].pause();
  22219. }
  22220. }
  22221. };
  22222. Scene.prototype._enableAudio = function () {
  22223. var i;
  22224. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22225. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22226. this.mainSoundTrack.soundCollection[i].play();
  22227. }
  22228. }
  22229. for (i = 0; i < this.soundTracks.length; i++) {
  22230. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22231. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22232. this.soundTracks[i].soundCollection[j].play();
  22233. }
  22234. }
  22235. }
  22236. };
  22237. Object.defineProperty(Scene.prototype, "headphone", {
  22238. get: function () {
  22239. return this._headphone;
  22240. },
  22241. set: function (value) {
  22242. this._headphone = value;
  22243. if (BABYLON.AudioEngine) {
  22244. if (this._headphone) {
  22245. this._switchAudioModeForHeadphones();
  22246. }
  22247. else {
  22248. this._switchAudioModeForNormalSpeakers();
  22249. }
  22250. }
  22251. },
  22252. enumerable: true,
  22253. configurable: true
  22254. });
  22255. Scene.prototype._switchAudioModeForHeadphones = function () {
  22256. this.mainSoundTrack.switchPanningModelToHRTF();
  22257. for (var i = 0; i < this.soundTracks.length; i++) {
  22258. this.soundTracks[i].switchPanningModelToHRTF();
  22259. }
  22260. };
  22261. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22262. this.mainSoundTrack.switchPanningModelToEqualPower();
  22263. for (var i = 0; i < this.soundTracks.length; i++) {
  22264. this.soundTracks[i].switchPanningModelToEqualPower();
  22265. }
  22266. };
  22267. Scene.prototype.enableDepthRenderer = function () {
  22268. if (this._depthRenderer) {
  22269. return this._depthRenderer;
  22270. }
  22271. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22272. return this._depthRenderer;
  22273. };
  22274. Scene.prototype.disableDepthRenderer = function () {
  22275. if (!this._depthRenderer) {
  22276. return;
  22277. }
  22278. this._depthRenderer.dispose();
  22279. this._depthRenderer = null;
  22280. };
  22281. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22282. if (ratio === void 0) { ratio = 1; }
  22283. if (this._geometryBufferRenderer) {
  22284. return this._geometryBufferRenderer;
  22285. }
  22286. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22287. if (!this._geometryBufferRenderer.isSupported) {
  22288. this._geometryBufferRenderer = null;
  22289. }
  22290. return this._geometryBufferRenderer;
  22291. };
  22292. Scene.prototype.disableGeometryBufferRenderer = function () {
  22293. if (!this._geometryBufferRenderer) {
  22294. return;
  22295. }
  22296. this._geometryBufferRenderer.dispose();
  22297. this._geometryBufferRenderer = null;
  22298. };
  22299. Scene.prototype.freezeMaterials = function () {
  22300. for (var i = 0; i < this.materials.length; i++) {
  22301. this.materials[i].freeze();
  22302. }
  22303. };
  22304. Scene.prototype.unfreezeMaterials = function () {
  22305. for (var i = 0; i < this.materials.length; i++) {
  22306. this.materials[i].unfreeze();
  22307. }
  22308. };
  22309. Scene.prototype.dispose = function () {
  22310. this.beforeRender = null;
  22311. this.afterRender = null;
  22312. this.skeletons = [];
  22313. this.morphTargetManagers = [];
  22314. this.importedMeshesFiles = new Array();
  22315. this.stopAllAnimations();
  22316. this.resetCachedMaterial();
  22317. if (this._depthRenderer) {
  22318. this._depthRenderer.dispose();
  22319. }
  22320. if (this._gamepadManager) {
  22321. this._gamepadManager.dispose();
  22322. this._gamepadManager = null;
  22323. }
  22324. // Smart arrays
  22325. if (this.activeCamera) {
  22326. this.activeCamera._activeMeshes.dispose();
  22327. this.activeCamera = null;
  22328. }
  22329. this._activeMeshes.dispose();
  22330. this._renderingManager.dispose();
  22331. this._processedMaterials.dispose();
  22332. this._activeParticleSystems.dispose();
  22333. this._activeSkeletons.dispose();
  22334. this._softwareSkinnedMeshes.dispose();
  22335. this._renderTargets.dispose();
  22336. if (this._boundingBoxRenderer) {
  22337. this._boundingBoxRenderer.dispose();
  22338. }
  22339. this._meshesForIntersections.dispose();
  22340. this._toBeDisposed.dispose();
  22341. // Abort active requests
  22342. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22343. var request = _a[_i];
  22344. request.abort();
  22345. }
  22346. // Debug layer
  22347. if (this._debugLayer) {
  22348. this._debugLayer.hide();
  22349. }
  22350. // Events
  22351. this.onDisposeObservable.notifyObservers(this);
  22352. this.onDisposeObservable.clear();
  22353. this.onBeforeRenderObservable.clear();
  22354. this.onAfterRenderObservable.clear();
  22355. this.OnBeforeRenderTargetsRenderObservable.clear();
  22356. this.OnAfterRenderTargetsRenderObservable.clear();
  22357. this.onAfterStepObservable.clear();
  22358. this.onBeforeStepObservable.clear();
  22359. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22360. this.onAfterActiveMeshesEvaluationObservable.clear();
  22361. this.onBeforeParticlesRenderingObservable.clear();
  22362. this.onAfterParticlesRenderingObservable.clear();
  22363. this.onBeforeSpritesRenderingObservable.clear();
  22364. this.onAfterSpritesRenderingObservable.clear();
  22365. this.onBeforeDrawPhaseObservable.clear();
  22366. this.onAfterDrawPhaseObservable.clear();
  22367. this.onBeforePhysicsObservable.clear();
  22368. this.onAfterPhysicsObservable.clear();
  22369. this.onBeforeAnimationsObservable.clear();
  22370. this.onAfterAnimationsObservable.clear();
  22371. this.onDataLoadedObservable.clear();
  22372. this.detachControl();
  22373. // Release sounds & sounds tracks
  22374. if (BABYLON.AudioEngine) {
  22375. this.disposeSounds();
  22376. }
  22377. // VR Helper
  22378. if (this.VRHelper) {
  22379. this.VRHelper.dispose();
  22380. }
  22381. // Detach cameras
  22382. var canvas = this._engine.getRenderingCanvas();
  22383. if (canvas) {
  22384. var index;
  22385. for (index = 0; index < this.cameras.length; index++) {
  22386. this.cameras[index].detachControl(canvas);
  22387. }
  22388. }
  22389. // Release animation groups
  22390. while (this.animationGroups.length) {
  22391. this.animationGroups[0].dispose();
  22392. }
  22393. // Release lights
  22394. while (this.lights.length) {
  22395. this.lights[0].dispose();
  22396. }
  22397. // Release meshes
  22398. while (this.meshes.length) {
  22399. this.meshes[0].dispose(true);
  22400. }
  22401. while (this.transformNodes.length) {
  22402. this.removeTransformNode(this.transformNodes[0]);
  22403. }
  22404. // Release cameras
  22405. while (this.cameras.length) {
  22406. this.cameras[0].dispose();
  22407. }
  22408. // Release materials
  22409. if (this.defaultMaterial) {
  22410. this.defaultMaterial.dispose();
  22411. }
  22412. while (this.multiMaterials.length) {
  22413. this.multiMaterials[0].dispose();
  22414. }
  22415. while (this.materials.length) {
  22416. this.materials[0].dispose();
  22417. }
  22418. // Release particles
  22419. while (this.particleSystems.length) {
  22420. this.particleSystems[0].dispose();
  22421. }
  22422. // Release sprites
  22423. while (this.spriteManagers.length) {
  22424. this.spriteManagers[0].dispose();
  22425. }
  22426. // Release postProcesses
  22427. while (this.postProcesses.length) {
  22428. this.postProcesses[0].dispose();
  22429. }
  22430. // Release layers
  22431. while (this.layers.length) {
  22432. this.layers[0].dispose();
  22433. }
  22434. while (this.highlightLayers.length) {
  22435. this.highlightLayers[0].dispose();
  22436. }
  22437. // Release textures
  22438. while (this.textures.length) {
  22439. this.textures[0].dispose();
  22440. }
  22441. // Release UBO
  22442. this._sceneUbo.dispose();
  22443. if (this._alternateSceneUbo) {
  22444. this._alternateSceneUbo.dispose();
  22445. }
  22446. // Post-processes
  22447. this.postProcessManager.dispose();
  22448. if (this._postProcessRenderPipelineManager) {
  22449. this._postProcessRenderPipelineManager.dispose();
  22450. }
  22451. // Physics
  22452. if (this._physicsEngine) {
  22453. this.disablePhysicsEngine();
  22454. }
  22455. // Remove from engine
  22456. index = this._engine.scenes.indexOf(this);
  22457. if (index > -1) {
  22458. this._engine.scenes.splice(index, 1);
  22459. }
  22460. this._engine.wipeCaches(true);
  22461. this._isDisposed = true;
  22462. };
  22463. Object.defineProperty(Scene.prototype, "isDisposed", {
  22464. get: function () {
  22465. return this._isDisposed;
  22466. },
  22467. enumerable: true,
  22468. configurable: true
  22469. });
  22470. // Release sounds & sounds tracks
  22471. Scene.prototype.disposeSounds = function () {
  22472. if (!this._mainSoundTrack) {
  22473. return;
  22474. }
  22475. this.mainSoundTrack.dispose();
  22476. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22477. this.soundTracks[scIndex].dispose();
  22478. }
  22479. };
  22480. // Octrees
  22481. Scene.prototype.getWorldExtends = function () {
  22482. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22483. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22484. for (var index = 0; index < this.meshes.length; index++) {
  22485. var mesh = this.meshes[index];
  22486. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22487. continue;
  22488. }
  22489. mesh.computeWorldMatrix(true);
  22490. var boundingInfo = mesh.getBoundingInfo();
  22491. var minBox = boundingInfo.boundingBox.minimumWorld;
  22492. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22493. BABYLON.Tools.CheckExtends(minBox, min, max);
  22494. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22495. }
  22496. return {
  22497. min: min,
  22498. max: max
  22499. };
  22500. };
  22501. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22502. if (maxCapacity === void 0) { maxCapacity = 64; }
  22503. if (maxDepth === void 0) { maxDepth = 2; }
  22504. if (!this._selectionOctree) {
  22505. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22506. }
  22507. var worldExtends = this.getWorldExtends();
  22508. // Update octree
  22509. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22510. return this._selectionOctree;
  22511. };
  22512. // Picking
  22513. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22514. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22515. var result = BABYLON.Ray.Zero();
  22516. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22517. return result;
  22518. };
  22519. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22520. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22521. var engine = this._engine;
  22522. if (!camera) {
  22523. if (!this.activeCamera)
  22524. throw new Error("Active camera not set");
  22525. camera = this.activeCamera;
  22526. }
  22527. var cameraViewport = camera.viewport;
  22528. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22529. // Moving coordinates to local viewport world
  22530. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22531. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22532. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22533. return this;
  22534. };
  22535. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22536. var result = BABYLON.Ray.Zero();
  22537. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22538. return result;
  22539. };
  22540. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22541. if (!BABYLON.PickingInfo) {
  22542. return this;
  22543. }
  22544. var engine = this._engine;
  22545. if (!camera) {
  22546. if (!this.activeCamera)
  22547. throw new Error("Active camera not set");
  22548. camera = this.activeCamera;
  22549. }
  22550. var cameraViewport = camera.viewport;
  22551. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22552. var identity = BABYLON.Matrix.Identity();
  22553. // Moving coordinates to local viewport world
  22554. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22555. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22556. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22557. return this;
  22558. };
  22559. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22560. if (!BABYLON.PickingInfo) {
  22561. return null;
  22562. }
  22563. var pickingInfo = null;
  22564. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22565. var mesh = this.meshes[meshIndex];
  22566. if (predicate) {
  22567. if (!predicate(mesh)) {
  22568. continue;
  22569. }
  22570. }
  22571. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22572. continue;
  22573. }
  22574. var world = mesh.getWorldMatrix();
  22575. var ray = rayFunction(world);
  22576. var result = mesh.intersects(ray, fastCheck);
  22577. if (!result || !result.hit)
  22578. continue;
  22579. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22580. continue;
  22581. pickingInfo = result;
  22582. if (fastCheck) {
  22583. break;
  22584. }
  22585. }
  22586. return pickingInfo || new BABYLON.PickingInfo();
  22587. };
  22588. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22589. if (!BABYLON.PickingInfo) {
  22590. return null;
  22591. }
  22592. var pickingInfos = new Array();
  22593. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22594. var mesh = this.meshes[meshIndex];
  22595. if (predicate) {
  22596. if (!predicate(mesh)) {
  22597. continue;
  22598. }
  22599. }
  22600. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22601. continue;
  22602. }
  22603. var world = mesh.getWorldMatrix();
  22604. var ray = rayFunction(world);
  22605. var result = mesh.intersects(ray, false);
  22606. if (!result || !result.hit)
  22607. continue;
  22608. pickingInfos.push(result);
  22609. }
  22610. return pickingInfos;
  22611. };
  22612. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22613. if (!BABYLON.PickingInfo) {
  22614. return null;
  22615. }
  22616. var pickingInfo = null;
  22617. if (!camera) {
  22618. if (!this.activeCamera) {
  22619. return null;
  22620. }
  22621. camera = this.activeCamera;
  22622. }
  22623. if (this.spriteManagers.length > 0) {
  22624. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22625. var spriteManager = this.spriteManagers[spriteIndex];
  22626. if (!spriteManager.isPickable) {
  22627. continue;
  22628. }
  22629. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22630. if (!result || !result.hit)
  22631. continue;
  22632. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22633. continue;
  22634. pickingInfo = result;
  22635. if (fastCheck) {
  22636. break;
  22637. }
  22638. }
  22639. }
  22640. return pickingInfo || new BABYLON.PickingInfo();
  22641. };
  22642. /** Launch a ray to try to pick a mesh in the scene
  22643. * @param x position on screen
  22644. * @param y position on screen
  22645. * @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
  22646. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22647. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22648. */
  22649. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22650. var _this = this;
  22651. if (!BABYLON.PickingInfo) {
  22652. return null;
  22653. }
  22654. return this._internalPick(function (world) {
  22655. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22656. return _this._tempPickingRay;
  22657. }, predicate, fastCheck);
  22658. };
  22659. /** Launch a ray to try to pick a sprite in the scene
  22660. * @param x position on screen
  22661. * @param y position on screen
  22662. * @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
  22663. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22664. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22665. */
  22666. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22667. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22668. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22669. };
  22670. /** Use the given ray to pick a mesh in the scene
  22671. * @param ray The ray to use to pick meshes
  22672. * @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
  22673. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22674. */
  22675. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22676. var _this = this;
  22677. return this._internalPick(function (world) {
  22678. if (!_this._pickWithRayInverseMatrix) {
  22679. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22680. }
  22681. world.invertToRef(_this._pickWithRayInverseMatrix);
  22682. if (!_this._cachedRayForTransform) {
  22683. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22684. }
  22685. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22686. return _this._cachedRayForTransform;
  22687. }, predicate, fastCheck);
  22688. };
  22689. /**
  22690. * Launch a ray to try to pick a mesh in the scene
  22691. * @param x X position on screen
  22692. * @param y Y position on screen
  22693. * @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
  22694. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22695. */
  22696. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22697. var _this = this;
  22698. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22699. };
  22700. /**
  22701. * Launch a ray to try to pick a mesh in the scene
  22702. * @param ray Ray to use
  22703. * @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
  22704. */
  22705. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22706. var _this = this;
  22707. return this._internalMultiPick(function (world) {
  22708. if (!_this._pickWithRayInverseMatrix) {
  22709. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22710. }
  22711. world.invertToRef(_this._pickWithRayInverseMatrix);
  22712. if (!_this._cachedRayForTransform) {
  22713. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22714. }
  22715. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22716. return _this._cachedRayForTransform;
  22717. }, predicate);
  22718. };
  22719. Scene.prototype.setPointerOverMesh = function (mesh) {
  22720. if (this._pointerOverMesh === mesh) {
  22721. return;
  22722. }
  22723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22725. }
  22726. this._pointerOverMesh = mesh;
  22727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22729. }
  22730. };
  22731. Scene.prototype.getPointerOverMesh = function () {
  22732. return this._pointerOverMesh;
  22733. };
  22734. Scene.prototype.setPointerOverSprite = function (sprite) {
  22735. if (this._pointerOverSprite === sprite) {
  22736. return;
  22737. }
  22738. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22739. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22740. }
  22741. this._pointerOverSprite = sprite;
  22742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22744. }
  22745. };
  22746. Scene.prototype.getPointerOverSprite = function () {
  22747. return this._pointerOverSprite;
  22748. };
  22749. // Physics
  22750. Scene.prototype.getPhysicsEngine = function () {
  22751. return this._physicsEngine;
  22752. };
  22753. /**
  22754. * Enables physics to the current scene
  22755. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22756. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22757. * @return {boolean} was the physics engine initialized
  22758. */
  22759. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22760. if (gravity === void 0) { gravity = null; }
  22761. if (this._physicsEngine) {
  22762. return true;
  22763. }
  22764. try {
  22765. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22766. return true;
  22767. }
  22768. catch (e) {
  22769. BABYLON.Tools.Error(e.message);
  22770. return false;
  22771. }
  22772. };
  22773. Scene.prototype.disablePhysicsEngine = function () {
  22774. if (!this._physicsEngine) {
  22775. return;
  22776. }
  22777. this._physicsEngine.dispose();
  22778. this._physicsEngine = null;
  22779. };
  22780. Scene.prototype.isPhysicsEnabled = function () {
  22781. return this._physicsEngine !== undefined;
  22782. };
  22783. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22784. var mesh = compound.parts[0].mesh;
  22785. if (mesh.physicsImpostor) {
  22786. mesh.physicsImpostor.dispose();
  22787. mesh.physicsImpostor = null;
  22788. }
  22789. };
  22790. // Misc.
  22791. Scene.prototype._rebuildGeometries = function () {
  22792. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22793. var geometry = _a[_i];
  22794. geometry._rebuild();
  22795. }
  22796. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22797. var mesh = _c[_b];
  22798. mesh._rebuild();
  22799. }
  22800. if (this.postProcessManager) {
  22801. this.postProcessManager._rebuild();
  22802. }
  22803. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22804. var layer = _e[_d];
  22805. layer._rebuild();
  22806. }
  22807. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22808. var highlightLayer = _g[_f];
  22809. highlightLayer._rebuild();
  22810. }
  22811. if (this._boundingBoxRenderer) {
  22812. this._boundingBoxRenderer._rebuild();
  22813. }
  22814. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22815. var system = _j[_h];
  22816. system.rebuild();
  22817. }
  22818. if (this._postProcessRenderPipelineManager) {
  22819. this._postProcessRenderPipelineManager._rebuild();
  22820. }
  22821. };
  22822. Scene.prototype._rebuildTextures = function () {
  22823. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22824. var texture = _a[_i];
  22825. texture._rebuild();
  22826. }
  22827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22828. };
  22829. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22830. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22831. if (replace === void 0) { replace = false; }
  22832. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22833. // Dispose existing camera or light in replace mode.
  22834. if (replace) {
  22835. if (this.activeCamera) {
  22836. this.activeCamera.dispose();
  22837. this.activeCamera = null;
  22838. }
  22839. if (this.lights) {
  22840. for (var i = 0; i < this.lights.length; i++) {
  22841. this.lights[i].dispose();
  22842. }
  22843. }
  22844. }
  22845. // Light
  22846. if (this.lights.length === 0) {
  22847. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22848. }
  22849. // Camera
  22850. if (!this.activeCamera) {
  22851. var worldExtends = this.getWorldExtends();
  22852. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22853. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22854. var camera;
  22855. var radius = worldSize.length() * 1.5;
  22856. if (createArcRotateCamera) {
  22857. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22858. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22859. arcRotateCamera.wheelPrecision = 100 / radius;
  22860. camera = arcRotateCamera;
  22861. }
  22862. else {
  22863. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22864. freeCamera.setTarget(worldCenter);
  22865. camera = freeCamera;
  22866. }
  22867. camera.minZ = radius * 0.01;
  22868. camera.maxZ = radius * 1000;
  22869. camera.speed = radius * 0.2;
  22870. this.activeCamera = camera;
  22871. var canvas = this.getEngine().getRenderingCanvas();
  22872. if (attachCameraControls && canvas) {
  22873. camera.attachControl(canvas);
  22874. }
  22875. }
  22876. };
  22877. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22878. if (pbr === void 0) { pbr = false; }
  22879. if (scale === void 0) { scale = 1000; }
  22880. if (blur === void 0) { blur = 0; }
  22881. if (environmentTexture) {
  22882. this.environmentTexture = environmentTexture;
  22883. }
  22884. if (!this.environmentTexture) {
  22885. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22886. return null;
  22887. }
  22888. // Skybox
  22889. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22890. if (pbr) {
  22891. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22892. hdrSkyboxMaterial.backFaceCulling = false;
  22893. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22894. if (hdrSkyboxMaterial.reflectionTexture) {
  22895. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22896. }
  22897. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22898. hdrSkyboxMaterial.disableLighting = true;
  22899. hdrSkyboxMaterial.twoSidedLighting = true;
  22900. hdrSkybox.infiniteDistance = true;
  22901. hdrSkybox.material = hdrSkyboxMaterial;
  22902. }
  22903. else {
  22904. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22905. skyboxMaterial.backFaceCulling = false;
  22906. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22907. if (skyboxMaterial.reflectionTexture) {
  22908. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22909. }
  22910. skyboxMaterial.disableLighting = true;
  22911. hdrSkybox.infiniteDistance = true;
  22912. hdrSkybox.material = skyboxMaterial;
  22913. }
  22914. return hdrSkybox;
  22915. };
  22916. Scene.prototype.createDefaultEnvironment = function (options) {
  22917. if (BABYLON.EnvironmentHelper) {
  22918. return new BABYLON.EnvironmentHelper(options, this);
  22919. }
  22920. return null;
  22921. };
  22922. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22923. if (webVROptions === void 0) { webVROptions = {}; }
  22924. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22925. };
  22926. // Tags
  22927. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22928. if (tagsQuery === undefined) {
  22929. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22930. return list;
  22931. }
  22932. var listByTags = [];
  22933. forEach = forEach || (function (item) { return; });
  22934. for (var i in list) {
  22935. var item = list[i];
  22936. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22937. listByTags.push(item);
  22938. forEach(item);
  22939. }
  22940. }
  22941. return listByTags;
  22942. };
  22943. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22944. return this._getByTags(this.meshes, tagsQuery, forEach);
  22945. };
  22946. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22947. return this._getByTags(this.cameras, tagsQuery, forEach);
  22948. };
  22949. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22950. return this._getByTags(this.lights, tagsQuery, forEach);
  22951. };
  22952. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22953. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22954. };
  22955. /**
  22956. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22957. * This allowed control for front to back rendering or reversly depending of the special needs.
  22958. *
  22959. * @param renderingGroupId The rendering group id corresponding to its index
  22960. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22961. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22962. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22963. */
  22964. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22965. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22966. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22967. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22968. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22969. };
  22970. /**
  22971. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22972. *
  22973. * @param renderingGroupId The rendering group id corresponding to its index
  22974. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22975. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22976. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22977. */
  22978. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22979. if (depth === void 0) { depth = true; }
  22980. if (stencil === void 0) { stencil = true; }
  22981. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22982. };
  22983. /**
  22984. * Will flag all materials as dirty to trigger new shader compilation
  22985. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22986. */
  22987. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22988. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22989. var material = _a[_i];
  22990. if (predicate && !predicate(material)) {
  22991. continue;
  22992. }
  22993. material.markAsDirty(flag);
  22994. }
  22995. };
  22996. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  22997. var _this = this;
  22998. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  22999. this._activeRequests.push(request);
  23000. request.onCompleteObservable.add(function (request) {
  23001. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23002. });
  23003. return request;
  23004. };
  23005. // Statics
  23006. Scene._FOGMODE_NONE = 0;
  23007. Scene._FOGMODE_EXP = 1;
  23008. Scene._FOGMODE_EXP2 = 2;
  23009. Scene._FOGMODE_LINEAR = 3;
  23010. Scene._uniqueIdCounter = 0;
  23011. Scene.MinDeltaTime = 1.0;
  23012. Scene.MaxDeltaTime = 1000.0;
  23013. /** The distance in pixel that you have to move to prevent some events */
  23014. Scene.DragMovementThreshold = 10; // in pixels
  23015. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23016. Scene.LongPressDelay = 500; // in milliseconds
  23017. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23018. Scene.DoubleClickDelay = 300; // in milliseconds
  23019. /** If you need to check double click without raising a single click at first click, enable this flag */
  23020. Scene.ExclusiveDoubleClickMode = false;
  23021. return Scene;
  23022. }());
  23023. BABYLON.Scene = Scene;
  23024. })(BABYLON || (BABYLON = {}));
  23025. //# sourceMappingURL=babylon.scene.js.map
  23026. var BABYLON;
  23027. (function (BABYLON) {
  23028. var Buffer = /** @class */ (function () {
  23029. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23030. if (instanced === void 0) { instanced = false; }
  23031. if (engine instanceof BABYLON.Mesh) {
  23032. this._engine = engine.getScene().getEngine();
  23033. }
  23034. else {
  23035. this._engine = engine;
  23036. }
  23037. this._updatable = updatable;
  23038. this._data = data;
  23039. this._strideSize = stride;
  23040. if (!postponeInternalCreation) {
  23041. this.create();
  23042. }
  23043. this._instanced = instanced;
  23044. this._instanceDivisor = instanced ? 1 : 0;
  23045. }
  23046. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23047. // a lot of these parameters are ignored as they are overriden by the buffer
  23048. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23049. };
  23050. // Properties
  23051. Buffer.prototype.isUpdatable = function () {
  23052. return this._updatable;
  23053. };
  23054. Buffer.prototype.getData = function () {
  23055. return this._data;
  23056. };
  23057. Buffer.prototype.getBuffer = function () {
  23058. return this._buffer;
  23059. };
  23060. Buffer.prototype.getStrideSize = function () {
  23061. return this._strideSize;
  23062. };
  23063. Buffer.prototype.getIsInstanced = function () {
  23064. return this._instanced;
  23065. };
  23066. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23067. get: function () {
  23068. return this._instanceDivisor;
  23069. },
  23070. set: function (value) {
  23071. this._instanceDivisor = value;
  23072. if (value == 0) {
  23073. this._instanced = false;
  23074. }
  23075. else {
  23076. this._instanced = true;
  23077. }
  23078. },
  23079. enumerable: true,
  23080. configurable: true
  23081. });
  23082. // Methods
  23083. Buffer.prototype.create = function (data) {
  23084. if (data === void 0) { data = null; }
  23085. if (!data && this._buffer) {
  23086. return; // nothing to do
  23087. }
  23088. data = data || this._data;
  23089. if (!data) {
  23090. return;
  23091. }
  23092. if (!this._buffer) {
  23093. if (this._updatable) {
  23094. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23095. this._data = data;
  23096. }
  23097. else {
  23098. this._buffer = this._engine.createVertexBuffer(data);
  23099. }
  23100. }
  23101. else if (this._updatable) {
  23102. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23103. this._data = data;
  23104. }
  23105. };
  23106. Buffer.prototype._rebuild = function () {
  23107. this._buffer = null;
  23108. this.create(this._data);
  23109. };
  23110. Buffer.prototype.update = function (data) {
  23111. this.create(data);
  23112. };
  23113. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23114. if (!this._buffer) {
  23115. return;
  23116. }
  23117. if (this._updatable) {
  23118. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23119. this._data = null;
  23120. }
  23121. };
  23122. Buffer.prototype.dispose = function () {
  23123. if (!this._buffer) {
  23124. return;
  23125. }
  23126. if (this._engine._releaseBuffer(this._buffer)) {
  23127. this._buffer = null;
  23128. }
  23129. };
  23130. return Buffer;
  23131. }());
  23132. BABYLON.Buffer = Buffer;
  23133. })(BABYLON || (BABYLON = {}));
  23134. //# sourceMappingURL=babylon.buffer.js.map
  23135. var BABYLON;
  23136. (function (BABYLON) {
  23137. var VertexBuffer = /** @class */ (function () {
  23138. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23139. if (!stride) {
  23140. // Deduce stride from kind
  23141. switch (kind) {
  23142. case VertexBuffer.PositionKind:
  23143. stride = 3;
  23144. break;
  23145. case VertexBuffer.NormalKind:
  23146. stride = 3;
  23147. break;
  23148. case VertexBuffer.UVKind:
  23149. case VertexBuffer.UV2Kind:
  23150. case VertexBuffer.UV3Kind:
  23151. case VertexBuffer.UV4Kind:
  23152. case VertexBuffer.UV5Kind:
  23153. case VertexBuffer.UV6Kind:
  23154. stride = 2;
  23155. break;
  23156. case VertexBuffer.TangentKind:
  23157. case VertexBuffer.ColorKind:
  23158. stride = 4;
  23159. break;
  23160. case VertexBuffer.MatricesIndicesKind:
  23161. case VertexBuffer.MatricesIndicesExtraKind:
  23162. stride = 4;
  23163. break;
  23164. case VertexBuffer.MatricesWeightsKind:
  23165. case VertexBuffer.MatricesWeightsExtraKind:
  23166. default:
  23167. stride = 4;
  23168. break;
  23169. }
  23170. }
  23171. if (data instanceof BABYLON.Buffer) {
  23172. if (!stride) {
  23173. stride = data.getStrideSize();
  23174. }
  23175. this._buffer = data;
  23176. this._ownsBuffer = false;
  23177. }
  23178. else {
  23179. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23180. this._ownsBuffer = true;
  23181. }
  23182. this._stride = stride;
  23183. this._offset = offset ? offset : 0;
  23184. this._size = size ? size : stride;
  23185. this._kind = kind;
  23186. }
  23187. VertexBuffer.prototype._rebuild = function () {
  23188. if (!this._buffer) {
  23189. return;
  23190. }
  23191. this._buffer._rebuild();
  23192. };
  23193. /**
  23194. * Returns the kind of the VertexBuffer (string).
  23195. */
  23196. VertexBuffer.prototype.getKind = function () {
  23197. return this._kind;
  23198. };
  23199. // Properties
  23200. /**
  23201. * Boolean : is the VertexBuffer updatable ?
  23202. */
  23203. VertexBuffer.prototype.isUpdatable = function () {
  23204. return this._buffer.isUpdatable();
  23205. };
  23206. /**
  23207. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23208. */
  23209. VertexBuffer.prototype.getData = function () {
  23210. return this._buffer.getData();
  23211. };
  23212. /**
  23213. * Returns the WebGLBuffer associated to the VertexBuffer.
  23214. */
  23215. VertexBuffer.prototype.getBuffer = function () {
  23216. return this._buffer.getBuffer();
  23217. };
  23218. /**
  23219. * Returns the stride of the VertexBuffer (integer).
  23220. */
  23221. VertexBuffer.prototype.getStrideSize = function () {
  23222. return this._stride;
  23223. };
  23224. /**
  23225. * Returns the offset (integer).
  23226. */
  23227. VertexBuffer.prototype.getOffset = function () {
  23228. return this._offset;
  23229. };
  23230. /**
  23231. * Returns the VertexBuffer total size (integer).
  23232. */
  23233. VertexBuffer.prototype.getSize = function () {
  23234. return this._size;
  23235. };
  23236. /**
  23237. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23238. */
  23239. VertexBuffer.prototype.getIsInstanced = function () {
  23240. return this._buffer.getIsInstanced();
  23241. };
  23242. /**
  23243. * Returns the instancing divisor, zero for non-instanced (integer).
  23244. */
  23245. VertexBuffer.prototype.getInstanceDivisor = function () {
  23246. return this._buffer.instanceDivisor;
  23247. };
  23248. // Methods
  23249. /**
  23250. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23251. * Returns the created WebGLBuffer.
  23252. */
  23253. VertexBuffer.prototype.create = function (data) {
  23254. return this._buffer.create(data);
  23255. };
  23256. /**
  23257. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23258. * Returns the updated WebGLBuffer.
  23259. */
  23260. VertexBuffer.prototype.update = function (data) {
  23261. return this._buffer.update(data);
  23262. };
  23263. /**
  23264. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23265. * Returns the directly updated WebGLBuffer.
  23266. */
  23267. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23268. return this._buffer.updateDirectly(data, offset);
  23269. };
  23270. /**
  23271. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23272. */
  23273. VertexBuffer.prototype.dispose = function () {
  23274. if (this._ownsBuffer) {
  23275. this._buffer.dispose();
  23276. }
  23277. };
  23278. Object.defineProperty(VertexBuffer, "PositionKind", {
  23279. get: function () {
  23280. return VertexBuffer._PositionKind;
  23281. },
  23282. enumerable: true,
  23283. configurable: true
  23284. });
  23285. Object.defineProperty(VertexBuffer, "NormalKind", {
  23286. get: function () {
  23287. return VertexBuffer._NormalKind;
  23288. },
  23289. enumerable: true,
  23290. configurable: true
  23291. });
  23292. Object.defineProperty(VertexBuffer, "TangentKind", {
  23293. get: function () {
  23294. return VertexBuffer._TangentKind;
  23295. },
  23296. enumerable: true,
  23297. configurable: true
  23298. });
  23299. Object.defineProperty(VertexBuffer, "UVKind", {
  23300. get: function () {
  23301. return VertexBuffer._UVKind;
  23302. },
  23303. enumerable: true,
  23304. configurable: true
  23305. });
  23306. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23307. get: function () {
  23308. return VertexBuffer._UV2Kind;
  23309. },
  23310. enumerable: true,
  23311. configurable: true
  23312. });
  23313. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23314. get: function () {
  23315. return VertexBuffer._UV3Kind;
  23316. },
  23317. enumerable: true,
  23318. configurable: true
  23319. });
  23320. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23321. get: function () {
  23322. return VertexBuffer._UV4Kind;
  23323. },
  23324. enumerable: true,
  23325. configurable: true
  23326. });
  23327. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23328. get: function () {
  23329. return VertexBuffer._UV5Kind;
  23330. },
  23331. enumerable: true,
  23332. configurable: true
  23333. });
  23334. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23335. get: function () {
  23336. return VertexBuffer._UV6Kind;
  23337. },
  23338. enumerable: true,
  23339. configurable: true
  23340. });
  23341. Object.defineProperty(VertexBuffer, "ColorKind", {
  23342. get: function () {
  23343. return VertexBuffer._ColorKind;
  23344. },
  23345. enumerable: true,
  23346. configurable: true
  23347. });
  23348. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23349. get: function () {
  23350. return VertexBuffer._MatricesIndicesKind;
  23351. },
  23352. enumerable: true,
  23353. configurable: true
  23354. });
  23355. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23356. get: function () {
  23357. return VertexBuffer._MatricesWeightsKind;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23363. get: function () {
  23364. return VertexBuffer._MatricesIndicesExtraKind;
  23365. },
  23366. enumerable: true,
  23367. configurable: true
  23368. });
  23369. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23370. get: function () {
  23371. return VertexBuffer._MatricesWeightsExtraKind;
  23372. },
  23373. enumerable: true,
  23374. configurable: true
  23375. });
  23376. // Enums
  23377. VertexBuffer._PositionKind = "position";
  23378. VertexBuffer._NormalKind = "normal";
  23379. VertexBuffer._TangentKind = "tangent";
  23380. VertexBuffer._UVKind = "uv";
  23381. VertexBuffer._UV2Kind = "uv2";
  23382. VertexBuffer._UV3Kind = "uv3";
  23383. VertexBuffer._UV4Kind = "uv4";
  23384. VertexBuffer._UV5Kind = "uv5";
  23385. VertexBuffer._UV6Kind = "uv6";
  23386. VertexBuffer._ColorKind = "color";
  23387. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23388. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23389. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23390. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23391. return VertexBuffer;
  23392. }());
  23393. BABYLON.VertexBuffer = VertexBuffer;
  23394. })(BABYLON || (BABYLON = {}));
  23395. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23396. var BABYLON;
  23397. (function (BABYLON) {
  23398. var InternalTexture = /** @class */ (function () {
  23399. function InternalTexture(engine, dataSource) {
  23400. this.onLoadedObservable = new BABYLON.Observable();
  23401. // Private
  23402. this._initialSlot = -1;
  23403. this._designatedSlot = -1;
  23404. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23405. this._references = 1;
  23406. this._engine = engine;
  23407. this._dataSource = dataSource;
  23408. this._webGLTexture = engine._createTexture();
  23409. }
  23410. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23411. get: function () {
  23412. return this._dataSource;
  23413. },
  23414. enumerable: true,
  23415. configurable: true
  23416. });
  23417. InternalTexture.prototype.incrementReferences = function () {
  23418. this._references++;
  23419. };
  23420. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23421. if (depth === void 0) { depth = 1; }
  23422. this.width = width;
  23423. this.height = height;
  23424. this.depth = depth;
  23425. this.baseWidth = width;
  23426. this.baseHeight = height;
  23427. this.baseDepth = depth;
  23428. this._size = width * height * depth;
  23429. };
  23430. InternalTexture.prototype._rebuild = function () {
  23431. var _this = this;
  23432. var proxy;
  23433. this.isReady = false;
  23434. this._cachedCoordinatesMode = null;
  23435. this._cachedWrapU = null;
  23436. this._cachedWrapV = null;
  23437. this._cachedAnisotropicFilteringLevel = null;
  23438. switch (this._dataSource) {
  23439. case InternalTexture.DATASOURCE_TEMP:
  23440. return;
  23441. case InternalTexture.DATASOURCE_URL:
  23442. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23443. _this.isReady = true;
  23444. }, null, this._buffer, undefined, this.format);
  23445. proxy._swapAndDie(this);
  23446. return;
  23447. case InternalTexture.DATASOURCE_RAW:
  23448. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23449. proxy._swapAndDie(this);
  23450. this.isReady = true;
  23451. return;
  23452. case InternalTexture.DATASOURCE_RAW3D:
  23453. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23454. proxy._swapAndDie(this);
  23455. this.isReady = true;
  23456. return;
  23457. case InternalTexture.DATASOURCE_DYNAMIC:
  23458. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23459. proxy._swapAndDie(this);
  23460. // The engine will make sure to update content so no need to flag it as isReady = true
  23461. return;
  23462. case InternalTexture.DATASOURCE_RENDERTARGET:
  23463. var options = new BABYLON.RenderTargetCreationOptions();
  23464. options.generateDepthBuffer = this._generateDepthBuffer;
  23465. options.generateMipMaps = this.generateMipMaps;
  23466. options.generateStencilBuffer = this._generateStencilBuffer;
  23467. options.samplingMode = this.samplingMode;
  23468. options.type = this.type;
  23469. if (this.isCube) {
  23470. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23471. }
  23472. else {
  23473. var size = {
  23474. width: this.width,
  23475. height: this.height
  23476. };
  23477. proxy = this._engine.createRenderTargetTexture(size, options);
  23478. }
  23479. proxy._swapAndDie(this);
  23480. this.isReady = true;
  23481. return;
  23482. case InternalTexture.DATASOURCE_CUBE:
  23483. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23484. _this.isReady = true;
  23485. }, null, this.format, this._extension);
  23486. proxy._swapAndDie(this);
  23487. return;
  23488. case InternalTexture.DATASOURCE_CUBERAW:
  23489. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23490. proxy._swapAndDie(this);
  23491. this.isReady = true;
  23492. return;
  23493. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23494. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23495. if (proxy) {
  23496. proxy._swapAndDie(_this);
  23497. }
  23498. _this.isReady = true;
  23499. }, null, this.format, this._extension);
  23500. return;
  23501. }
  23502. };
  23503. InternalTexture.prototype._swapAndDie = function (target) {
  23504. target._webGLTexture = this._webGLTexture;
  23505. if (this._framebuffer) {
  23506. target._framebuffer = this._framebuffer;
  23507. }
  23508. if (this._depthStencilBuffer) {
  23509. target._depthStencilBuffer = this._depthStencilBuffer;
  23510. }
  23511. if (this._lodTextureHigh) {
  23512. if (target._lodTextureHigh) {
  23513. target._lodTextureHigh.dispose();
  23514. }
  23515. target._lodTextureHigh = this._lodTextureHigh;
  23516. }
  23517. if (this._lodTextureMid) {
  23518. if (target._lodTextureMid) {
  23519. target._lodTextureMid.dispose();
  23520. }
  23521. target._lodTextureMid = this._lodTextureMid;
  23522. }
  23523. if (this._lodTextureLow) {
  23524. if (target._lodTextureLow) {
  23525. target._lodTextureLow.dispose();
  23526. }
  23527. target._lodTextureLow = this._lodTextureLow;
  23528. }
  23529. var cache = this._engine.getLoadedTexturesCache();
  23530. var index = cache.indexOf(this);
  23531. if (index !== -1) {
  23532. cache.splice(index, 1);
  23533. }
  23534. };
  23535. InternalTexture.prototype.dispose = function () {
  23536. if (!this._webGLTexture) {
  23537. return;
  23538. }
  23539. this._references--;
  23540. if (this._references === 0) {
  23541. this._engine._releaseTexture(this);
  23542. this._webGLTexture = null;
  23543. }
  23544. };
  23545. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23546. InternalTexture.DATASOURCE_URL = 1;
  23547. InternalTexture.DATASOURCE_TEMP = 2;
  23548. InternalTexture.DATASOURCE_RAW = 3;
  23549. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23550. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23551. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23552. InternalTexture.DATASOURCE_CUBE = 7;
  23553. InternalTexture.DATASOURCE_CUBERAW = 8;
  23554. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23555. InternalTexture.DATASOURCE_RAW3D = 10;
  23556. return InternalTexture;
  23557. }());
  23558. BABYLON.InternalTexture = InternalTexture;
  23559. })(BABYLON || (BABYLON = {}));
  23560. //# sourceMappingURL=babylon.internalTexture.js.map
  23561. var BABYLON;
  23562. (function (BABYLON) {
  23563. var BaseTexture = /** @class */ (function () {
  23564. function BaseTexture(scene) {
  23565. this._hasAlpha = false;
  23566. this.getAlphaFromRGB = false;
  23567. this.level = 1;
  23568. this.coordinatesIndex = 0;
  23569. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23570. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23571. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23572. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23573. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23574. this.isCube = false;
  23575. this.is3D = false;
  23576. this.gammaSpace = true;
  23577. this.invertZ = false;
  23578. this.lodLevelInAlpha = false;
  23579. this.lodGenerationOffset = 0.0;
  23580. this.lodGenerationScale = 0.8;
  23581. this.isRenderTarget = false;
  23582. this.animations = new Array();
  23583. /**
  23584. * An event triggered when the texture is disposed.
  23585. * @type {BABYLON.Observable}
  23586. */
  23587. this.onDisposeObservable = new BABYLON.Observable();
  23588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23590. if (this._scene) {
  23591. this._scene.textures.push(this);
  23592. }
  23593. this._uid = null;
  23594. }
  23595. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23596. get: function () {
  23597. return this._hasAlpha;
  23598. },
  23599. set: function (value) {
  23600. if (this._hasAlpha === value) {
  23601. return;
  23602. }
  23603. this._hasAlpha = value;
  23604. if (this._scene) {
  23605. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23606. }
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23612. get: function () {
  23613. return this._coordinatesMode;
  23614. },
  23615. set: function (value) {
  23616. if (this._coordinatesMode === value) {
  23617. return;
  23618. }
  23619. this._coordinatesMode = value;
  23620. if (this._scene) {
  23621. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23622. }
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(BaseTexture.prototype, "uid", {
  23628. get: function () {
  23629. if (!this._uid) {
  23630. this._uid = BABYLON.Tools.RandomId();
  23631. }
  23632. return this._uid;
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. BaseTexture.prototype.toString = function () {
  23638. return this.name;
  23639. };
  23640. BaseTexture.prototype.getClassName = function () {
  23641. return "BaseTexture";
  23642. };
  23643. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23644. set: function (callback) {
  23645. if (this._onDisposeObserver) {
  23646. this.onDisposeObservable.remove(this._onDisposeObserver);
  23647. }
  23648. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23649. },
  23650. enumerable: true,
  23651. configurable: true
  23652. });
  23653. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23654. get: function () {
  23655. return true;
  23656. },
  23657. enumerable: true,
  23658. configurable: true
  23659. });
  23660. BaseTexture.prototype.getScene = function () {
  23661. return this._scene;
  23662. };
  23663. BaseTexture.prototype.getTextureMatrix = function () {
  23664. return BABYLON.Matrix.IdentityReadOnly;
  23665. };
  23666. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23667. return BABYLON.Matrix.IdentityReadOnly;
  23668. };
  23669. BaseTexture.prototype.getInternalTexture = function () {
  23670. return this._texture;
  23671. };
  23672. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23673. return !this.isBlocking || this.isReady();
  23674. };
  23675. BaseTexture.prototype.isReady = function () {
  23676. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23677. this.delayLoad();
  23678. return false;
  23679. }
  23680. if (this._texture) {
  23681. return this._texture.isReady;
  23682. }
  23683. return false;
  23684. };
  23685. BaseTexture.prototype.getSize = function () {
  23686. if (this._texture && this._texture.width) {
  23687. return new BABYLON.Size(this._texture.width, this._texture.height);
  23688. }
  23689. if (this._texture && this._texture._size) {
  23690. return new BABYLON.Size(this._texture._size, this._texture._size);
  23691. }
  23692. return BABYLON.Size.Zero();
  23693. };
  23694. BaseTexture.prototype.getBaseSize = function () {
  23695. if (!this.isReady() || !this._texture)
  23696. return BABYLON.Size.Zero();
  23697. if (this._texture._size) {
  23698. return new BABYLON.Size(this._texture._size, this._texture._size);
  23699. }
  23700. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23701. };
  23702. BaseTexture.prototype.scale = function (ratio) {
  23703. };
  23704. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23705. get: function () {
  23706. return false;
  23707. },
  23708. enumerable: true,
  23709. configurable: true
  23710. });
  23711. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23712. if (!this._scene) {
  23713. return null;
  23714. }
  23715. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23716. for (var index = 0; index < texturesCache.length; index++) {
  23717. var texturesCacheEntry = texturesCache[index];
  23718. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23719. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23720. texturesCacheEntry.incrementReferences();
  23721. return texturesCacheEntry;
  23722. }
  23723. }
  23724. }
  23725. return null;
  23726. };
  23727. BaseTexture.prototype._rebuild = function () {
  23728. };
  23729. BaseTexture.prototype.delayLoad = function () {
  23730. };
  23731. BaseTexture.prototype.clone = function () {
  23732. return null;
  23733. };
  23734. Object.defineProperty(BaseTexture.prototype, "textureType", {
  23735. get: function () {
  23736. if (!this._texture) {
  23737. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23738. }
  23739. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23740. },
  23741. enumerable: true,
  23742. configurable: true
  23743. });
  23744. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  23745. get: function () {
  23746. if (!this._texture) {
  23747. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23748. }
  23749. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23750. },
  23751. enumerable: true,
  23752. configurable: true
  23753. });
  23754. BaseTexture.prototype.readPixels = function (faceIndex) {
  23755. if (faceIndex === void 0) { faceIndex = 0; }
  23756. if (!this._texture) {
  23757. return null;
  23758. }
  23759. var size = this.getSize();
  23760. var scene = this.getScene();
  23761. if (!scene) {
  23762. return null;
  23763. }
  23764. var engine = scene.getEngine();
  23765. if (this._texture.isCube) {
  23766. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  23767. }
  23768. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  23769. };
  23770. BaseTexture.prototype.releaseInternalTexture = function () {
  23771. if (this._texture) {
  23772. this._texture.dispose();
  23773. this._texture = null;
  23774. }
  23775. };
  23776. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  23777. get: function () {
  23778. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  23779. return null;
  23780. }
  23781. if (!this._texture._sphericalPolynomial) {
  23782. this._texture._sphericalPolynomial =
  23783. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  23784. }
  23785. return this._texture._sphericalPolynomial;
  23786. },
  23787. set: function (value) {
  23788. if (this._texture) {
  23789. this._texture._sphericalPolynomial = value;
  23790. }
  23791. },
  23792. enumerable: true,
  23793. configurable: true
  23794. });
  23795. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  23796. get: function () {
  23797. if (this._texture) {
  23798. return this._texture._lodTextureHigh;
  23799. }
  23800. return null;
  23801. },
  23802. enumerable: true,
  23803. configurable: true
  23804. });
  23805. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  23806. get: function () {
  23807. if (this._texture) {
  23808. return this._texture._lodTextureMid;
  23809. }
  23810. return null;
  23811. },
  23812. enumerable: true,
  23813. configurable: true
  23814. });
  23815. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  23816. get: function () {
  23817. if (this._texture) {
  23818. return this._texture._lodTextureLow;
  23819. }
  23820. return null;
  23821. },
  23822. enumerable: true,
  23823. configurable: true
  23824. });
  23825. BaseTexture.prototype.dispose = function () {
  23826. if (!this._scene) {
  23827. return;
  23828. }
  23829. // Animations
  23830. this._scene.stopAnimation(this);
  23831. // Remove from scene
  23832. this._scene._removePendingData(this);
  23833. var index = this._scene.textures.indexOf(this);
  23834. if (index >= 0) {
  23835. this._scene.textures.splice(index, 1);
  23836. }
  23837. if (this._texture === undefined) {
  23838. return;
  23839. }
  23840. // Release
  23841. this.releaseInternalTexture();
  23842. // Callback
  23843. this.onDisposeObservable.notifyObservers(this);
  23844. this.onDisposeObservable.clear();
  23845. };
  23846. BaseTexture.prototype.serialize = function () {
  23847. if (!this.name) {
  23848. return null;
  23849. }
  23850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23851. // Animations
  23852. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23853. return serializationObject;
  23854. };
  23855. BaseTexture.WhenAllReady = function (textures, callback) {
  23856. var numRemaining = textures.length;
  23857. if (numRemaining === 0) {
  23858. callback();
  23859. return;
  23860. }
  23861. var _loop_1 = function () {
  23862. texture = textures[i];
  23863. if (texture.isReady()) {
  23864. if (--numRemaining === 0) {
  23865. callback();
  23866. }
  23867. }
  23868. else {
  23869. onLoadObservable = texture.onLoadObservable;
  23870. var onLoadCallback_1 = function () {
  23871. onLoadObservable.removeCallback(onLoadCallback_1);
  23872. if (--numRemaining === 0) {
  23873. callback();
  23874. }
  23875. };
  23876. onLoadObservable.add(onLoadCallback_1);
  23877. }
  23878. };
  23879. var texture, onLoadObservable;
  23880. for (var i = 0; i < textures.length; i++) {
  23881. _loop_1();
  23882. }
  23883. };
  23884. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23885. __decorate([
  23886. BABYLON.serialize()
  23887. ], BaseTexture.prototype, "name", void 0);
  23888. __decorate([
  23889. BABYLON.serialize("hasAlpha")
  23890. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23891. __decorate([
  23892. BABYLON.serialize()
  23893. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23894. __decorate([
  23895. BABYLON.serialize()
  23896. ], BaseTexture.prototype, "level", void 0);
  23897. __decorate([
  23898. BABYLON.serialize()
  23899. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23900. __decorate([
  23901. BABYLON.serialize("coordinatesMode")
  23902. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23903. __decorate([
  23904. BABYLON.serialize()
  23905. ], BaseTexture.prototype, "wrapU", void 0);
  23906. __decorate([
  23907. BABYLON.serialize()
  23908. ], BaseTexture.prototype, "wrapV", void 0);
  23909. __decorate([
  23910. BABYLON.serialize()
  23911. ], BaseTexture.prototype, "wrapR", void 0);
  23912. __decorate([
  23913. BABYLON.serialize()
  23914. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23915. __decorate([
  23916. BABYLON.serialize()
  23917. ], BaseTexture.prototype, "isCube", void 0);
  23918. __decorate([
  23919. BABYLON.serialize()
  23920. ], BaseTexture.prototype, "is3D", void 0);
  23921. __decorate([
  23922. BABYLON.serialize()
  23923. ], BaseTexture.prototype, "gammaSpace", void 0);
  23924. __decorate([
  23925. BABYLON.serialize()
  23926. ], BaseTexture.prototype, "invertZ", void 0);
  23927. __decorate([
  23928. BABYLON.serialize()
  23929. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23930. __decorate([
  23931. BABYLON.serialize()
  23932. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  23933. __decorate([
  23934. BABYLON.serialize()
  23935. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  23936. __decorate([
  23937. BABYLON.serialize()
  23938. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23939. return BaseTexture;
  23940. }());
  23941. BABYLON.BaseTexture = BaseTexture;
  23942. })(BABYLON || (BABYLON = {}));
  23943. //# sourceMappingURL=babylon.baseTexture.js.map
  23944. var BABYLON;
  23945. (function (BABYLON) {
  23946. var Texture = /** @class */ (function (_super) {
  23947. __extends(Texture, _super);
  23948. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  23949. if (noMipmap === void 0) { noMipmap = false; }
  23950. if (invertY === void 0) { invertY = true; }
  23951. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23952. if (onLoad === void 0) { onLoad = null; }
  23953. if (onError === void 0) { onError = null; }
  23954. if (buffer === void 0) { buffer = null; }
  23955. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23956. var _this = _super.call(this, scene) || this;
  23957. _this.uOffset = 0;
  23958. _this.vOffset = 0;
  23959. _this.uScale = 1.0;
  23960. _this.vScale = 1.0;
  23961. _this.uAng = 0;
  23962. _this.vAng = 0;
  23963. _this.wAng = 0;
  23964. _this._isBlocking = true;
  23965. _this.name = url || "";
  23966. _this.url = url;
  23967. _this._noMipmap = noMipmap;
  23968. _this._invertY = invertY;
  23969. _this._samplingMode = samplingMode;
  23970. _this._buffer = buffer;
  23971. _this._deleteBuffer = deleteBuffer;
  23972. if (format) {
  23973. _this._format = format;
  23974. }
  23975. scene = _this.getScene();
  23976. if (!scene) {
  23977. return _this;
  23978. }
  23979. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  23980. var load = function () {
  23981. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  23982. _this.onLoadObservable.notifyObservers(_this);
  23983. }
  23984. if (onLoad) {
  23985. onLoad();
  23986. }
  23987. if (!_this.isBlocking && scene) {
  23988. scene.resetCachedMaterial();
  23989. }
  23990. };
  23991. if (!_this.url) {
  23992. _this._delayedOnLoad = load;
  23993. _this._delayedOnError = onError;
  23994. return _this;
  23995. }
  23996. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  23997. if (!_this._texture) {
  23998. if (!scene.useDelayedTextureLoading) {
  23999. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24000. if (deleteBuffer) {
  24001. delete _this._buffer;
  24002. }
  24003. }
  24004. else {
  24005. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24006. _this._delayedOnLoad = load;
  24007. _this._delayedOnError = onError;
  24008. }
  24009. }
  24010. else {
  24011. if (_this._texture.isReady) {
  24012. BABYLON.Tools.SetImmediate(function () { return load(); });
  24013. }
  24014. else {
  24015. _this._texture.onLoadedObservable.add(load);
  24016. }
  24017. }
  24018. return _this;
  24019. }
  24020. Object.defineProperty(Texture.prototype, "noMipmap", {
  24021. get: function () {
  24022. return this._noMipmap;
  24023. },
  24024. enumerable: true,
  24025. configurable: true
  24026. });
  24027. Object.defineProperty(Texture.prototype, "isBlocking", {
  24028. get: function () {
  24029. return this._isBlocking;
  24030. },
  24031. set: function (value) {
  24032. this._isBlocking = value;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. Object.defineProperty(Texture.prototype, "samplingMode", {
  24038. get: function () {
  24039. return this._samplingMode;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Texture.prototype.updateURL = function (url) {
  24045. this.url = url;
  24046. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24047. this.delayLoad();
  24048. };
  24049. Texture.prototype.delayLoad = function () {
  24050. var _this = this;
  24051. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24052. return;
  24053. }
  24054. var scene = this.getScene();
  24055. if (!scene) {
  24056. return;
  24057. }
  24058. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24059. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24060. if (!this._texture) {
  24061. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24062. if (this._deleteBuffer) {
  24063. delete this._buffer;
  24064. }
  24065. }
  24066. else {
  24067. if (this._texture.isReady) {
  24068. BABYLON.Tools.SetImmediate(function () {
  24069. if (!_this._delayedOnLoad) {
  24070. return;
  24071. }
  24072. _this._delayedOnLoad();
  24073. });
  24074. }
  24075. else {
  24076. if (this._delayedOnLoad) {
  24077. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24078. }
  24079. }
  24080. }
  24081. };
  24082. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24083. if (!this._texture) {
  24084. return;
  24085. }
  24086. var scene = this.getScene();
  24087. if (!scene) {
  24088. return;
  24089. }
  24090. this._samplingMode = samplingMode;
  24091. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24092. };
  24093. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24094. x *= this.uScale;
  24095. y *= this.vScale;
  24096. x -= 0.5 * this.uScale;
  24097. y -= 0.5 * this.vScale;
  24098. z -= 0.5;
  24099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24100. t.x += 0.5 * this.uScale + this.uOffset;
  24101. t.y += 0.5 * this.vScale + this.vOffset;
  24102. t.z += 0.5;
  24103. };
  24104. Texture.prototype.getTextureMatrix = function () {
  24105. var _this = this;
  24106. if (this.uOffset === this._cachedUOffset &&
  24107. this.vOffset === this._cachedVOffset &&
  24108. this.uScale === this._cachedUScale &&
  24109. this.vScale === this._cachedVScale &&
  24110. this.uAng === this._cachedUAng &&
  24111. this.vAng === this._cachedVAng &&
  24112. this.wAng === this._cachedWAng) {
  24113. return this._cachedTextureMatrix;
  24114. }
  24115. this._cachedUOffset = this.uOffset;
  24116. this._cachedVOffset = this.vOffset;
  24117. this._cachedUScale = this.uScale;
  24118. this._cachedVScale = this.vScale;
  24119. this._cachedUAng = this.uAng;
  24120. this._cachedVAng = this.vAng;
  24121. this._cachedWAng = this.wAng;
  24122. if (!this._cachedTextureMatrix) {
  24123. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24124. this._rowGenerationMatrix = new BABYLON.Matrix();
  24125. this._t0 = BABYLON.Vector3.Zero();
  24126. this._t1 = BABYLON.Vector3.Zero();
  24127. this._t2 = BABYLON.Vector3.Zero();
  24128. }
  24129. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24130. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24131. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24132. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24133. this._t1.subtractInPlace(this._t0);
  24134. this._t2.subtractInPlace(this._t0);
  24135. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24136. this._cachedTextureMatrix.m[0] = this._t1.x;
  24137. this._cachedTextureMatrix.m[1] = this._t1.y;
  24138. this._cachedTextureMatrix.m[2] = this._t1.z;
  24139. this._cachedTextureMatrix.m[4] = this._t2.x;
  24140. this._cachedTextureMatrix.m[5] = this._t2.y;
  24141. this._cachedTextureMatrix.m[6] = this._t2.z;
  24142. this._cachedTextureMatrix.m[8] = this._t0.x;
  24143. this._cachedTextureMatrix.m[9] = this._t0.y;
  24144. this._cachedTextureMatrix.m[10] = this._t0.z;
  24145. var scene = this.getScene();
  24146. if (!scene) {
  24147. return this._cachedTextureMatrix;
  24148. }
  24149. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24150. return mat.hasTexture(_this);
  24151. });
  24152. return this._cachedTextureMatrix;
  24153. };
  24154. Texture.prototype.getReflectionTextureMatrix = function () {
  24155. var _this = this;
  24156. var scene = this.getScene();
  24157. if (!scene) {
  24158. return this._cachedTextureMatrix;
  24159. }
  24160. if (this.uOffset === this._cachedUOffset &&
  24161. this.vOffset === this._cachedVOffset &&
  24162. this.uScale === this._cachedUScale &&
  24163. this.vScale === this._cachedVScale &&
  24164. this.coordinatesMode === this._cachedCoordinatesMode) {
  24165. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24166. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24167. return this._cachedTextureMatrix;
  24168. }
  24169. }
  24170. else {
  24171. return this._cachedTextureMatrix;
  24172. }
  24173. }
  24174. if (!this._cachedTextureMatrix) {
  24175. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24176. }
  24177. if (!this._projectionModeMatrix) {
  24178. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24179. }
  24180. this._cachedUOffset = this.uOffset;
  24181. this._cachedVOffset = this.vOffset;
  24182. this._cachedUScale = this.uScale;
  24183. this._cachedVScale = this.vScale;
  24184. this._cachedCoordinatesMode = this.coordinatesMode;
  24185. switch (this.coordinatesMode) {
  24186. case Texture.PLANAR_MODE:
  24187. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24188. this._cachedTextureMatrix[0] = this.uScale;
  24189. this._cachedTextureMatrix[5] = this.vScale;
  24190. this._cachedTextureMatrix[12] = this.uOffset;
  24191. this._cachedTextureMatrix[13] = this.vOffset;
  24192. break;
  24193. case Texture.PROJECTION_MODE:
  24194. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24195. this._projectionModeMatrix.m[0] = 0.5;
  24196. this._projectionModeMatrix.m[5] = -0.5;
  24197. this._projectionModeMatrix.m[10] = 0.0;
  24198. this._projectionModeMatrix.m[12] = 0.5;
  24199. this._projectionModeMatrix.m[13] = 0.5;
  24200. this._projectionModeMatrix.m[14] = 1.0;
  24201. this._projectionModeMatrix.m[15] = 1.0;
  24202. var projectionMatrix = scene.getProjectionMatrix();
  24203. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24204. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24205. break;
  24206. default:
  24207. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24208. break;
  24209. }
  24210. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24211. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24212. });
  24213. return this._cachedTextureMatrix;
  24214. };
  24215. Texture.prototype.clone = function () {
  24216. var _this = this;
  24217. return BABYLON.SerializationHelper.Clone(function () {
  24218. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24219. }, this);
  24220. };
  24221. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24222. get: function () {
  24223. if (!this._onLoadObservable) {
  24224. this._onLoadObservable = new BABYLON.Observable();
  24225. }
  24226. return this._onLoadObservable;
  24227. },
  24228. enumerable: true,
  24229. configurable: true
  24230. });
  24231. Texture.prototype.serialize = function () {
  24232. var serializationObject = _super.prototype.serialize.call(this);
  24233. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24234. serializationObject.base64String = this._buffer;
  24235. serializationObject.name = serializationObject.name.replace("data:", "");
  24236. }
  24237. return serializationObject;
  24238. };
  24239. Texture.prototype.getClassName = function () {
  24240. return "Texture";
  24241. };
  24242. Texture.prototype.dispose = function () {
  24243. _super.prototype.dispose.call(this);
  24244. if (this.onLoadObservable) {
  24245. this.onLoadObservable.clear();
  24246. this._onLoadObservable = null;
  24247. }
  24248. this._delayedOnLoad = null;
  24249. this._delayedOnError = null;
  24250. };
  24251. // Statics
  24252. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24253. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24254. if (onLoad === void 0) { onLoad = null; }
  24255. if (onError === void 0) { onError = null; }
  24256. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24257. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24258. };
  24259. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24260. if (parsedTexture.customType) {
  24261. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24262. // Update Sampling Mode
  24263. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24264. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24265. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24266. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24267. }
  24268. }
  24269. return parsedCustomTexture;
  24270. }
  24271. if (parsedTexture.isCube) {
  24272. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24273. }
  24274. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24275. return null;
  24276. }
  24277. var texture = BABYLON.SerializationHelper.Parse(function () {
  24278. var generateMipMaps = true;
  24279. if (parsedTexture.noMipmap) {
  24280. generateMipMaps = false;
  24281. }
  24282. if (parsedTexture.mirrorPlane) {
  24283. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24284. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24285. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24286. return mirrorTexture;
  24287. }
  24288. else if (parsedTexture.isRenderTarget) {
  24289. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24290. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24291. return renderTargetTexture;
  24292. }
  24293. else {
  24294. var texture;
  24295. if (parsedTexture.base64String) {
  24296. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24297. }
  24298. else {
  24299. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24300. }
  24301. return texture;
  24302. }
  24303. }, parsedTexture, scene);
  24304. // Update Sampling Mode
  24305. if (parsedTexture.samplingMode) {
  24306. var sampling = parsedTexture.samplingMode;
  24307. if (texture._samplingMode !== sampling) {
  24308. texture.updateSamplingMode(sampling);
  24309. }
  24310. }
  24311. // Animations
  24312. if (parsedTexture.animations) {
  24313. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24314. var parsedAnimation = parsedTexture.animations[animationIndex];
  24315. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24316. }
  24317. }
  24318. return texture;
  24319. };
  24320. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24321. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24322. if (noMipmap === void 0) { noMipmap = false; }
  24323. if (invertY === void 0) { invertY = true; }
  24324. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24325. if (onLoad === void 0) { onLoad = null; }
  24326. if (onError === void 0) { onError = null; }
  24327. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24328. if (name.substr(0, 5) !== "data:") {
  24329. name = "data:" + name;
  24330. }
  24331. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24332. };
  24333. // Constants
  24334. Texture.NEAREST_SAMPLINGMODE = 1;
  24335. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24336. Texture.BILINEAR_SAMPLINGMODE = 2;
  24337. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24338. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24339. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24340. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24341. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24342. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24343. Texture.NEAREST_LINEAR = 7;
  24344. Texture.NEAREST_NEAREST = 8;
  24345. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24346. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24347. Texture.LINEAR_LINEAR = 11;
  24348. Texture.LINEAR_NEAREST = 12;
  24349. Texture.EXPLICIT_MODE = 0;
  24350. Texture.SPHERICAL_MODE = 1;
  24351. Texture.PLANAR_MODE = 2;
  24352. Texture.CUBIC_MODE = 3;
  24353. Texture.PROJECTION_MODE = 4;
  24354. Texture.SKYBOX_MODE = 5;
  24355. Texture.INVCUBIC_MODE = 6;
  24356. Texture.EQUIRECTANGULAR_MODE = 7;
  24357. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24358. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24359. Texture.CLAMP_ADDRESSMODE = 0;
  24360. Texture.WRAP_ADDRESSMODE = 1;
  24361. Texture.MIRROR_ADDRESSMODE = 2;
  24362. __decorate([
  24363. BABYLON.serialize()
  24364. ], Texture.prototype, "url", void 0);
  24365. __decorate([
  24366. BABYLON.serialize()
  24367. ], Texture.prototype, "uOffset", void 0);
  24368. __decorate([
  24369. BABYLON.serialize()
  24370. ], Texture.prototype, "vOffset", void 0);
  24371. __decorate([
  24372. BABYLON.serialize()
  24373. ], Texture.prototype, "uScale", void 0);
  24374. __decorate([
  24375. BABYLON.serialize()
  24376. ], Texture.prototype, "vScale", void 0);
  24377. __decorate([
  24378. BABYLON.serialize()
  24379. ], Texture.prototype, "uAng", void 0);
  24380. __decorate([
  24381. BABYLON.serialize()
  24382. ], Texture.prototype, "vAng", void 0);
  24383. __decorate([
  24384. BABYLON.serialize()
  24385. ], Texture.prototype, "wAng", void 0);
  24386. __decorate([
  24387. BABYLON.serialize()
  24388. ], Texture.prototype, "isBlocking", null);
  24389. return Texture;
  24390. }(BABYLON.BaseTexture));
  24391. BABYLON.Texture = Texture;
  24392. })(BABYLON || (BABYLON = {}));
  24393. //# sourceMappingURL=babylon.texture.js.map
  24394. var BABYLON;
  24395. (function (BABYLON) {
  24396. var _InstancesBatch = /** @class */ (function () {
  24397. function _InstancesBatch() {
  24398. this.mustReturn = false;
  24399. this.visibleInstances = new Array();
  24400. this.renderSelf = new Array();
  24401. }
  24402. return _InstancesBatch;
  24403. }());
  24404. BABYLON._InstancesBatch = _InstancesBatch;
  24405. var Mesh = /** @class */ (function (_super) {
  24406. __extends(Mesh, _super);
  24407. /**
  24408. * @constructor
  24409. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24410. * @param {Scene} scene The scene to add this mesh to.
  24411. * @param {Node} parent The parent of this mesh, if it has one
  24412. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24413. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24414. * When false, achieved by calling a clone(), also passing False.
  24415. * This will make creation of children, recursive.
  24416. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24417. */
  24418. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24419. if (scene === void 0) { scene = null; }
  24420. if (parent === void 0) { parent = null; }
  24421. if (source === void 0) { source = null; }
  24422. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24423. var _this = _super.call(this, name, scene) || this;
  24424. // Events
  24425. /**
  24426. * An event triggered before rendering the mesh
  24427. * @type {BABYLON.Observable}
  24428. */
  24429. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24430. /**
  24431. * An event triggered after rendering the mesh
  24432. * @type {BABYLON.Observable}
  24433. */
  24434. _this.onAfterRenderObservable = new BABYLON.Observable();
  24435. /**
  24436. * An event triggered before drawing the mesh
  24437. * @type {BABYLON.Observable}
  24438. */
  24439. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24440. // Members
  24441. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24442. _this.instances = new Array();
  24443. _this._LODLevels = new Array();
  24444. _this._visibleInstances = {};
  24445. _this._renderIdForInstances = new Array();
  24446. _this._batchCache = new _InstancesBatch();
  24447. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24448. // Use by builder only to know what orientation were the mesh build in.
  24449. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24450. _this.overrideMaterialSideOrientation = null;
  24451. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24452. // Will be used to save a source mesh reference, If any
  24453. _this._source = null;
  24454. scene = _this.getScene();
  24455. if (source) {
  24456. // Source mesh
  24457. _this._source = source;
  24458. // Geometry
  24459. if (source._geometry) {
  24460. source._geometry.applyToMesh(_this);
  24461. }
  24462. // Deep copy
  24463. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  24464. // Tags
  24465. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24466. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24467. }
  24468. _this.metadata = source.metadata;
  24469. // Parent
  24470. _this.parent = source.parent;
  24471. // Pivot
  24472. _this.setPivotMatrix(source.getPivotMatrix());
  24473. _this.id = name + "." + source.id;
  24474. // Material
  24475. _this.material = source.material;
  24476. var index;
  24477. if (!doNotCloneChildren) {
  24478. // Children
  24479. var directDescendants = source.getDescendants(true);
  24480. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24481. var child = directDescendants[index_1];
  24482. if (child.clone) {
  24483. child.clone(name + "." + child.name, _this);
  24484. }
  24485. }
  24486. }
  24487. // Physics clone
  24488. var physicsEngine = _this.getScene().getPhysicsEngine();
  24489. if (clonePhysicsImpostor && physicsEngine) {
  24490. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24491. if (impostor) {
  24492. _this.physicsImpostor = impostor.clone(_this);
  24493. }
  24494. }
  24495. // Particles
  24496. for (index = 0; index < scene.particleSystems.length; index++) {
  24497. var system = scene.particleSystems[index];
  24498. if (system.emitter === source) {
  24499. system.clone(system.name, _this);
  24500. }
  24501. }
  24502. _this.computeWorldMatrix(true);
  24503. }
  24504. // Parent
  24505. if (parent !== null) {
  24506. _this.parent = parent;
  24507. }
  24508. return _this;
  24509. }
  24510. Object.defineProperty(Mesh, "FRONTSIDE", {
  24511. /**
  24512. * Mesh side orientation : usually the external or front surface
  24513. */
  24514. get: function () {
  24515. return Mesh._FRONTSIDE;
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Mesh, "BACKSIDE", {
  24521. /**
  24522. * Mesh side orientation : usually the internal or back surface
  24523. */
  24524. get: function () {
  24525. return Mesh._BACKSIDE;
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24531. /**
  24532. * Mesh side orientation : both internal and external or front and back surfaces
  24533. */
  24534. get: function () {
  24535. return Mesh._DOUBLESIDE;
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24541. /**
  24542. * Mesh side orientation : by default, `FRONTSIDE`
  24543. */
  24544. get: function () {
  24545. return Mesh._DEFAULTSIDE;
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(Mesh, "NO_CAP", {
  24551. /**
  24552. * Mesh cap setting : no cap
  24553. */
  24554. get: function () {
  24555. return Mesh._NO_CAP;
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(Mesh, "CAP_START", {
  24561. /**
  24562. * Mesh cap setting : one cap at the beginning of the mesh
  24563. */
  24564. get: function () {
  24565. return Mesh._CAP_START;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Mesh, "CAP_END", {
  24571. /**
  24572. * Mesh cap setting : one cap at the end of the mesh
  24573. */
  24574. get: function () {
  24575. return Mesh._CAP_END;
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Mesh, "CAP_ALL", {
  24581. /**
  24582. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24583. */
  24584. get: function () {
  24585. return Mesh._CAP_ALL;
  24586. },
  24587. enumerable: true,
  24588. configurable: true
  24589. });
  24590. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24591. set: function (callback) {
  24592. if (this._onBeforeDrawObserver) {
  24593. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24594. }
  24595. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24596. },
  24597. enumerable: true,
  24598. configurable: true
  24599. });
  24600. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24601. get: function () {
  24602. return this._morphTargetManager;
  24603. },
  24604. set: function (value) {
  24605. if (this._morphTargetManager === value) {
  24606. return;
  24607. }
  24608. this._morphTargetManager = value;
  24609. this._syncGeometryWithMorphTargetManager();
  24610. },
  24611. enumerable: true,
  24612. configurable: true
  24613. });
  24614. Object.defineProperty(Mesh.prototype, "source", {
  24615. get: function () {
  24616. return this._source;
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24622. get: function () {
  24623. return this._unIndexed;
  24624. },
  24625. set: function (value) {
  24626. if (this._unIndexed !== value) {
  24627. this._unIndexed = value;
  24628. this._markSubMeshesAsAttributesDirty();
  24629. }
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. // Methods
  24635. /**
  24636. * Returns the string "Mesh".
  24637. */
  24638. Mesh.prototype.getClassName = function () {
  24639. return "Mesh";
  24640. };
  24641. /**
  24642. * Returns a string.
  24643. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24644. */
  24645. Mesh.prototype.toString = function (fullDetails) {
  24646. var ret = _super.prototype.toString.call(this, fullDetails);
  24647. ret += ", n vertices: " + this.getTotalVertices();
  24648. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24649. if (this.animations) {
  24650. for (var i = 0; i < this.animations.length; i++) {
  24651. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24652. }
  24653. }
  24654. if (fullDetails) {
  24655. if (this._geometry) {
  24656. var ib = this.getIndices();
  24657. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24658. if (vb && ib) {
  24659. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24660. }
  24661. }
  24662. else {
  24663. ret += ", flat shading: UNKNOWN";
  24664. }
  24665. }
  24666. return ret;
  24667. };
  24668. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24669. /**
  24670. * True if the mesh has some Levels Of Details (LOD).
  24671. * Returns a boolean.
  24672. */
  24673. get: function () {
  24674. return this._LODLevels.length > 0;
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Mesh.prototype._sortLODLevels = function () {
  24680. this._LODLevels.sort(function (a, b) {
  24681. if (a.distance < b.distance) {
  24682. return 1;
  24683. }
  24684. if (a.distance > b.distance) {
  24685. return -1;
  24686. }
  24687. return 0;
  24688. });
  24689. };
  24690. /**
  24691. * Add a mesh as LOD level triggered at the given distance.
  24692. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24693. * @param {number} distance The distance from the center of the object to show this level
  24694. * @param {Mesh} mesh The mesh to be added as LOD level
  24695. * @return {Mesh} This mesh (for chaining)
  24696. */
  24697. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24698. if (mesh && mesh._masterMesh) {
  24699. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24700. return this;
  24701. }
  24702. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24703. this._LODLevels.push(level);
  24704. if (mesh) {
  24705. mesh._masterMesh = this;
  24706. }
  24707. this._sortLODLevels();
  24708. return this;
  24709. };
  24710. /**
  24711. * Returns the LOD level mesh at the passed distance or null if not found.
  24712. * It is related to the method `addLODLevel(distance, mesh)`.
  24713. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24714. * Returns an object Mesh or `null`.
  24715. */
  24716. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24717. for (var index = 0; index < this._LODLevels.length; index++) {
  24718. var level = this._LODLevels[index];
  24719. if (level.distance === distance) {
  24720. return level.mesh;
  24721. }
  24722. }
  24723. return null;
  24724. };
  24725. /**
  24726. * Remove a mesh from the LOD array
  24727. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24728. * @param {Mesh} mesh The mesh to be removed.
  24729. * @return {Mesh} This mesh (for chaining)
  24730. */
  24731. Mesh.prototype.removeLODLevel = function (mesh) {
  24732. for (var index = 0; index < this._LODLevels.length; index++) {
  24733. if (this._LODLevels[index].mesh === mesh) {
  24734. this._LODLevels.splice(index, 1);
  24735. if (mesh) {
  24736. mesh._masterMesh = null;
  24737. }
  24738. }
  24739. }
  24740. this._sortLODLevels();
  24741. return this;
  24742. };
  24743. /**
  24744. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24745. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24746. */
  24747. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24748. if (!this._LODLevels || this._LODLevels.length === 0) {
  24749. return this;
  24750. }
  24751. var bSphere;
  24752. if (boundingSphere) {
  24753. bSphere = boundingSphere;
  24754. }
  24755. else {
  24756. var boundingInfo = this.getBoundingInfo();
  24757. bSphere = boundingInfo.boundingSphere;
  24758. }
  24759. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  24760. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24761. if (this.onLODLevelSelection) {
  24762. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24763. }
  24764. return this;
  24765. }
  24766. for (var index = 0; index < this._LODLevels.length; index++) {
  24767. var level = this._LODLevels[index];
  24768. if (level.distance < distanceToCamera) {
  24769. if (level.mesh) {
  24770. level.mesh._preActivate();
  24771. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24772. }
  24773. if (this.onLODLevelSelection) {
  24774. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24775. }
  24776. return level.mesh;
  24777. }
  24778. }
  24779. if (this.onLODLevelSelection) {
  24780. this.onLODLevelSelection(distanceToCamera, this, this);
  24781. }
  24782. return this;
  24783. };
  24784. Object.defineProperty(Mesh.prototype, "geometry", {
  24785. /**
  24786. * Returns the mesh internal Geometry object.
  24787. */
  24788. get: function () {
  24789. return this._geometry;
  24790. },
  24791. enumerable: true,
  24792. configurable: true
  24793. });
  24794. /**
  24795. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24796. */
  24797. Mesh.prototype.getTotalVertices = function () {
  24798. if (this._geometry === null || this._geometry === undefined) {
  24799. return 0;
  24800. }
  24801. return this._geometry.getTotalVertices();
  24802. };
  24803. /**
  24804. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24805. * 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.
  24806. * You can force the copy with forceCopy === true
  24807. * Returns null if the mesh has no geometry or no vertex buffer.
  24808. * Possible `kind` values :
  24809. * - BABYLON.VertexBuffer.PositionKind
  24810. * - BABYLON.VertexBuffer.UVKind
  24811. * - BABYLON.VertexBuffer.UV2Kind
  24812. * - BABYLON.VertexBuffer.UV3Kind
  24813. * - BABYLON.VertexBuffer.UV4Kind
  24814. * - BABYLON.VertexBuffer.UV5Kind
  24815. * - BABYLON.VertexBuffer.UV6Kind
  24816. * - BABYLON.VertexBuffer.ColorKind
  24817. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24818. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24819. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24820. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24821. */
  24822. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24823. if (!this._geometry) {
  24824. return null;
  24825. }
  24826. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24827. };
  24828. /**
  24829. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24830. * Returns `null` if the mesh has no geometry.
  24831. * Possible `kind` values :
  24832. * - BABYLON.VertexBuffer.PositionKind
  24833. * - BABYLON.VertexBuffer.UVKind
  24834. * - BABYLON.VertexBuffer.UV2Kind
  24835. * - BABYLON.VertexBuffer.UV3Kind
  24836. * - BABYLON.VertexBuffer.UV4Kind
  24837. * - BABYLON.VertexBuffer.UV5Kind
  24838. * - BABYLON.VertexBuffer.UV6Kind
  24839. * - BABYLON.VertexBuffer.ColorKind
  24840. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24841. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24842. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24843. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24844. */
  24845. Mesh.prototype.getVertexBuffer = function (kind) {
  24846. if (!this._geometry) {
  24847. return null;
  24848. }
  24849. return this._geometry.getVertexBuffer(kind);
  24850. };
  24851. /**
  24852. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24853. * Possible `kind` values :
  24854. * - BABYLON.VertexBuffer.PositionKind
  24855. * - BABYLON.VertexBuffer.UVKind
  24856. * - BABYLON.VertexBuffer.UV2Kind
  24857. * - BABYLON.VertexBuffer.UV3Kind
  24858. * - BABYLON.VertexBuffer.UV4Kind
  24859. * - BABYLON.VertexBuffer.UV5Kind
  24860. * - BABYLON.VertexBuffer.UV6Kind
  24861. * - BABYLON.VertexBuffer.ColorKind
  24862. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24863. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24864. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24865. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24866. */
  24867. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24868. if (!this._geometry) {
  24869. if (this._delayInfo) {
  24870. return this._delayInfo.indexOf(kind) !== -1;
  24871. }
  24872. return false;
  24873. }
  24874. return this._geometry.isVerticesDataPresent(kind);
  24875. };
  24876. /**
  24877. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24878. * Possible `kind` values :
  24879. * - BABYLON.VertexBuffer.PositionKind
  24880. * - BABYLON.VertexBuffer.UVKind
  24881. * - BABYLON.VertexBuffer.UV2Kind
  24882. * - BABYLON.VertexBuffer.UV3Kind
  24883. * - BABYLON.VertexBuffer.UV4Kind
  24884. * - BABYLON.VertexBuffer.UV5Kind
  24885. * - BABYLON.VertexBuffer.UV6Kind
  24886. * - BABYLON.VertexBuffer.ColorKind
  24887. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24888. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24889. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24890. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24891. */
  24892. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24893. if (!this._geometry) {
  24894. if (this._delayInfo) {
  24895. return this._delayInfo.indexOf(kind) !== -1;
  24896. }
  24897. return false;
  24898. }
  24899. return this._geometry.isVertexBufferUpdatable(kind);
  24900. };
  24901. /**
  24902. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24903. * Possible `kind` values :
  24904. * - BABYLON.VertexBuffer.PositionKind
  24905. * - BABYLON.VertexBuffer.UVKind
  24906. * - BABYLON.VertexBuffer.UV2Kind
  24907. * - BABYLON.VertexBuffer.UV3Kind
  24908. * - BABYLON.VertexBuffer.UV4Kind
  24909. * - BABYLON.VertexBuffer.UV5Kind
  24910. * - BABYLON.VertexBuffer.UV6Kind
  24911. * - BABYLON.VertexBuffer.ColorKind
  24912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24916. */
  24917. Mesh.prototype.getVerticesDataKinds = function () {
  24918. if (!this._geometry) {
  24919. var result = new Array();
  24920. if (this._delayInfo) {
  24921. this._delayInfo.forEach(function (kind, index, array) {
  24922. result.push(kind);
  24923. });
  24924. }
  24925. return result;
  24926. }
  24927. return this._geometry.getVerticesDataKinds();
  24928. };
  24929. /**
  24930. * Returns a positive integer : the total number of indices in this mesh geometry.
  24931. * Returns zero if the mesh has no geometry.
  24932. */
  24933. Mesh.prototype.getTotalIndices = function () {
  24934. if (!this._geometry) {
  24935. return 0;
  24936. }
  24937. return this._geometry.getTotalIndices();
  24938. };
  24939. /**
  24940. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  24941. * 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.
  24942. * Returns an empty array if the mesh has no geometry.
  24943. */
  24944. Mesh.prototype.getIndices = function (copyWhenShared) {
  24945. if (!this._geometry) {
  24946. return [];
  24947. }
  24948. return this._geometry.getIndices(copyWhenShared);
  24949. };
  24950. Object.defineProperty(Mesh.prototype, "isBlocked", {
  24951. get: function () {
  24952. return this._masterMesh !== null && this._masterMesh !== undefined;
  24953. },
  24954. enumerable: true,
  24955. configurable: true
  24956. });
  24957. /**
  24958. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  24959. */
  24960. Mesh.prototype.isReady = function () {
  24961. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24962. return false;
  24963. }
  24964. return _super.prototype.isReady.call(this);
  24965. };
  24966. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  24967. /**
  24968. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  24969. * This property is pertinent only for updatable parametric shapes.
  24970. */
  24971. get: function () {
  24972. return this._areNormalsFrozen;
  24973. },
  24974. enumerable: true,
  24975. configurable: true
  24976. });
  24977. /**
  24978. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24979. * It has no effect at all on other shapes.
  24980. * It prevents the mesh normals from being recomputed on next `positions` array update.
  24981. * Returns the Mesh.
  24982. */
  24983. Mesh.prototype.freezeNormals = function () {
  24984. this._areNormalsFrozen = true;
  24985. return this;
  24986. };
  24987. /**
  24988. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24989. * It has no effect at all on other shapes.
  24990. * It reactivates the mesh normals computation if it was previously frozen.
  24991. * Returns the Mesh.
  24992. */
  24993. Mesh.prototype.unfreezeNormals = function () {
  24994. this._areNormalsFrozen = false;
  24995. return this;
  24996. };
  24997. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  24998. /**
  24999. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25000. */
  25001. set: function (count) {
  25002. this._overridenInstanceCount = count;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. // Methods
  25008. Mesh.prototype._preActivate = function () {
  25009. var sceneRenderId = this.getScene().getRenderId();
  25010. if (this._preActivateId === sceneRenderId) {
  25011. return this;
  25012. }
  25013. this._preActivateId = sceneRenderId;
  25014. this._visibleInstances = null;
  25015. return this;
  25016. };
  25017. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25018. if (this._visibleInstances) {
  25019. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25020. }
  25021. return this;
  25022. };
  25023. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25024. if (!this._visibleInstances) {
  25025. this._visibleInstances = {};
  25026. this._visibleInstances.defaultRenderId = renderId;
  25027. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25028. }
  25029. if (!this._visibleInstances[renderId]) {
  25030. this._visibleInstances[renderId] = new Array();
  25031. }
  25032. this._visibleInstances[renderId].push(instance);
  25033. return this;
  25034. };
  25035. /**
  25036. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25037. * This means the mesh underlying bounding box and sphere are recomputed.
  25038. * Returns the Mesh.
  25039. */
  25040. Mesh.prototype.refreshBoundingInfo = function () {
  25041. return this._refreshBoundingInfo(false);
  25042. };
  25043. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25044. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25045. return this;
  25046. }
  25047. var data = this._getPositionData(applySkeleton);
  25048. if (data) {
  25049. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25050. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25051. }
  25052. if (this.subMeshes) {
  25053. for (var index = 0; index < this.subMeshes.length; index++) {
  25054. this.subMeshes[index].refreshBoundingInfo();
  25055. }
  25056. }
  25057. this._updateBoundingInfo();
  25058. return this;
  25059. };
  25060. Mesh.prototype._getPositionData = function (applySkeleton) {
  25061. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25062. if (data && applySkeleton && this.skeleton) {
  25063. data = data.slice();
  25064. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25065. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25066. if (matricesWeightsData && matricesIndicesData) {
  25067. var needExtras = this.numBoneInfluencers > 4;
  25068. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25069. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25070. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25071. var tempVector = BABYLON.Tmp.Vector3[0];
  25072. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25073. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25074. var matWeightIdx = 0;
  25075. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25076. finalMatrix.reset();
  25077. var inf;
  25078. var weight;
  25079. for (inf = 0; inf < 4; inf++) {
  25080. weight = matricesWeightsData[matWeightIdx + inf];
  25081. if (weight <= 0)
  25082. break;
  25083. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25084. finalMatrix.addToSelf(tempMatrix);
  25085. }
  25086. if (needExtras) {
  25087. for (inf = 0; inf < 4; inf++) {
  25088. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25089. if (weight <= 0)
  25090. break;
  25091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25092. finalMatrix.addToSelf(tempMatrix);
  25093. }
  25094. }
  25095. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25096. tempVector.toArray(data, index);
  25097. }
  25098. }
  25099. }
  25100. return data;
  25101. };
  25102. Mesh.prototype._createGlobalSubMesh = function (force) {
  25103. var totalVertices = this.getTotalVertices();
  25104. if (!totalVertices || !this.getIndices()) {
  25105. return null;
  25106. }
  25107. // Check if we need to recreate the submeshes
  25108. if (this.subMeshes && this.subMeshes.length > 0) {
  25109. var ib = this.getIndices();
  25110. if (!ib) {
  25111. return null;
  25112. }
  25113. var totalIndices = ib.length;
  25114. var needToRecreate = false;
  25115. if (force) {
  25116. needToRecreate = true;
  25117. }
  25118. else {
  25119. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25120. var submesh = _a[_i];
  25121. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25122. needToRecreate = true;
  25123. break;
  25124. }
  25125. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25126. needToRecreate = true;
  25127. break;
  25128. }
  25129. }
  25130. }
  25131. if (!needToRecreate) {
  25132. return this.subMeshes[0];
  25133. }
  25134. }
  25135. this.releaseSubMeshes();
  25136. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25137. };
  25138. Mesh.prototype.subdivide = function (count) {
  25139. if (count < 1) {
  25140. return;
  25141. }
  25142. var totalIndices = this.getTotalIndices();
  25143. var subdivisionSize = (totalIndices / count) | 0;
  25144. var offset = 0;
  25145. // Ensure that subdivisionSize is a multiple of 3
  25146. while (subdivisionSize % 3 !== 0) {
  25147. subdivisionSize++;
  25148. }
  25149. this.releaseSubMeshes();
  25150. for (var index = 0; index < count; index++) {
  25151. if (offset >= totalIndices) {
  25152. break;
  25153. }
  25154. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25155. offset += subdivisionSize;
  25156. }
  25157. this.synchronizeInstances();
  25158. };
  25159. /**
  25160. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25161. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25162. * The `data` are either a numeric array either a Float32Array.
  25163. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25164. * 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).
  25165. * Note that a new underlying VertexBuffer object is created each call.
  25166. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25167. *
  25168. * Possible `kind` values :
  25169. * - BABYLON.VertexBuffer.PositionKind
  25170. * - BABYLON.VertexBuffer.UVKind
  25171. * - BABYLON.VertexBuffer.UV2Kind
  25172. * - BABYLON.VertexBuffer.UV3Kind
  25173. * - BABYLON.VertexBuffer.UV4Kind
  25174. * - BABYLON.VertexBuffer.UV5Kind
  25175. * - BABYLON.VertexBuffer.UV6Kind
  25176. * - BABYLON.VertexBuffer.ColorKind
  25177. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25178. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25179. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25180. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25181. *
  25182. * Returns the Mesh.
  25183. */
  25184. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25185. if (updatable === void 0) { updatable = false; }
  25186. if (!this._geometry) {
  25187. var vertexData = new BABYLON.VertexData();
  25188. vertexData.set(data, kind);
  25189. var scene = this.getScene();
  25190. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25191. }
  25192. else {
  25193. this._geometry.setVerticesData(kind, data, updatable, stride);
  25194. }
  25195. return this;
  25196. };
  25197. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25198. if (updatable === void 0) { updatable = true; }
  25199. var vb = this.getVertexBuffer(kind);
  25200. if (!vb || vb.isUpdatable() === updatable) {
  25201. return;
  25202. }
  25203. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25204. };
  25205. /**
  25206. * Sets the mesh VertexBuffer.
  25207. * Returns the Mesh.
  25208. */
  25209. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25210. if (!this._geometry) {
  25211. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25212. }
  25213. this._geometry.setVerticesBuffer(buffer);
  25214. return this;
  25215. };
  25216. /**
  25217. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25218. * If the mesh has no geometry, it is simply returned as it is.
  25219. * The `data` are either a numeric array either a Float32Array.
  25220. * No new underlying VertexBuffer object is created.
  25221. * 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.
  25222. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25223. *
  25224. * Possible `kind` values :
  25225. * - BABYLON.VertexBuffer.PositionKind
  25226. * - BABYLON.VertexBuffer.UVKind
  25227. * - BABYLON.VertexBuffer.UV2Kind
  25228. * - BABYLON.VertexBuffer.UV3Kind
  25229. * - BABYLON.VertexBuffer.UV4Kind
  25230. * - BABYLON.VertexBuffer.UV5Kind
  25231. * - BABYLON.VertexBuffer.UV6Kind
  25232. * - BABYLON.VertexBuffer.ColorKind
  25233. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25234. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25235. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25236. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25237. *
  25238. * Returns the Mesh.
  25239. */
  25240. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25241. if (!this._geometry) {
  25242. return this;
  25243. }
  25244. if (!makeItUnique) {
  25245. this._geometry.updateVerticesData(kind, data, updateExtends);
  25246. }
  25247. else {
  25248. this.makeGeometryUnique();
  25249. this.updateVerticesData(kind, data, updateExtends, false);
  25250. }
  25251. return this;
  25252. };
  25253. /**
  25254. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25255. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25256. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25257. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25258. * Returns the Mesh.
  25259. */
  25260. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25261. if (computeNormals === void 0) { computeNormals = true; }
  25262. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25263. if (!positions) {
  25264. return this;
  25265. }
  25266. positionFunction(positions);
  25267. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25268. if (computeNormals) {
  25269. var indices = this.getIndices();
  25270. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25271. if (!normals) {
  25272. return this;
  25273. }
  25274. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25275. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25276. }
  25277. return this;
  25278. };
  25279. /**
  25280. * Creates a un-shared specific occurence of the geometry for the mesh.
  25281. * Returns the Mesh.
  25282. */
  25283. Mesh.prototype.makeGeometryUnique = function () {
  25284. if (!this._geometry) {
  25285. return this;
  25286. }
  25287. var oldGeometry = this._geometry;
  25288. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25289. oldGeometry.releaseForMesh(this, true);
  25290. geometry.applyToMesh(this);
  25291. return this;
  25292. };
  25293. /**
  25294. * Sets the mesh indices.
  25295. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25296. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25297. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25298. * This method creates a new index buffer each call.
  25299. * Returns the Mesh.
  25300. */
  25301. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25302. if (totalVertices === void 0) { totalVertices = null; }
  25303. if (updatable === void 0) { updatable = false; }
  25304. if (!this._geometry) {
  25305. var vertexData = new BABYLON.VertexData();
  25306. vertexData.indices = indices;
  25307. var scene = this.getScene();
  25308. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25309. }
  25310. else {
  25311. this._geometry.setIndices(indices, totalVertices, updatable);
  25312. }
  25313. return this;
  25314. };
  25315. /**
  25316. * Update the current index buffer
  25317. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25318. * Returns the Mesh.
  25319. */
  25320. Mesh.prototype.updateIndices = function (indices, offset) {
  25321. if (!this._geometry) {
  25322. return this;
  25323. }
  25324. this._geometry.updateIndices(indices, offset);
  25325. return this;
  25326. };
  25327. /**
  25328. * Invert the geometry to move from a right handed system to a left handed one.
  25329. * Returns the Mesh.
  25330. */
  25331. Mesh.prototype.toLeftHanded = function () {
  25332. if (!this._geometry) {
  25333. return this;
  25334. }
  25335. this._geometry.toLeftHanded();
  25336. return this;
  25337. };
  25338. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25339. if (!this._geometry) {
  25340. return this;
  25341. }
  25342. var engine = this.getScene().getEngine();
  25343. // Wireframe
  25344. var indexToBind;
  25345. if (this._unIndexed) {
  25346. indexToBind = null;
  25347. }
  25348. else {
  25349. switch (fillMode) {
  25350. case BABYLON.Material.PointFillMode:
  25351. indexToBind = null;
  25352. break;
  25353. case BABYLON.Material.WireFrameFillMode:
  25354. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25355. break;
  25356. default:
  25357. case BABYLON.Material.TriangleFillMode:
  25358. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25359. break;
  25360. }
  25361. }
  25362. // VBOs
  25363. this._geometry._bind(effect, indexToBind);
  25364. return this;
  25365. };
  25366. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25367. if (alternate === void 0) { alternate = false; }
  25368. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25369. return this;
  25370. }
  25371. this.onBeforeDrawObservable.notifyObservers(this);
  25372. var scene = this.getScene();
  25373. var engine = scene.getEngine();
  25374. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25375. // or triangles as points
  25376. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25377. }
  25378. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25379. // Triangles as wireframe
  25380. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25381. }
  25382. else {
  25383. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25384. }
  25385. if (scene._isAlternateRenderingEnabled && !alternate) {
  25386. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25387. if (!effect || !scene.activeCamera) {
  25388. return this;
  25389. }
  25390. scene._switchToAlternateCameraConfiguration(true);
  25391. this._effectiveMaterial.bindView(effect);
  25392. this._effectiveMaterial.bindViewProjection(effect);
  25393. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25394. this._draw(subMesh, fillMode, instancesCount, true);
  25395. engine.setViewport(scene.activeCamera.viewport);
  25396. scene._switchToAlternateCameraConfiguration(false);
  25397. this._effectiveMaterial.bindView(effect);
  25398. this._effectiveMaterial.bindViewProjection(effect);
  25399. }
  25400. return this;
  25401. };
  25402. /**
  25403. * Registers for this mesh a javascript function called just before the rendering process.
  25404. * This function is passed the current mesh.
  25405. * Return the Mesh.
  25406. */
  25407. Mesh.prototype.registerBeforeRender = function (func) {
  25408. this.onBeforeRenderObservable.add(func);
  25409. return this;
  25410. };
  25411. /**
  25412. * Disposes a previously registered javascript function called before the rendering.
  25413. * This function is passed the current mesh.
  25414. * Returns the Mesh.
  25415. */
  25416. Mesh.prototype.unregisterBeforeRender = function (func) {
  25417. this.onBeforeRenderObservable.removeCallback(func);
  25418. return this;
  25419. };
  25420. /**
  25421. * Registers for this mesh a javascript function called just after the rendering is complete.
  25422. * This function is passed the current mesh.
  25423. * Returns the Mesh.
  25424. */
  25425. Mesh.prototype.registerAfterRender = function (func) {
  25426. this.onAfterRenderObservable.add(func);
  25427. return this;
  25428. };
  25429. /**
  25430. * Disposes a previously registered javascript function called after the rendering.
  25431. * This function is passed the current mesh.
  25432. * Return the Mesh.
  25433. */
  25434. Mesh.prototype.unregisterAfterRender = function (func) {
  25435. this.onAfterRenderObservable.removeCallback(func);
  25436. return this;
  25437. };
  25438. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25439. var scene = this.getScene();
  25440. this._batchCache.mustReturn = false;
  25441. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25442. this._batchCache.visibleInstances[subMeshId] = null;
  25443. if (this._visibleInstances) {
  25444. var currentRenderId = scene.getRenderId();
  25445. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25446. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25447. var selfRenderId = this._renderId;
  25448. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25449. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25450. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25451. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25452. }
  25453. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25454. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25455. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25456. this._batchCache.mustReturn = true;
  25457. return this._batchCache;
  25458. }
  25459. if (currentRenderId !== selfRenderId) {
  25460. this._batchCache.renderSelf[subMeshId] = false;
  25461. }
  25462. }
  25463. this._renderIdForInstances[subMeshId] = currentRenderId;
  25464. }
  25465. return this._batchCache;
  25466. };
  25467. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25468. var visibleInstances = batch.visibleInstances[subMesh._id];
  25469. if (!visibleInstances) {
  25470. return this;
  25471. }
  25472. var matricesCount = visibleInstances.length + 1;
  25473. var bufferSize = matricesCount * 16 * 4;
  25474. var currentInstancesBufferSize = this._instancesBufferSize;
  25475. var instancesBuffer = this._instancesBuffer;
  25476. while (this._instancesBufferSize < bufferSize) {
  25477. this._instancesBufferSize *= 2;
  25478. }
  25479. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25480. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25481. }
  25482. var offset = 0;
  25483. var instancesCount = 0;
  25484. var world = this.getWorldMatrix();
  25485. if (batch.renderSelf[subMesh._id]) {
  25486. world.copyToArray(this._instancesData, offset);
  25487. offset += 16;
  25488. instancesCount++;
  25489. }
  25490. if (visibleInstances) {
  25491. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25492. var instance = visibleInstances[instanceIndex];
  25493. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25494. offset += 16;
  25495. instancesCount++;
  25496. }
  25497. }
  25498. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25499. if (instancesBuffer) {
  25500. instancesBuffer.dispose();
  25501. }
  25502. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25503. this._instancesBuffer = instancesBuffer;
  25504. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25505. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25506. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25507. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25508. }
  25509. else {
  25510. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25511. }
  25512. this._bind(subMesh, effect, fillMode);
  25513. this._draw(subMesh, fillMode, instancesCount);
  25514. engine.unbindInstanceAttributes();
  25515. return this;
  25516. };
  25517. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25518. var scene = this.getScene();
  25519. var engine = scene.getEngine();
  25520. if (hardwareInstancedRendering) {
  25521. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25522. }
  25523. else {
  25524. if (batch.renderSelf[subMesh._id]) {
  25525. // Draw
  25526. if (onBeforeDraw) {
  25527. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25528. }
  25529. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25530. }
  25531. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25532. if (visibleInstancesForSubMesh) {
  25533. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25534. var instance = visibleInstancesForSubMesh[instanceIndex];
  25535. // World
  25536. var world = instance.getWorldMatrix();
  25537. if (onBeforeDraw) {
  25538. onBeforeDraw(true, world, effectiveMaterial);
  25539. }
  25540. // Draw
  25541. this._draw(subMesh, fillMode);
  25542. }
  25543. }
  25544. }
  25545. return this;
  25546. };
  25547. /**
  25548. * Triggers the draw call for the mesh.
  25549. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25550. * Returns the Mesh.
  25551. */
  25552. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25553. this.checkOcclusionQuery();
  25554. if (this._isOccluded) {
  25555. return this;
  25556. }
  25557. var scene = this.getScene();
  25558. // Managing instances
  25559. var batch = this._getInstancesRenderList(subMesh._id);
  25560. if (batch.mustReturn) {
  25561. return this;
  25562. }
  25563. // Checking geometry state
  25564. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25565. return this;
  25566. }
  25567. this.onBeforeRenderObservable.notifyObservers(this);
  25568. var engine = scene.getEngine();
  25569. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25570. // Material
  25571. var material = subMesh.getMaterial();
  25572. if (!material) {
  25573. return this;
  25574. }
  25575. this._effectiveMaterial = material;
  25576. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25577. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25578. return this;
  25579. }
  25580. }
  25581. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25582. return this;
  25583. }
  25584. // Alpha mode
  25585. if (enableAlphaMode) {
  25586. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25587. }
  25588. // Outline - step 1
  25589. var savedDepthWrite = engine.getDepthWrite();
  25590. if (this.renderOutline) {
  25591. engine.setDepthWrite(false);
  25592. scene.getOutlineRenderer().render(subMesh, batch);
  25593. engine.setDepthWrite(savedDepthWrite);
  25594. }
  25595. var effect;
  25596. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25597. effect = subMesh.effect;
  25598. }
  25599. else {
  25600. effect = this._effectiveMaterial.getEffect();
  25601. }
  25602. if (!effect) {
  25603. return this;
  25604. }
  25605. var sideOrientation = this.overrideMaterialSideOrientation;
  25606. if (sideOrientation == null) {
  25607. sideOrientation = this._effectiveMaterial.sideOrientation;
  25608. if (this._getWorldMatrixDeterminant() < 0) {
  25609. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25610. }
  25611. }
  25612. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25613. if (this._effectiveMaterial.forceDepthWrite) {
  25614. engine.setDepthWrite(true);
  25615. }
  25616. // Bind
  25617. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25618. if (!hardwareInstancedRendering) {
  25619. this._bind(subMesh, effect, fillMode);
  25620. }
  25621. var world = this.getWorldMatrix();
  25622. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25623. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25624. }
  25625. else {
  25626. this._effectiveMaterial.bind(world, this);
  25627. }
  25628. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25629. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25630. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25631. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25632. }
  25633. // Draw
  25634. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25635. // Unbind
  25636. this._effectiveMaterial.unbind();
  25637. // Outline - step 2
  25638. if (this.renderOutline && savedDepthWrite) {
  25639. engine.setDepthWrite(true);
  25640. engine.setColorWrite(false);
  25641. scene.getOutlineRenderer().render(subMesh, batch);
  25642. engine.setColorWrite(true);
  25643. }
  25644. // Overlay
  25645. if (this.renderOverlay) {
  25646. var currentMode = engine.getAlphaMode();
  25647. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25648. scene.getOutlineRenderer().render(subMesh, batch, true);
  25649. engine.setAlphaMode(currentMode);
  25650. }
  25651. this.onAfterRenderObservable.notifyObservers(this);
  25652. return this;
  25653. };
  25654. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25655. if (isInstance && effectiveMaterial) {
  25656. effectiveMaterial.bindOnlyWorldMatrix(world);
  25657. }
  25658. };
  25659. /**
  25660. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25661. */
  25662. Mesh.prototype.getEmittedParticleSystems = function () {
  25663. var results = new Array();
  25664. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25665. var particleSystem = this.getScene().particleSystems[index];
  25666. if (particleSystem.emitter === this) {
  25667. results.push(particleSystem);
  25668. }
  25669. }
  25670. return results;
  25671. };
  25672. /**
  25673. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25674. */
  25675. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25676. var results = new Array();
  25677. var descendants = this.getDescendants();
  25678. descendants.push(this);
  25679. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25680. var particleSystem = this.getScene().particleSystems[index];
  25681. var emitter = particleSystem.emitter;
  25682. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  25683. results.push(particleSystem);
  25684. }
  25685. }
  25686. return results;
  25687. };
  25688. Mesh.prototype._checkDelayState = function () {
  25689. var scene = this.getScene();
  25690. if (this._geometry) {
  25691. this._geometry.load(scene);
  25692. }
  25693. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25695. this._queueLoad(scene);
  25696. }
  25697. return this;
  25698. };
  25699. Mesh.prototype._queueLoad = function (scene) {
  25700. var _this = this;
  25701. scene._addPendingData(this);
  25702. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25703. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25704. if (data instanceof ArrayBuffer) {
  25705. _this._delayLoadingFunction(data, _this);
  25706. }
  25707. else {
  25708. _this._delayLoadingFunction(JSON.parse(data), _this);
  25709. }
  25710. _this.instances.forEach(function (instance) {
  25711. instance._syncSubMeshes();
  25712. });
  25713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25714. scene._removePendingData(_this);
  25715. }, function () { }, scene.database, getBinaryData);
  25716. return this;
  25717. };
  25718. /**
  25719. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25720. */
  25721. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25722. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25723. return false;
  25724. }
  25725. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25726. return false;
  25727. }
  25728. this._checkDelayState();
  25729. return true;
  25730. };
  25731. /**
  25732. * Sets the mesh material by the material or multiMaterial `id` property.
  25733. * The material `id` is a string identifying the material or the multiMaterial.
  25734. * This method returns the Mesh.
  25735. */
  25736. Mesh.prototype.setMaterialByID = function (id) {
  25737. var materials = this.getScene().materials;
  25738. var index;
  25739. for (index = materials.length - 1; index > -1; index--) {
  25740. if (materials[index].id === id) {
  25741. this.material = materials[index];
  25742. return this;
  25743. }
  25744. }
  25745. // Multi
  25746. var multiMaterials = this.getScene().multiMaterials;
  25747. for (index = multiMaterials.length - 1; index > -1; index--) {
  25748. if (multiMaterials[index].id === id) {
  25749. this.material = multiMaterials[index];
  25750. return this;
  25751. }
  25752. }
  25753. return this;
  25754. };
  25755. /**
  25756. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25757. */
  25758. Mesh.prototype.getAnimatables = function () {
  25759. var results = new Array();
  25760. if (this.material) {
  25761. results.push(this.material);
  25762. }
  25763. if (this.skeleton) {
  25764. results.push(this.skeleton);
  25765. }
  25766. return results;
  25767. };
  25768. /**
  25769. * Modifies the mesh geometry according to the passed transformation matrix.
  25770. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25771. * The mesh normals are modified accordingly the same transformation.
  25772. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25773. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25774. * Returns the Mesh.
  25775. */
  25776. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25777. // Position
  25778. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25779. return this;
  25780. }
  25781. var submeshes = this.subMeshes.splice(0);
  25782. this._resetPointsArrayCache();
  25783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25784. var temp = new Array();
  25785. var index;
  25786. for (index = 0; index < data.length; index += 3) {
  25787. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25788. }
  25789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25790. // Normals
  25791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25792. return this;
  25793. }
  25794. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25795. temp = [];
  25796. for (index = 0; index < data.length; index += 3) {
  25797. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25798. }
  25799. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25800. // flip faces?
  25801. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25802. this.flipFaces();
  25803. }
  25804. // Restore submeshes
  25805. this.releaseSubMeshes();
  25806. this.subMeshes = submeshes;
  25807. return this;
  25808. };
  25809. /**
  25810. * Modifies the mesh geometry according to its own current World Matrix.
  25811. * The mesh World Matrix is then reset.
  25812. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25813. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  25814. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25815. * Returns the Mesh.
  25816. */
  25817. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25818. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25819. this.scaling.copyFromFloats(1, 1, 1);
  25820. this.position.copyFromFloats(0, 0, 0);
  25821. this.rotation.copyFromFloats(0, 0, 0);
  25822. //only if quaternion is already set
  25823. if (this.rotationQuaternion) {
  25824. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25825. }
  25826. this._worldMatrix = BABYLON.Matrix.Identity();
  25827. return this;
  25828. };
  25829. Object.defineProperty(Mesh.prototype, "_positions", {
  25830. // Cache
  25831. get: function () {
  25832. if (this._geometry) {
  25833. return this._geometry._positions;
  25834. }
  25835. return null;
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. Mesh.prototype._resetPointsArrayCache = function () {
  25841. if (this._geometry) {
  25842. this._geometry._resetPointsArrayCache();
  25843. }
  25844. return this;
  25845. };
  25846. Mesh.prototype._generatePointsArray = function () {
  25847. if (this._geometry) {
  25848. return this._geometry._generatePointsArray();
  25849. }
  25850. return false;
  25851. };
  25852. /**
  25853. * Returns a new Mesh object generated from the current mesh properties.
  25854. * This method must not get confused with createInstance().
  25855. * The parameter `name` is a string, the name given to the new mesh.
  25856. * The optional parameter `newParent` can be any Node object (default `null`).
  25857. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25858. * 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.
  25859. */
  25860. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25861. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25862. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25863. };
  25864. /**
  25865. * Disposes the Mesh.
  25866. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25867. * Returns nothing.
  25868. */
  25869. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25870. var _this = this;
  25871. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25872. this.morphTargetManager = null;
  25873. if (this._geometry) {
  25874. this._geometry.releaseForMesh(this, true);
  25875. }
  25876. // Sources
  25877. var meshes = this.getScene().meshes;
  25878. meshes.forEach(function (abstractMesh) {
  25879. var mesh = abstractMesh;
  25880. if (mesh._source && mesh._source === _this) {
  25881. mesh._source = null;
  25882. }
  25883. });
  25884. this._source = null;
  25885. // Instances
  25886. if (this._instancesBuffer) {
  25887. this._instancesBuffer.dispose();
  25888. this._instancesBuffer = null;
  25889. }
  25890. while (this.instances.length) {
  25891. this.instances[0].dispose();
  25892. }
  25893. // Highlight layers.
  25894. var highlightLayers = this.getScene().highlightLayers;
  25895. for (var i = 0; i < highlightLayers.length; i++) {
  25896. var highlightLayer = highlightLayers[i];
  25897. if (highlightLayer) {
  25898. highlightLayer.removeMesh(this);
  25899. highlightLayer.removeExcludedMesh(this);
  25900. }
  25901. }
  25902. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25903. };
  25904. /**
  25905. * Modifies the mesh geometry according to a displacement map.
  25906. * 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.
  25907. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25908. * This method returns nothing.
  25909. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25910. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25911. * 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.
  25912. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25913. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25914. *
  25915. * Returns the Mesh.
  25916. */
  25917. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25918. var _this = this;
  25919. var scene = this.getScene();
  25920. var onload = function (img) {
  25921. // Getting height map data
  25922. var canvas = document.createElement("canvas");
  25923. var context = canvas.getContext("2d");
  25924. var heightMapWidth = img.width;
  25925. var heightMapHeight = img.height;
  25926. canvas.width = heightMapWidth;
  25927. canvas.height = heightMapHeight;
  25928. context.drawImage(img, 0, 0);
  25929. // Create VertexData from map data
  25930. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25931. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  25932. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  25933. //execute success callback, if set
  25934. if (onSuccess) {
  25935. onSuccess(_this);
  25936. }
  25937. };
  25938. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25939. return this;
  25940. };
  25941. /**
  25942. * Modifies the mesh geometry according to a displacementMap buffer.
  25943. * 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.
  25944. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25945. * This method returns nothing.
  25946. * 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.
  25947. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  25948. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25949. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25950. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25951. *
  25952. * Returns the Mesh.
  25953. */
  25954. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  25955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  25956. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  25957. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25958. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  25959. return this;
  25960. }
  25961. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25962. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25963. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25964. var position = BABYLON.Vector3.Zero();
  25965. var normal = BABYLON.Vector3.Zero();
  25966. var uv = BABYLON.Vector2.Zero();
  25967. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  25968. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  25969. for (var index = 0; index < positions.length; index += 3) {
  25970. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  25971. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  25972. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  25973. // Compute height
  25974. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  25975. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  25976. var pos = (u + v * heightMapWidth) * 4;
  25977. var r = buffer[pos] / 255.0;
  25978. var g = buffer[pos + 1] / 255.0;
  25979. var b = buffer[pos + 2] / 255.0;
  25980. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25981. normal.normalize();
  25982. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  25983. position = position.add(normal);
  25984. position.toArray(positions, index);
  25985. }
  25986. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  25987. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  25988. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25989. return this;
  25990. };
  25991. /**
  25992. * Modify the mesh to get a flat shading rendering.
  25993. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  25994. * This method returns the Mesh.
  25995. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  25996. */
  25997. Mesh.prototype.convertToFlatShadedMesh = function () {
  25998. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  25999. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26000. var kinds = this.getVerticesDataKinds();
  26001. var vbs = {};
  26002. var data = {};
  26003. var newdata = {};
  26004. var updatableNormals = false;
  26005. var kindIndex;
  26006. var kind;
  26007. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26008. kind = kinds[kindIndex];
  26009. var vertexBuffer = this.getVertexBuffer(kind);
  26010. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26011. updatableNormals = vertexBuffer.isUpdatable();
  26012. kinds.splice(kindIndex, 1);
  26013. kindIndex--;
  26014. continue;
  26015. }
  26016. vbs[kind] = vertexBuffer;
  26017. data[kind] = vbs[kind].getData();
  26018. newdata[kind] = [];
  26019. }
  26020. // Save previous submeshes
  26021. var previousSubmeshes = this.subMeshes.slice(0);
  26022. var indices = this.getIndices();
  26023. var totalIndices = this.getTotalIndices();
  26024. // Generating unique vertices per face
  26025. var index;
  26026. for (index = 0; index < totalIndices; index++) {
  26027. var vertexIndex = indices[index];
  26028. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26029. kind = kinds[kindIndex];
  26030. var stride = vbs[kind].getStrideSize();
  26031. for (var offset = 0; offset < stride; offset++) {
  26032. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26033. }
  26034. }
  26035. }
  26036. // Updating faces & normal
  26037. var normals = [];
  26038. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26039. for (index = 0; index < totalIndices; index += 3) {
  26040. indices[index] = index;
  26041. indices[index + 1] = index + 1;
  26042. indices[index + 2] = index + 2;
  26043. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26044. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26045. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26046. var p1p2 = p1.subtract(p2);
  26047. var p3p2 = p3.subtract(p2);
  26048. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26049. // Store same normals for every vertex
  26050. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26051. normals.push(normal.x);
  26052. normals.push(normal.y);
  26053. normals.push(normal.z);
  26054. }
  26055. }
  26056. this.setIndices(indices);
  26057. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26058. // Updating vertex buffers
  26059. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26060. kind = kinds[kindIndex];
  26061. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26062. }
  26063. // Updating submeshes
  26064. this.releaseSubMeshes();
  26065. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26066. var previousOne = previousSubmeshes[submeshIndex];
  26067. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26068. }
  26069. this.synchronizeInstances();
  26070. return this;
  26071. };
  26072. /**
  26073. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26074. * In other words, more vertices, no more indices and a single bigger VBO.
  26075. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26076. * Returns the Mesh.
  26077. */
  26078. Mesh.prototype.convertToUnIndexedMesh = function () {
  26079. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26080. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26081. var kinds = this.getVerticesDataKinds();
  26082. var vbs = {};
  26083. var data = {};
  26084. var newdata = {};
  26085. var kindIndex;
  26086. var kind;
  26087. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26088. kind = kinds[kindIndex];
  26089. var vertexBuffer = this.getVertexBuffer(kind);
  26090. vbs[kind] = vertexBuffer;
  26091. data[kind] = vbs[kind].getData();
  26092. newdata[kind] = [];
  26093. }
  26094. // Save previous submeshes
  26095. var previousSubmeshes = this.subMeshes.slice(0);
  26096. var indices = this.getIndices();
  26097. var totalIndices = this.getTotalIndices();
  26098. // Generating unique vertices per face
  26099. var index;
  26100. for (index = 0; index < totalIndices; index++) {
  26101. var vertexIndex = indices[index];
  26102. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26103. kind = kinds[kindIndex];
  26104. var stride = vbs[kind].getStrideSize();
  26105. for (var offset = 0; offset < stride; offset++) {
  26106. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26107. }
  26108. }
  26109. }
  26110. // Updating indices
  26111. for (index = 0; index < totalIndices; index += 3) {
  26112. indices[index] = index;
  26113. indices[index + 1] = index + 1;
  26114. indices[index + 2] = index + 2;
  26115. }
  26116. this.setIndices(indices);
  26117. // Updating vertex buffers
  26118. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26119. kind = kinds[kindIndex];
  26120. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26121. }
  26122. // Updating submeshes
  26123. this.releaseSubMeshes();
  26124. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26125. var previousOne = previousSubmeshes[submeshIndex];
  26126. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26127. }
  26128. this._unIndexed = true;
  26129. this.synchronizeInstances();
  26130. return this;
  26131. };
  26132. /**
  26133. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26134. * This method returns the Mesh.
  26135. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26136. */
  26137. Mesh.prototype.flipFaces = function (flipNormals) {
  26138. if (flipNormals === void 0) { flipNormals = false; }
  26139. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26140. var i;
  26141. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26142. for (i = 0; i < vertex_data.normals.length; i++) {
  26143. vertex_data.normals[i] *= -1;
  26144. }
  26145. }
  26146. if (vertex_data.indices) {
  26147. var temp;
  26148. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26149. // reassign indices
  26150. temp = vertex_data.indices[i + 1];
  26151. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26152. vertex_data.indices[i + 2] = temp;
  26153. }
  26154. }
  26155. vertex_data.applyToMesh(this);
  26156. return this;
  26157. };
  26158. // Instances
  26159. /**
  26160. * Creates a new InstancedMesh object from the mesh model.
  26161. * An instance shares the same properties and the same material than its model.
  26162. * Only these properties of each instance can then be set individually :
  26163. * - position
  26164. * - rotation
  26165. * - rotationQuaternion
  26166. * - setPivotMatrix
  26167. * - scaling
  26168. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26169. * Warning : this method is not supported for Line mesh and LineSystem
  26170. */
  26171. Mesh.prototype.createInstance = function (name) {
  26172. return new BABYLON.InstancedMesh(name, this);
  26173. };
  26174. /**
  26175. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26176. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26177. * This method returns the Mesh.
  26178. */
  26179. Mesh.prototype.synchronizeInstances = function () {
  26180. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26181. var instance = this.instances[instanceIndex];
  26182. instance._syncSubMeshes();
  26183. }
  26184. return this;
  26185. };
  26186. /**
  26187. * Simplify the mesh according to the given array of settings.
  26188. * Function will return immediately and will simplify async. It returns the Mesh.
  26189. * @param settings a collection of simplification settings.
  26190. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26191. * @param type the type of simplification to run.
  26192. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26193. */
  26194. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26195. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26196. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26197. this.getScene().simplificationQueue.addTask({
  26198. settings: settings,
  26199. parallelProcessing: parallelProcessing,
  26200. mesh: this,
  26201. simplificationType: simplificationType,
  26202. successCallback: successCallback
  26203. });
  26204. return this;
  26205. };
  26206. /**
  26207. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26208. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26209. * This should be used together with the simplification to avoid disappearing triangles.
  26210. * Returns the Mesh.
  26211. * @param successCallback an optional success callback to be called after the optimization finished.
  26212. */
  26213. Mesh.prototype.optimizeIndices = function (successCallback) {
  26214. var _this = this;
  26215. var indices = this.getIndices();
  26216. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26217. if (!positions || !indices) {
  26218. return this;
  26219. }
  26220. var vectorPositions = new Array();
  26221. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26222. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26223. }
  26224. var dupes = new Array();
  26225. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26226. var realPos = vectorPositions.length - 1 - iteration;
  26227. var testedPosition = vectorPositions[realPos];
  26228. for (var j = 0; j < realPos; ++j) {
  26229. var againstPosition = vectorPositions[j];
  26230. if (testedPosition.equals(againstPosition)) {
  26231. dupes[realPos] = j;
  26232. break;
  26233. }
  26234. }
  26235. }, function () {
  26236. for (var i = 0; i < indices.length; ++i) {
  26237. indices[i] = dupes[indices[i]] || indices[i];
  26238. }
  26239. //indices are now reordered
  26240. var originalSubMeshes = _this.subMeshes.slice(0);
  26241. _this.setIndices(indices);
  26242. _this.subMeshes = originalSubMeshes;
  26243. if (successCallback) {
  26244. successCallback(_this);
  26245. }
  26246. });
  26247. return this;
  26248. };
  26249. Mesh.prototype.serialize = function (serializationObject) {
  26250. serializationObject.name = this.name;
  26251. serializationObject.id = this.id;
  26252. serializationObject.type = this.getClassName();
  26253. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26254. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26255. }
  26256. serializationObject.position = this.position.asArray();
  26257. if (this.rotationQuaternion) {
  26258. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26259. }
  26260. else if (this.rotation) {
  26261. serializationObject.rotation = this.rotation.asArray();
  26262. }
  26263. serializationObject.scaling = this.scaling.asArray();
  26264. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26265. serializationObject.isEnabled = this.isEnabled(false);
  26266. serializationObject.isVisible = this.isVisible;
  26267. serializationObject.infiniteDistance = this.infiniteDistance;
  26268. serializationObject.pickable = this.isPickable;
  26269. serializationObject.receiveShadows = this.receiveShadows;
  26270. serializationObject.billboardMode = this.billboardMode;
  26271. serializationObject.visibility = this.visibility;
  26272. serializationObject.checkCollisions = this.checkCollisions;
  26273. serializationObject.isBlocker = this.isBlocker;
  26274. // Parent
  26275. if (this.parent) {
  26276. serializationObject.parentId = this.parent.id;
  26277. }
  26278. // Geometry
  26279. serializationObject.isUnIndexed = this.isUnIndexed;
  26280. var geometry = this._geometry;
  26281. if (geometry) {
  26282. var geometryId = geometry.id;
  26283. serializationObject.geometryId = geometryId;
  26284. // SubMeshes
  26285. serializationObject.subMeshes = [];
  26286. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26287. var subMesh = this.subMeshes[subIndex];
  26288. serializationObject.subMeshes.push({
  26289. materialIndex: subMesh.materialIndex,
  26290. verticesStart: subMesh.verticesStart,
  26291. verticesCount: subMesh.verticesCount,
  26292. indexStart: subMesh.indexStart,
  26293. indexCount: subMesh.indexCount
  26294. });
  26295. }
  26296. }
  26297. // Material
  26298. if (this.material) {
  26299. serializationObject.materialId = this.material.id;
  26300. }
  26301. else {
  26302. this.material = null;
  26303. }
  26304. // Morph targets
  26305. if (this.morphTargetManager) {
  26306. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26307. }
  26308. // Skeleton
  26309. if (this.skeleton) {
  26310. serializationObject.skeletonId = this.skeleton.id;
  26311. }
  26312. // Physics
  26313. //TODO implement correct serialization for physics impostors.
  26314. var impostor = this.getPhysicsImpostor();
  26315. if (impostor) {
  26316. serializationObject.physicsMass = impostor.getParam("mass");
  26317. serializationObject.physicsFriction = impostor.getParam("friction");
  26318. serializationObject.physicsRestitution = impostor.getParam("mass");
  26319. serializationObject.physicsImpostor = impostor.type;
  26320. }
  26321. // Metadata
  26322. if (this.metadata) {
  26323. serializationObject.metadata = this.metadata;
  26324. }
  26325. // Instances
  26326. serializationObject.instances = [];
  26327. for (var index = 0; index < this.instances.length; index++) {
  26328. var instance = this.instances[index];
  26329. var serializationInstance = {
  26330. name: instance.name,
  26331. id: instance.id,
  26332. position: instance.position.asArray(),
  26333. scaling: instance.scaling.asArray()
  26334. };
  26335. if (instance.rotationQuaternion) {
  26336. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26337. }
  26338. else if (instance.rotation) {
  26339. serializationInstance.rotation = instance.rotation.asArray();
  26340. }
  26341. serializationObject.instances.push(serializationInstance);
  26342. // Animations
  26343. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26344. serializationInstance.ranges = instance.serializeAnimationRanges();
  26345. }
  26346. //
  26347. // Animations
  26348. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26349. serializationObject.ranges = this.serializeAnimationRanges();
  26350. // Layer mask
  26351. serializationObject.layerMask = this.layerMask;
  26352. // Alpha
  26353. serializationObject.alphaIndex = this.alphaIndex;
  26354. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26355. // Overlay
  26356. serializationObject.overlayAlpha = this.overlayAlpha;
  26357. serializationObject.overlayColor = this.overlayColor.asArray();
  26358. serializationObject.renderOverlay = this.renderOverlay;
  26359. // Fog
  26360. serializationObject.applyFog = this.applyFog;
  26361. // Action Manager
  26362. if (this.actionManager) {
  26363. serializationObject.actions = this.actionManager.serialize(this.name);
  26364. }
  26365. };
  26366. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26367. if (!this.geometry) {
  26368. return;
  26369. }
  26370. this._markSubMeshesAsAttributesDirty();
  26371. var morphTargetManager = this._morphTargetManager;
  26372. if (morphTargetManager && morphTargetManager.vertexCount) {
  26373. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26374. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26375. this.morphTargetManager = null;
  26376. return;
  26377. }
  26378. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26379. var morphTarget = morphTargetManager.getActiveTarget(index);
  26380. var positions = morphTarget.getPositions();
  26381. if (!positions) {
  26382. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26383. return;
  26384. }
  26385. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26386. var normals = morphTarget.getNormals();
  26387. if (normals) {
  26388. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26389. }
  26390. var tangents = morphTarget.getTangents();
  26391. if (tangents) {
  26392. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26393. }
  26394. }
  26395. }
  26396. else {
  26397. var index = 0;
  26398. // Positions
  26399. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26400. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26401. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26402. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26403. }
  26404. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26405. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26406. }
  26407. index++;
  26408. }
  26409. }
  26410. };
  26411. // Statics
  26412. /**
  26413. * Returns a new Mesh object parsed from the source provided.
  26414. * The parameter `parsedMesh` is the source.
  26415. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26416. */
  26417. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26418. var mesh;
  26419. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26420. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26421. }
  26422. else {
  26423. mesh = new Mesh(parsedMesh.name, scene);
  26424. }
  26425. mesh.id = parsedMesh.id;
  26426. if (BABYLON.Tags) {
  26427. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26428. }
  26429. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26430. if (parsedMesh.metadata !== undefined) {
  26431. mesh.metadata = parsedMesh.metadata;
  26432. }
  26433. if (parsedMesh.rotationQuaternion) {
  26434. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26435. }
  26436. else if (parsedMesh.rotation) {
  26437. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26438. }
  26439. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26440. if (parsedMesh.localMatrix) {
  26441. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26442. }
  26443. else if (parsedMesh.pivotMatrix) {
  26444. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26445. }
  26446. mesh.setEnabled(parsedMesh.isEnabled);
  26447. mesh.isVisible = parsedMesh.isVisible;
  26448. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26449. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26450. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26451. if (parsedMesh.applyFog !== undefined) {
  26452. mesh.applyFog = parsedMesh.applyFog;
  26453. }
  26454. if (parsedMesh.pickable !== undefined) {
  26455. mesh.isPickable = parsedMesh.pickable;
  26456. }
  26457. if (parsedMesh.alphaIndex !== undefined) {
  26458. mesh.alphaIndex = parsedMesh.alphaIndex;
  26459. }
  26460. mesh.receiveShadows = parsedMesh.receiveShadows;
  26461. mesh.billboardMode = parsedMesh.billboardMode;
  26462. if (parsedMesh.visibility !== undefined) {
  26463. mesh.visibility = parsedMesh.visibility;
  26464. }
  26465. mesh.checkCollisions = parsedMesh.checkCollisions;
  26466. if (parsedMesh.isBlocker !== undefined) {
  26467. mesh.isBlocker = parsedMesh.isBlocker;
  26468. }
  26469. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26470. // freezeWorldMatrix
  26471. if (parsedMesh.freezeWorldMatrix) {
  26472. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26473. }
  26474. // Parent
  26475. if (parsedMesh.parentId) {
  26476. mesh._waitingParentId = parsedMesh.parentId;
  26477. }
  26478. // Actions
  26479. if (parsedMesh.actions !== undefined) {
  26480. mesh._waitingActions = parsedMesh.actions;
  26481. }
  26482. // Overlay
  26483. if (parsedMesh.overlayAlpha !== undefined) {
  26484. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26485. }
  26486. if (parsedMesh.overlayColor !== undefined) {
  26487. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26488. }
  26489. if (parsedMesh.renderOverlay !== undefined) {
  26490. mesh.renderOverlay = parsedMesh.renderOverlay;
  26491. }
  26492. // Geometry
  26493. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26494. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26495. if (parsedMesh.delayLoadingFile) {
  26496. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26497. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26498. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26499. if (parsedMesh._binaryInfo) {
  26500. mesh._binaryInfo = parsedMesh._binaryInfo;
  26501. }
  26502. mesh._delayInfo = [];
  26503. if (parsedMesh.hasUVs) {
  26504. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26505. }
  26506. if (parsedMesh.hasUVs2) {
  26507. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26508. }
  26509. if (parsedMesh.hasUVs3) {
  26510. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26511. }
  26512. if (parsedMesh.hasUVs4) {
  26513. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26514. }
  26515. if (parsedMesh.hasUVs5) {
  26516. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26517. }
  26518. if (parsedMesh.hasUVs6) {
  26519. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26520. }
  26521. if (parsedMesh.hasColors) {
  26522. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26523. }
  26524. if (parsedMesh.hasMatricesIndices) {
  26525. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26526. }
  26527. if (parsedMesh.hasMatricesWeights) {
  26528. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26529. }
  26530. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26531. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26532. mesh._checkDelayState();
  26533. }
  26534. }
  26535. else {
  26536. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26537. }
  26538. // Material
  26539. if (parsedMesh.materialId) {
  26540. mesh.setMaterialByID(parsedMesh.materialId);
  26541. }
  26542. else {
  26543. mesh.material = null;
  26544. }
  26545. // Morph targets
  26546. if (parsedMesh.morphTargetManagerId > -1) {
  26547. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26548. }
  26549. // Skeleton
  26550. if (parsedMesh.skeletonId > -1) {
  26551. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26552. if (parsedMesh.numBoneInfluencers) {
  26553. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26554. }
  26555. }
  26556. // Animations
  26557. if (parsedMesh.animations) {
  26558. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26559. var parsedAnimation = parsedMesh.animations[animationIndex];
  26560. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26561. }
  26562. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26563. }
  26564. if (parsedMesh.autoAnimate) {
  26565. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26566. }
  26567. // Layer Mask
  26568. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26569. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26570. }
  26571. else {
  26572. mesh.layerMask = 0x0FFFFFFF;
  26573. }
  26574. // Physics
  26575. if (parsedMesh.physicsImpostor) {
  26576. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26577. mass: parsedMesh.physicsMass,
  26578. friction: parsedMesh.physicsFriction,
  26579. restitution: parsedMesh.physicsRestitution
  26580. }, scene);
  26581. }
  26582. // Instances
  26583. if (parsedMesh.instances) {
  26584. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26585. var parsedInstance = parsedMesh.instances[index];
  26586. var instance = mesh.createInstance(parsedInstance.name);
  26587. if (parsedInstance.id) {
  26588. instance.id = parsedInstance.id;
  26589. }
  26590. if (BABYLON.Tags) {
  26591. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26592. }
  26593. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26594. if (parsedInstance.parentId) {
  26595. instance._waitingParentId = parsedInstance.parentId;
  26596. }
  26597. if (parsedInstance.rotationQuaternion) {
  26598. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26599. }
  26600. else if (parsedInstance.rotation) {
  26601. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26602. }
  26603. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26604. instance.checkCollisions = mesh.checkCollisions;
  26605. if (parsedMesh.animations) {
  26606. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26607. parsedAnimation = parsedMesh.animations[animationIndex];
  26608. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26609. }
  26610. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26611. }
  26612. }
  26613. }
  26614. return mesh;
  26615. };
  26616. /**
  26617. * Creates a ribbon mesh.
  26618. * Please consider using the same method from the MeshBuilder class instead.
  26619. * 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.
  26620. *
  26621. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26622. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26623. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26624. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26625. * 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.
  26626. * 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.
  26627. * 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
  26628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26629. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26631. */
  26632. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26633. if (closeArray === void 0) { closeArray = false; }
  26634. if (updatable === void 0) { updatable = false; }
  26635. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26636. pathArray: pathArray,
  26637. closeArray: closeArray,
  26638. closePath: closePath,
  26639. offset: offset,
  26640. updatable: updatable,
  26641. sideOrientation: sideOrientation,
  26642. instance: instance
  26643. }, scene);
  26644. };
  26645. /**
  26646. * Creates a plane polygonal mesh. By default, this is a disc.
  26647. * Please consider using the same method from the MeshBuilder class instead.
  26648. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26649. * 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.
  26650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26653. */
  26654. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26655. if (scene === void 0) { scene = null; }
  26656. var options = {
  26657. radius: radius,
  26658. tessellation: tessellation,
  26659. sideOrientation: sideOrientation,
  26660. updatable: updatable
  26661. };
  26662. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26663. };
  26664. /**
  26665. * Creates a box mesh.
  26666. * Please consider using the same method from the MeshBuilder class instead.
  26667. * The parameter `size` sets the size (float) of each box side (default 1).
  26668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26669. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26671. */
  26672. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26673. if (scene === void 0) { scene = null; }
  26674. var options = {
  26675. size: size,
  26676. sideOrientation: sideOrientation,
  26677. updatable: updatable
  26678. };
  26679. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26680. };
  26681. /**
  26682. * Creates a sphere mesh.
  26683. * Please consider using the same method from the MeshBuilder class instead.
  26684. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26685. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26689. */
  26690. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26691. var options = {
  26692. segments: segments,
  26693. diameterX: diameter,
  26694. diameterY: diameter,
  26695. diameterZ: diameter,
  26696. sideOrientation: sideOrientation,
  26697. updatable: updatable
  26698. };
  26699. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26700. };
  26701. /**
  26702. * Creates a cylinder or a cone mesh.
  26703. * Please consider using the same method from the MeshBuilder class instead.
  26704. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26705. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26706. * 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.
  26707. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26708. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26710. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26712. */
  26713. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26714. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26715. if (scene !== undefined) {
  26716. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26717. updatable = scene;
  26718. }
  26719. scene = subdivisions;
  26720. subdivisions = 1;
  26721. }
  26722. var options = {
  26723. height: height,
  26724. diameterTop: diameterTop,
  26725. diameterBottom: diameterBottom,
  26726. tessellation: tessellation,
  26727. subdivisions: subdivisions,
  26728. sideOrientation: sideOrientation,
  26729. updatable: updatable
  26730. };
  26731. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26732. };
  26733. // Torus (Code from SharpDX.org)
  26734. /**
  26735. * Creates a torus mesh.
  26736. * Please consider using the same method from the MeshBuilder class instead.
  26737. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26738. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26739. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26743. */
  26744. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26745. var options = {
  26746. diameter: diameter,
  26747. thickness: thickness,
  26748. tessellation: tessellation,
  26749. sideOrientation: sideOrientation,
  26750. updatable: updatable
  26751. };
  26752. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26753. };
  26754. /**
  26755. * Creates a torus knot mesh.
  26756. * Please consider using the same method from the MeshBuilder class instead.
  26757. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26758. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26759. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26760. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26762. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26764. */
  26765. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26766. var options = {
  26767. radius: radius,
  26768. tube: tube,
  26769. radialSegments: radialSegments,
  26770. tubularSegments: tubularSegments,
  26771. p: p,
  26772. q: q,
  26773. sideOrientation: sideOrientation,
  26774. updatable: updatable
  26775. };
  26776. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26777. };
  26778. /**
  26779. * Creates a line mesh.
  26780. * Please consider using the same method from the MeshBuilder class instead.
  26781. * 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.
  26782. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26783. * The parameter `points` is an array successive Vector3.
  26784. * 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
  26785. * When updating an instance, remember that only point positions can change, not the number of points.
  26786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26787. */
  26788. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26789. if (scene === void 0) { scene = null; }
  26790. if (updatable === void 0) { updatable = false; }
  26791. if (instance === void 0) { instance = null; }
  26792. var options = {
  26793. points: points,
  26794. updatable: updatable,
  26795. instance: instance
  26796. };
  26797. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26798. };
  26799. /**
  26800. * Creates a dashed line mesh.
  26801. * Please consider using the same method from the MeshBuilder class instead.
  26802. * 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.
  26803. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26804. * The parameter `points` is an array successive Vector3.
  26805. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26806. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26807. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26808. * 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
  26809. * When updating an instance, remember that only point positions can change, not the number of points.
  26810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26811. */
  26812. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26813. if (scene === void 0) { scene = null; }
  26814. var options = {
  26815. points: points,
  26816. dashSize: dashSize,
  26817. gapSize: gapSize,
  26818. dashNb: dashNb,
  26819. updatable: updatable,
  26820. instance: instance
  26821. };
  26822. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26823. };
  26824. /**
  26825. * Creates a polygon mesh.
  26826. * Please consider using the same method from the MeshBuilder class instead.
  26827. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26828. * 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.
  26829. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26831. * Remember you can only change the shape positions, not their number when updating a polygon.
  26832. */
  26833. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26834. var options = {
  26835. shape: shape,
  26836. holes: holes,
  26837. updatable: updatable,
  26838. sideOrientation: sideOrientation
  26839. };
  26840. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26841. };
  26842. /**
  26843. * Creates an extruded polygon mesh, with depth in the Y direction.
  26844. * Please consider using the same method from the MeshBuilder class instead.
  26845. */
  26846. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26847. var options = {
  26848. shape: shape,
  26849. holes: holes,
  26850. depth: depth,
  26851. updatable: updatable,
  26852. sideOrientation: sideOrientation
  26853. };
  26854. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26855. };
  26856. /**
  26857. * Creates an extruded shape mesh.
  26858. * 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.
  26859. * Please consider using the same method from the MeshBuilder class instead.
  26860. *
  26861. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26862. * 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
  26863. * extruded along the Z axis.
  26864. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26865. * 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.
  26866. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26867. * 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
  26868. * 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
  26869. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26873. */
  26874. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26875. if (scene === void 0) { scene = null; }
  26876. var options = {
  26877. shape: shape,
  26878. path: path,
  26879. scale: scale,
  26880. rotation: rotation,
  26881. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26882. sideOrientation: sideOrientation,
  26883. instance: instance,
  26884. updatable: updatable
  26885. };
  26886. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26887. };
  26888. /**
  26889. * Creates an custom extruded shape mesh.
  26890. * 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.
  26891. * Please consider using the same method from the MeshBuilder class instead.
  26892. *
  26893. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26894. * 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
  26895. * extruded along the Z axis.
  26896. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26897. * 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
  26898. * and the distance of this point from the begining of the path :
  26899. * ```javascript
  26900. * var rotationFunction = function(i, distance) {
  26901. * // do things
  26902. * return rotationValue; }
  26903. * ```
  26904. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26905. * 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
  26906. * and the distance of this point from the begining of the path :
  26907. * ```javascript
  26908. * var scaleFunction = function(i, distance) {
  26909. * // do things
  26910. * return scaleValue;}
  26911. * ```
  26912. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26913. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26914. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26915. * 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
  26916. * 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
  26917. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26921. */
  26922. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26923. var options = {
  26924. shape: shape,
  26925. path: path,
  26926. scaleFunction: scaleFunction,
  26927. rotationFunction: rotationFunction,
  26928. ribbonCloseArray: ribbonCloseArray,
  26929. ribbonClosePath: ribbonClosePath,
  26930. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26931. sideOrientation: sideOrientation,
  26932. instance: instance,
  26933. updatable: updatable
  26934. };
  26935. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  26936. };
  26937. /**
  26938. * Creates lathe mesh.
  26939. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26940. * Please consider using the same method from the MeshBuilder class instead.
  26941. * 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
  26942. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26943. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26944. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26945. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26946. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26948. */
  26949. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  26950. var options = {
  26951. shape: shape,
  26952. radius: radius,
  26953. tessellation: tessellation,
  26954. sideOrientation: sideOrientation,
  26955. updatable: updatable
  26956. };
  26957. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  26958. };
  26959. /**
  26960. * Creates a plane mesh.
  26961. * Please consider using the same method from the MeshBuilder class instead.
  26962. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26963. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26964. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26966. */
  26967. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  26968. var options = {
  26969. size: size,
  26970. width: size,
  26971. height: size,
  26972. sideOrientation: sideOrientation,
  26973. updatable: updatable
  26974. };
  26975. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  26976. };
  26977. /**
  26978. * Creates a ground mesh.
  26979. * Please consider using the same method from the MeshBuilder class instead.
  26980. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26981. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26983. */
  26984. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  26985. var options = {
  26986. width: width,
  26987. height: height,
  26988. subdivisions: subdivisions,
  26989. updatable: updatable
  26990. };
  26991. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  26992. };
  26993. /**
  26994. * Creates a tiled ground mesh.
  26995. * Please consider using the same method from the MeshBuilder class instead.
  26996. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26997. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26998. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26999. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27000. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27001. * numbers of subdivisions on the ground width and height of each tile.
  27002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27003. */
  27004. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27005. var options = {
  27006. xmin: xmin,
  27007. zmin: zmin,
  27008. xmax: xmax,
  27009. zmax: zmax,
  27010. subdivisions: subdivisions,
  27011. precision: precision,
  27012. updatable: updatable
  27013. };
  27014. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27015. };
  27016. /**
  27017. * Creates a ground mesh from a height map.
  27018. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27019. * Please consider using the same method from the MeshBuilder class instead.
  27020. * The parameter `url` sets the URL of the height map image resource.
  27021. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27022. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27023. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27024. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27025. * 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).
  27026. * This function is passed the newly built mesh :
  27027. * ```javascript
  27028. * function(mesh) { // do things
  27029. * return; }
  27030. * ```
  27031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27032. */
  27033. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27034. var options = {
  27035. width: width,
  27036. height: height,
  27037. subdivisions: subdivisions,
  27038. minHeight: minHeight,
  27039. maxHeight: maxHeight,
  27040. updatable: updatable,
  27041. onReady: onReady
  27042. };
  27043. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27044. };
  27045. /**
  27046. * Creates a tube mesh.
  27047. * 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.
  27048. * Please consider using the same method from the MeshBuilder class instead.
  27049. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27050. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27051. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27052. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27053. * 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.
  27054. * It must return a radius value (positive float) :
  27055. * ```javascript
  27056. * var radiusFunction = function(i, distance) {
  27057. * // do things
  27058. * return radius; }
  27059. * ```
  27060. * 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
  27061. * 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
  27062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27065. */
  27066. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27067. var options = {
  27068. path: path,
  27069. radius: radius,
  27070. tessellation: tessellation,
  27071. radiusFunction: radiusFunction,
  27072. arc: 1,
  27073. cap: cap,
  27074. updatable: updatable,
  27075. sideOrientation: sideOrientation,
  27076. instance: instance
  27077. };
  27078. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27079. };
  27080. /**
  27081. * Creates a polyhedron mesh.
  27082. * Please consider using the same method from the MeshBuilder class instead.
  27083. * 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
  27084. * to choose the wanted type.
  27085. * The parameter `size` (positive float, default 1) sets the polygon size.
  27086. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27087. * 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`.
  27088. * 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
  27089. * 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)`).
  27090. * 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
  27091. * 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.
  27092. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27093. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27095. */
  27096. Mesh.CreatePolyhedron = function (name, options, scene) {
  27097. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27098. };
  27099. /**
  27100. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27101. * Please consider using the same method from the MeshBuilder class instead.
  27102. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27103. * 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`).
  27104. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27105. * 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.
  27106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27109. */
  27110. Mesh.CreateIcoSphere = function (name, options, scene) {
  27111. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27112. };
  27113. /**
  27114. * Creates a decal mesh.
  27115. * Please consider using the same method from the MeshBuilder class instead.
  27116. * 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.
  27117. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27118. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27119. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27120. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27121. */
  27122. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27123. var options = {
  27124. position: position,
  27125. normal: normal,
  27126. size: size,
  27127. angle: angle
  27128. };
  27129. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27130. };
  27131. // Skeletons
  27132. /**
  27133. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27134. */
  27135. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27136. if (!this._sourcePositions) {
  27137. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27138. if (!source) {
  27139. return this._sourcePositions;
  27140. }
  27141. this._sourcePositions = new Float32Array(source);
  27142. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27143. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27144. }
  27145. }
  27146. return this._sourcePositions;
  27147. };
  27148. /**
  27149. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27150. */
  27151. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27152. if (!this._sourceNormals) {
  27153. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27154. if (!source) {
  27155. return this._sourceNormals;
  27156. }
  27157. this._sourceNormals = new Float32Array(source);
  27158. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27159. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27160. }
  27161. }
  27162. return this._sourceNormals;
  27163. };
  27164. /**
  27165. * Updates the vertex buffer by applying transformation from the bones.
  27166. * Returns the Mesh.
  27167. *
  27168. * @param {skeleton} skeleton to apply
  27169. */
  27170. Mesh.prototype.applySkeleton = function (skeleton) {
  27171. if (!this.geometry) {
  27172. return this;
  27173. }
  27174. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27175. return this;
  27176. }
  27177. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27178. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27179. return this;
  27180. }
  27181. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27182. return this;
  27183. }
  27184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27185. return this;
  27186. }
  27187. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27188. return this;
  27189. }
  27190. if (!this._sourcePositions) {
  27191. var submeshes = this.subMeshes.slice();
  27192. this.setPositionsForCPUSkinning();
  27193. this.subMeshes = submeshes;
  27194. }
  27195. if (!this._sourceNormals) {
  27196. this.setNormalsForCPUSkinning();
  27197. }
  27198. // positionsData checks for not being Float32Array will only pass at most once
  27199. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27200. if (!positionsData) {
  27201. return this;
  27202. }
  27203. if (!(positionsData instanceof Float32Array)) {
  27204. positionsData = new Float32Array(positionsData);
  27205. }
  27206. // normalsData checks for not being Float32Array will only pass at most once
  27207. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27208. if (!normalsData) {
  27209. return this;
  27210. }
  27211. if (!(normalsData instanceof Float32Array)) {
  27212. normalsData = new Float32Array(normalsData);
  27213. }
  27214. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27215. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27216. if (!matricesWeightsData || !matricesIndicesData) {
  27217. return this;
  27218. }
  27219. var needExtras = this.numBoneInfluencers > 4;
  27220. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27221. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27222. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27223. var tempVector3 = BABYLON.Vector3.Zero();
  27224. var finalMatrix = new BABYLON.Matrix();
  27225. var tempMatrix = new BABYLON.Matrix();
  27226. var matWeightIdx = 0;
  27227. var inf;
  27228. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27229. var weight;
  27230. for (inf = 0; inf < 4; inf++) {
  27231. weight = matricesWeightsData[matWeightIdx + inf];
  27232. if (weight > 0) {
  27233. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27234. finalMatrix.addToSelf(tempMatrix);
  27235. }
  27236. else
  27237. break;
  27238. }
  27239. if (needExtras) {
  27240. for (inf = 0; inf < 4; inf++) {
  27241. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27242. if (weight > 0) {
  27243. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27244. finalMatrix.addToSelf(tempMatrix);
  27245. }
  27246. else
  27247. break;
  27248. }
  27249. }
  27250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27251. tempVector3.toArray(positionsData, index);
  27252. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27253. tempVector3.toArray(normalsData, index);
  27254. finalMatrix.reset();
  27255. }
  27256. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27257. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27258. return this;
  27259. };
  27260. // Tools
  27261. /**
  27262. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27263. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27264. */
  27265. Mesh.MinMax = function (meshes) {
  27266. var minVector = null;
  27267. var maxVector = null;
  27268. meshes.forEach(function (mesh, index, array) {
  27269. var boundingInfo = mesh.getBoundingInfo();
  27270. var boundingBox = boundingInfo.boundingBox;
  27271. if (!minVector || !maxVector) {
  27272. minVector = boundingBox.minimumWorld;
  27273. maxVector = boundingBox.maximumWorld;
  27274. }
  27275. else {
  27276. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27277. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27278. }
  27279. });
  27280. if (!minVector || !maxVector) {
  27281. return {
  27282. min: BABYLON.Vector3.Zero(),
  27283. max: BABYLON.Vector3.Zero()
  27284. };
  27285. }
  27286. return {
  27287. min: minVector,
  27288. max: maxVector
  27289. };
  27290. };
  27291. /**
  27292. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27293. */
  27294. Mesh.Center = function (meshesOrMinMaxVector) {
  27295. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27296. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27297. };
  27298. /**
  27299. * Merge the array of meshes into a single mesh for performance reasons.
  27300. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27301. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27302. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27303. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27304. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27305. */
  27306. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27307. if (disposeSource === void 0) { disposeSource = true; }
  27308. var index;
  27309. if (!allow32BitsIndices) {
  27310. var totalVertices = 0;
  27311. // Counting vertices
  27312. for (index = 0; index < meshes.length; index++) {
  27313. if (meshes[index]) {
  27314. totalVertices += meshes[index].getTotalVertices();
  27315. if (totalVertices > 65536) {
  27316. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27317. return null;
  27318. }
  27319. }
  27320. }
  27321. }
  27322. // Merge
  27323. var vertexData = null;
  27324. var otherVertexData;
  27325. var indiceArray = new Array();
  27326. var source = null;
  27327. for (index = 0; index < meshes.length; index++) {
  27328. if (meshes[index]) {
  27329. meshes[index].computeWorldMatrix(true);
  27330. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27331. otherVertexData.transform(meshes[index].getWorldMatrix());
  27332. if (vertexData) {
  27333. vertexData.merge(otherVertexData);
  27334. }
  27335. else {
  27336. vertexData = otherVertexData;
  27337. source = meshes[index];
  27338. }
  27339. if (subdivideWithSubMeshes) {
  27340. indiceArray.push(meshes[index].getTotalIndices());
  27341. }
  27342. }
  27343. }
  27344. source = source;
  27345. if (!meshSubclass) {
  27346. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27347. }
  27348. vertexData.applyToMesh(meshSubclass);
  27349. // Setting properties
  27350. meshSubclass.material = source.material;
  27351. meshSubclass.checkCollisions = source.checkCollisions;
  27352. // Cleaning
  27353. if (disposeSource) {
  27354. for (index = 0; index < meshes.length; index++) {
  27355. if (meshes[index]) {
  27356. meshes[index].dispose();
  27357. }
  27358. }
  27359. }
  27360. // Subdivide
  27361. if (subdivideWithSubMeshes) {
  27362. //-- Suppresions du submesh global
  27363. meshSubclass.releaseSubMeshes();
  27364. index = 0;
  27365. var offset = 0;
  27366. //-- aplique la subdivision en fonction du tableau d'indices
  27367. while (index < indiceArray.length) {
  27368. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27369. offset += indiceArray[index];
  27370. index++;
  27371. }
  27372. }
  27373. return meshSubclass;
  27374. };
  27375. // Consts
  27376. Mesh._FRONTSIDE = 0;
  27377. Mesh._BACKSIDE = 1;
  27378. Mesh._DOUBLESIDE = 2;
  27379. Mesh._DEFAULTSIDE = 0;
  27380. Mesh._NO_CAP = 0;
  27381. Mesh._CAP_START = 1;
  27382. Mesh._CAP_END = 2;
  27383. Mesh._CAP_ALL = 3;
  27384. return Mesh;
  27385. }(BABYLON.AbstractMesh));
  27386. BABYLON.Mesh = Mesh;
  27387. })(BABYLON || (BABYLON = {}));
  27388. //# sourceMappingURL=babylon.mesh.js.map
  27389. var BABYLON;
  27390. (function (BABYLON) {
  27391. var BaseSubMesh = /** @class */ (function () {
  27392. function BaseSubMesh() {
  27393. }
  27394. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27395. get: function () {
  27396. return this._materialEffect;
  27397. },
  27398. enumerable: true,
  27399. configurable: true
  27400. });
  27401. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27402. if (defines === void 0) { defines = null; }
  27403. if (this._materialEffect === effect) {
  27404. if (!effect) {
  27405. this._materialDefines = null;
  27406. }
  27407. return;
  27408. }
  27409. this._materialDefines = defines;
  27410. this._materialEffect = effect;
  27411. };
  27412. return BaseSubMesh;
  27413. }());
  27414. BABYLON.BaseSubMesh = BaseSubMesh;
  27415. var SubMesh = /** @class */ (function (_super) {
  27416. __extends(SubMesh, _super);
  27417. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27418. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27419. var _this = _super.call(this) || this;
  27420. _this.materialIndex = materialIndex;
  27421. _this.verticesStart = verticesStart;
  27422. _this.verticesCount = verticesCount;
  27423. _this.indexStart = indexStart;
  27424. _this.indexCount = indexCount;
  27425. _this._renderId = 0;
  27426. _this._mesh = mesh;
  27427. _this._renderingMesh = renderingMesh || mesh;
  27428. mesh.subMeshes.push(_this);
  27429. _this._trianglePlanes = [];
  27430. _this._id = mesh.subMeshes.length - 1;
  27431. if (createBoundingBox) {
  27432. _this.refreshBoundingInfo();
  27433. mesh.computeWorldMatrix(true);
  27434. }
  27435. return _this;
  27436. }
  27437. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27438. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27439. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27440. };
  27441. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27442. get: function () {
  27443. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27444. },
  27445. enumerable: true,
  27446. configurable: true
  27447. });
  27448. /**
  27449. * Returns the submesh BoudingInfo object.
  27450. */
  27451. SubMesh.prototype.getBoundingInfo = function () {
  27452. if (this.IsGlobal) {
  27453. return this._mesh.getBoundingInfo();
  27454. }
  27455. return this._boundingInfo;
  27456. };
  27457. /**
  27458. * Sets the submesh BoundingInfo.
  27459. * Return the SubMesh.
  27460. */
  27461. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27462. this._boundingInfo = boundingInfo;
  27463. return this;
  27464. };
  27465. /**
  27466. * Returns the mesh of the current submesh.
  27467. */
  27468. SubMesh.prototype.getMesh = function () {
  27469. return this._mesh;
  27470. };
  27471. /**
  27472. * Returns the rendering mesh of the submesh.
  27473. */
  27474. SubMesh.prototype.getRenderingMesh = function () {
  27475. return this._renderingMesh;
  27476. };
  27477. /**
  27478. * Returns the submesh material.
  27479. */
  27480. SubMesh.prototype.getMaterial = function () {
  27481. var rootMaterial = this._renderingMesh.material;
  27482. if (rootMaterial === null || rootMaterial === undefined) {
  27483. return this._mesh.getScene().defaultMaterial;
  27484. }
  27485. else if (rootMaterial.getSubMaterial) {
  27486. var multiMaterial = rootMaterial;
  27487. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27488. if (this._currentMaterial !== effectiveMaterial) {
  27489. this._currentMaterial = effectiveMaterial;
  27490. this._materialDefines = null;
  27491. }
  27492. return effectiveMaterial;
  27493. }
  27494. return rootMaterial;
  27495. };
  27496. // Methods
  27497. /**
  27498. * Sets a new updated BoundingInfo object to the submesh.
  27499. * Returns the SubMesh.
  27500. */
  27501. SubMesh.prototype.refreshBoundingInfo = function () {
  27502. this._lastColliderWorldVertices = null;
  27503. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27504. return this;
  27505. }
  27506. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27507. if (!data) {
  27508. this._boundingInfo = this._mesh.getBoundingInfo();
  27509. return this;
  27510. }
  27511. var indices = this._renderingMesh.getIndices();
  27512. var extend;
  27513. //is this the only submesh?
  27514. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27515. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27516. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27517. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27518. }
  27519. else {
  27520. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27521. }
  27522. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27523. return this;
  27524. };
  27525. SubMesh.prototype._checkCollision = function (collider) {
  27526. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27527. return boundingInfo._checkCollision(collider);
  27528. };
  27529. /**
  27530. * Updates the submesh BoundingInfo.
  27531. * Returns the Submesh.
  27532. */
  27533. SubMesh.prototype.updateBoundingInfo = function (world) {
  27534. var boundingInfo = this.getBoundingInfo();
  27535. if (!boundingInfo) {
  27536. this.refreshBoundingInfo();
  27537. boundingInfo = this.getBoundingInfo();
  27538. }
  27539. boundingInfo.update(world);
  27540. return this;
  27541. };
  27542. /**
  27543. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27544. * Boolean returned.
  27545. */
  27546. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27547. var boundingInfo = this.getBoundingInfo();
  27548. if (!boundingInfo) {
  27549. return false;
  27550. }
  27551. return boundingInfo.isInFrustum(frustumPlanes);
  27552. };
  27553. /**
  27554. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27555. * Boolean returned.
  27556. */
  27557. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27558. var boundingInfo = this.getBoundingInfo();
  27559. if (!boundingInfo) {
  27560. return false;
  27561. }
  27562. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27563. };
  27564. /**
  27565. * Renders the submesh.
  27566. * Returns it.
  27567. */
  27568. SubMesh.prototype.render = function (enableAlphaMode) {
  27569. this._renderingMesh.render(this, enableAlphaMode);
  27570. return this;
  27571. };
  27572. /**
  27573. * Returns a new Index Buffer.
  27574. * Type returned : WebGLBuffer.
  27575. */
  27576. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27577. if (!this._linesIndexBuffer) {
  27578. var linesIndices = [];
  27579. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27580. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27581. }
  27582. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27583. this.linesIndexCount = linesIndices.length;
  27584. }
  27585. return this._linesIndexBuffer;
  27586. };
  27587. /**
  27588. * True is the passed Ray intersects the submesh bounding box.
  27589. * Boolean returned.
  27590. */
  27591. SubMesh.prototype.canIntersects = function (ray) {
  27592. var boundingInfo = this.getBoundingInfo();
  27593. if (!boundingInfo) {
  27594. return false;
  27595. }
  27596. return ray.intersectsBox(boundingInfo.boundingBox);
  27597. };
  27598. /**
  27599. * Returns an object IntersectionInfo.
  27600. */
  27601. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27602. var intersectInfo = null;
  27603. // LineMesh first as it's also a Mesh...
  27604. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27605. var lineMesh = this._mesh;
  27606. // Line test
  27607. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27608. var p0 = positions[indices[index]];
  27609. var p1 = positions[indices[index + 1]];
  27610. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27611. if (length < 0) {
  27612. continue;
  27613. }
  27614. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27615. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27616. if (fastCheck) {
  27617. break;
  27618. }
  27619. }
  27620. }
  27621. }
  27622. else {
  27623. // Triangles test
  27624. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27625. var p0 = positions[indices[index]];
  27626. var p1 = positions[indices[index + 1]];
  27627. var p2 = positions[indices[index + 2]];
  27628. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27629. if (currentIntersectInfo) {
  27630. if (currentIntersectInfo.distance < 0) {
  27631. continue;
  27632. }
  27633. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27634. intersectInfo = currentIntersectInfo;
  27635. intersectInfo.faceId = index / 3;
  27636. if (fastCheck) {
  27637. break;
  27638. }
  27639. }
  27640. }
  27641. }
  27642. }
  27643. return intersectInfo;
  27644. };
  27645. SubMesh.prototype._rebuild = function () {
  27646. if (this._linesIndexBuffer) {
  27647. this._linesIndexBuffer = null;
  27648. }
  27649. };
  27650. // Clone
  27651. /**
  27652. * Creates a new Submesh from the passed Mesh.
  27653. */
  27654. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27655. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27656. if (!this.IsGlobal) {
  27657. var boundingInfo = this.getBoundingInfo();
  27658. if (!boundingInfo) {
  27659. return result;
  27660. }
  27661. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27662. }
  27663. return result;
  27664. };
  27665. // Dispose
  27666. /**
  27667. * Disposes the Submesh.
  27668. * Returns nothing.
  27669. */
  27670. SubMesh.prototype.dispose = function () {
  27671. if (this._linesIndexBuffer) {
  27672. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  27673. this._linesIndexBuffer = null;
  27674. }
  27675. // Remove from mesh
  27676. var index = this._mesh.subMeshes.indexOf(this);
  27677. this._mesh.subMeshes.splice(index, 1);
  27678. };
  27679. // Statics
  27680. /**
  27681. * Creates a new Submesh from the passed parameters :
  27682. * - materialIndex (integer) : the index of the main mesh material.
  27683. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  27684. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  27685. * - mesh (Mesh) : the main mesh to create the submesh from.
  27686. * - renderingMesh (optional Mesh) : rendering mesh.
  27687. */
  27688. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  27689. var minVertexIndex = Number.MAX_VALUE;
  27690. var maxVertexIndex = -Number.MAX_VALUE;
  27691. renderingMesh = (renderingMesh || mesh);
  27692. var indices = renderingMesh.getIndices();
  27693. for (var index = startIndex; index < startIndex + indexCount; index++) {
  27694. var vertexIndex = indices[index];
  27695. if (vertexIndex < minVertexIndex)
  27696. minVertexIndex = vertexIndex;
  27697. if (vertexIndex > maxVertexIndex)
  27698. maxVertexIndex = vertexIndex;
  27699. }
  27700. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  27701. };
  27702. return SubMesh;
  27703. }(BaseSubMesh));
  27704. BABYLON.SubMesh = SubMesh;
  27705. })(BABYLON || (BABYLON = {}));
  27706. //# sourceMappingURL=babylon.subMesh.js.map
  27707. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27708. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27709. s = arguments[i];
  27710. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27711. t[p] = s[p];
  27712. }
  27713. return t;
  27714. };
  27715. var BABYLON;
  27716. (function (BABYLON) {
  27717. var MaterialDefines = /** @class */ (function () {
  27718. function MaterialDefines() {
  27719. this._isDirty = true;
  27720. this._areLightsDirty = true;
  27721. this._areAttributesDirty = true;
  27722. this._areTexturesDirty = true;
  27723. this._areFresnelDirty = true;
  27724. this._areMiscDirty = true;
  27725. this._areImageProcessingDirty = true;
  27726. this._normals = false;
  27727. this._uvs = false;
  27728. this._needNormals = false;
  27729. this._needUVs = false;
  27730. }
  27731. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27732. get: function () {
  27733. return this._isDirty;
  27734. },
  27735. enumerable: true,
  27736. configurable: true
  27737. });
  27738. MaterialDefines.prototype.markAsProcessed = function () {
  27739. this._isDirty = false;
  27740. this._areAttributesDirty = false;
  27741. this._areTexturesDirty = false;
  27742. this._areFresnelDirty = false;
  27743. this._areLightsDirty = false;
  27744. this._areMiscDirty = false;
  27745. this._areImageProcessingDirty = false;
  27746. };
  27747. MaterialDefines.prototype.markAsUnprocessed = function () {
  27748. this._isDirty = true;
  27749. };
  27750. MaterialDefines.prototype.markAllAsDirty = function () {
  27751. this._areTexturesDirty = true;
  27752. this._areAttributesDirty = true;
  27753. this._areLightsDirty = true;
  27754. this._areFresnelDirty = true;
  27755. this._areMiscDirty = true;
  27756. this._areImageProcessingDirty = true;
  27757. this._isDirty = true;
  27758. };
  27759. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27760. this._areImageProcessingDirty = true;
  27761. this._isDirty = true;
  27762. };
  27763. MaterialDefines.prototype.markAsLightDirty = function () {
  27764. this._areLightsDirty = true;
  27765. this._isDirty = true;
  27766. };
  27767. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27768. this._areAttributesDirty = true;
  27769. this._isDirty = true;
  27770. };
  27771. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27772. this._areTexturesDirty = true;
  27773. this._isDirty = true;
  27774. };
  27775. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27776. this._areFresnelDirty = true;
  27777. this._isDirty = true;
  27778. };
  27779. MaterialDefines.prototype.markAsMiscDirty = function () {
  27780. this._areMiscDirty = true;
  27781. this._isDirty = true;
  27782. };
  27783. MaterialDefines.prototype.rebuild = function () {
  27784. if (this._keys) {
  27785. delete this._keys;
  27786. }
  27787. this._keys = [];
  27788. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27789. var key = _a[_i];
  27790. if (key[0] === "_") {
  27791. continue;
  27792. }
  27793. this._keys.push(key);
  27794. }
  27795. };
  27796. MaterialDefines.prototype.isEqual = function (other) {
  27797. if (this._keys.length !== other._keys.length) {
  27798. return false;
  27799. }
  27800. for (var index = 0; index < this._keys.length; index++) {
  27801. var prop = this._keys[index];
  27802. if (this[prop] !== other[prop]) {
  27803. return false;
  27804. }
  27805. }
  27806. return true;
  27807. };
  27808. MaterialDefines.prototype.cloneTo = function (other) {
  27809. if (this._keys.length !== other._keys.length) {
  27810. other._keys = this._keys.slice(0);
  27811. }
  27812. for (var index = 0; index < this._keys.length; index++) {
  27813. var prop = this._keys[index];
  27814. other[prop] = this[prop];
  27815. }
  27816. };
  27817. MaterialDefines.prototype.reset = function () {
  27818. for (var index = 0; index < this._keys.length; index++) {
  27819. var prop = this._keys[index];
  27820. if (typeof (this[prop]) === "number") {
  27821. this[prop] = 0;
  27822. }
  27823. else {
  27824. this[prop] = false;
  27825. }
  27826. }
  27827. };
  27828. MaterialDefines.prototype.toString = function () {
  27829. var result = "";
  27830. for (var index = 0; index < this._keys.length; index++) {
  27831. var prop = this._keys[index];
  27832. var value = this[prop];
  27833. if (typeof (value) === "number") {
  27834. result += "#define " + prop + " " + this[prop] + "\n";
  27835. }
  27836. else if (value) {
  27837. result += "#define " + prop + "\n";
  27838. }
  27839. }
  27840. return result;
  27841. };
  27842. return MaterialDefines;
  27843. }());
  27844. BABYLON.MaterialDefines = MaterialDefines;
  27845. var Material = /** @class */ (function () {
  27846. function Material(name, scene, doNotAdd) {
  27847. this.checkReadyOnEveryCall = false;
  27848. this.checkReadyOnlyOnce = false;
  27849. this.state = "";
  27850. this.alpha = 1.0;
  27851. this._backFaceCulling = true;
  27852. this.doNotSerialize = false;
  27853. this.storeEffectOnSubMeshes = false;
  27854. /**
  27855. * An event triggered when the material is disposed.
  27856. * @type {BABYLON.Observable}
  27857. */
  27858. this.onDisposeObservable = new BABYLON.Observable();
  27859. /**
  27860. * An event triggered when the material is bound.
  27861. * @type {BABYLON.Observable}
  27862. */
  27863. this.onBindObservable = new BABYLON.Observable();
  27864. /**
  27865. * An event triggered when the material is unbound.
  27866. * @type {BABYLON.Observable}
  27867. */
  27868. this.onUnBindObservable = new BABYLON.Observable();
  27869. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27870. this._needDepthPrePass = false;
  27871. this.disableDepthWrite = false;
  27872. this.forceDepthWrite = false;
  27873. this.separateCullingPass = false;
  27874. this._fogEnabled = true;
  27875. this.pointSize = 1.0;
  27876. this.zOffset = 0;
  27877. this._wasPreviouslyReady = false;
  27878. this._fillMode = Material.TriangleFillMode;
  27879. this.name = name;
  27880. this.id = name || BABYLON.Tools.RandomId();
  27881. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27882. if (this._scene.useRightHandedSystem) {
  27883. this.sideOrientation = Material.ClockWiseSideOrientation;
  27884. }
  27885. else {
  27886. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27887. }
  27888. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27889. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27890. if (!doNotAdd) {
  27891. this._scene.materials.push(this);
  27892. }
  27893. }
  27894. Object.defineProperty(Material, "TriangleFillMode", {
  27895. get: function () {
  27896. return Material._TriangleFillMode;
  27897. },
  27898. enumerable: true,
  27899. configurable: true
  27900. });
  27901. Object.defineProperty(Material, "WireFrameFillMode", {
  27902. get: function () {
  27903. return Material._WireFrameFillMode;
  27904. },
  27905. enumerable: true,
  27906. configurable: true
  27907. });
  27908. Object.defineProperty(Material, "PointFillMode", {
  27909. get: function () {
  27910. return Material._PointFillMode;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Object.defineProperty(Material, "PointListDrawMode", {
  27916. get: function () {
  27917. return Material._PointListDrawMode;
  27918. },
  27919. enumerable: true,
  27920. configurable: true
  27921. });
  27922. Object.defineProperty(Material, "LineListDrawMode", {
  27923. get: function () {
  27924. return Material._LineListDrawMode;
  27925. },
  27926. enumerable: true,
  27927. configurable: true
  27928. });
  27929. Object.defineProperty(Material, "LineLoopDrawMode", {
  27930. get: function () {
  27931. return Material._LineLoopDrawMode;
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. Object.defineProperty(Material, "LineStripDrawMode", {
  27937. get: function () {
  27938. return Material._LineStripDrawMode;
  27939. },
  27940. enumerable: true,
  27941. configurable: true
  27942. });
  27943. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27944. get: function () {
  27945. return Material._TriangleStripDrawMode;
  27946. },
  27947. enumerable: true,
  27948. configurable: true
  27949. });
  27950. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27951. get: function () {
  27952. return Material._TriangleFanDrawMode;
  27953. },
  27954. enumerable: true,
  27955. configurable: true
  27956. });
  27957. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27958. get: function () {
  27959. return Material._ClockWiseSideOrientation;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27965. get: function () {
  27966. return Material._CounterClockWiseSideOrientation;
  27967. },
  27968. enumerable: true,
  27969. configurable: true
  27970. });
  27971. Object.defineProperty(Material, "TextureDirtyFlag", {
  27972. get: function () {
  27973. return Material._TextureDirtyFlag;
  27974. },
  27975. enumerable: true,
  27976. configurable: true
  27977. });
  27978. Object.defineProperty(Material, "LightDirtyFlag", {
  27979. get: function () {
  27980. return Material._LightDirtyFlag;
  27981. },
  27982. enumerable: true,
  27983. configurable: true
  27984. });
  27985. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27986. get: function () {
  27987. return Material._FresnelDirtyFlag;
  27988. },
  27989. enumerable: true,
  27990. configurable: true
  27991. });
  27992. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27993. get: function () {
  27994. return Material._AttributesDirtyFlag;
  27995. },
  27996. enumerable: true,
  27997. configurable: true
  27998. });
  27999. Object.defineProperty(Material, "MiscDirtyFlag", {
  28000. get: function () {
  28001. return Material._MiscDirtyFlag;
  28002. },
  28003. enumerable: true,
  28004. configurable: true
  28005. });
  28006. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28007. get: function () {
  28008. return this._backFaceCulling;
  28009. },
  28010. set: function (value) {
  28011. if (this._backFaceCulling === value) {
  28012. return;
  28013. }
  28014. this._backFaceCulling = value;
  28015. this.markAsDirty(Material.TextureDirtyFlag);
  28016. },
  28017. enumerable: true,
  28018. configurable: true
  28019. });
  28020. Object.defineProperty(Material.prototype, "onDispose", {
  28021. set: function (callback) {
  28022. if (this._onDisposeObserver) {
  28023. this.onDisposeObservable.remove(this._onDisposeObserver);
  28024. }
  28025. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28026. },
  28027. enumerable: true,
  28028. configurable: true
  28029. });
  28030. Object.defineProperty(Material.prototype, "onBind", {
  28031. set: function (callback) {
  28032. if (this._onBindObserver) {
  28033. this.onBindObservable.remove(this._onBindObserver);
  28034. }
  28035. this._onBindObserver = this.onBindObservable.add(callback);
  28036. },
  28037. enumerable: true,
  28038. configurable: true
  28039. });
  28040. Object.defineProperty(Material.prototype, "alphaMode", {
  28041. get: function () {
  28042. return this._alphaMode;
  28043. },
  28044. set: function (value) {
  28045. if (this._alphaMode === value) {
  28046. return;
  28047. }
  28048. this._alphaMode = value;
  28049. this.markAsDirty(Material.TextureDirtyFlag);
  28050. },
  28051. enumerable: true,
  28052. configurable: true
  28053. });
  28054. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28055. get: function () {
  28056. return this._needDepthPrePass;
  28057. },
  28058. set: function (value) {
  28059. if (this._needDepthPrePass === value) {
  28060. return;
  28061. }
  28062. this._needDepthPrePass = value;
  28063. if (this._needDepthPrePass) {
  28064. this.checkReadyOnEveryCall = true;
  28065. }
  28066. },
  28067. enumerable: true,
  28068. configurable: true
  28069. });
  28070. Object.defineProperty(Material.prototype, "fogEnabled", {
  28071. get: function () {
  28072. return this._fogEnabled;
  28073. },
  28074. set: function (value) {
  28075. if (this._fogEnabled === value) {
  28076. return;
  28077. }
  28078. this._fogEnabled = value;
  28079. this.markAsDirty(Material.MiscDirtyFlag);
  28080. },
  28081. enumerable: true,
  28082. configurable: true
  28083. });
  28084. Object.defineProperty(Material.prototype, "wireframe", {
  28085. get: function () {
  28086. return this._fillMode === Material.WireFrameFillMode;
  28087. },
  28088. set: function (value) {
  28089. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28090. },
  28091. enumerable: true,
  28092. configurable: true
  28093. });
  28094. Object.defineProperty(Material.prototype, "pointsCloud", {
  28095. get: function () {
  28096. return this._fillMode === Material.PointFillMode;
  28097. },
  28098. set: function (value) {
  28099. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28100. },
  28101. enumerable: true,
  28102. configurable: true
  28103. });
  28104. Object.defineProperty(Material.prototype, "fillMode", {
  28105. get: function () {
  28106. return this._fillMode;
  28107. },
  28108. set: function (value) {
  28109. if (this._fillMode === value) {
  28110. return;
  28111. }
  28112. this._fillMode = value;
  28113. this.markAsDirty(Material.MiscDirtyFlag);
  28114. },
  28115. enumerable: true,
  28116. configurable: true
  28117. });
  28118. /**
  28119. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28120. * subclasses should override adding information pertainent to themselves
  28121. */
  28122. Material.prototype.toString = function (fullDetails) {
  28123. var ret = "Name: " + this.name;
  28124. if (fullDetails) {
  28125. }
  28126. return ret;
  28127. };
  28128. /**
  28129. * Child classes can use it to update shaders
  28130. */
  28131. Material.prototype.getClassName = function () {
  28132. return "Material";
  28133. };
  28134. Object.defineProperty(Material.prototype, "isFrozen", {
  28135. get: function () {
  28136. return this.checkReadyOnlyOnce;
  28137. },
  28138. enumerable: true,
  28139. configurable: true
  28140. });
  28141. Material.prototype.freeze = function () {
  28142. this.checkReadyOnlyOnce = true;
  28143. };
  28144. Material.prototype.unfreeze = function () {
  28145. this.checkReadyOnlyOnce = false;
  28146. };
  28147. Material.prototype.isReady = function (mesh, useInstances) {
  28148. return true;
  28149. };
  28150. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28151. return false;
  28152. };
  28153. Material.prototype.getEffect = function () {
  28154. return this._effect;
  28155. };
  28156. Material.prototype.getScene = function () {
  28157. return this._scene;
  28158. };
  28159. Material.prototype.needAlphaBlending = function () {
  28160. return (this.alpha < 1.0);
  28161. };
  28162. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28163. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28164. };
  28165. Material.prototype.needAlphaTesting = function () {
  28166. return false;
  28167. };
  28168. Material.prototype.getAlphaTestTexture = function () {
  28169. return null;
  28170. };
  28171. Material.prototype.markDirty = function () {
  28172. this._wasPreviouslyReady = false;
  28173. };
  28174. Material.prototype._preBind = function (effect, overrideOrientation) {
  28175. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28176. var engine = this._scene.getEngine();
  28177. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28178. var reverse = orientation === Material.ClockWiseSideOrientation;
  28179. engine.enableEffect(effect ? effect : this._effect);
  28180. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28181. return reverse;
  28182. };
  28183. Material.prototype.bind = function (world, mesh) {
  28184. };
  28185. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28186. };
  28187. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28188. };
  28189. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28190. sceneUbo.bindToEffect(effect, "Scene");
  28191. };
  28192. Material.prototype.bindView = function (effect) {
  28193. if (!this._useUBO) {
  28194. effect.setMatrix("view", this.getScene().getViewMatrix());
  28195. }
  28196. else {
  28197. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28198. }
  28199. };
  28200. Material.prototype.bindViewProjection = function (effect) {
  28201. if (!this._useUBO) {
  28202. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28203. }
  28204. else {
  28205. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28206. }
  28207. };
  28208. Material.prototype._afterBind = function (mesh) {
  28209. this._scene._cachedMaterial = this;
  28210. if (mesh) {
  28211. this._scene._cachedVisibility = mesh.visibility;
  28212. }
  28213. else {
  28214. this._scene._cachedVisibility = 1;
  28215. }
  28216. if (mesh) {
  28217. this.onBindObservable.notifyObservers(mesh);
  28218. }
  28219. if (this.disableDepthWrite) {
  28220. var engine = this._scene.getEngine();
  28221. this._cachedDepthWriteState = engine.getDepthWrite();
  28222. engine.setDepthWrite(false);
  28223. }
  28224. };
  28225. Material.prototype.unbind = function () {
  28226. this.onUnBindObservable.notifyObservers(this);
  28227. if (this.disableDepthWrite) {
  28228. var engine = this._scene.getEngine();
  28229. engine.setDepthWrite(this._cachedDepthWriteState);
  28230. }
  28231. };
  28232. Material.prototype.getActiveTextures = function () {
  28233. return [];
  28234. };
  28235. Material.prototype.hasTexture = function (texture) {
  28236. return false;
  28237. };
  28238. Material.prototype.clone = function (name) {
  28239. return null;
  28240. };
  28241. Material.prototype.getBindedMeshes = function () {
  28242. var result = new Array();
  28243. for (var index = 0; index < this._scene.meshes.length; index++) {
  28244. var mesh = this._scene.meshes[index];
  28245. if (mesh.material === this) {
  28246. result.push(mesh);
  28247. }
  28248. }
  28249. return result;
  28250. };
  28251. /**
  28252. * Force shader compilation including textures ready check
  28253. */
  28254. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28255. var _this = this;
  28256. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28257. var subMesh = new BABYLON.BaseSubMesh();
  28258. var scene = this.getScene();
  28259. var engine = scene.getEngine();
  28260. var checkReady = function () {
  28261. if (!_this._scene || !_this._scene.getEngine()) {
  28262. return;
  28263. }
  28264. if (subMesh._materialDefines) {
  28265. subMesh._materialDefines._renderId = -1;
  28266. }
  28267. var alphaTestState = engine.getAlphaTesting();
  28268. var clipPlaneState = scene.clipPlane;
  28269. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28270. if (localOptions.clipPlane) {
  28271. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28272. }
  28273. if (_this.storeEffectOnSubMeshes) {
  28274. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28275. if (onCompiled) {
  28276. onCompiled(_this);
  28277. }
  28278. }
  28279. else {
  28280. setTimeout(checkReady, 16);
  28281. }
  28282. }
  28283. else {
  28284. if (_this.isReady(mesh)) {
  28285. if (onCompiled) {
  28286. onCompiled(_this);
  28287. }
  28288. }
  28289. else {
  28290. setTimeout(checkReady, 16);
  28291. }
  28292. }
  28293. engine.setAlphaTesting(alphaTestState);
  28294. if (options && options.clipPlane) {
  28295. scene.clipPlane = clipPlaneState;
  28296. }
  28297. };
  28298. checkReady();
  28299. };
  28300. Material.prototype.markAsDirty = function (flag) {
  28301. if (flag & Material.TextureDirtyFlag) {
  28302. this._markAllSubMeshesAsTexturesDirty();
  28303. }
  28304. if (flag & Material.LightDirtyFlag) {
  28305. this._markAllSubMeshesAsLightsDirty();
  28306. }
  28307. if (flag & Material.FresnelDirtyFlag) {
  28308. this._markAllSubMeshesAsFresnelDirty();
  28309. }
  28310. if (flag & Material.AttributesDirtyFlag) {
  28311. this._markAllSubMeshesAsAttributesDirty();
  28312. }
  28313. if (flag & Material.MiscDirtyFlag) {
  28314. this._markAllSubMeshesAsMiscDirty();
  28315. }
  28316. this.getScene().resetCachedMaterial();
  28317. };
  28318. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28319. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28320. var mesh = _a[_i];
  28321. if (!mesh.subMeshes) {
  28322. continue;
  28323. }
  28324. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28325. var subMesh = _c[_b];
  28326. if (subMesh.getMaterial() !== this) {
  28327. continue;
  28328. }
  28329. if (!subMesh._materialDefines) {
  28330. continue;
  28331. }
  28332. func(subMesh._materialDefines);
  28333. }
  28334. }
  28335. };
  28336. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28338. };
  28339. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28340. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28341. };
  28342. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28344. };
  28345. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28346. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28347. };
  28348. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28350. };
  28351. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28352. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28353. };
  28354. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28355. // Animations
  28356. this.getScene().stopAnimation(this);
  28357. // Remove from scene
  28358. var index = this._scene.materials.indexOf(this);
  28359. if (index >= 0) {
  28360. this._scene.materials.splice(index, 1);
  28361. }
  28362. // Remove from meshes
  28363. for (index = 0; index < this._scene.meshes.length; index++) {
  28364. var mesh = this._scene.meshes[index];
  28365. if (mesh.material === this) {
  28366. mesh.material = null;
  28367. if (mesh.geometry) {
  28368. var geometry = (mesh.geometry);
  28369. if (this.storeEffectOnSubMeshes) {
  28370. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28371. var subMesh = _a[_i];
  28372. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28373. if (forceDisposeEffect && subMesh._materialEffect) {
  28374. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28375. }
  28376. }
  28377. }
  28378. else {
  28379. geometry._releaseVertexArrayObject(this._effect);
  28380. }
  28381. }
  28382. }
  28383. }
  28384. this._uniformBuffer.dispose();
  28385. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28386. if (forceDisposeEffect && this._effect) {
  28387. if (!this.storeEffectOnSubMeshes) {
  28388. this._scene.getEngine()._releaseEffect(this._effect);
  28389. }
  28390. this._effect = null;
  28391. }
  28392. // Callback
  28393. this.onDisposeObservable.notifyObservers(this);
  28394. this.onDisposeObservable.clear();
  28395. this.onBindObservable.clear();
  28396. this.onUnBindObservable.clear();
  28397. };
  28398. Material.prototype.serialize = function () {
  28399. return BABYLON.SerializationHelper.Serialize(this);
  28400. };
  28401. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28402. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28403. multiMaterial.id = parsedMultiMaterial.id;
  28404. if (BABYLON.Tags) {
  28405. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28406. }
  28407. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28408. var subMatId = parsedMultiMaterial.materials[matIndex];
  28409. if (subMatId) {
  28410. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28411. }
  28412. else {
  28413. multiMaterial.subMaterials.push(null);
  28414. }
  28415. }
  28416. return multiMaterial;
  28417. };
  28418. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28419. if (!parsedMaterial.customType) {
  28420. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28421. }
  28422. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28423. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28424. if (!BABYLON.LegacyPBRMaterial) {
  28425. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28426. return;
  28427. }
  28428. }
  28429. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28430. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28431. ;
  28432. };
  28433. // Triangle views
  28434. Material._TriangleFillMode = 0;
  28435. Material._WireFrameFillMode = 1;
  28436. Material._PointFillMode = 2;
  28437. // Draw modes
  28438. Material._PointListDrawMode = 3;
  28439. Material._LineListDrawMode = 4;
  28440. Material._LineLoopDrawMode = 5;
  28441. Material._LineStripDrawMode = 6;
  28442. Material._TriangleStripDrawMode = 7;
  28443. Material._TriangleFanDrawMode = 8;
  28444. Material._ClockWiseSideOrientation = 0;
  28445. Material._CounterClockWiseSideOrientation = 1;
  28446. Material._TextureDirtyFlag = 1;
  28447. Material._LightDirtyFlag = 2;
  28448. Material._FresnelDirtyFlag = 4;
  28449. Material._AttributesDirtyFlag = 8;
  28450. Material._MiscDirtyFlag = 16;
  28451. __decorate([
  28452. BABYLON.serialize()
  28453. ], Material.prototype, "id", void 0);
  28454. __decorate([
  28455. BABYLON.serialize()
  28456. ], Material.prototype, "name", void 0);
  28457. __decorate([
  28458. BABYLON.serialize()
  28459. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28460. __decorate([
  28461. BABYLON.serialize()
  28462. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28463. __decorate([
  28464. BABYLON.serialize()
  28465. ], Material.prototype, "state", void 0);
  28466. __decorate([
  28467. BABYLON.serialize()
  28468. ], Material.prototype, "alpha", void 0);
  28469. __decorate([
  28470. BABYLON.serialize("backFaceCulling")
  28471. ], Material.prototype, "_backFaceCulling", void 0);
  28472. __decorate([
  28473. BABYLON.serialize()
  28474. ], Material.prototype, "sideOrientation", void 0);
  28475. __decorate([
  28476. BABYLON.serialize("alphaMode")
  28477. ], Material.prototype, "_alphaMode", void 0);
  28478. __decorate([
  28479. BABYLON.serialize()
  28480. ], Material.prototype, "_needDepthPrePass", void 0);
  28481. __decorate([
  28482. BABYLON.serialize()
  28483. ], Material.prototype, "disableDepthWrite", void 0);
  28484. __decorate([
  28485. BABYLON.serialize()
  28486. ], Material.prototype, "forceDepthWrite", void 0);
  28487. __decorate([
  28488. BABYLON.serialize()
  28489. ], Material.prototype, "separateCullingPass", void 0);
  28490. __decorate([
  28491. BABYLON.serialize("fogEnabled")
  28492. ], Material.prototype, "_fogEnabled", void 0);
  28493. __decorate([
  28494. BABYLON.serialize()
  28495. ], Material.prototype, "pointSize", void 0);
  28496. __decorate([
  28497. BABYLON.serialize()
  28498. ], Material.prototype, "zOffset", void 0);
  28499. __decorate([
  28500. BABYLON.serialize()
  28501. ], Material.prototype, "wireframe", null);
  28502. __decorate([
  28503. BABYLON.serialize()
  28504. ], Material.prototype, "pointsCloud", null);
  28505. __decorate([
  28506. BABYLON.serialize()
  28507. ], Material.prototype, "fillMode", null);
  28508. return Material;
  28509. }());
  28510. BABYLON.Material = Material;
  28511. })(BABYLON || (BABYLON = {}));
  28512. //# sourceMappingURL=babylon.material.js.map
  28513. var BABYLON;
  28514. (function (BABYLON) {
  28515. var UniformBuffer = /** @class */ (function () {
  28516. /**
  28517. * Uniform buffer objects.
  28518. *
  28519. * Handles blocks of uniform on the GPU.
  28520. *
  28521. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28522. *
  28523. * For more information, please refer to :
  28524. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28525. */
  28526. function UniformBuffer(engine, data, dynamic) {
  28527. this._engine = engine;
  28528. this._noUBO = !engine.supportsUniformBuffers;
  28529. this._dynamic = dynamic;
  28530. this._data = data || [];
  28531. this._uniformLocations = {};
  28532. this._uniformSizes = {};
  28533. this._uniformLocationPointer = 0;
  28534. this._needSync = false;
  28535. if (this._noUBO) {
  28536. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28537. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28538. this.updateFloat = this._updateFloatForEffect;
  28539. this.updateFloat2 = this._updateFloat2ForEffect;
  28540. this.updateFloat3 = this._updateFloat3ForEffect;
  28541. this.updateFloat4 = this._updateFloat4ForEffect;
  28542. this.updateMatrix = this._updateMatrixForEffect;
  28543. this.updateVector3 = this._updateVector3ForEffect;
  28544. this.updateVector4 = this._updateVector4ForEffect;
  28545. this.updateColor3 = this._updateColor3ForEffect;
  28546. this.updateColor4 = this._updateColor4ForEffect;
  28547. }
  28548. else {
  28549. this._engine._uniformBuffers.push(this);
  28550. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28551. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28552. this.updateFloat = this._updateFloatForUniform;
  28553. this.updateFloat2 = this._updateFloat2ForUniform;
  28554. this.updateFloat3 = this._updateFloat3ForUniform;
  28555. this.updateFloat4 = this._updateFloat4ForUniform;
  28556. this.updateMatrix = this._updateMatrixForUniform;
  28557. this.updateVector3 = this._updateVector3ForUniform;
  28558. this.updateVector4 = this._updateVector4ForUniform;
  28559. this.updateColor3 = this._updateColor3ForUniform;
  28560. this.updateColor4 = this._updateColor4ForUniform;
  28561. }
  28562. }
  28563. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28564. // Properties
  28565. /**
  28566. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28567. * or just falling back on setUniformXXX calls.
  28568. */
  28569. get: function () {
  28570. return !this._noUBO;
  28571. },
  28572. enumerable: true,
  28573. configurable: true
  28574. });
  28575. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28576. /**
  28577. * Indicates if the WebGL underlying uniform buffer is in sync
  28578. * with the javascript cache data.
  28579. */
  28580. get: function () {
  28581. return !this._needSync;
  28582. },
  28583. enumerable: true,
  28584. configurable: true
  28585. });
  28586. /**
  28587. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28588. * Also, a dynamic UniformBuffer will disable cache verification and always
  28589. * update the underlying WebGL uniform buffer to the GPU.
  28590. */
  28591. UniformBuffer.prototype.isDynamic = function () {
  28592. return this._dynamic !== undefined;
  28593. };
  28594. /**
  28595. * The data cache on JS side.
  28596. */
  28597. UniformBuffer.prototype.getData = function () {
  28598. return this._bufferData;
  28599. };
  28600. /**
  28601. * The underlying WebGL Uniform buffer.
  28602. */
  28603. UniformBuffer.prototype.getBuffer = function () {
  28604. return this._buffer;
  28605. };
  28606. /**
  28607. * std140 layout specifies how to align data within an UBO structure.
  28608. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28609. * for specs.
  28610. */
  28611. UniformBuffer.prototype._fillAlignment = function (size) {
  28612. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28613. // and 4x4 matrices
  28614. // TODO : change if other types are used
  28615. var alignment;
  28616. if (size <= 2) {
  28617. alignment = size;
  28618. }
  28619. else {
  28620. alignment = 4;
  28621. }
  28622. if ((this._uniformLocationPointer % alignment) !== 0) {
  28623. var oldPointer = this._uniformLocationPointer;
  28624. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28625. var diff = this._uniformLocationPointer - oldPointer;
  28626. for (var i = 0; i < diff; i++) {
  28627. this._data.push(0);
  28628. }
  28629. }
  28630. };
  28631. /**
  28632. * Adds an uniform in the buffer.
  28633. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28634. * for the layout to be correct !
  28635. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28636. * @param {number|number[]} size Data size, or data directly.
  28637. */
  28638. UniformBuffer.prototype.addUniform = function (name, size) {
  28639. if (this._noUBO) {
  28640. return;
  28641. }
  28642. if (this._uniformLocations[name] !== undefined) {
  28643. // Already existing uniform
  28644. return;
  28645. }
  28646. // This function must be called in the order of the shader layout !
  28647. // size can be the size of the uniform, or data directly
  28648. var data;
  28649. if (size instanceof Array) {
  28650. data = size;
  28651. size = data.length;
  28652. }
  28653. else {
  28654. size = size;
  28655. data = [];
  28656. // Fill with zeros
  28657. for (var i = 0; i < size; i++) {
  28658. data.push(0);
  28659. }
  28660. }
  28661. this._fillAlignment(size);
  28662. this._uniformSizes[name] = size;
  28663. this._uniformLocations[name] = this._uniformLocationPointer;
  28664. this._uniformLocationPointer += size;
  28665. for (var i = 0; i < size; i++) {
  28666. this._data.push(data[i]);
  28667. }
  28668. this._needSync = true;
  28669. };
  28670. /**
  28671. * Wrapper for addUniform.
  28672. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28673. * @param {Matrix} mat A 4x4 matrix.
  28674. */
  28675. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28676. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28677. };
  28678. /**
  28679. * Wrapper for addUniform.
  28680. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28681. * @param {number} x
  28682. * @param {number} y
  28683. */
  28684. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28685. var temp = [x, y];
  28686. this.addUniform(name, temp);
  28687. };
  28688. /**
  28689. * Wrapper for addUniform.
  28690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28691. * @param {number} x
  28692. * @param {number} y
  28693. * @param {number} z
  28694. */
  28695. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28696. var temp = [x, y, z];
  28697. this.addUniform(name, temp);
  28698. };
  28699. /**
  28700. * Wrapper for addUniform.
  28701. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28702. * @param {Color3} color
  28703. */
  28704. UniformBuffer.prototype.addColor3 = function (name, color) {
  28705. var temp = new Array();
  28706. color.toArray(temp);
  28707. this.addUniform(name, temp);
  28708. };
  28709. /**
  28710. * Wrapper for addUniform.
  28711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28712. * @param {Color3} color
  28713. * @param {number} alpha
  28714. */
  28715. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28716. var temp = new Array();
  28717. color.toArray(temp);
  28718. temp.push(alpha);
  28719. this.addUniform(name, temp);
  28720. };
  28721. /**
  28722. * Wrapper for addUniform.
  28723. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28724. * @param {Vector3} vector
  28725. */
  28726. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28727. var temp = new Array();
  28728. vector.toArray(temp);
  28729. this.addUniform(name, temp);
  28730. };
  28731. /**
  28732. * Wrapper for addUniform.
  28733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28734. */
  28735. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28736. this.addUniform(name, 12);
  28737. };
  28738. /**
  28739. * Wrapper for addUniform.
  28740. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28741. */
  28742. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28743. this.addUniform(name, 8);
  28744. };
  28745. /**
  28746. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28747. */
  28748. UniformBuffer.prototype.create = function () {
  28749. if (this._noUBO) {
  28750. return;
  28751. }
  28752. if (this._buffer) {
  28753. return; // nothing to do
  28754. }
  28755. // See spec, alignment must be filled as a vec4
  28756. this._fillAlignment(4);
  28757. this._bufferData = new Float32Array(this._data);
  28758. this._rebuild();
  28759. this._needSync = true;
  28760. };
  28761. UniformBuffer.prototype._rebuild = function () {
  28762. if (this._noUBO) {
  28763. return;
  28764. }
  28765. if (this._dynamic) {
  28766. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28767. }
  28768. else {
  28769. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28770. }
  28771. };
  28772. /**
  28773. * Updates the WebGL Uniform Buffer on the GPU.
  28774. * If the `dynamic` flag is set to true, no cache comparison is done.
  28775. * Otherwise, the buffer will be updated only if the cache differs.
  28776. */
  28777. UniformBuffer.prototype.update = function () {
  28778. if (!this._buffer) {
  28779. this.create();
  28780. return;
  28781. }
  28782. if (!this._dynamic && !this._needSync) {
  28783. return;
  28784. }
  28785. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28786. this._needSync = false;
  28787. };
  28788. /**
  28789. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28790. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28791. * @param {number[]|Float32Array} data Flattened data
  28792. * @param {number} size Size of the data.
  28793. */
  28794. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28795. var location = this._uniformLocations[uniformName];
  28796. if (location === undefined) {
  28797. if (this._buffer) {
  28798. // Cannot add an uniform if the buffer is already created
  28799. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28800. return;
  28801. }
  28802. this.addUniform(uniformName, size);
  28803. location = this._uniformLocations[uniformName];
  28804. }
  28805. if (!this._buffer) {
  28806. this.create();
  28807. }
  28808. if (!this._dynamic) {
  28809. // Cache for static uniform buffers
  28810. var changed = false;
  28811. for (var i = 0; i < size; i++) {
  28812. if (this._bufferData[location + i] !== data[i]) {
  28813. changed = true;
  28814. this._bufferData[location + i] = data[i];
  28815. }
  28816. }
  28817. this._needSync = this._needSync || changed;
  28818. }
  28819. else {
  28820. // No cache for dynamic
  28821. for (var i = 0; i < size; i++) {
  28822. this._bufferData[location + i] = data[i];
  28823. }
  28824. }
  28825. };
  28826. // Update methods
  28827. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28828. // To match std140, matrix must be realigned
  28829. for (var i = 0; i < 3; i++) {
  28830. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28831. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28832. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28833. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28834. }
  28835. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28836. };
  28837. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28838. this._currentEffect.setMatrix3x3(name, matrix);
  28839. };
  28840. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28841. this._currentEffect.setMatrix2x2(name, matrix);
  28842. };
  28843. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28844. // To match std140, matrix must be realigned
  28845. for (var i = 0; i < 2; i++) {
  28846. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28847. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28848. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28849. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28850. }
  28851. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28852. };
  28853. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28854. this._currentEffect.setFloat(name, x);
  28855. };
  28856. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28857. UniformBuffer._tempBuffer[0] = x;
  28858. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28859. };
  28860. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28861. if (suffix === void 0) { suffix = ""; }
  28862. this._currentEffect.setFloat2(name + suffix, x, y);
  28863. };
  28864. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28865. if (suffix === void 0) { suffix = ""; }
  28866. UniformBuffer._tempBuffer[0] = x;
  28867. UniformBuffer._tempBuffer[1] = y;
  28868. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28869. };
  28870. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28871. if (suffix === void 0) { suffix = ""; }
  28872. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28873. };
  28874. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28875. if (suffix === void 0) { suffix = ""; }
  28876. UniformBuffer._tempBuffer[0] = x;
  28877. UniformBuffer._tempBuffer[1] = y;
  28878. UniformBuffer._tempBuffer[2] = z;
  28879. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28880. };
  28881. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28882. if (suffix === void 0) { suffix = ""; }
  28883. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28884. };
  28885. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28886. if (suffix === void 0) { suffix = ""; }
  28887. UniformBuffer._tempBuffer[0] = x;
  28888. UniformBuffer._tempBuffer[1] = y;
  28889. UniformBuffer._tempBuffer[2] = z;
  28890. UniformBuffer._tempBuffer[3] = w;
  28891. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28892. };
  28893. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28894. this._currentEffect.setMatrix(name, mat);
  28895. };
  28896. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28897. this.updateUniform(name, mat.toArray(), 16);
  28898. };
  28899. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28900. this._currentEffect.setVector3(name, vector);
  28901. };
  28902. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28903. vector.toArray(UniformBuffer._tempBuffer);
  28904. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28905. };
  28906. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28907. this._currentEffect.setVector4(name, vector);
  28908. };
  28909. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28910. vector.toArray(UniformBuffer._tempBuffer);
  28911. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28912. };
  28913. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28914. if (suffix === void 0) { suffix = ""; }
  28915. this._currentEffect.setColor3(name + suffix, color);
  28916. };
  28917. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28918. if (suffix === void 0) { suffix = ""; }
  28919. color.toArray(UniformBuffer._tempBuffer);
  28920. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28921. };
  28922. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28923. if (suffix === void 0) { suffix = ""; }
  28924. this._currentEffect.setColor4(name + suffix, color, alpha);
  28925. };
  28926. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28927. if (suffix === void 0) { suffix = ""; }
  28928. color.toArray(UniformBuffer._tempBuffer);
  28929. UniformBuffer._tempBuffer[3] = alpha;
  28930. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28931. };
  28932. /**
  28933. * Sets a sampler uniform on the effect.
  28934. * @param {string} name Name of the sampler.
  28935. * @param {Texture} texture
  28936. */
  28937. UniformBuffer.prototype.setTexture = function (name, texture) {
  28938. this._currentEffect.setTexture(name, texture);
  28939. };
  28940. /**
  28941. * Directly updates the value of the uniform in the cache AND on the GPU.
  28942. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28943. * @param {number[]|Float32Array} data Flattened data
  28944. */
  28945. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28946. this.updateUniform(uniformName, data, data.length);
  28947. this.update();
  28948. };
  28949. /**
  28950. * Binds this uniform buffer to an effect.
  28951. * @param {Effect} effect
  28952. * @param {string} name Name of the uniform block in the shader.
  28953. */
  28954. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28955. this._currentEffect = effect;
  28956. if (this._noUBO || !this._buffer) {
  28957. return;
  28958. }
  28959. effect.bindUniformBuffer(this._buffer, name);
  28960. };
  28961. /**
  28962. * Disposes the uniform buffer.
  28963. */
  28964. UniformBuffer.prototype.dispose = function () {
  28965. if (this._noUBO) {
  28966. return;
  28967. }
  28968. var index = this._engine._uniformBuffers.indexOf(this);
  28969. if (index !== -1) {
  28970. this._engine._uniformBuffers.splice(index, 1);
  28971. }
  28972. if (!this._buffer) {
  28973. return;
  28974. }
  28975. if (this._engine._releaseBuffer(this._buffer)) {
  28976. this._buffer = null;
  28977. }
  28978. };
  28979. // Pool for avoiding memory leaks
  28980. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28981. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28982. return UniformBuffer;
  28983. }());
  28984. BABYLON.UniformBuffer = UniformBuffer;
  28985. })(BABYLON || (BABYLON = {}));
  28986. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28987. var BABYLON;
  28988. (function (BABYLON) {
  28989. var VertexData = /** @class */ (function () {
  28990. function VertexData() {
  28991. }
  28992. VertexData.prototype.set = function (data, kind) {
  28993. switch (kind) {
  28994. case BABYLON.VertexBuffer.PositionKind:
  28995. this.positions = data;
  28996. break;
  28997. case BABYLON.VertexBuffer.NormalKind:
  28998. this.normals = data;
  28999. break;
  29000. case BABYLON.VertexBuffer.TangentKind:
  29001. this.tangents = data;
  29002. break;
  29003. case BABYLON.VertexBuffer.UVKind:
  29004. this.uvs = data;
  29005. break;
  29006. case BABYLON.VertexBuffer.UV2Kind:
  29007. this.uvs2 = data;
  29008. break;
  29009. case BABYLON.VertexBuffer.UV3Kind:
  29010. this.uvs3 = data;
  29011. break;
  29012. case BABYLON.VertexBuffer.UV4Kind:
  29013. this.uvs4 = data;
  29014. break;
  29015. case BABYLON.VertexBuffer.UV5Kind:
  29016. this.uvs5 = data;
  29017. break;
  29018. case BABYLON.VertexBuffer.UV6Kind:
  29019. this.uvs6 = data;
  29020. break;
  29021. case BABYLON.VertexBuffer.ColorKind:
  29022. this.colors = data;
  29023. break;
  29024. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29025. this.matricesIndices = data;
  29026. break;
  29027. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29028. this.matricesWeights = data;
  29029. break;
  29030. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29031. this.matricesIndicesExtra = data;
  29032. break;
  29033. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29034. this.matricesWeightsExtra = data;
  29035. break;
  29036. }
  29037. };
  29038. /**
  29039. * Associates the vertexData to the passed Mesh.
  29040. * Sets it as updatable or not (default `false`).
  29041. * Returns the VertexData.
  29042. */
  29043. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29044. this._applyTo(mesh, updatable);
  29045. return this;
  29046. };
  29047. /**
  29048. * Associates the vertexData to the passed Geometry.
  29049. * Sets it as updatable or not (default `false`).
  29050. * Returns the VertexData.
  29051. */
  29052. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29053. this._applyTo(geometry, updatable);
  29054. return this;
  29055. };
  29056. /**
  29057. * Updates the associated mesh.
  29058. * Returns the VertexData.
  29059. */
  29060. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29061. this._update(mesh);
  29062. return this;
  29063. };
  29064. /**
  29065. * Updates the associated geometry.
  29066. * Returns the VertexData.
  29067. */
  29068. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29069. this._update(geometry);
  29070. return this;
  29071. };
  29072. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29073. if (updatable === void 0) { updatable = false; }
  29074. if (this.positions) {
  29075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29076. }
  29077. if (this.normals) {
  29078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29079. }
  29080. if (this.tangents) {
  29081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29082. }
  29083. if (this.uvs) {
  29084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29085. }
  29086. if (this.uvs2) {
  29087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29088. }
  29089. if (this.uvs3) {
  29090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29091. }
  29092. if (this.uvs4) {
  29093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29094. }
  29095. if (this.uvs5) {
  29096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29097. }
  29098. if (this.uvs6) {
  29099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29100. }
  29101. if (this.colors) {
  29102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29103. }
  29104. if (this.matricesIndices) {
  29105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29106. }
  29107. if (this.matricesWeights) {
  29108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29109. }
  29110. if (this.matricesIndicesExtra) {
  29111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29112. }
  29113. if (this.matricesWeightsExtra) {
  29114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29115. }
  29116. if (this.indices) {
  29117. meshOrGeometry.setIndices(this.indices, null, updatable);
  29118. }
  29119. return this;
  29120. };
  29121. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29122. if (this.positions) {
  29123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29124. }
  29125. if (this.normals) {
  29126. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29127. }
  29128. if (this.tangents) {
  29129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29130. }
  29131. if (this.uvs) {
  29132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29133. }
  29134. if (this.uvs2) {
  29135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29136. }
  29137. if (this.uvs3) {
  29138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29139. }
  29140. if (this.uvs4) {
  29141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29142. }
  29143. if (this.uvs5) {
  29144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29145. }
  29146. if (this.uvs6) {
  29147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29148. }
  29149. if (this.colors) {
  29150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29151. }
  29152. if (this.matricesIndices) {
  29153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29154. }
  29155. if (this.matricesWeights) {
  29156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29157. }
  29158. if (this.matricesIndicesExtra) {
  29159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29160. }
  29161. if (this.matricesWeightsExtra) {
  29162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29163. }
  29164. if (this.indices) {
  29165. meshOrGeometry.setIndices(this.indices, null);
  29166. }
  29167. return this;
  29168. };
  29169. /**
  29170. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29171. * Returns the VertexData.
  29172. */
  29173. VertexData.prototype.transform = function (matrix) {
  29174. var transformed = BABYLON.Vector3.Zero();
  29175. var index;
  29176. if (this.positions) {
  29177. var position = BABYLON.Vector3.Zero();
  29178. for (index = 0; index < this.positions.length; index += 3) {
  29179. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29180. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29181. this.positions[index] = transformed.x;
  29182. this.positions[index + 1] = transformed.y;
  29183. this.positions[index + 2] = transformed.z;
  29184. }
  29185. }
  29186. if (this.normals) {
  29187. var normal = BABYLON.Vector3.Zero();
  29188. for (index = 0; index < this.normals.length; index += 3) {
  29189. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29190. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29191. this.normals[index] = transformed.x;
  29192. this.normals[index + 1] = transformed.y;
  29193. this.normals[index + 2] = transformed.z;
  29194. }
  29195. }
  29196. if (this.tangents) {
  29197. var tangent = BABYLON.Vector4.Zero();
  29198. var tangentTransformed = BABYLON.Vector4.Zero();
  29199. for (index = 0; index < this.tangents.length; index += 4) {
  29200. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29201. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29202. this.tangents[index] = tangentTransformed.x;
  29203. this.tangents[index + 1] = tangentTransformed.y;
  29204. this.tangents[index + 2] = tangentTransformed.z;
  29205. this.tangents[index + 3] = tangentTransformed.w;
  29206. }
  29207. }
  29208. return this;
  29209. };
  29210. /**
  29211. * Merges the passed VertexData into the current one.
  29212. * Returns the modified VertexData.
  29213. */
  29214. VertexData.prototype.merge = function (other, options) {
  29215. options = options || {};
  29216. if (other.indices) {
  29217. if (!this.indices) {
  29218. this.indices = [];
  29219. }
  29220. var offset = this.positions ? this.positions.length / 3 : 0;
  29221. for (var index = 0; index < other.indices.length; index++) {
  29222. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29223. this.indices.push(other.indices[index] + offset);
  29224. }
  29225. }
  29226. this.positions = this._mergeElement(this.positions, other.positions);
  29227. if (!this.positions) {
  29228. return this;
  29229. }
  29230. var count = this.positions.length / 3;
  29231. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29232. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29233. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29234. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29235. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29236. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29237. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29238. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29239. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29240. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29241. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29242. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29243. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29244. return this;
  29245. };
  29246. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29247. if (length === void 0) { length = 0; }
  29248. if (defaultValue === void 0) { defaultValue = 0; }
  29249. if (!other && !source) {
  29250. return null;
  29251. }
  29252. if (!other) {
  29253. var padding = new Float32Array(source.length);
  29254. padding.fill(defaultValue);
  29255. return this._mergeElement(source, padding, length);
  29256. }
  29257. if (!source) {
  29258. if (length === 0 || length === other.length) {
  29259. return other;
  29260. }
  29261. var padding = new Float32Array(length - other.length);
  29262. padding.fill(defaultValue);
  29263. return this._mergeElement(padding, other, length);
  29264. }
  29265. var len = other.length + source.length;
  29266. var isSrcTypedArray = source instanceof Float32Array;
  29267. var isOthTypedArray = other instanceof Float32Array;
  29268. // use non-loop method when the source is Float32Array
  29269. if (isSrcTypedArray) {
  29270. var ret32 = new Float32Array(len);
  29271. ret32.set(source);
  29272. ret32.set(other, source.length);
  29273. return ret32;
  29274. // source is number[], when other is also use concat
  29275. }
  29276. else if (!isOthTypedArray) {
  29277. return source.concat(other);
  29278. // source is a number[], but other is a Float32Array, loop required
  29279. }
  29280. else {
  29281. var ret = source.slice(0); // copy source to a separate array
  29282. for (var i = 0, len = other.length; i < len; i++) {
  29283. ret.push(other[i]);
  29284. }
  29285. return ret;
  29286. }
  29287. };
  29288. /**
  29289. * Serializes the VertexData.
  29290. * Returns a serialized object.
  29291. */
  29292. VertexData.prototype.serialize = function () {
  29293. var serializationObject = this.serialize();
  29294. if (this.positions) {
  29295. serializationObject.positions = this.positions;
  29296. }
  29297. if (this.normals) {
  29298. serializationObject.normals = this.normals;
  29299. }
  29300. if (this.tangents) {
  29301. serializationObject.tangents = this.tangents;
  29302. }
  29303. if (this.uvs) {
  29304. serializationObject.uvs = this.uvs;
  29305. }
  29306. if (this.uvs2) {
  29307. serializationObject.uvs2 = this.uvs2;
  29308. }
  29309. if (this.uvs3) {
  29310. serializationObject.uvs3 = this.uvs3;
  29311. }
  29312. if (this.uvs4) {
  29313. serializationObject.uvs4 = this.uvs4;
  29314. }
  29315. if (this.uvs5) {
  29316. serializationObject.uvs5 = this.uvs5;
  29317. }
  29318. if (this.uvs6) {
  29319. serializationObject.uvs6 = this.uvs6;
  29320. }
  29321. if (this.colors) {
  29322. serializationObject.colors = this.colors;
  29323. }
  29324. if (this.matricesIndices) {
  29325. serializationObject.matricesIndices = this.matricesIndices;
  29326. serializationObject.matricesIndices._isExpanded = true;
  29327. }
  29328. if (this.matricesWeights) {
  29329. serializationObject.matricesWeights = this.matricesWeights;
  29330. }
  29331. if (this.matricesIndicesExtra) {
  29332. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29333. serializationObject.matricesIndicesExtra._isExpanded = true;
  29334. }
  29335. if (this.matricesWeightsExtra) {
  29336. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29337. }
  29338. serializationObject.indices = this.indices;
  29339. return serializationObject;
  29340. };
  29341. // Statics
  29342. /**
  29343. * Returns the object VertexData associated to the passed mesh.
  29344. */
  29345. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29346. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29347. };
  29348. /**
  29349. * Returns the object VertexData associated to the passed geometry.
  29350. */
  29351. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29352. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29353. };
  29354. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29355. var result = new VertexData();
  29356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29357. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29358. }
  29359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29360. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29361. }
  29362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29363. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29364. }
  29365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29366. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29367. }
  29368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29369. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29370. }
  29371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29372. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29373. }
  29374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29375. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29376. }
  29377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29378. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29379. }
  29380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29381. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29382. }
  29383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29384. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29385. }
  29386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29387. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29388. }
  29389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29390. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29391. }
  29392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29393. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29394. }
  29395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29396. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29397. }
  29398. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29399. return result;
  29400. };
  29401. /**
  29402. * Creates the vertexData of the Ribbon.
  29403. */
  29404. VertexData.CreateRibbon = function (options) {
  29405. var pathArray = options.pathArray;
  29406. var closeArray = options.closeArray || false;
  29407. var closePath = options.closePath || false;
  29408. var invertUV = options.invertUV || false;
  29409. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29410. var offset = options.offset || defaultOffset;
  29411. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29413. var customUV = options.uvs;
  29414. var customColors = options.colors;
  29415. var positions = [];
  29416. var indices = [];
  29417. var normals = [];
  29418. var uvs = [];
  29419. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29420. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29421. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29422. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29423. var minlg; // minimal length among all paths from pathArray
  29424. var lg = []; // array of path lengths : nb of vertex per path
  29425. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29426. var p; // path iterator
  29427. var i; // point iterator
  29428. var j; // point iterator
  29429. // if single path in pathArray
  29430. if (pathArray.length < 2) {
  29431. var ar1 = [];
  29432. var ar2 = [];
  29433. for (i = 0; i < pathArray[0].length - offset; i++) {
  29434. ar1.push(pathArray[0][i]);
  29435. ar2.push(pathArray[0][i + offset]);
  29436. }
  29437. pathArray = [ar1, ar2];
  29438. }
  29439. // positions and horizontal distances (u)
  29440. var idc = 0;
  29441. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29442. var path;
  29443. var l;
  29444. minlg = pathArray[0].length;
  29445. var vectlg;
  29446. var dist;
  29447. for (p = 0; p < pathArray.length; p++) {
  29448. uTotalDistance[p] = 0;
  29449. us[p] = [0];
  29450. path = pathArray[p];
  29451. l = path.length;
  29452. minlg = (minlg < l) ? minlg : l;
  29453. j = 0;
  29454. while (j < l) {
  29455. positions.push(path[j].x, path[j].y, path[j].z);
  29456. if (j > 0) {
  29457. vectlg = path[j].subtract(path[j - 1]).length();
  29458. dist = vectlg + uTotalDistance[p];
  29459. us[p].push(dist);
  29460. uTotalDistance[p] = dist;
  29461. }
  29462. j++;
  29463. }
  29464. if (closePath) {
  29465. j--;
  29466. positions.push(path[0].x, path[0].y, path[0].z);
  29467. vectlg = path[j].subtract(path[0]).length();
  29468. dist = vectlg + uTotalDistance[p];
  29469. us[p].push(dist);
  29470. uTotalDistance[p] = dist;
  29471. }
  29472. lg[p] = l + closePathCorr;
  29473. idx[p] = idc;
  29474. idc += (l + closePathCorr);
  29475. }
  29476. // vertical distances (v)
  29477. var path1;
  29478. var path2;
  29479. var vertex1 = null;
  29480. var vertex2 = null;
  29481. for (i = 0; i < minlg + closePathCorr; i++) {
  29482. vTotalDistance[i] = 0;
  29483. vs[i] = [0];
  29484. for (p = 0; p < pathArray.length - 1; p++) {
  29485. path1 = pathArray[p];
  29486. path2 = pathArray[p + 1];
  29487. if (i === minlg) {
  29488. vertex1 = path1[0];
  29489. vertex2 = path2[0];
  29490. }
  29491. else {
  29492. vertex1 = path1[i];
  29493. vertex2 = path2[i];
  29494. }
  29495. vectlg = vertex2.subtract(vertex1).length();
  29496. dist = vectlg + vTotalDistance[i];
  29497. vs[i].push(dist);
  29498. vTotalDistance[i] = dist;
  29499. }
  29500. if (closeArray && vertex2 && vertex1) {
  29501. path1 = pathArray[p];
  29502. path2 = pathArray[0];
  29503. if (i === minlg) {
  29504. vertex2 = path2[0];
  29505. }
  29506. vectlg = vertex2.subtract(vertex1).length();
  29507. dist = vectlg + vTotalDistance[i];
  29508. vTotalDistance[i] = dist;
  29509. }
  29510. }
  29511. // uvs
  29512. var u;
  29513. var v;
  29514. if (customUV) {
  29515. for (p = 0; p < customUV.length; p++) {
  29516. uvs.push(customUV[p].x, customUV[p].y);
  29517. }
  29518. }
  29519. else {
  29520. for (p = 0; p < pathArray.length; p++) {
  29521. for (i = 0; i < minlg + closePathCorr; i++) {
  29522. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29523. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29524. if (invertUV) {
  29525. uvs.push(v, u);
  29526. }
  29527. else {
  29528. uvs.push(u, v);
  29529. }
  29530. }
  29531. }
  29532. }
  29533. // indices
  29534. p = 0; // path index
  29535. var pi = 0; // positions array index
  29536. var l1 = lg[p] - 1; // path1 length
  29537. var l2 = lg[p + 1] - 1; // path2 length
  29538. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29539. var shft = idx[1] - idx[0]; // shift
  29540. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29541. while (pi <= min && p < path1nb) {
  29542. // 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
  29543. indices.push(pi, pi + shft, pi + 1);
  29544. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29545. pi += 1;
  29546. if (pi === min) {
  29547. p++;
  29548. if (p === lg.length - 1) {
  29549. shft = idx[0] - idx[p];
  29550. l1 = lg[p] - 1;
  29551. l2 = lg[0] - 1;
  29552. }
  29553. else {
  29554. shft = idx[p + 1] - idx[p];
  29555. l1 = lg[p] - 1;
  29556. l2 = lg[p + 1] - 1;
  29557. }
  29558. pi = idx[p];
  29559. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29560. }
  29561. }
  29562. // normals
  29563. VertexData.ComputeNormals(positions, indices, normals);
  29564. if (closePath) {
  29565. var indexFirst = 0;
  29566. var indexLast = 0;
  29567. for (p = 0; p < pathArray.length; p++) {
  29568. indexFirst = idx[p] * 3;
  29569. if (p + 1 < pathArray.length) {
  29570. indexLast = (idx[p + 1] - 1) * 3;
  29571. }
  29572. else {
  29573. indexLast = normals.length - 3;
  29574. }
  29575. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29576. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29577. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29578. normals[indexLast] = normals[indexFirst];
  29579. normals[indexLast + 1] = normals[indexFirst + 1];
  29580. normals[indexLast + 2] = normals[indexFirst + 2];
  29581. }
  29582. }
  29583. // sides
  29584. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29585. // Colors
  29586. var colors = null;
  29587. if (customColors) {
  29588. colors = new Float32Array(customColors.length * 4);
  29589. for (var c = 0; c < customColors.length; c++) {
  29590. colors[c * 4] = customColors[c].r;
  29591. colors[c * 4 + 1] = customColors[c].g;
  29592. colors[c * 4 + 2] = customColors[c].b;
  29593. colors[c * 4 + 3] = customColors[c].a;
  29594. }
  29595. }
  29596. // Result
  29597. var vertexData = new VertexData();
  29598. var positions32 = new Float32Array(positions);
  29599. var normals32 = new Float32Array(normals);
  29600. var uvs32 = new Float32Array(uvs);
  29601. vertexData.indices = indices;
  29602. vertexData.positions = positions32;
  29603. vertexData.normals = normals32;
  29604. vertexData.uvs = uvs32;
  29605. if (colors) {
  29606. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29607. }
  29608. if (closePath) {
  29609. vertexData._idx = idx;
  29610. }
  29611. return vertexData;
  29612. };
  29613. /**
  29614. * Creates the VertexData of the Box.
  29615. */
  29616. VertexData.CreateBox = function (options) {
  29617. var normalsSource = [
  29618. new BABYLON.Vector3(0, 0, 1),
  29619. new BABYLON.Vector3(0, 0, -1),
  29620. new BABYLON.Vector3(1, 0, 0),
  29621. new BABYLON.Vector3(-1, 0, 0),
  29622. new BABYLON.Vector3(0, 1, 0),
  29623. new BABYLON.Vector3(0, -1, 0)
  29624. ];
  29625. var indices = [];
  29626. var positions = [];
  29627. var normals = [];
  29628. var uvs = [];
  29629. var width = options.width || options.size || 1;
  29630. var height = options.height || options.size || 1;
  29631. var depth = options.depth || options.size || 1;
  29632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29633. var faceUV = options.faceUV || new Array(6);
  29634. var faceColors = options.faceColors;
  29635. var colors = [];
  29636. // default face colors and UV if undefined
  29637. for (var f = 0; f < 6; f++) {
  29638. if (faceUV[f] === undefined) {
  29639. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29640. }
  29641. if (faceColors && faceColors[f] === undefined) {
  29642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29643. }
  29644. }
  29645. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29646. // Create each face in turn.
  29647. for (var index = 0; index < normalsSource.length; index++) {
  29648. var normal = normalsSource[index];
  29649. // Get two vectors perpendicular to the face normal and to each other.
  29650. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29651. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29652. // Six indices (two triangles) per face.
  29653. var verticesLength = positions.length / 3;
  29654. indices.push(verticesLength);
  29655. indices.push(verticesLength + 1);
  29656. indices.push(verticesLength + 2);
  29657. indices.push(verticesLength);
  29658. indices.push(verticesLength + 2);
  29659. indices.push(verticesLength + 3);
  29660. // Four vertices per face.
  29661. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29662. positions.push(vertex.x, vertex.y, vertex.z);
  29663. normals.push(normal.x, normal.y, normal.z);
  29664. uvs.push(faceUV[index].z, faceUV[index].w);
  29665. if (faceColors) {
  29666. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29667. }
  29668. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29669. positions.push(vertex.x, vertex.y, vertex.z);
  29670. normals.push(normal.x, normal.y, normal.z);
  29671. uvs.push(faceUV[index].x, faceUV[index].w);
  29672. if (faceColors) {
  29673. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29674. }
  29675. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29676. positions.push(vertex.x, vertex.y, vertex.z);
  29677. normals.push(normal.x, normal.y, normal.z);
  29678. uvs.push(faceUV[index].x, faceUV[index].y);
  29679. if (faceColors) {
  29680. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29681. }
  29682. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29683. positions.push(vertex.x, vertex.y, vertex.z);
  29684. normals.push(normal.x, normal.y, normal.z);
  29685. uvs.push(faceUV[index].z, faceUV[index].y);
  29686. if (faceColors) {
  29687. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29688. }
  29689. }
  29690. // sides
  29691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29692. // Result
  29693. var vertexData = new VertexData();
  29694. vertexData.indices = indices;
  29695. vertexData.positions = positions;
  29696. vertexData.normals = normals;
  29697. vertexData.uvs = uvs;
  29698. if (faceColors) {
  29699. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29700. vertexData.colors = totalColors;
  29701. }
  29702. return vertexData;
  29703. };
  29704. /**
  29705. * Creates the VertexData of the Sphere.
  29706. */
  29707. VertexData.CreateSphere = function (options) {
  29708. var segments = options.segments || 32;
  29709. var diameterX = options.diameterX || options.diameter || 1;
  29710. var diameterY = options.diameterY || options.diameter || 1;
  29711. var diameterZ = options.diameterZ || options.diameter || 1;
  29712. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29713. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29715. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29716. var totalZRotationSteps = 2 + segments;
  29717. var totalYRotationSteps = 2 * totalZRotationSteps;
  29718. var indices = [];
  29719. var positions = [];
  29720. var normals = [];
  29721. var uvs = [];
  29722. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29723. var normalizedZ = zRotationStep / totalZRotationSteps;
  29724. var angleZ = normalizedZ * Math.PI * slice;
  29725. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29726. var normalizedY = yRotationStep / totalYRotationSteps;
  29727. var angleY = normalizedY * Math.PI * 2 * arc;
  29728. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29729. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29730. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29731. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29732. var vertex = complete.multiply(radius);
  29733. var normal = complete.divide(radius).normalize();
  29734. positions.push(vertex.x, vertex.y, vertex.z);
  29735. normals.push(normal.x, normal.y, normal.z);
  29736. uvs.push(normalizedY, normalizedZ);
  29737. }
  29738. if (zRotationStep > 0) {
  29739. var verticesCount = positions.length / 3;
  29740. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29741. indices.push((firstIndex));
  29742. indices.push((firstIndex + 1));
  29743. indices.push(firstIndex + totalYRotationSteps + 1);
  29744. indices.push((firstIndex + totalYRotationSteps + 1));
  29745. indices.push((firstIndex + 1));
  29746. indices.push((firstIndex + totalYRotationSteps + 2));
  29747. }
  29748. }
  29749. }
  29750. // Sides
  29751. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29752. // Result
  29753. var vertexData = new VertexData();
  29754. vertexData.indices = indices;
  29755. vertexData.positions = positions;
  29756. vertexData.normals = normals;
  29757. vertexData.uvs = uvs;
  29758. return vertexData;
  29759. };
  29760. /**
  29761. * Creates the VertexData of the Cylinder or Cone.
  29762. */
  29763. VertexData.CreateCylinder = function (options) {
  29764. var height = options.height || 2;
  29765. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29766. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29767. var tessellation = options.tessellation || 24;
  29768. var subdivisions = options.subdivisions || 1;
  29769. var hasRings = options.hasRings ? true : false;
  29770. var enclose = options.enclose ? true : false;
  29771. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29772. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29773. var faceUV = options.faceUV || new Array(3);
  29774. var faceColors = options.faceColors;
  29775. // default face colors and UV if undefined
  29776. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29777. var ringNb = (hasRings) ? subdivisions : 1;
  29778. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29779. var f;
  29780. for (f = 0; f < surfaceNb; f++) {
  29781. if (faceColors && faceColors[f] === undefined) {
  29782. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29783. }
  29784. }
  29785. for (f = 0; f < surfaceNb; f++) {
  29786. if (faceUV && faceUV[f] === undefined) {
  29787. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29788. }
  29789. }
  29790. var indices = new Array();
  29791. var positions = new Array();
  29792. var normals = new Array();
  29793. var uvs = new Array();
  29794. var colors = new Array();
  29795. var angle_step = Math.PI * 2 * arc / tessellation;
  29796. var angle;
  29797. var h;
  29798. var radius;
  29799. var tan = (diameterBottom - diameterTop) / 2 / height;
  29800. var ringVertex = BABYLON.Vector3.Zero();
  29801. var ringNormal = BABYLON.Vector3.Zero();
  29802. var ringFirstVertex = BABYLON.Vector3.Zero();
  29803. var ringFirstNormal = BABYLON.Vector3.Zero();
  29804. var quadNormal = BABYLON.Vector3.Zero();
  29805. var Y = BABYLON.Axis.Y;
  29806. // positions, normals, uvs
  29807. var i;
  29808. var j;
  29809. var r;
  29810. var ringIdx = 1;
  29811. var s = 1; // surface index
  29812. var cs = 0;
  29813. var v = 0;
  29814. for (i = 0; i <= subdivisions; i++) {
  29815. h = i / subdivisions;
  29816. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29817. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29818. for (r = 0; r < ringIdx; r++) {
  29819. if (hasRings) {
  29820. s += r;
  29821. }
  29822. if (enclose) {
  29823. s += 2 * r;
  29824. }
  29825. for (j = 0; j <= tessellation; j++) {
  29826. angle = j * angle_step;
  29827. // position
  29828. ringVertex.x = Math.cos(-angle) * radius;
  29829. ringVertex.y = -height / 2 + h * height;
  29830. ringVertex.z = Math.sin(-angle) * radius;
  29831. // normal
  29832. if (diameterTop === 0 && i === subdivisions) {
  29833. // if no top cap, reuse former normals
  29834. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29835. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29836. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29837. }
  29838. else {
  29839. ringNormal.x = ringVertex.x;
  29840. ringNormal.z = ringVertex.z;
  29841. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29842. ringNormal.normalize();
  29843. }
  29844. // keep first ring vertex values for enclose
  29845. if (j === 0) {
  29846. ringFirstVertex.copyFrom(ringVertex);
  29847. ringFirstNormal.copyFrom(ringNormal);
  29848. }
  29849. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29850. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29851. if (hasRings) {
  29852. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29853. }
  29854. else {
  29855. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29856. }
  29857. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29858. if (faceColors) {
  29859. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29860. }
  29861. }
  29862. // if enclose, add four vertices and their dedicated normals
  29863. if (arc !== 1 && enclose) {
  29864. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29865. positions.push(0, ringVertex.y, 0);
  29866. positions.push(0, ringVertex.y, 0);
  29867. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29868. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29869. quadNormal.normalize();
  29870. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29871. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29872. quadNormal.normalize();
  29873. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29874. if (hasRings) {
  29875. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29876. }
  29877. else {
  29878. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29879. }
  29880. uvs.push(faceUV[s + 1].x, v);
  29881. uvs.push(faceUV[s + 1].z, v);
  29882. if (hasRings) {
  29883. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29884. }
  29885. else {
  29886. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29887. }
  29888. uvs.push(faceUV[s + 2].x, v);
  29889. uvs.push(faceUV[s + 2].z, v);
  29890. if (faceColors) {
  29891. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29892. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29893. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29894. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29895. }
  29896. }
  29897. if (cs !== s) {
  29898. cs = s;
  29899. }
  29900. }
  29901. }
  29902. // indices
  29903. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29904. var s;
  29905. i = 0;
  29906. for (s = 0; s < subdivisions; s++) {
  29907. var i0 = 0;
  29908. var i1 = 0;
  29909. var i2 = 0;
  29910. var i3 = 0;
  29911. for (j = 0; j < tessellation; j++) {
  29912. i0 = i * (e + 1) + j;
  29913. i1 = (i + 1) * (e + 1) + j;
  29914. i2 = i * (e + 1) + (j + 1);
  29915. i3 = (i + 1) * (e + 1) + (j + 1);
  29916. indices.push(i0, i1, i2);
  29917. indices.push(i3, i2, i1);
  29918. }
  29919. if (arc !== 1 && enclose) {
  29920. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29921. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29922. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29923. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29924. }
  29925. i = (hasRings) ? (i + 2) : (i + 1);
  29926. }
  29927. // Caps
  29928. var createCylinderCap = function (isTop) {
  29929. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29930. if (radius === 0) {
  29931. return;
  29932. }
  29933. // Cap positions, normals & uvs
  29934. var angle;
  29935. var circleVector;
  29936. var i;
  29937. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29938. var c = null;
  29939. if (faceColors) {
  29940. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29941. }
  29942. // cap center
  29943. var vbase = positions.length / 3;
  29944. var offset = isTop ? height / 2 : -height / 2;
  29945. var center = new BABYLON.Vector3(0, offset, 0);
  29946. positions.push(center.x, center.y, center.z);
  29947. normals.push(0, isTop ? 1 : -1, 0);
  29948. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29949. if (c) {
  29950. colors.push(c.r, c.g, c.b, c.a);
  29951. }
  29952. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29953. for (i = 0; i <= tessellation; i++) {
  29954. angle = Math.PI * 2 * i * arc / tessellation;
  29955. var cos = Math.cos(-angle);
  29956. var sin = Math.sin(-angle);
  29957. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29958. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29959. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29960. normals.push(0, isTop ? 1 : -1, 0);
  29961. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29962. if (c) {
  29963. colors.push(c.r, c.g, c.b, c.a);
  29964. }
  29965. }
  29966. // Cap indices
  29967. for (i = 0; i < tessellation; i++) {
  29968. if (!isTop) {
  29969. indices.push(vbase);
  29970. indices.push(vbase + (i + 1));
  29971. indices.push(vbase + (i + 2));
  29972. }
  29973. else {
  29974. indices.push(vbase);
  29975. indices.push(vbase + (i + 2));
  29976. indices.push(vbase + (i + 1));
  29977. }
  29978. }
  29979. };
  29980. // add caps to geometry
  29981. createCylinderCap(false);
  29982. createCylinderCap(true);
  29983. // Sides
  29984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29985. var vertexData = new VertexData();
  29986. vertexData.indices = indices;
  29987. vertexData.positions = positions;
  29988. vertexData.normals = normals;
  29989. vertexData.uvs = uvs;
  29990. if (faceColors) {
  29991. vertexData.colors = colors;
  29992. }
  29993. return vertexData;
  29994. };
  29995. /**
  29996. * Creates the VertexData of the Torus.
  29997. */
  29998. VertexData.CreateTorus = function (options) {
  29999. var indices = [];
  30000. var positions = [];
  30001. var normals = [];
  30002. var uvs = [];
  30003. var diameter = options.diameter || 1;
  30004. var thickness = options.thickness || 0.5;
  30005. var tessellation = options.tessellation || 16;
  30006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30007. var stride = tessellation + 1;
  30008. for (var i = 0; i <= tessellation; i++) {
  30009. var u = i / tessellation;
  30010. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30011. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30012. for (var j = 0; j <= tessellation; j++) {
  30013. var v = 1 - j / tessellation;
  30014. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30015. var dx = Math.cos(innerAngle);
  30016. var dy = Math.sin(innerAngle);
  30017. // Create a vertex.
  30018. var normal = new BABYLON.Vector3(dx, dy, 0);
  30019. var position = normal.scale(thickness / 2);
  30020. var textureCoordinate = new BABYLON.Vector2(u, v);
  30021. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30022. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30023. positions.push(position.x, position.y, position.z);
  30024. normals.push(normal.x, normal.y, normal.z);
  30025. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30026. // And create indices for two triangles.
  30027. var nextI = (i + 1) % stride;
  30028. var nextJ = (j + 1) % stride;
  30029. indices.push(i * stride + j);
  30030. indices.push(i * stride + nextJ);
  30031. indices.push(nextI * stride + j);
  30032. indices.push(i * stride + nextJ);
  30033. indices.push(nextI * stride + nextJ);
  30034. indices.push(nextI * stride + j);
  30035. }
  30036. }
  30037. // Sides
  30038. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30039. // Result
  30040. var vertexData = new VertexData();
  30041. vertexData.indices = indices;
  30042. vertexData.positions = positions;
  30043. vertexData.normals = normals;
  30044. vertexData.uvs = uvs;
  30045. return vertexData;
  30046. };
  30047. /**
  30048. * Creates the VertexData of the LineSystem.
  30049. */
  30050. VertexData.CreateLineSystem = function (options) {
  30051. var indices = [];
  30052. var positions = [];
  30053. var lines = options.lines;
  30054. var colors = options.colors;
  30055. var vertexColors = [];
  30056. var idx = 0;
  30057. for (var l = 0; l < lines.length; l++) {
  30058. var points = lines[l];
  30059. for (var index = 0; index < points.length; index++) {
  30060. positions.push(points[index].x, points[index].y, points[index].z);
  30061. if (colors) {
  30062. var color = colors[l];
  30063. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30064. }
  30065. if (index > 0) {
  30066. indices.push(idx - 1);
  30067. indices.push(idx);
  30068. }
  30069. idx++;
  30070. }
  30071. }
  30072. var vertexData = new VertexData();
  30073. vertexData.indices = indices;
  30074. vertexData.positions = positions;
  30075. if (colors) {
  30076. vertexData.colors = vertexColors;
  30077. }
  30078. return vertexData;
  30079. };
  30080. /**
  30081. * Create the VertexData of the DashedLines.
  30082. */
  30083. VertexData.CreateDashedLines = function (options) {
  30084. var dashSize = options.dashSize || 3;
  30085. var gapSize = options.gapSize || 1;
  30086. var dashNb = options.dashNb || 200;
  30087. var points = options.points;
  30088. var positions = new Array();
  30089. var indices = new Array();
  30090. var curvect = BABYLON.Vector3.Zero();
  30091. var lg = 0;
  30092. var nb = 0;
  30093. var shft = 0;
  30094. var dashshft = 0;
  30095. var curshft = 0;
  30096. var idx = 0;
  30097. var i = 0;
  30098. for (i = 0; i < points.length - 1; i++) {
  30099. points[i + 1].subtractToRef(points[i], curvect);
  30100. lg += curvect.length();
  30101. }
  30102. shft = lg / dashNb;
  30103. dashshft = dashSize * shft / (dashSize + gapSize);
  30104. for (i = 0; i < points.length - 1; i++) {
  30105. points[i + 1].subtractToRef(points[i], curvect);
  30106. nb = Math.floor(curvect.length() / shft);
  30107. curvect.normalize();
  30108. for (var j = 0; j < nb; j++) {
  30109. curshft = shft * j;
  30110. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30111. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30112. indices.push(idx, idx + 1);
  30113. idx += 2;
  30114. }
  30115. }
  30116. // Result
  30117. var vertexData = new VertexData();
  30118. vertexData.positions = positions;
  30119. vertexData.indices = indices;
  30120. return vertexData;
  30121. };
  30122. /**
  30123. * Creates the VertexData of the Ground.
  30124. */
  30125. VertexData.CreateGround = function (options) {
  30126. var indices = [];
  30127. var positions = [];
  30128. var normals = [];
  30129. var uvs = [];
  30130. var row, col;
  30131. var width = options.width || 1;
  30132. var height = options.height || 1;
  30133. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30134. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30135. for (row = 0; row <= subdivisionsY; row++) {
  30136. for (col = 0; col <= subdivisionsX; col++) {
  30137. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30138. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30139. positions.push(position.x, position.y, position.z);
  30140. normals.push(normal.x, normal.y, normal.z);
  30141. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30142. }
  30143. }
  30144. for (row = 0; row < subdivisionsY; row++) {
  30145. for (col = 0; col < subdivisionsX; col++) {
  30146. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30147. indices.push(col + 1 + row * (subdivisionsX + 1));
  30148. indices.push(col + row * (subdivisionsX + 1));
  30149. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30150. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30151. indices.push(col + row * (subdivisionsX + 1));
  30152. }
  30153. }
  30154. // Result
  30155. var vertexData = new VertexData();
  30156. vertexData.indices = indices;
  30157. vertexData.positions = positions;
  30158. vertexData.normals = normals;
  30159. vertexData.uvs = uvs;
  30160. return vertexData;
  30161. };
  30162. /**
  30163. * Creates the VertexData of the TiledGround.
  30164. */
  30165. VertexData.CreateTiledGround = function (options) {
  30166. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30167. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30168. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30169. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30170. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30171. var precision = options.precision || { w: 1, h: 1 };
  30172. var indices = new Array();
  30173. var positions = new Array();
  30174. var normals = new Array();
  30175. var uvs = new Array();
  30176. var row, col, tileRow, tileCol;
  30177. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30178. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30179. precision.w = (precision.w < 1) ? 1 : precision.w;
  30180. precision.h = (precision.h < 1) ? 1 : precision.h;
  30181. var tileSize = {
  30182. 'w': (xmax - xmin) / subdivisions.w,
  30183. 'h': (zmax - zmin) / subdivisions.h
  30184. };
  30185. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30186. // Indices
  30187. var base = positions.length / 3;
  30188. var rowLength = precision.w + 1;
  30189. for (row = 0; row < precision.h; row++) {
  30190. for (col = 0; col < precision.w; col++) {
  30191. var square = [
  30192. base + col + row * rowLength,
  30193. base + (col + 1) + row * rowLength,
  30194. base + (col + 1) + (row + 1) * rowLength,
  30195. base + col + (row + 1) * rowLength
  30196. ];
  30197. indices.push(square[1]);
  30198. indices.push(square[2]);
  30199. indices.push(square[3]);
  30200. indices.push(square[0]);
  30201. indices.push(square[1]);
  30202. indices.push(square[3]);
  30203. }
  30204. }
  30205. // Position, normals and uvs
  30206. var position = BABYLON.Vector3.Zero();
  30207. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30208. for (row = 0; row <= precision.h; row++) {
  30209. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30210. for (col = 0; col <= precision.w; col++) {
  30211. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30212. position.y = 0;
  30213. positions.push(position.x, position.y, position.z);
  30214. normals.push(normal.x, normal.y, normal.z);
  30215. uvs.push(col / precision.w, row / precision.h);
  30216. }
  30217. }
  30218. }
  30219. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30220. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30221. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30222. }
  30223. }
  30224. // Result
  30225. var vertexData = new VertexData();
  30226. vertexData.indices = indices;
  30227. vertexData.positions = positions;
  30228. vertexData.normals = normals;
  30229. vertexData.uvs = uvs;
  30230. return vertexData;
  30231. };
  30232. /**
  30233. * Creates the VertexData of the Ground designed from a heightmap.
  30234. */
  30235. VertexData.CreateGroundFromHeightMap = function (options) {
  30236. var indices = [];
  30237. var positions = [];
  30238. var normals = [];
  30239. var uvs = [];
  30240. var row, col;
  30241. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30242. // Vertices
  30243. for (row = 0; row <= options.subdivisions; row++) {
  30244. for (col = 0; col <= options.subdivisions; col++) {
  30245. 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));
  30246. // Compute height
  30247. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30248. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30249. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30250. var r = options.buffer[pos] / 255.0;
  30251. var g = options.buffer[pos + 1] / 255.0;
  30252. var b = options.buffer[pos + 2] / 255.0;
  30253. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30254. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30255. // Add vertex
  30256. positions.push(position.x, position.y, position.z);
  30257. normals.push(0, 0, 0);
  30258. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30259. }
  30260. }
  30261. // Indices
  30262. for (row = 0; row < options.subdivisions; row++) {
  30263. for (col = 0; col < options.subdivisions; col++) {
  30264. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30265. indices.push(col + 1 + row * (options.subdivisions + 1));
  30266. indices.push(col + row * (options.subdivisions + 1));
  30267. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30268. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30269. indices.push(col + row * (options.subdivisions + 1));
  30270. }
  30271. }
  30272. // Normals
  30273. VertexData.ComputeNormals(positions, indices, normals);
  30274. // Result
  30275. var vertexData = new VertexData();
  30276. vertexData.indices = indices;
  30277. vertexData.positions = positions;
  30278. vertexData.normals = normals;
  30279. vertexData.uvs = uvs;
  30280. return vertexData;
  30281. };
  30282. /**
  30283. * Creates the VertexData of the Plane.
  30284. */
  30285. VertexData.CreatePlane = function (options) {
  30286. var indices = [];
  30287. var positions = [];
  30288. var normals = [];
  30289. var uvs = [];
  30290. var width = options.width || options.size || 1;
  30291. var height = options.height || options.size || 1;
  30292. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30293. // Vertices
  30294. var halfWidth = width / 2.0;
  30295. var halfHeight = height / 2.0;
  30296. positions.push(-halfWidth, -halfHeight, 0);
  30297. normals.push(0, 0, -1.0);
  30298. uvs.push(0.0, 0.0);
  30299. positions.push(halfWidth, -halfHeight, 0);
  30300. normals.push(0, 0, -1.0);
  30301. uvs.push(1.0, 0.0);
  30302. positions.push(halfWidth, halfHeight, 0);
  30303. normals.push(0, 0, -1.0);
  30304. uvs.push(1.0, 1.0);
  30305. positions.push(-halfWidth, halfHeight, 0);
  30306. normals.push(0, 0, -1.0);
  30307. uvs.push(0.0, 1.0);
  30308. // Indices
  30309. indices.push(0);
  30310. indices.push(1);
  30311. indices.push(2);
  30312. indices.push(0);
  30313. indices.push(2);
  30314. indices.push(3);
  30315. // Sides
  30316. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30317. // Result
  30318. var vertexData = new VertexData();
  30319. vertexData.indices = indices;
  30320. vertexData.positions = positions;
  30321. vertexData.normals = normals;
  30322. vertexData.uvs = uvs;
  30323. return vertexData;
  30324. };
  30325. /**
  30326. * Creates the VertexData of the Disc or regular Polygon.
  30327. */
  30328. VertexData.CreateDisc = function (options) {
  30329. var positions = new Array();
  30330. var indices = new Array();
  30331. var normals = new Array();
  30332. var uvs = new Array();
  30333. var radius = options.radius || 0.5;
  30334. var tessellation = options.tessellation || 64;
  30335. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30337. // positions and uvs
  30338. positions.push(0, 0, 0); // disc center first
  30339. uvs.push(0.5, 0.5);
  30340. var theta = Math.PI * 2 * arc;
  30341. var step = theta / tessellation;
  30342. for (var a = 0; a < theta; a += step) {
  30343. var x = Math.cos(a);
  30344. var y = Math.sin(a);
  30345. var u = (x + 1) / 2;
  30346. var v = (1 - y) / 2;
  30347. positions.push(radius * x, radius * y, 0);
  30348. uvs.push(u, v);
  30349. }
  30350. if (arc === 1) {
  30351. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30352. uvs.push(uvs[2], uvs[3]);
  30353. }
  30354. //indices
  30355. var vertexNb = positions.length / 3;
  30356. for (var i = 1; i < vertexNb - 1; i++) {
  30357. indices.push(i + 1, 0, i);
  30358. }
  30359. // result
  30360. VertexData.ComputeNormals(positions, indices, normals);
  30361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30362. var vertexData = new VertexData();
  30363. vertexData.indices = indices;
  30364. vertexData.positions = positions;
  30365. vertexData.normals = normals;
  30366. vertexData.uvs = uvs;
  30367. return vertexData;
  30368. };
  30369. /**
  30370. * Re-creates the VertexData of the Polygon for sideOrientation.
  30371. */
  30372. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30373. var faceUV = fUV || new Array(3);
  30374. var faceColors = fColors;
  30375. var colors = [];
  30376. // default face colors and UV if undefined
  30377. for (var f = 0; f < 3; f++) {
  30378. if (faceUV[f] === undefined) {
  30379. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30380. }
  30381. if (faceColors && faceColors[f] === undefined) {
  30382. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30383. }
  30384. }
  30385. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30386. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30387. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30388. var indices = polygon.getIndices();
  30389. // set face colours and textures
  30390. var idx = 0;
  30391. var face = 0;
  30392. for (var index = 0; index < normals.length; index += 3) {
  30393. //Edge Face no. 1
  30394. if (Math.abs(normals[index + 1]) < 0.001) {
  30395. face = 1;
  30396. }
  30397. //Top Face no. 0
  30398. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30399. face = 0;
  30400. }
  30401. //Bottom Face no. 2
  30402. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30403. face = 2;
  30404. }
  30405. idx = index / 3;
  30406. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30407. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30408. if (faceColors) {
  30409. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30410. }
  30411. }
  30412. // sides
  30413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30414. // Result
  30415. var vertexData = new VertexData();
  30416. vertexData.indices = indices;
  30417. vertexData.positions = positions;
  30418. vertexData.normals = normals;
  30419. vertexData.uvs = uvs;
  30420. if (faceColors) {
  30421. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30422. vertexData.colors = totalColors;
  30423. }
  30424. return vertexData;
  30425. };
  30426. /**
  30427. * Creates the VertexData of the IcoSphere.
  30428. */
  30429. VertexData.CreateIcoSphere = function (options) {
  30430. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30431. var radius = options.radius || 1;
  30432. var flat = (options.flat === undefined) ? true : options.flat;
  30433. var subdivisions = options.subdivisions || 4;
  30434. var radiusX = options.radiusX || radius;
  30435. var radiusY = options.radiusY || radius;
  30436. var radiusZ = options.radiusZ || radius;
  30437. var t = (1 + Math.sqrt(5)) / 2;
  30438. // 12 vertex x,y,z
  30439. var ico_vertices = [
  30440. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30441. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30442. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30443. ];
  30444. // index of 3 vertex makes a face of icopshere
  30445. var ico_indices = [
  30446. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30447. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30448. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30449. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30450. ];
  30451. // vertex for uv have aliased position, not for UV
  30452. var vertices_unalias_id = [
  30453. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30454. // vertex alias
  30455. 0,
  30456. 2,
  30457. 3,
  30458. 3,
  30459. 3,
  30460. 4,
  30461. 7,
  30462. 8,
  30463. 9,
  30464. 9,
  30465. 10,
  30466. 11 // 23: B + 12
  30467. ];
  30468. // uv as integer step (not pixels !)
  30469. var ico_vertexuv = [
  30470. 5, 1, 3, 1, 6, 4, 0, 0,
  30471. 5, 3, 4, 2, 2, 2, 4, 0,
  30472. 2, 0, 1, 1, 6, 0, 6, 2,
  30473. // vertex alias (for same vertex on different faces)
  30474. 0, 4,
  30475. 3, 3,
  30476. 4, 4,
  30477. 3, 1,
  30478. 4, 2,
  30479. 4, 4,
  30480. 0, 2,
  30481. 1, 1,
  30482. 2, 2,
  30483. 3, 3,
  30484. 1, 3,
  30485. 2, 4 // 23: B + 12
  30486. ];
  30487. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30488. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30489. // First island of uv mapping
  30490. // v = 4h 3+ 2
  30491. // v = 3h 9+ 4
  30492. // v = 2h 9+ 5 B
  30493. // v = 1h 9 1 0
  30494. // v = 0h 3 8 7 A
  30495. // u = 0 1 2 3 4 5 6 *a
  30496. // Second island of uv mapping
  30497. // v = 4h 0+ B+ 4+
  30498. // v = 3h A+ 2+
  30499. // v = 2h 7+ 6 3+
  30500. // v = 1h 8+ 3+
  30501. // v = 0h
  30502. // u = 0 1 2 3 4 5 6 *a
  30503. // Face layout on texture UV mapping
  30504. // ============
  30505. // \ 4 /\ 16 / ======
  30506. // \ / \ / /\ 11 /
  30507. // \/ 7 \/ / \ /
  30508. // ======= / 10 \/
  30509. // /\ 17 /\ =======
  30510. // / \ / \ \ 15 /\
  30511. // / 8 \/ 12 \ \ / \
  30512. // ============ \/ 6 \
  30513. // \ 18 /\ ============
  30514. // \ / \ \ 5 /\ 0 /
  30515. // \/ 13 \ \ / \ /
  30516. // ======= \/ 1 \/
  30517. // =============
  30518. // /\ 19 /\ 2 /\
  30519. // / \ / \ / \
  30520. // / 14 \/ 9 \/ 3 \
  30521. // ===================
  30522. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30523. var ustep = 138 / 1024;
  30524. var vstep = 239 / 1024;
  30525. var uoffset = 60 / 1024;
  30526. var voffset = 26 / 1024;
  30527. // Second island should have margin, not to touch the first island
  30528. // avoid any borderline artefact in pixel rounding
  30529. var island_u_offset = -40 / 1024;
  30530. var island_v_offset = +20 / 1024;
  30531. // face is either island 0 or 1 :
  30532. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30533. var island = [
  30534. 0, 0, 0, 0, 1,
  30535. 0, 0, 1, 1, 0,
  30536. 0, 0, 1, 1, 0,
  30537. 0, 1, 1, 1, 0 // 15 - 19
  30538. ];
  30539. var indices = new Array();
  30540. var positions = new Array();
  30541. var normals = new Array();
  30542. var uvs = new Array();
  30543. var current_indice = 0;
  30544. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30545. var face_vertex_pos = new Array(3);
  30546. var face_vertex_uv = new Array(3);
  30547. var v012;
  30548. for (v012 = 0; v012 < 3; v012++) {
  30549. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30550. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30551. }
  30552. // create all with normals
  30553. for (var face = 0; face < 20; face++) {
  30554. // 3 vertex per face
  30555. for (v012 = 0; v012 < 3; v012++) {
  30556. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30557. var v_id = ico_indices[3 * face + v012];
  30558. // vertex have 3D position (x,y,z)
  30559. 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]);
  30560. // Normalize to get normal, then scale to radius
  30561. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30562. // uv Coordinates from vertex ID
  30563. 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);
  30564. }
  30565. // Subdivide the face (interpolate pos, norm, uv)
  30566. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30567. // - norm is linear interpolation of vertex corner normal
  30568. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30569. // - uv is linear interpolation
  30570. //
  30571. // Topology is as below for sub-divide by 2
  30572. // vertex shown as v0,v1,v2
  30573. // interp index is i1 to progress in range [v0,v1[
  30574. // interp index is i2 to progress in range [v0,v2[
  30575. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30576. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30577. //
  30578. //
  30579. // i2 v2
  30580. // ^ ^
  30581. // / / \
  30582. // / / \
  30583. // / / \
  30584. // / / (0,1) \
  30585. // / #---------\
  30586. // / / \ (0,0)'/ \
  30587. // / / \ / \
  30588. // / / \ / \
  30589. // / / (0,0) \ / (1,0) \
  30590. // / #---------#---------\
  30591. // v0 v1
  30592. //
  30593. // --------------------> i1
  30594. //
  30595. // interp of (i1,i2):
  30596. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30597. // along i1 : lerp(x0,x1, i1/(S-i2))
  30598. //
  30599. // centroid of triangle is needed to get help normal computation
  30600. // (c1,c2) are used for centroid location
  30601. var interp_vertex = function (i1, i2, c1, c2) {
  30602. // vertex is interpolated from
  30603. // - face_vertex_pos[0..2]
  30604. // - face_vertex_uv[0..2]
  30605. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30606. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30607. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30608. pos_interp.normalize();
  30609. var vertex_normal;
  30610. if (flat) {
  30611. // in flat mode, recalculate normal as face centroid normal
  30612. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30613. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30614. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30615. }
  30616. else {
  30617. // in smooth mode, recalculate normal from each single vertex position
  30618. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30619. }
  30620. // Vertex normal need correction due to X,Y,Z radius scaling
  30621. vertex_normal.x /= radiusX;
  30622. vertex_normal.y /= radiusY;
  30623. vertex_normal.z /= radiusZ;
  30624. vertex_normal.normalize();
  30625. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30626. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30627. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30628. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30629. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30630. uvs.push(uv_interp.x, uv_interp.y);
  30631. // push each vertex has member of a face
  30632. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30633. indices.push(current_indice);
  30634. current_indice++;
  30635. };
  30636. for (var i2 = 0; i2 < subdivisions; i2++) {
  30637. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30638. // face : (i1,i2) for /\ :
  30639. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30640. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30641. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30642. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30643. if (i1 + i2 + 1 < subdivisions) {
  30644. // face : (i1,i2)' for \/ :
  30645. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30646. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30647. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30648. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30649. }
  30650. }
  30651. }
  30652. }
  30653. // Sides
  30654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30655. // Result
  30656. var vertexData = new VertexData();
  30657. vertexData.indices = indices;
  30658. vertexData.positions = positions;
  30659. vertexData.normals = normals;
  30660. vertexData.uvs = uvs;
  30661. return vertexData;
  30662. };
  30663. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30664. /**
  30665. * Creates the VertexData of the Polyhedron.
  30666. */
  30667. VertexData.CreatePolyhedron = function (options) {
  30668. // provided polyhedron types :
  30669. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30670. // 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)
  30671. var polyhedra = [];
  30672. 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]] };
  30673. 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]] };
  30674. polyhedra[2] = {
  30675. 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]],
  30676. 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]]
  30677. };
  30678. polyhedra[3] = {
  30679. 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]],
  30680. 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]]
  30681. };
  30682. polyhedra[4] = {
  30683. 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]],
  30684. 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]]
  30685. };
  30686. 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]] };
  30687. 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]] };
  30688. 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]] };
  30689. 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]] };
  30690. 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]] };
  30691. 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]] };
  30692. 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]] };
  30693. 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]] };
  30694. 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]] };
  30695. polyhedra[14] = {
  30696. 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]],
  30697. 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]]
  30698. };
  30699. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30700. var size = options.size;
  30701. var sizeX = options.sizeX || size || 1;
  30702. var sizeY = options.sizeY || size || 1;
  30703. var sizeZ = options.sizeZ || size || 1;
  30704. var data = options.custom || polyhedra[type];
  30705. var nbfaces = data.face.length;
  30706. var faceUV = options.faceUV || new Array(nbfaces);
  30707. var faceColors = options.faceColors;
  30708. var flat = (options.flat === undefined) ? true : options.flat;
  30709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30710. var positions = new Array();
  30711. var indices = new Array();
  30712. var normals = new Array();
  30713. var uvs = new Array();
  30714. var colors = new Array();
  30715. var index = 0;
  30716. var faceIdx = 0; // face cursor in the array "indexes"
  30717. var indexes = new Array();
  30718. var i = 0;
  30719. var f = 0;
  30720. var u, v, ang, x, y, tmp;
  30721. // default face colors and UV if undefined
  30722. if (flat) {
  30723. for (f = 0; f < nbfaces; f++) {
  30724. if (faceColors && faceColors[f] === undefined) {
  30725. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30726. }
  30727. if (faceUV && faceUV[f] === undefined) {
  30728. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30729. }
  30730. }
  30731. }
  30732. if (!flat) {
  30733. for (i = 0; i < data.vertex.length; i++) {
  30734. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30735. uvs.push(0, 0);
  30736. }
  30737. for (f = 0; f < nbfaces; f++) {
  30738. for (i = 0; i < data.face[f].length - 2; i++) {
  30739. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30740. }
  30741. }
  30742. }
  30743. else {
  30744. for (f = 0; f < nbfaces; f++) {
  30745. var fl = data.face[f].length; // number of vertices of the current face
  30746. ang = 2 * Math.PI / fl;
  30747. x = 0.5 * Math.tan(ang / 2);
  30748. y = 0.5;
  30749. // positions, uvs, colors
  30750. for (i = 0; i < fl; i++) {
  30751. // positions
  30752. 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);
  30753. indexes.push(index);
  30754. index++;
  30755. // uvs
  30756. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30757. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30758. uvs.push(u, v);
  30759. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30760. y = x * Math.sin(ang) + y * Math.cos(ang);
  30761. x = tmp;
  30762. // colors
  30763. if (faceColors) {
  30764. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30765. }
  30766. }
  30767. // indices from indexes
  30768. for (i = 0; i < fl - 2; i++) {
  30769. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30770. }
  30771. faceIdx += fl;
  30772. }
  30773. }
  30774. VertexData.ComputeNormals(positions, indices, normals);
  30775. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30776. var vertexData = new VertexData();
  30777. vertexData.positions = positions;
  30778. vertexData.indices = indices;
  30779. vertexData.normals = normals;
  30780. vertexData.uvs = uvs;
  30781. if (faceColors && flat) {
  30782. vertexData.colors = colors;
  30783. }
  30784. return vertexData;
  30785. };
  30786. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30787. /**
  30788. * Creates the VertexData of the Torus Knot.
  30789. */
  30790. VertexData.CreateTorusKnot = function (options) {
  30791. var indices = new Array();
  30792. var positions = new Array();
  30793. var normals = new Array();
  30794. var uvs = new Array();
  30795. var radius = options.radius || 2;
  30796. var tube = options.tube || 0.5;
  30797. var radialSegments = options.radialSegments || 32;
  30798. var tubularSegments = options.tubularSegments || 32;
  30799. var p = options.p || 2;
  30800. var q = options.q || 3;
  30801. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30802. // Helper
  30803. var getPos = function (angle) {
  30804. var cu = Math.cos(angle);
  30805. var su = Math.sin(angle);
  30806. var quOverP = q / p * angle;
  30807. var cs = Math.cos(quOverP);
  30808. var tx = radius * (2 + cs) * 0.5 * cu;
  30809. var ty = radius * (2 + cs) * su * 0.5;
  30810. var tz = radius * Math.sin(quOverP) * 0.5;
  30811. return new BABYLON.Vector3(tx, ty, tz);
  30812. };
  30813. // Vertices
  30814. var i;
  30815. var j;
  30816. for (i = 0; i <= radialSegments; i++) {
  30817. var modI = i % radialSegments;
  30818. var u = modI / radialSegments * 2 * p * Math.PI;
  30819. var p1 = getPos(u);
  30820. var p2 = getPos(u + 0.01);
  30821. var tang = p2.subtract(p1);
  30822. var n = p2.add(p1);
  30823. var bitan = BABYLON.Vector3.Cross(tang, n);
  30824. n = BABYLON.Vector3.Cross(bitan, tang);
  30825. bitan.normalize();
  30826. n.normalize();
  30827. for (j = 0; j < tubularSegments; j++) {
  30828. var modJ = j % tubularSegments;
  30829. var v = modJ / tubularSegments * 2 * Math.PI;
  30830. var cx = -tube * Math.cos(v);
  30831. var cy = tube * Math.sin(v);
  30832. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30833. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30834. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30835. uvs.push(i / radialSegments);
  30836. uvs.push(j / tubularSegments);
  30837. }
  30838. }
  30839. for (i = 0; i < radialSegments; i++) {
  30840. for (j = 0; j < tubularSegments; j++) {
  30841. var jNext = (j + 1) % tubularSegments;
  30842. var a = i * tubularSegments + j;
  30843. var b = (i + 1) * tubularSegments + j;
  30844. var c = (i + 1) * tubularSegments + jNext;
  30845. var d = i * tubularSegments + jNext;
  30846. indices.push(d);
  30847. indices.push(b);
  30848. indices.push(a);
  30849. indices.push(d);
  30850. indices.push(c);
  30851. indices.push(b);
  30852. }
  30853. }
  30854. // Normals
  30855. VertexData.ComputeNormals(positions, indices, normals);
  30856. // Sides
  30857. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30858. // Result
  30859. var vertexData = new VertexData();
  30860. vertexData.indices = indices;
  30861. vertexData.positions = positions;
  30862. vertexData.normals = normals;
  30863. vertexData.uvs = uvs;
  30864. return vertexData;
  30865. };
  30866. // Tools
  30867. /**
  30868. * @param {any} - positions (number[] or Float32Array)
  30869. * @param {any} - indices (number[] or Uint16Array)
  30870. * @param {any} - normals (number[] or Float32Array)
  30871. * options (optional) :
  30872. * facetPositions : optional array of facet positions (vector3)
  30873. * facetNormals : optional array of facet normals (vector3)
  30874. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30875. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30876. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30877. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30878. * bInfo : optional bounding info, required for facetPartitioning computation
  30879. * useRightHandedSystem: optional boolean to for right handed system computation
  30880. * depthSort : optional boolean to enable the facet depth sort computation
  30881. * distanceTo : optional Vector3 to compute the facet depth from this location
  30882. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30883. */
  30884. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30885. // temporary scalar variables
  30886. var index = 0; // facet index
  30887. var p1p2x = 0.0; // p1p2 vector x coordinate
  30888. var p1p2y = 0.0; // p1p2 vector y coordinate
  30889. var p1p2z = 0.0; // p1p2 vector z coordinate
  30890. var p3p2x = 0.0; // p3p2 vector x coordinate
  30891. var p3p2y = 0.0; // p3p2 vector y coordinate
  30892. var p3p2z = 0.0; // p3p2 vector z coordinate
  30893. var faceNormalx = 0.0; // facet normal x coordinate
  30894. var faceNormaly = 0.0; // facet normal y coordinate
  30895. var faceNormalz = 0.0; // facet normal z coordinate
  30896. var length = 0.0; // facet normal length before normalization
  30897. var v1x = 0; // vector1 x index in the positions array
  30898. var v1y = 0; // vector1 y index in the positions array
  30899. var v1z = 0; // vector1 z index in the positions array
  30900. var v2x = 0; // vector2 x index in the positions array
  30901. var v2y = 0; // vector2 y index in the positions array
  30902. var v2z = 0; // vector2 z index in the positions array
  30903. var v3x = 0; // vector3 x index in the positions array
  30904. var v3y = 0; // vector3 y index in the positions array
  30905. var v3z = 0; // vector3 z index in the positions array
  30906. var computeFacetNormals = false;
  30907. var computeFacetPositions = false;
  30908. var computeFacetPartitioning = false;
  30909. var computeDepthSort = false;
  30910. var faceNormalSign = 1;
  30911. var ratio = 0;
  30912. var distanceTo = null;
  30913. if (options) {
  30914. computeFacetNormals = (options.facetNormals) ? true : false;
  30915. computeFacetPositions = (options.facetPositions) ? true : false;
  30916. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30917. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30918. ratio = options.ratio || 0;
  30919. computeDepthSort = (options.depthSort) ? true : false;
  30920. distanceTo = (options.distanceTo);
  30921. if (computeDepthSort) {
  30922. if (distanceTo === undefined) {
  30923. distanceTo = BABYLON.Vector3.Zero();
  30924. }
  30925. var depthSortedFacets = options.depthSortedFacets;
  30926. }
  30927. }
  30928. // facetPartitioning reinit if needed
  30929. var xSubRatio = 0;
  30930. var ySubRatio = 0;
  30931. var zSubRatio = 0;
  30932. var subSq = 0;
  30933. if (computeFacetPartitioning && options && options.bbSize) {
  30934. var ox = 0; // X partitioning index for facet position
  30935. var oy = 0; // Y partinioning index for facet position
  30936. var oz = 0; // Z partinioning index for facet position
  30937. var b1x = 0; // X partitioning index for facet v1 vertex
  30938. var b1y = 0; // Y partitioning index for facet v1 vertex
  30939. var b1z = 0; // z partitioning index for facet v1 vertex
  30940. var b2x = 0; // X partitioning index for facet v2 vertex
  30941. var b2y = 0; // Y partitioning index for facet v2 vertex
  30942. var b2z = 0; // Z partitioning index for facet v2 vertex
  30943. var b3x = 0; // X partitioning index for facet v3 vertex
  30944. var b3y = 0; // Y partitioning index for facet v3 vertex
  30945. var b3z = 0; // Z partitioning index for facet v3 vertex
  30946. var block_idx_o = 0; // facet barycenter block index
  30947. var block_idx_v1 = 0; // v1 vertex block index
  30948. var block_idx_v2 = 0; // v2 vertex block index
  30949. var block_idx_v3 = 0; // v3 vertex block index
  30950. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30951. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30952. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30953. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30954. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30955. subSq = options.subDiv.max * options.subDiv.max;
  30956. options.facetPartitioning.length = 0;
  30957. }
  30958. // reset the normals
  30959. for (index = 0; index < positions.length; index++) {
  30960. normals[index] = 0.0;
  30961. }
  30962. // Loop : 1 indice triplet = 1 facet
  30963. var nbFaces = (indices.length / 3) | 0;
  30964. for (index = 0; index < nbFaces; index++) {
  30965. // get the indexes of the coordinates of each vertex of the facet
  30966. v1x = indices[index * 3] * 3;
  30967. v1y = v1x + 1;
  30968. v1z = v1x + 2;
  30969. v2x = indices[index * 3 + 1] * 3;
  30970. v2y = v2x + 1;
  30971. v2z = v2x + 2;
  30972. v3x = indices[index * 3 + 2] * 3;
  30973. v3y = v3x + 1;
  30974. v3z = v3x + 2;
  30975. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30976. p1p2y = positions[v1y] - positions[v2y];
  30977. p1p2z = positions[v1z] - positions[v2z];
  30978. p3p2x = positions[v3x] - positions[v2x];
  30979. p3p2y = positions[v3y] - positions[v2y];
  30980. p3p2z = positions[v3z] - positions[v2z];
  30981. // compute the face normal with the cross product
  30982. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30983. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30984. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30985. // normalize this normal and store it in the array facetData
  30986. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30987. length = (length === 0) ? 1.0 : length;
  30988. faceNormalx /= length;
  30989. faceNormaly /= length;
  30990. faceNormalz /= length;
  30991. if (computeFacetNormals && options) {
  30992. options.facetNormals[index].x = faceNormalx;
  30993. options.facetNormals[index].y = faceNormaly;
  30994. options.facetNormals[index].z = faceNormalz;
  30995. }
  30996. if (computeFacetPositions && options) {
  30997. // compute and the facet barycenter coordinates in the array facetPositions
  30998. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30999. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31000. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31001. }
  31002. if (computeFacetPartitioning && options) {
  31003. // store the facet indexes in arrays in the main facetPartitioning array :
  31004. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31005. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31006. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31007. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31008. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31009. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31010. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31011. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31012. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31013. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31014. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31015. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31016. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31017. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31018. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31019. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31020. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31021. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31022. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31023. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31024. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31025. // push each facet index in each block containing the vertex
  31026. options.facetPartitioning[block_idx_v1].push(index);
  31027. if (block_idx_v2 != block_idx_v1) {
  31028. options.facetPartitioning[block_idx_v2].push(index);
  31029. }
  31030. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31031. options.facetPartitioning[block_idx_v3].push(index);
  31032. }
  31033. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31034. options.facetPartitioning[block_idx_o].push(index);
  31035. }
  31036. }
  31037. if (computeDepthSort && options && options.facetPositions) {
  31038. var dsf = depthSortedFacets[index];
  31039. dsf.ind = index * 3;
  31040. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31041. }
  31042. // compute the normals anyway
  31043. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31044. normals[v1y] += faceNormaly;
  31045. normals[v1z] += faceNormalz;
  31046. normals[v2x] += faceNormalx;
  31047. normals[v2y] += faceNormaly;
  31048. normals[v2z] += faceNormalz;
  31049. normals[v3x] += faceNormalx;
  31050. normals[v3y] += faceNormaly;
  31051. normals[v3z] += faceNormalz;
  31052. }
  31053. // last normalization of each normal
  31054. for (index = 0; index < normals.length / 3; index++) {
  31055. faceNormalx = normals[index * 3];
  31056. faceNormaly = normals[index * 3 + 1];
  31057. faceNormalz = normals[index * 3 + 2];
  31058. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31059. length = (length === 0) ? 1.0 : length;
  31060. faceNormalx /= length;
  31061. faceNormaly /= length;
  31062. faceNormalz /= length;
  31063. normals[index * 3] = faceNormalx;
  31064. normals[index * 3 + 1] = faceNormaly;
  31065. normals[index * 3 + 2] = faceNormalz;
  31066. }
  31067. };
  31068. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31069. var li = indices.length;
  31070. var ln = normals.length;
  31071. var i;
  31072. var n;
  31073. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31074. switch (sideOrientation) {
  31075. case BABYLON.Mesh.FRONTSIDE:
  31076. // nothing changed
  31077. break;
  31078. case BABYLON.Mesh.BACKSIDE:
  31079. var tmp;
  31080. // indices
  31081. for (i = 0; i < li; i += 3) {
  31082. tmp = indices[i];
  31083. indices[i] = indices[i + 2];
  31084. indices[i + 2] = tmp;
  31085. }
  31086. // normals
  31087. for (n = 0; n < ln; n++) {
  31088. normals[n] = -normals[n];
  31089. }
  31090. break;
  31091. case BABYLON.Mesh.DOUBLESIDE:
  31092. // positions
  31093. var lp = positions.length;
  31094. var l = lp / 3;
  31095. for (var p = 0; p < lp; p++) {
  31096. positions[lp + p] = positions[p];
  31097. }
  31098. // indices
  31099. for (i = 0; i < li; i += 3) {
  31100. indices[i + li] = indices[i + 2] + l;
  31101. indices[i + 1 + li] = indices[i + 1] + l;
  31102. indices[i + 2 + li] = indices[i] + l;
  31103. }
  31104. // normals
  31105. for (n = 0; n < ln; n++) {
  31106. normals[ln + n] = -normals[n];
  31107. }
  31108. // uvs
  31109. var lu = uvs.length;
  31110. var u = 0;
  31111. for (u = 0; u < lu; u++) {
  31112. uvs[u + lu] = uvs[u];
  31113. }
  31114. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31115. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31116. u = 0;
  31117. for (i = 0; i < lu / 2; i++) {
  31118. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31119. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31120. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31121. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31122. u += 2;
  31123. }
  31124. break;
  31125. }
  31126. };
  31127. /**
  31128. * Creates a new VertexData from the imported parameters.
  31129. */
  31130. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31131. var vertexData = new VertexData();
  31132. // positions
  31133. var positions = parsedVertexData.positions;
  31134. if (positions) {
  31135. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31136. }
  31137. // normals
  31138. var normals = parsedVertexData.normals;
  31139. if (normals) {
  31140. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31141. }
  31142. // tangents
  31143. var tangents = parsedVertexData.tangents;
  31144. if (tangents) {
  31145. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31146. }
  31147. // uvs
  31148. var uvs = parsedVertexData.uvs;
  31149. if (uvs) {
  31150. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31151. }
  31152. // uv2s
  31153. var uv2s = parsedVertexData.uv2s;
  31154. if (uv2s) {
  31155. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31156. }
  31157. // uv3s
  31158. var uv3s = parsedVertexData.uv3s;
  31159. if (uv3s) {
  31160. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31161. }
  31162. // uv4s
  31163. var uv4s = parsedVertexData.uv4s;
  31164. if (uv4s) {
  31165. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31166. }
  31167. // uv5s
  31168. var uv5s = parsedVertexData.uv5s;
  31169. if (uv5s) {
  31170. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31171. }
  31172. // uv6s
  31173. var uv6s = parsedVertexData.uv6s;
  31174. if (uv6s) {
  31175. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31176. }
  31177. // colors
  31178. var colors = parsedVertexData.colors;
  31179. if (colors) {
  31180. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31181. }
  31182. // matricesIndices
  31183. var matricesIndices = parsedVertexData.matricesIndices;
  31184. if (matricesIndices) {
  31185. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31186. }
  31187. // matricesWeights
  31188. var matricesWeights = parsedVertexData.matricesWeights;
  31189. if (matricesWeights) {
  31190. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31191. }
  31192. // indices
  31193. var indices = parsedVertexData.indices;
  31194. if (indices) {
  31195. vertexData.indices = indices;
  31196. }
  31197. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31198. };
  31199. return VertexData;
  31200. }());
  31201. BABYLON.VertexData = VertexData;
  31202. })(BABYLON || (BABYLON = {}));
  31203. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31204. var BABYLON;
  31205. (function (BABYLON) {
  31206. var Geometry = /** @class */ (function () {
  31207. function Geometry(id, scene, vertexData, updatable, mesh) {
  31208. if (updatable === void 0) { updatable = false; }
  31209. if (mesh === void 0) { mesh = null; }
  31210. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31211. this._totalVertices = 0;
  31212. this._isDisposed = false;
  31213. this._indexBufferIsUpdatable = false;
  31214. this.id = id;
  31215. this._engine = scene.getEngine();
  31216. this._meshes = [];
  31217. this._scene = scene;
  31218. //Init vertex buffer cache
  31219. this._vertexBuffers = {};
  31220. this._indices = [];
  31221. this._updatable = updatable;
  31222. // vertexData
  31223. if (vertexData) {
  31224. this.setAllVerticesData(vertexData, updatable);
  31225. }
  31226. else {
  31227. this._totalVertices = 0;
  31228. this._indices = [];
  31229. }
  31230. if (this._engine.getCaps().vertexArrayObject) {
  31231. this._vertexArrayObjects = {};
  31232. }
  31233. // applyToMesh
  31234. if (mesh) {
  31235. if (mesh.getClassName() === "LinesMesh") {
  31236. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31237. this.updateExtend();
  31238. }
  31239. this.applyToMesh(mesh);
  31240. mesh.computeWorldMatrix(true);
  31241. }
  31242. }
  31243. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31244. /**
  31245. * 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
  31246. * @returns The Bias Vector
  31247. */
  31248. get: function () {
  31249. return this._boundingBias;
  31250. },
  31251. set: function (value) {
  31252. if (this._boundingBias && this._boundingBias.equals(value)) {
  31253. return;
  31254. }
  31255. this._boundingBias = value.clone();
  31256. this.updateBoundingInfo(true, null);
  31257. },
  31258. enumerable: true,
  31259. configurable: true
  31260. });
  31261. Geometry.CreateGeometryForMesh = function (mesh) {
  31262. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31263. geometry.applyToMesh(mesh);
  31264. return geometry;
  31265. };
  31266. Object.defineProperty(Geometry.prototype, "extend", {
  31267. get: function () {
  31268. return this._extend;
  31269. },
  31270. enumerable: true,
  31271. configurable: true
  31272. });
  31273. Geometry.prototype.getScene = function () {
  31274. return this._scene;
  31275. };
  31276. Geometry.prototype.getEngine = function () {
  31277. return this._engine;
  31278. };
  31279. Geometry.prototype.isReady = function () {
  31280. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31281. };
  31282. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31283. get: function () {
  31284. for (var index = 0; index < this._meshes.length; index++) {
  31285. if (!this._meshes[index].doNotSerialize) {
  31286. return false;
  31287. }
  31288. }
  31289. return true;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Geometry.prototype._rebuild = function () {
  31295. if (this._vertexArrayObjects) {
  31296. this._vertexArrayObjects = {};
  31297. }
  31298. // Index buffer
  31299. if (this._meshes.length !== 0 && this._indices) {
  31300. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31301. }
  31302. // Vertex buffers
  31303. for (var key in this._vertexBuffers) {
  31304. var vertexBuffer = this._vertexBuffers[key];
  31305. vertexBuffer._rebuild();
  31306. }
  31307. };
  31308. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31309. vertexData.applyToGeometry(this, updatable);
  31310. this.notifyUpdate();
  31311. };
  31312. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31313. if (updatable === void 0) { updatable = false; }
  31314. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31315. this.setVerticesBuffer(buffer);
  31316. };
  31317. Geometry.prototype.removeVerticesData = function (kind) {
  31318. if (this._vertexBuffers[kind]) {
  31319. this._vertexBuffers[kind].dispose();
  31320. delete this._vertexBuffers[kind];
  31321. }
  31322. };
  31323. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31324. var kind = buffer.getKind();
  31325. if (this._vertexBuffers[kind]) {
  31326. this._vertexBuffers[kind].dispose();
  31327. }
  31328. this._vertexBuffers[kind] = buffer;
  31329. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31330. var data = buffer.getData();
  31331. var stride = buffer.getStrideSize();
  31332. this._totalVertices = data.length / stride;
  31333. this.updateExtend(data, stride);
  31334. this._resetPointsArrayCache();
  31335. var meshes = this._meshes;
  31336. var numOfMeshes = meshes.length;
  31337. for (var index = 0; index < numOfMeshes; index++) {
  31338. var mesh = meshes[index];
  31339. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31340. mesh._createGlobalSubMesh(false);
  31341. mesh.computeWorldMatrix(true);
  31342. }
  31343. }
  31344. this.notifyUpdate(kind);
  31345. if (this._vertexArrayObjects) {
  31346. this._disposeVertexArrayObjects();
  31347. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31348. }
  31349. };
  31350. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31351. var vertexBuffer = this.getVertexBuffer(kind);
  31352. if (!vertexBuffer) {
  31353. return;
  31354. }
  31355. vertexBuffer.updateDirectly(data, offset);
  31356. this.notifyUpdate(kind);
  31357. };
  31358. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31359. if (updateExtends === void 0) { updateExtends = false; }
  31360. var vertexBuffer = this.getVertexBuffer(kind);
  31361. if (!vertexBuffer) {
  31362. return;
  31363. }
  31364. vertexBuffer.update(data);
  31365. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31366. var stride = vertexBuffer.getStrideSize();
  31367. this._totalVertices = data.length / stride;
  31368. this.updateBoundingInfo(updateExtends, data);
  31369. }
  31370. this.notifyUpdate(kind);
  31371. };
  31372. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31373. if (updateExtends) {
  31374. this.updateExtend(data);
  31375. }
  31376. var meshes = this._meshes;
  31377. var numOfMeshes = meshes.length;
  31378. this._resetPointsArrayCache();
  31379. for (var index = 0; index < numOfMeshes; index++) {
  31380. var mesh = meshes[index];
  31381. if (updateExtends) {
  31382. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31383. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31384. var subMesh = mesh.subMeshes[subIndex];
  31385. subMesh.refreshBoundingInfo();
  31386. }
  31387. }
  31388. }
  31389. };
  31390. Geometry.prototype._bind = function (effect, indexToBind) {
  31391. if (!effect) {
  31392. return;
  31393. }
  31394. if (indexToBind === undefined) {
  31395. indexToBind = this._indexBuffer;
  31396. }
  31397. var vbs = this.getVertexBuffers();
  31398. if (!vbs) {
  31399. return;
  31400. }
  31401. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31402. this._engine.bindBuffers(vbs, indexToBind, effect);
  31403. return;
  31404. }
  31405. // Using VAO
  31406. if (!this._vertexArrayObjects[effect.key]) {
  31407. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31408. }
  31409. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31410. };
  31411. Geometry.prototype.getTotalVertices = function () {
  31412. if (!this.isReady()) {
  31413. return 0;
  31414. }
  31415. return this._totalVertices;
  31416. };
  31417. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31418. var vertexBuffer = this.getVertexBuffer(kind);
  31419. if (!vertexBuffer) {
  31420. return null;
  31421. }
  31422. var orig = vertexBuffer.getData();
  31423. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31424. return orig;
  31425. }
  31426. else {
  31427. var len = orig.length;
  31428. var copy = [];
  31429. for (var i = 0; i < len; i++) {
  31430. copy.push(orig[i]);
  31431. }
  31432. return copy;
  31433. }
  31434. };
  31435. /**
  31436. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31437. * Possible `kind` values :
  31438. * - BABYLON.VertexBuffer.PositionKind
  31439. * - BABYLON.VertexBuffer.UVKind
  31440. * - BABYLON.VertexBuffer.UV2Kind
  31441. * - BABYLON.VertexBuffer.UV3Kind
  31442. * - BABYLON.VertexBuffer.UV4Kind
  31443. * - BABYLON.VertexBuffer.UV5Kind
  31444. * - BABYLON.VertexBuffer.UV6Kind
  31445. * - BABYLON.VertexBuffer.ColorKind
  31446. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31447. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31448. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31449. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31450. */
  31451. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31452. var vb = this._vertexBuffers[kind];
  31453. if (!vb) {
  31454. return false;
  31455. }
  31456. return vb.isUpdatable();
  31457. };
  31458. Geometry.prototype.getVertexBuffer = function (kind) {
  31459. if (!this.isReady()) {
  31460. return null;
  31461. }
  31462. return this._vertexBuffers[kind];
  31463. };
  31464. Geometry.prototype.getVertexBuffers = function () {
  31465. if (!this.isReady()) {
  31466. return null;
  31467. }
  31468. return this._vertexBuffers;
  31469. };
  31470. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31471. if (!this._vertexBuffers) {
  31472. if (this._delayInfo) {
  31473. return this._delayInfo.indexOf(kind) !== -1;
  31474. }
  31475. return false;
  31476. }
  31477. return this._vertexBuffers[kind] !== undefined;
  31478. };
  31479. Geometry.prototype.getVerticesDataKinds = function () {
  31480. var result = [];
  31481. var kind;
  31482. if (!this._vertexBuffers && this._delayInfo) {
  31483. for (kind in this._delayInfo) {
  31484. result.push(kind);
  31485. }
  31486. }
  31487. else {
  31488. for (kind in this._vertexBuffers) {
  31489. result.push(kind);
  31490. }
  31491. }
  31492. return result;
  31493. };
  31494. Geometry.prototype.updateIndices = function (indices, offset) {
  31495. if (!this._indexBuffer) {
  31496. return;
  31497. }
  31498. if (!this._indexBufferIsUpdatable) {
  31499. this.setIndices(indices, null, true);
  31500. }
  31501. else {
  31502. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31503. }
  31504. };
  31505. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31506. if (totalVertices === void 0) { totalVertices = null; }
  31507. if (updatable === void 0) { updatable = false; }
  31508. if (this._indexBuffer) {
  31509. this._engine._releaseBuffer(this._indexBuffer);
  31510. }
  31511. this._disposeVertexArrayObjects();
  31512. this._indices = indices;
  31513. this._indexBufferIsUpdatable = updatable;
  31514. if (this._meshes.length !== 0 && this._indices) {
  31515. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31516. }
  31517. if (totalVertices != undefined) {
  31518. this._totalVertices = totalVertices;
  31519. }
  31520. var meshes = this._meshes;
  31521. var numOfMeshes = meshes.length;
  31522. for (var index = 0; index < numOfMeshes; index++) {
  31523. meshes[index]._createGlobalSubMesh(true);
  31524. }
  31525. this.notifyUpdate();
  31526. };
  31527. Geometry.prototype.getTotalIndices = function () {
  31528. if (!this.isReady()) {
  31529. return 0;
  31530. }
  31531. return this._indices.length;
  31532. };
  31533. Geometry.prototype.getIndices = function (copyWhenShared) {
  31534. if (!this.isReady()) {
  31535. return null;
  31536. }
  31537. var orig = this._indices;
  31538. if (!copyWhenShared || this._meshes.length === 1) {
  31539. return orig;
  31540. }
  31541. else {
  31542. var len = orig.length;
  31543. var copy = [];
  31544. for (var i = 0; i < len; i++) {
  31545. copy.push(orig[i]);
  31546. }
  31547. return copy;
  31548. }
  31549. };
  31550. Geometry.prototype.getIndexBuffer = function () {
  31551. if (!this.isReady()) {
  31552. return null;
  31553. }
  31554. return this._indexBuffer;
  31555. };
  31556. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31557. if (effect === void 0) { effect = null; }
  31558. if (!effect || !this._vertexArrayObjects) {
  31559. return;
  31560. }
  31561. if (this._vertexArrayObjects[effect.key]) {
  31562. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31563. delete this._vertexArrayObjects[effect.key];
  31564. }
  31565. };
  31566. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31567. var meshes = this._meshes;
  31568. var index = meshes.indexOf(mesh);
  31569. if (index === -1) {
  31570. return;
  31571. }
  31572. meshes.splice(index, 1);
  31573. mesh._geometry = null;
  31574. if (meshes.length === 0 && shouldDispose) {
  31575. this.dispose();
  31576. }
  31577. };
  31578. Geometry.prototype.applyToMesh = function (mesh) {
  31579. if (mesh._geometry === this) {
  31580. return;
  31581. }
  31582. var previousGeometry = mesh._geometry;
  31583. if (previousGeometry) {
  31584. previousGeometry.releaseForMesh(mesh);
  31585. }
  31586. var meshes = this._meshes;
  31587. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31588. mesh._geometry = this;
  31589. this._scene.pushGeometry(this);
  31590. meshes.push(mesh);
  31591. if (this.isReady()) {
  31592. this._applyToMesh(mesh);
  31593. }
  31594. else {
  31595. mesh._boundingInfo = this._boundingInfo;
  31596. }
  31597. };
  31598. Geometry.prototype.updateExtend = function (data, stride) {
  31599. if (data === void 0) { data = null; }
  31600. if (!data) {
  31601. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31602. }
  31603. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31604. };
  31605. Geometry.prototype._applyToMesh = function (mesh) {
  31606. var numOfMeshes = this._meshes.length;
  31607. // vertexBuffers
  31608. for (var kind in this._vertexBuffers) {
  31609. if (numOfMeshes === 1) {
  31610. this._vertexBuffers[kind].create();
  31611. }
  31612. var buffer = this._vertexBuffers[kind].getBuffer();
  31613. if (buffer)
  31614. buffer.references = numOfMeshes;
  31615. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31616. if (!this._extend) {
  31617. this.updateExtend(this._vertexBuffers[kind].getData());
  31618. }
  31619. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31620. mesh._createGlobalSubMesh(false);
  31621. //bounding info was just created again, world matrix should be applied again.
  31622. mesh._updateBoundingInfo();
  31623. }
  31624. }
  31625. // indexBuffer
  31626. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31627. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31628. }
  31629. if (this._indexBuffer) {
  31630. this._indexBuffer.references = numOfMeshes;
  31631. }
  31632. };
  31633. Geometry.prototype.notifyUpdate = function (kind) {
  31634. if (this.onGeometryUpdated) {
  31635. this.onGeometryUpdated(this, kind);
  31636. }
  31637. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31638. var mesh = _a[_i];
  31639. mesh._markSubMeshesAsAttributesDirty();
  31640. }
  31641. };
  31642. Geometry.prototype.load = function (scene, onLoaded) {
  31643. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31644. return;
  31645. }
  31646. if (this.isReady()) {
  31647. if (onLoaded) {
  31648. onLoaded();
  31649. }
  31650. return;
  31651. }
  31652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31653. this._queueLoad(scene, onLoaded);
  31654. };
  31655. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31656. var _this = this;
  31657. if (!this.delayLoadingFile) {
  31658. return;
  31659. }
  31660. scene._addPendingData(this);
  31661. scene._loadFile(this.delayLoadingFile, function (data) {
  31662. if (!_this._delayLoadingFunction) {
  31663. return;
  31664. }
  31665. _this._delayLoadingFunction(JSON.parse(data), _this);
  31666. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31667. _this._delayInfo = [];
  31668. scene._removePendingData(_this);
  31669. var meshes = _this._meshes;
  31670. var numOfMeshes = meshes.length;
  31671. for (var index = 0; index < numOfMeshes; index++) {
  31672. _this._applyToMesh(meshes[index]);
  31673. }
  31674. if (onLoaded) {
  31675. onLoaded();
  31676. }
  31677. }, undefined, true);
  31678. };
  31679. /**
  31680. * Invert the geometry to move from a right handed system to a left handed one.
  31681. */
  31682. Geometry.prototype.toLeftHanded = function () {
  31683. // Flip faces
  31684. var tIndices = this.getIndices(false);
  31685. if (tIndices != null && tIndices.length > 0) {
  31686. for (var i = 0; i < tIndices.length; i += 3) {
  31687. var tTemp = tIndices[i + 0];
  31688. tIndices[i + 0] = tIndices[i + 2];
  31689. tIndices[i + 2] = tTemp;
  31690. }
  31691. this.setIndices(tIndices);
  31692. }
  31693. // Negate position.z
  31694. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31695. if (tPositions != null && tPositions.length > 0) {
  31696. for (var i = 0; i < tPositions.length; i += 3) {
  31697. tPositions[i + 2] = -tPositions[i + 2];
  31698. }
  31699. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31700. }
  31701. // Negate normal.z
  31702. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31703. if (tNormals != null && tNormals.length > 0) {
  31704. for (var i = 0; i < tNormals.length; i += 3) {
  31705. tNormals[i + 2] = -tNormals[i + 2];
  31706. }
  31707. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31708. }
  31709. };
  31710. // Cache
  31711. Geometry.prototype._resetPointsArrayCache = function () {
  31712. this._positions = null;
  31713. };
  31714. Geometry.prototype._generatePointsArray = function () {
  31715. if (this._positions)
  31716. return true;
  31717. this._positions = [];
  31718. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31719. if (!data) {
  31720. return false;
  31721. }
  31722. for (var index = 0; index < data.length; index += 3) {
  31723. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31724. }
  31725. return true;
  31726. };
  31727. Geometry.prototype.isDisposed = function () {
  31728. return this._isDisposed;
  31729. };
  31730. Geometry.prototype._disposeVertexArrayObjects = function () {
  31731. if (this._vertexArrayObjects) {
  31732. for (var kind in this._vertexArrayObjects) {
  31733. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31734. }
  31735. this._vertexArrayObjects = {};
  31736. }
  31737. };
  31738. Geometry.prototype.dispose = function () {
  31739. var meshes = this._meshes;
  31740. var numOfMeshes = meshes.length;
  31741. var index;
  31742. for (index = 0; index < numOfMeshes; index++) {
  31743. this.releaseForMesh(meshes[index]);
  31744. }
  31745. this._meshes = [];
  31746. this._disposeVertexArrayObjects();
  31747. for (var kind in this._vertexBuffers) {
  31748. this._vertexBuffers[kind].dispose();
  31749. }
  31750. this._vertexBuffers = {};
  31751. this._totalVertices = 0;
  31752. if (this._indexBuffer) {
  31753. this._engine._releaseBuffer(this._indexBuffer);
  31754. }
  31755. this._indexBuffer = null;
  31756. this._indices = [];
  31757. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31758. this.delayLoadingFile = null;
  31759. this._delayLoadingFunction = null;
  31760. this._delayInfo = [];
  31761. this._boundingInfo = null;
  31762. this._scene.removeGeometry(this);
  31763. this._isDisposed = true;
  31764. };
  31765. Geometry.prototype.copy = function (id) {
  31766. var vertexData = new BABYLON.VertexData();
  31767. vertexData.indices = [];
  31768. var indices = this.getIndices();
  31769. if (indices) {
  31770. for (var index = 0; index < indices.length; index++) {
  31771. vertexData.indices.push(indices[index]);
  31772. }
  31773. }
  31774. var updatable = false;
  31775. var stopChecking = false;
  31776. var kind;
  31777. for (kind in this._vertexBuffers) {
  31778. // using slice() to make a copy of the array and not just reference it
  31779. var data = this.getVerticesData(kind);
  31780. if (data instanceof Float32Array) {
  31781. vertexData.set(new Float32Array(data), kind);
  31782. }
  31783. else {
  31784. vertexData.set(data.slice(0), kind);
  31785. }
  31786. if (!stopChecking) {
  31787. var vb = this.getVertexBuffer(kind);
  31788. if (vb) {
  31789. updatable = vb.isUpdatable();
  31790. stopChecking = !updatable;
  31791. }
  31792. }
  31793. }
  31794. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31795. geometry.delayLoadState = this.delayLoadState;
  31796. geometry.delayLoadingFile = this.delayLoadingFile;
  31797. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31798. for (kind in this._delayInfo) {
  31799. geometry._delayInfo = geometry._delayInfo || [];
  31800. geometry._delayInfo.push(kind);
  31801. }
  31802. // Bounding info
  31803. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31804. return geometry;
  31805. };
  31806. Geometry.prototype.serialize = function () {
  31807. var serializationObject = {};
  31808. serializationObject.id = this.id;
  31809. serializationObject.updatable = this._updatable;
  31810. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31811. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31812. }
  31813. return serializationObject;
  31814. };
  31815. Geometry.prototype.toNumberArray = function (origin) {
  31816. if (Array.isArray(origin)) {
  31817. return origin;
  31818. }
  31819. else {
  31820. return Array.prototype.slice.call(origin);
  31821. }
  31822. };
  31823. Geometry.prototype.serializeVerticeData = function () {
  31824. var serializationObject = this.serialize();
  31825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31826. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31827. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31828. serializationObject.positions._updatable = true;
  31829. }
  31830. }
  31831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31832. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31833. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31834. serializationObject.normals._updatable = true;
  31835. }
  31836. }
  31837. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31838. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31839. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31840. serializationObject.uvs._updatable = true;
  31841. }
  31842. }
  31843. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31844. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31845. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31846. serializationObject.uv2s._updatable = true;
  31847. }
  31848. }
  31849. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31850. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31851. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31852. serializationObject.uv3s._updatable = true;
  31853. }
  31854. }
  31855. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31856. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31857. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31858. serializationObject.uv4s._updatable = true;
  31859. }
  31860. }
  31861. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31862. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31863. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31864. serializationObject.uv5s._updatable = true;
  31865. }
  31866. }
  31867. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31868. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31869. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31870. serializationObject.uv6s._updatable = true;
  31871. }
  31872. }
  31873. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31874. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31875. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31876. serializationObject.colors._updatable = true;
  31877. }
  31878. }
  31879. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31880. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31881. serializationObject.matricesIndices._isExpanded = true;
  31882. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31883. serializationObject.matricesIndices._updatable = true;
  31884. }
  31885. }
  31886. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31887. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31888. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31889. serializationObject.matricesWeights._updatable = true;
  31890. }
  31891. }
  31892. serializationObject.indices = this.toNumberArray(this.getIndices());
  31893. return serializationObject;
  31894. };
  31895. // Statics
  31896. Geometry.ExtractFromMesh = function (mesh, id) {
  31897. var geometry = mesh._geometry;
  31898. if (!geometry) {
  31899. return null;
  31900. }
  31901. return geometry.copy(id);
  31902. };
  31903. /**
  31904. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31905. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31906. * Be aware Math.random() could cause collisions, but:
  31907. * "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"
  31908. */
  31909. Geometry.RandomId = function () {
  31910. return BABYLON.Tools.RandomId();
  31911. };
  31912. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31913. var scene = mesh.getScene();
  31914. // Geometry
  31915. var geometryId = parsedGeometry.geometryId;
  31916. if (geometryId) {
  31917. var geometry = scene.getGeometryByID(geometryId);
  31918. if (geometry) {
  31919. geometry.applyToMesh(mesh);
  31920. }
  31921. }
  31922. else if (parsedGeometry instanceof ArrayBuffer) {
  31923. var binaryInfo = mesh._binaryInfo;
  31924. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31925. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31926. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31927. }
  31928. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31929. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31930. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31931. }
  31932. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31933. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31934. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31935. }
  31936. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31937. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31938. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31939. }
  31940. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31941. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31942. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31943. }
  31944. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31945. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31946. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31947. }
  31948. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31949. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31950. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31951. }
  31952. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31953. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31954. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31955. }
  31956. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31957. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31958. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31959. }
  31960. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31961. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31962. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31963. }
  31964. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31965. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31966. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31967. }
  31968. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31969. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31970. mesh.setIndices(indicesData, null);
  31971. }
  31972. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31973. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31974. mesh.subMeshes = [];
  31975. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31976. var materialIndex = subMeshesData[(i * 5) + 0];
  31977. var verticesStart = subMeshesData[(i * 5) + 1];
  31978. var verticesCount = subMeshesData[(i * 5) + 2];
  31979. var indexStart = subMeshesData[(i * 5) + 3];
  31980. var indexCount = subMeshesData[(i * 5) + 4];
  31981. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31982. }
  31983. }
  31984. }
  31985. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31986. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31987. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31988. if (parsedGeometry.uvs) {
  31989. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31990. }
  31991. if (parsedGeometry.uvs2) {
  31992. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31993. }
  31994. if (parsedGeometry.uvs3) {
  31995. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31996. }
  31997. if (parsedGeometry.uvs4) {
  31998. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31999. }
  32000. if (parsedGeometry.uvs5) {
  32001. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32002. }
  32003. if (parsedGeometry.uvs6) {
  32004. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32005. }
  32006. if (parsedGeometry.colors) {
  32007. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32008. }
  32009. if (parsedGeometry.matricesIndices) {
  32010. if (!parsedGeometry.matricesIndices._isExpanded) {
  32011. var floatIndices = [];
  32012. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32013. var matricesIndex = parsedGeometry.matricesIndices[i];
  32014. floatIndices.push(matricesIndex & 0x000000FF);
  32015. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32016. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32017. floatIndices.push(matricesIndex >> 24);
  32018. }
  32019. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32020. }
  32021. else {
  32022. delete parsedGeometry.matricesIndices._isExpanded;
  32023. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32024. }
  32025. }
  32026. if (parsedGeometry.matricesIndicesExtra) {
  32027. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32028. var floatIndices = [];
  32029. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32030. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32031. floatIndices.push(matricesIndex & 0x000000FF);
  32032. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32033. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32034. floatIndices.push(matricesIndex >> 24);
  32035. }
  32036. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32037. }
  32038. else {
  32039. delete parsedGeometry.matricesIndices._isExpanded;
  32040. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32041. }
  32042. }
  32043. if (parsedGeometry.matricesWeights) {
  32044. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32046. }
  32047. if (parsedGeometry.matricesWeightsExtra) {
  32048. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32049. }
  32050. mesh.setIndices(parsedGeometry.indices, null);
  32051. }
  32052. // SubMeshes
  32053. if (parsedGeometry.subMeshes) {
  32054. mesh.subMeshes = [];
  32055. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32056. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32057. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32058. }
  32059. }
  32060. // Flat shading
  32061. if (mesh._shouldGenerateFlatShading) {
  32062. mesh.convertToFlatShadedMesh();
  32063. delete mesh._shouldGenerateFlatShading;
  32064. }
  32065. // Update
  32066. mesh.computeWorldMatrix(true);
  32067. // Octree
  32068. var sceneOctree = scene.selectionOctree;
  32069. if (sceneOctree !== undefined && sceneOctree !== null) {
  32070. sceneOctree.addMesh(mesh);
  32071. }
  32072. };
  32073. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32074. var epsilon = 1e-3;
  32075. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32076. return;
  32077. }
  32078. var noInfluenceBoneIndex = 0.0;
  32079. if (parsedGeometry.skeletonId > -1) {
  32080. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32081. if (!skeleton) {
  32082. return;
  32083. }
  32084. noInfluenceBoneIndex = skeleton.bones.length;
  32085. }
  32086. else {
  32087. return;
  32088. }
  32089. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32090. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32091. var matricesWeights = parsedGeometry.matricesWeights;
  32092. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32093. var influencers = parsedGeometry.numBoneInfluencer;
  32094. var size = matricesWeights.length;
  32095. for (var i = 0; i < size; i += 4) {
  32096. var weight = 0.0;
  32097. var firstZeroWeight = -1;
  32098. for (var j = 0; j < 4; j++) {
  32099. var w = matricesWeights[i + j];
  32100. weight += w;
  32101. if (w < epsilon && firstZeroWeight < 0) {
  32102. firstZeroWeight = j;
  32103. }
  32104. }
  32105. if (matricesWeightsExtra) {
  32106. for (var j = 0; j < 4; j++) {
  32107. var w = matricesWeightsExtra[i + j];
  32108. weight += w;
  32109. if (w < epsilon && firstZeroWeight < 0) {
  32110. firstZeroWeight = j + 4;
  32111. }
  32112. }
  32113. }
  32114. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32115. firstZeroWeight = influencers - 1;
  32116. }
  32117. if (weight > epsilon) {
  32118. var mweight = 1.0 / weight;
  32119. for (var j = 0; j < 4; j++) {
  32120. matricesWeights[i + j] *= mweight;
  32121. }
  32122. if (matricesWeightsExtra) {
  32123. for (var j = 0; j < 4; j++) {
  32124. matricesWeightsExtra[i + j] *= mweight;
  32125. }
  32126. }
  32127. }
  32128. else {
  32129. if (firstZeroWeight >= 4) {
  32130. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32131. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32132. }
  32133. else {
  32134. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32135. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32136. }
  32137. }
  32138. }
  32139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32140. if (parsedGeometry.matricesWeightsExtra) {
  32141. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32142. }
  32143. };
  32144. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32145. if (scene.getGeometryByID(parsedVertexData.id)) {
  32146. return null; // null since geometry could be something else than a box...
  32147. }
  32148. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32149. if (BABYLON.Tags) {
  32150. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32151. }
  32152. if (parsedVertexData.delayLoadingFile) {
  32153. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32154. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32155. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32156. geometry._delayInfo = [];
  32157. if (parsedVertexData.hasUVs) {
  32158. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32159. }
  32160. if (parsedVertexData.hasUVs2) {
  32161. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32162. }
  32163. if (parsedVertexData.hasUVs3) {
  32164. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32165. }
  32166. if (parsedVertexData.hasUVs4) {
  32167. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32168. }
  32169. if (parsedVertexData.hasUVs5) {
  32170. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32171. }
  32172. if (parsedVertexData.hasUVs6) {
  32173. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32174. }
  32175. if (parsedVertexData.hasColors) {
  32176. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32177. }
  32178. if (parsedVertexData.hasMatricesIndices) {
  32179. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32180. }
  32181. if (parsedVertexData.hasMatricesWeights) {
  32182. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32183. }
  32184. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32185. }
  32186. else {
  32187. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32188. }
  32189. scene.pushGeometry(geometry, true);
  32190. return geometry;
  32191. };
  32192. return Geometry;
  32193. }());
  32194. BABYLON.Geometry = Geometry;
  32195. /////// Primitives //////////////////////////////////////////////
  32196. //export module Geometry.Primitives {
  32197. /// Abstract class
  32198. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32199. __extends(_PrimitiveGeometry, _super);
  32200. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32201. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32202. if (mesh === void 0) { mesh = null; }
  32203. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32204. _this._canBeRegenerated = _canBeRegenerated;
  32205. _this._beingRegenerated = true;
  32206. _this.regenerate();
  32207. _this._beingRegenerated = false;
  32208. return _this;
  32209. }
  32210. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32211. return this._canBeRegenerated;
  32212. };
  32213. _PrimitiveGeometry.prototype.regenerate = function () {
  32214. if (!this._canBeRegenerated) {
  32215. return;
  32216. }
  32217. this._beingRegenerated = true;
  32218. this.setAllVerticesData(this._regenerateVertexData(), false);
  32219. this._beingRegenerated = false;
  32220. };
  32221. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32222. return _super.prototype.copy.call(this, id);
  32223. };
  32224. // overrides
  32225. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32226. if (!this._beingRegenerated) {
  32227. return;
  32228. }
  32229. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32230. };
  32231. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32232. if (!this._beingRegenerated) {
  32233. return;
  32234. }
  32235. _super.prototype.setVerticesData.call(this, kind, data, false);
  32236. };
  32237. // to override
  32238. // protected
  32239. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32240. throw new Error("Abstract method");
  32241. };
  32242. _PrimitiveGeometry.prototype.copy = function (id) {
  32243. throw new Error("Must be overriden in sub-classes.");
  32244. };
  32245. _PrimitiveGeometry.prototype.serialize = function () {
  32246. var serializationObject = _super.prototype.serialize.call(this);
  32247. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32248. return serializationObject;
  32249. };
  32250. return _PrimitiveGeometry;
  32251. }(Geometry));
  32252. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32253. var RibbonGeometry = /** @class */ (function (_super) {
  32254. __extends(RibbonGeometry, _super);
  32255. // Members
  32256. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32257. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32258. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32259. _this.pathArray = pathArray;
  32260. _this.closeArray = closeArray;
  32261. _this.closePath = closePath;
  32262. _this.offset = offset;
  32263. _this.side = side;
  32264. return _this;
  32265. }
  32266. RibbonGeometry.prototype._regenerateVertexData = function () {
  32267. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32268. };
  32269. RibbonGeometry.prototype.copy = function (id) {
  32270. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32271. };
  32272. return RibbonGeometry;
  32273. }(_PrimitiveGeometry));
  32274. BABYLON.RibbonGeometry = RibbonGeometry;
  32275. var BoxGeometry = /** @class */ (function (_super) {
  32276. __extends(BoxGeometry, _super);
  32277. // Members
  32278. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32279. if (mesh === void 0) { mesh = null; }
  32280. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32281. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32282. _this.size = size;
  32283. _this.side = side;
  32284. return _this;
  32285. }
  32286. BoxGeometry.prototype._regenerateVertexData = function () {
  32287. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32288. };
  32289. BoxGeometry.prototype.copy = function (id) {
  32290. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32291. };
  32292. BoxGeometry.prototype.serialize = function () {
  32293. var serializationObject = _super.prototype.serialize.call(this);
  32294. serializationObject.size = this.size;
  32295. return serializationObject;
  32296. };
  32297. BoxGeometry.Parse = function (parsedBox, scene) {
  32298. if (scene.getGeometryByID(parsedBox.id)) {
  32299. return null; // null since geometry could be something else than a box...
  32300. }
  32301. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32302. if (BABYLON.Tags) {
  32303. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32304. }
  32305. scene.pushGeometry(box, true);
  32306. return box;
  32307. };
  32308. return BoxGeometry;
  32309. }(_PrimitiveGeometry));
  32310. BABYLON.BoxGeometry = BoxGeometry;
  32311. var SphereGeometry = /** @class */ (function (_super) {
  32312. __extends(SphereGeometry, _super);
  32313. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32314. if (mesh === void 0) { mesh = null; }
  32315. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32316. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32317. _this.segments = segments;
  32318. _this.diameter = diameter;
  32319. _this.side = side;
  32320. return _this;
  32321. }
  32322. SphereGeometry.prototype._regenerateVertexData = function () {
  32323. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32324. };
  32325. SphereGeometry.prototype.copy = function (id) {
  32326. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32327. };
  32328. SphereGeometry.prototype.serialize = function () {
  32329. var serializationObject = _super.prototype.serialize.call(this);
  32330. serializationObject.segments = this.segments;
  32331. serializationObject.diameter = this.diameter;
  32332. return serializationObject;
  32333. };
  32334. SphereGeometry.Parse = function (parsedSphere, scene) {
  32335. if (scene.getGeometryByID(parsedSphere.id)) {
  32336. return null; // null since geometry could be something else than a sphere...
  32337. }
  32338. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32339. if (BABYLON.Tags) {
  32340. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32341. }
  32342. scene.pushGeometry(sphere, true);
  32343. return sphere;
  32344. };
  32345. return SphereGeometry;
  32346. }(_PrimitiveGeometry));
  32347. BABYLON.SphereGeometry = SphereGeometry;
  32348. var DiscGeometry = /** @class */ (function (_super) {
  32349. __extends(DiscGeometry, _super);
  32350. // Members
  32351. function DiscGeometry(id, scene, radius, tessellation, 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.radius = radius;
  32356. _this.tessellation = tessellation;
  32357. _this.side = side;
  32358. return _this;
  32359. }
  32360. DiscGeometry.prototype._regenerateVertexData = function () {
  32361. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32362. };
  32363. DiscGeometry.prototype.copy = function (id) {
  32364. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32365. };
  32366. return DiscGeometry;
  32367. }(_PrimitiveGeometry));
  32368. BABYLON.DiscGeometry = DiscGeometry;
  32369. var CylinderGeometry = /** @class */ (function (_super) {
  32370. __extends(CylinderGeometry, _super);
  32371. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32372. if (subdivisions === void 0) { subdivisions = 1; }
  32373. if (mesh === void 0) { mesh = null; }
  32374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32375. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32376. _this.height = height;
  32377. _this.diameterTop = diameterTop;
  32378. _this.diameterBottom = diameterBottom;
  32379. _this.tessellation = tessellation;
  32380. _this.subdivisions = subdivisions;
  32381. _this.side = side;
  32382. return _this;
  32383. }
  32384. CylinderGeometry.prototype._regenerateVertexData = function () {
  32385. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32386. };
  32387. CylinderGeometry.prototype.copy = function (id) {
  32388. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32389. };
  32390. CylinderGeometry.prototype.serialize = function () {
  32391. var serializationObject = _super.prototype.serialize.call(this);
  32392. serializationObject.height = this.height;
  32393. serializationObject.diameterTop = this.diameterTop;
  32394. serializationObject.diameterBottom = this.diameterBottom;
  32395. serializationObject.tessellation = this.tessellation;
  32396. return serializationObject;
  32397. };
  32398. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32399. if (scene.getGeometryByID(parsedCylinder.id)) {
  32400. return null; // null since geometry could be something else than a cylinder...
  32401. }
  32402. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32403. if (BABYLON.Tags) {
  32404. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32405. }
  32406. scene.pushGeometry(cylinder, true);
  32407. return cylinder;
  32408. };
  32409. return CylinderGeometry;
  32410. }(_PrimitiveGeometry));
  32411. BABYLON.CylinderGeometry = CylinderGeometry;
  32412. var TorusGeometry = /** @class */ (function (_super) {
  32413. __extends(TorusGeometry, _super);
  32414. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32415. if (mesh === void 0) { mesh = null; }
  32416. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32417. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32418. _this.diameter = diameter;
  32419. _this.thickness = thickness;
  32420. _this.tessellation = tessellation;
  32421. _this.side = side;
  32422. return _this;
  32423. }
  32424. TorusGeometry.prototype._regenerateVertexData = function () {
  32425. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32426. };
  32427. TorusGeometry.prototype.copy = function (id) {
  32428. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32429. };
  32430. TorusGeometry.prototype.serialize = function () {
  32431. var serializationObject = _super.prototype.serialize.call(this);
  32432. serializationObject.diameter = this.diameter;
  32433. serializationObject.thickness = this.thickness;
  32434. serializationObject.tessellation = this.tessellation;
  32435. return serializationObject;
  32436. };
  32437. TorusGeometry.Parse = function (parsedTorus, scene) {
  32438. if (scene.getGeometryByID(parsedTorus.id)) {
  32439. return null; // null since geometry could be something else than a torus...
  32440. }
  32441. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32442. if (BABYLON.Tags) {
  32443. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32444. }
  32445. scene.pushGeometry(torus, true);
  32446. return torus;
  32447. };
  32448. return TorusGeometry;
  32449. }(_PrimitiveGeometry));
  32450. BABYLON.TorusGeometry = TorusGeometry;
  32451. var GroundGeometry = /** @class */ (function (_super) {
  32452. __extends(GroundGeometry, _super);
  32453. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32454. if (mesh === void 0) { mesh = null; }
  32455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32456. _this.width = width;
  32457. _this.height = height;
  32458. _this.subdivisions = subdivisions;
  32459. return _this;
  32460. }
  32461. GroundGeometry.prototype._regenerateVertexData = function () {
  32462. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32463. };
  32464. GroundGeometry.prototype.copy = function (id) {
  32465. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32466. };
  32467. GroundGeometry.prototype.serialize = function () {
  32468. var serializationObject = _super.prototype.serialize.call(this);
  32469. serializationObject.width = this.width;
  32470. serializationObject.height = this.height;
  32471. serializationObject.subdivisions = this.subdivisions;
  32472. return serializationObject;
  32473. };
  32474. GroundGeometry.Parse = function (parsedGround, scene) {
  32475. if (scene.getGeometryByID(parsedGround.id)) {
  32476. return null; // null since geometry could be something else than a ground...
  32477. }
  32478. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32479. if (BABYLON.Tags) {
  32480. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32481. }
  32482. scene.pushGeometry(ground, true);
  32483. return ground;
  32484. };
  32485. return GroundGeometry;
  32486. }(_PrimitiveGeometry));
  32487. BABYLON.GroundGeometry = GroundGeometry;
  32488. var TiledGroundGeometry = /** @class */ (function (_super) {
  32489. __extends(TiledGroundGeometry, _super);
  32490. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32491. if (mesh === void 0) { mesh = null; }
  32492. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32493. _this.xmin = xmin;
  32494. _this.zmin = zmin;
  32495. _this.xmax = xmax;
  32496. _this.zmax = zmax;
  32497. _this.subdivisions = subdivisions;
  32498. _this.precision = precision;
  32499. return _this;
  32500. }
  32501. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32502. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32503. };
  32504. TiledGroundGeometry.prototype.copy = function (id) {
  32505. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32506. };
  32507. return TiledGroundGeometry;
  32508. }(_PrimitiveGeometry));
  32509. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32510. var PlaneGeometry = /** @class */ (function (_super) {
  32511. __extends(PlaneGeometry, _super);
  32512. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32513. if (mesh === void 0) { mesh = null; }
  32514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32516. _this.size = size;
  32517. _this.side = side;
  32518. return _this;
  32519. }
  32520. PlaneGeometry.prototype._regenerateVertexData = function () {
  32521. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32522. };
  32523. PlaneGeometry.prototype.copy = function (id) {
  32524. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32525. };
  32526. PlaneGeometry.prototype.serialize = function () {
  32527. var serializationObject = _super.prototype.serialize.call(this);
  32528. serializationObject.size = this.size;
  32529. return serializationObject;
  32530. };
  32531. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32532. if (scene.getGeometryByID(parsedPlane.id)) {
  32533. return null; // null since geometry could be something else than a ground...
  32534. }
  32535. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32536. if (BABYLON.Tags) {
  32537. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32538. }
  32539. scene.pushGeometry(plane, true);
  32540. return plane;
  32541. };
  32542. return PlaneGeometry;
  32543. }(_PrimitiveGeometry));
  32544. BABYLON.PlaneGeometry = PlaneGeometry;
  32545. var TorusKnotGeometry = /** @class */ (function (_super) {
  32546. __extends(TorusKnotGeometry, _super);
  32547. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32548. if (mesh === void 0) { mesh = null; }
  32549. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32550. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32551. _this.radius = radius;
  32552. _this.tube = tube;
  32553. _this.radialSegments = radialSegments;
  32554. _this.tubularSegments = tubularSegments;
  32555. _this.p = p;
  32556. _this.q = q;
  32557. _this.side = side;
  32558. return _this;
  32559. }
  32560. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32561. 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 });
  32562. };
  32563. TorusKnotGeometry.prototype.copy = function (id) {
  32564. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32565. };
  32566. TorusKnotGeometry.prototype.serialize = function () {
  32567. var serializationObject = _super.prototype.serialize.call(this);
  32568. serializationObject.radius = this.radius;
  32569. serializationObject.tube = this.tube;
  32570. serializationObject.radialSegments = this.radialSegments;
  32571. serializationObject.tubularSegments = this.tubularSegments;
  32572. serializationObject.p = this.p;
  32573. serializationObject.q = this.q;
  32574. return serializationObject;
  32575. };
  32576. ;
  32577. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32578. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32579. return null; // null since geometry could be something else than a ground...
  32580. }
  32581. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32582. if (BABYLON.Tags) {
  32583. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32584. }
  32585. scene.pushGeometry(torusKnot, true);
  32586. return torusKnot;
  32587. };
  32588. return TorusKnotGeometry;
  32589. }(_PrimitiveGeometry));
  32590. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32591. //}
  32592. })(BABYLON || (BABYLON = {}));
  32593. //# sourceMappingURL=babylon.geometry.js.map
  32594. var BABYLON;
  32595. (function (BABYLON) {
  32596. var PostProcessManager = /** @class */ (function () {
  32597. function PostProcessManager(scene) {
  32598. this._vertexBuffers = {};
  32599. this._scene = scene;
  32600. }
  32601. PostProcessManager.prototype._prepareBuffers = function () {
  32602. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32603. return;
  32604. }
  32605. // VBO
  32606. var vertices = [];
  32607. vertices.push(1, 1);
  32608. vertices.push(-1, 1);
  32609. vertices.push(-1, -1);
  32610. vertices.push(1, -1);
  32611. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32612. this._buildIndexBuffer();
  32613. };
  32614. PostProcessManager.prototype._buildIndexBuffer = function () {
  32615. // Indices
  32616. var indices = [];
  32617. indices.push(0);
  32618. indices.push(1);
  32619. indices.push(2);
  32620. indices.push(0);
  32621. indices.push(2);
  32622. indices.push(3);
  32623. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32624. };
  32625. PostProcessManager.prototype._rebuild = function () {
  32626. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32627. if (!vb) {
  32628. return;
  32629. }
  32630. vb._rebuild();
  32631. this._buildIndexBuffer();
  32632. };
  32633. // Methods
  32634. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32635. if (sourceTexture === void 0) { sourceTexture = null; }
  32636. if (postProcesses === void 0) { postProcesses = null; }
  32637. var camera = this._scene.activeCamera;
  32638. if (!camera) {
  32639. return false;
  32640. }
  32641. var postProcesses = postProcesses || camera._postProcesses;
  32642. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32643. return false;
  32644. }
  32645. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32646. return true;
  32647. };
  32648. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32649. if (targetTexture === void 0) { targetTexture = null; }
  32650. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32651. var engine = this._scene.getEngine();
  32652. for (var index = 0; index < postProcesses.length; index++) {
  32653. if (index < postProcesses.length - 1) {
  32654. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32655. }
  32656. else {
  32657. if (targetTexture) {
  32658. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32659. }
  32660. else {
  32661. engine.restoreDefaultFramebuffer();
  32662. }
  32663. }
  32664. var pp = postProcesses[index];
  32665. var effect = pp.apply();
  32666. if (effect) {
  32667. pp.onBeforeRenderObservable.notifyObservers(effect);
  32668. // VBOs
  32669. this._prepareBuffers();
  32670. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32671. // Draw order
  32672. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32673. pp.onAfterRenderObservable.notifyObservers(effect);
  32674. }
  32675. }
  32676. // Restore depth buffer
  32677. engine.setDepthBuffer(true);
  32678. engine.setDepthWrite(true);
  32679. };
  32680. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32681. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32682. var camera = this._scene.activeCamera;
  32683. if (!camera) {
  32684. return;
  32685. }
  32686. postProcesses = postProcesses || camera._postProcesses;
  32687. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32688. return;
  32689. }
  32690. var engine = this._scene.getEngine();
  32691. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32692. if (index < len - 1) {
  32693. postProcesses[index + 1].activate(camera, targetTexture);
  32694. }
  32695. else {
  32696. if (targetTexture) {
  32697. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32698. }
  32699. else {
  32700. engine.restoreDefaultFramebuffer();
  32701. }
  32702. }
  32703. if (doNotPresent) {
  32704. break;
  32705. }
  32706. var pp = postProcesses[index];
  32707. var effect = pp.apply();
  32708. if (effect) {
  32709. pp.onBeforeRenderObservable.notifyObservers(effect);
  32710. // VBOs
  32711. this._prepareBuffers();
  32712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32713. // Draw order
  32714. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32715. pp.onAfterRenderObservable.notifyObservers(effect);
  32716. }
  32717. }
  32718. // Restore states
  32719. engine.setDepthBuffer(true);
  32720. engine.setDepthWrite(true);
  32721. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32722. };
  32723. PostProcessManager.prototype.dispose = function () {
  32724. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32725. if (buffer) {
  32726. buffer.dispose();
  32727. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32728. }
  32729. if (this._indexBuffer) {
  32730. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32731. this._indexBuffer = null;
  32732. }
  32733. };
  32734. return PostProcessManager;
  32735. }());
  32736. BABYLON.PostProcessManager = PostProcessManager;
  32737. })(BABYLON || (BABYLON = {}));
  32738. //# sourceMappingURL=babylon.postProcessManager.js.map
  32739. BABYLON.Effect.IncludesShadersStore['depthPrePass'] = "#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";
  32740. 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";
  32741. 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";
  32742. BABYLON.Effect.IncludesShadersStore['pointCloudVertexDeclaration'] = "#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  32743. BABYLON.Effect.IncludesShadersStore['bumpVertexDeclaration'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";
  32744. BABYLON.Effect.IncludesShadersStore['clipPlaneVertexDeclaration'] = "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif";
  32745. BABYLON.Effect.IncludesShadersStore['fogVertexDeclaration'] = "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";
  32746. BABYLON.Effect.IncludesShadersStore['morphTargetsVertexGlobalDeclaration'] = "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";
  32747. 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";
  32748. BABYLON.Effect.IncludesShadersStore['logDepthDeclaration'] = "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";
  32749. 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";
  32750. BABYLON.Effect.IncludesShadersStore['instancesVertex'] = "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";
  32751. 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";
  32752. 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";
  32753. BABYLON.Effect.IncludesShadersStore['clipPlaneVertex'] = "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif";
  32754. BABYLON.Effect.IncludesShadersStore['fogVertex'] = "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";
  32755. 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";
  32756. BABYLON.Effect.IncludesShadersStore['pointCloudVertex'] = "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";
  32757. BABYLON.Effect.IncludesShadersStore['logDepthVertex'] = "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";
  32758. 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}";
  32759. 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";
  32760. 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";
  32761. 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";
  32762. 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";
  32763. 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";
  32764. 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};";
  32765. 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";
  32766. 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";
  32767. 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}";
  32768. 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";
  32769. 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}";
  32770. 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";
  32771. BABYLON.Effect.IncludesShadersStore['clipPlaneFragmentDeclaration'] = "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif";
  32772. 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";
  32773. BABYLON.Effect.IncludesShadersStore['clipPlaneFragment'] = "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif";
  32774. 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";
  32775. 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";
  32776. BABYLON.Effect.IncludesShadersStore['logDepthFragment'] = "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";
  32777. BABYLON.Effect.IncludesShadersStore['fogFragment'] = "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";
  32778. var BABYLON;
  32779. (function (BABYLON) {
  32780. /**
  32781. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32782. */
  32783. var PerformanceMonitor = /** @class */ (function () {
  32784. /**
  32785. * constructor
  32786. * @param frameSampleSize The number of samples required to saturate the sliding window
  32787. */
  32788. function PerformanceMonitor(frameSampleSize) {
  32789. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32790. this._enabled = true;
  32791. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32792. }
  32793. /**
  32794. * Samples current frame
  32795. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32796. */
  32797. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32798. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32799. if (!this._enabled)
  32800. return;
  32801. if (this._lastFrameTimeMs != null) {
  32802. var dt = timeMs - this._lastFrameTimeMs;
  32803. this._rollingFrameTime.add(dt);
  32804. }
  32805. this._lastFrameTimeMs = timeMs;
  32806. };
  32807. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32808. /**
  32809. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32810. * @return Average frame time in milliseconds
  32811. */
  32812. get: function () {
  32813. return this._rollingFrameTime.average;
  32814. },
  32815. enumerable: true,
  32816. configurable: true
  32817. });
  32818. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32819. /**
  32820. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32821. * @return Frame time variance in milliseconds squared
  32822. */
  32823. get: function () {
  32824. return this._rollingFrameTime.variance;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32830. /**
  32831. * Returns the frame time of the most recent frame
  32832. * @return Frame time in milliseconds
  32833. */
  32834. get: function () {
  32835. return this._rollingFrameTime.history(0);
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32841. /**
  32842. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32843. * @return Framerate in frames per second
  32844. */
  32845. get: function () {
  32846. return 1000.0 / this._rollingFrameTime.average;
  32847. },
  32848. enumerable: true,
  32849. configurable: true
  32850. });
  32851. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32852. /**
  32853. * Returns the average framerate in frames per second using the most recent frame time
  32854. * @return Framerate in frames per second
  32855. */
  32856. get: function () {
  32857. var history = this._rollingFrameTime.history(0);
  32858. if (history === 0) {
  32859. return 0;
  32860. }
  32861. return 1000.0 / history;
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32867. /**
  32868. * Returns true if enough samples have been taken to completely fill the sliding window
  32869. * @return true if saturated
  32870. */
  32871. get: function () {
  32872. return this._rollingFrameTime.isSaturated();
  32873. },
  32874. enumerable: true,
  32875. configurable: true
  32876. });
  32877. /**
  32878. * Enables contributions to the sliding window sample set
  32879. */
  32880. PerformanceMonitor.prototype.enable = function () {
  32881. this._enabled = true;
  32882. };
  32883. /**
  32884. * Disables contributions to the sliding window sample set
  32885. * Samples will not be interpolated over the disabled period
  32886. */
  32887. PerformanceMonitor.prototype.disable = function () {
  32888. this._enabled = false;
  32889. //clear last sample to avoid interpolating over the disabled period when next enabled
  32890. this._lastFrameTimeMs = null;
  32891. };
  32892. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32893. /**
  32894. * Returns true if sampling is enabled
  32895. * @return true if enabled
  32896. */
  32897. get: function () {
  32898. return this._enabled;
  32899. },
  32900. enumerable: true,
  32901. configurable: true
  32902. });
  32903. /**
  32904. * Resets performance monitor
  32905. */
  32906. PerformanceMonitor.prototype.reset = function () {
  32907. //clear last sample to avoid interpolating over the disabled period when next enabled
  32908. this._lastFrameTimeMs = null;
  32909. //wipe record
  32910. this._rollingFrameTime.reset();
  32911. };
  32912. return PerformanceMonitor;
  32913. }());
  32914. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32915. /**
  32916. * RollingAverage
  32917. *
  32918. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32919. */
  32920. var RollingAverage = /** @class */ (function () {
  32921. /**
  32922. * constructor
  32923. * @param length The number of samples required to saturate the sliding window
  32924. */
  32925. function RollingAverage(length) {
  32926. this._samples = new Array(length);
  32927. this.reset();
  32928. }
  32929. /**
  32930. * Adds a sample to the sample set
  32931. * @param v The sample value
  32932. */
  32933. RollingAverage.prototype.add = function (v) {
  32934. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32935. var delta;
  32936. //we need to check if we've already wrapped round
  32937. if (this.isSaturated()) {
  32938. //remove bottom of stack from mean
  32939. var bottomValue = this._samples[this._pos];
  32940. delta = bottomValue - this.average;
  32941. this.average -= delta / (this._sampleCount - 1);
  32942. this._m2 -= delta * (bottomValue - this.average);
  32943. }
  32944. else {
  32945. this._sampleCount++;
  32946. }
  32947. //add new value to mean
  32948. delta = v - this.average;
  32949. this.average += delta / (this._sampleCount);
  32950. this._m2 += delta * (v - this.average);
  32951. //set the new variance
  32952. this.variance = this._m2 / (this._sampleCount - 1);
  32953. this._samples[this._pos] = v;
  32954. this._pos++;
  32955. this._pos %= this._samples.length; //positive wrap around
  32956. };
  32957. /**
  32958. * Returns previously added values or null if outside of history or outside the sliding window domain
  32959. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32960. * @return Value previously recorded with add() or null if outside of range
  32961. */
  32962. RollingAverage.prototype.history = function (i) {
  32963. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32964. return 0;
  32965. }
  32966. var i0 = this._wrapPosition(this._pos - 1.0);
  32967. return this._samples[this._wrapPosition(i0 - i)];
  32968. };
  32969. /**
  32970. * Returns true if enough samples have been taken to completely fill the sliding window
  32971. * @return true if sample-set saturated
  32972. */
  32973. RollingAverage.prototype.isSaturated = function () {
  32974. return this._sampleCount >= this._samples.length;
  32975. };
  32976. /**
  32977. * Resets the rolling average (equivalent to 0 samples taken so far)
  32978. */
  32979. RollingAverage.prototype.reset = function () {
  32980. this.average = 0;
  32981. this.variance = 0;
  32982. this._sampleCount = 0;
  32983. this._pos = 0;
  32984. this._m2 = 0;
  32985. };
  32986. /**
  32987. * Wraps a value around the sample range boundaries
  32988. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32989. * @return Wrapped position in sample range
  32990. */
  32991. RollingAverage.prototype._wrapPosition = function (i) {
  32992. var max = this._samples.length;
  32993. return ((i % max) + max) % max;
  32994. };
  32995. return RollingAverage;
  32996. }());
  32997. BABYLON.RollingAverage = RollingAverage;
  32998. })(BABYLON || (BABYLON = {}));
  32999. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33000. var BABYLON;
  33001. (function (BABYLON) {
  33002. /**
  33003. * This groups together the common properties used for image processing either in direct forward pass
  33004. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33005. * or not.
  33006. */
  33007. var ImageProcessingConfiguration = /** @class */ (function () {
  33008. function ImageProcessingConfiguration() {
  33009. /**
  33010. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33011. */
  33012. this.colorCurves = new BABYLON.ColorCurves();
  33013. this._colorCurvesEnabled = false;
  33014. this._colorGradingEnabled = false;
  33015. this._colorGradingWithGreenDepth = true;
  33016. this._colorGradingBGR = true;
  33017. this._exposure = 1.0;
  33018. this._toneMappingEnabled = false;
  33019. this._contrast = 1.0;
  33020. /**
  33021. * Vignette stretch size.
  33022. */
  33023. this.vignetteStretch = 0;
  33024. /**
  33025. * Vignette centre X Offset.
  33026. */
  33027. this.vignetteCentreX = 0;
  33028. /**
  33029. * Vignette centre Y Offset.
  33030. */
  33031. this.vignetteCentreY = 0;
  33032. /**
  33033. * Vignette weight or intensity of the vignette effect.
  33034. */
  33035. this.vignetteWeight = 1.5;
  33036. /**
  33037. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33038. * if vignetteEnabled is set to true.
  33039. */
  33040. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33041. /**
  33042. * Camera field of view used by the Vignette effect.
  33043. */
  33044. this.vignetteCameraFov = 0.5;
  33045. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33046. this._vignetteEnabled = false;
  33047. this._applyByPostProcess = false;
  33048. this._isEnabled = true;
  33049. /**
  33050. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33051. * @type {BABYLON.Observable}
  33052. */
  33053. this.onUpdateParameters = new BABYLON.Observable();
  33054. }
  33055. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33056. /**
  33057. * Gets wether the color curves effect is enabled.
  33058. */
  33059. get: function () {
  33060. return this._colorCurvesEnabled;
  33061. },
  33062. /**
  33063. * Sets wether the color curves effect is enabled.
  33064. */
  33065. set: function (value) {
  33066. if (this._colorCurvesEnabled === value) {
  33067. return;
  33068. }
  33069. this._colorCurvesEnabled = value;
  33070. this._updateParameters();
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33076. /**
  33077. * Gets wether the color grading effect is enabled.
  33078. */
  33079. get: function () {
  33080. return this._colorGradingEnabled;
  33081. },
  33082. /**
  33083. * Sets wether the color grading effect is enabled.
  33084. */
  33085. set: function (value) {
  33086. if (this._colorGradingEnabled === value) {
  33087. return;
  33088. }
  33089. this._colorGradingEnabled = value;
  33090. this._updateParameters();
  33091. },
  33092. enumerable: true,
  33093. configurable: true
  33094. });
  33095. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33096. /**
  33097. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33098. */
  33099. get: function () {
  33100. return this._colorGradingWithGreenDepth;
  33101. },
  33102. /**
  33103. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33104. */
  33105. set: function (value) {
  33106. if (this._colorGradingWithGreenDepth === value) {
  33107. return;
  33108. }
  33109. this._colorGradingWithGreenDepth = value;
  33110. this._updateParameters();
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33116. /**
  33117. * Gets wether the color grading texture contains BGR values.
  33118. */
  33119. get: function () {
  33120. return this._colorGradingBGR;
  33121. },
  33122. /**
  33123. * Sets wether the color grading texture contains BGR values.
  33124. */
  33125. set: function (value) {
  33126. if (this._colorGradingBGR === value) {
  33127. return;
  33128. }
  33129. this._colorGradingBGR = value;
  33130. this._updateParameters();
  33131. },
  33132. enumerable: true,
  33133. configurable: true
  33134. });
  33135. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33136. /**
  33137. * Gets the Exposure used in the effect.
  33138. */
  33139. get: function () {
  33140. return this._exposure;
  33141. },
  33142. /**
  33143. * Sets the Exposure used in the effect.
  33144. */
  33145. set: function (value) {
  33146. if (this._exposure === value) {
  33147. return;
  33148. }
  33149. this._exposure = value;
  33150. this._updateParameters();
  33151. },
  33152. enumerable: true,
  33153. configurable: true
  33154. });
  33155. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33156. /**
  33157. * Gets wether the tone mapping effect is enabled.
  33158. */
  33159. get: function () {
  33160. return this._toneMappingEnabled;
  33161. },
  33162. /**
  33163. * Sets wether the tone mapping effect is enabled.
  33164. */
  33165. set: function (value) {
  33166. if (this._toneMappingEnabled === value) {
  33167. return;
  33168. }
  33169. this._toneMappingEnabled = value;
  33170. this._updateParameters();
  33171. },
  33172. enumerable: true,
  33173. configurable: true
  33174. });
  33175. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33176. /**
  33177. * Gets the contrast used in the effect.
  33178. */
  33179. get: function () {
  33180. return this._contrast;
  33181. },
  33182. /**
  33183. * Sets the contrast used in the effect.
  33184. */
  33185. set: function (value) {
  33186. if (this._contrast === value) {
  33187. return;
  33188. }
  33189. this._contrast = value;
  33190. this._updateParameters();
  33191. },
  33192. enumerable: true,
  33193. configurable: true
  33194. });
  33195. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33196. /**
  33197. * Gets the vignette blend mode allowing different kind of effect.
  33198. */
  33199. get: function () {
  33200. return this._vignetteBlendMode;
  33201. },
  33202. /**
  33203. * Sets the vignette blend mode allowing different kind of effect.
  33204. */
  33205. set: function (value) {
  33206. if (this._vignetteBlendMode === value) {
  33207. return;
  33208. }
  33209. this._vignetteBlendMode = value;
  33210. this._updateParameters();
  33211. },
  33212. enumerable: true,
  33213. configurable: true
  33214. });
  33215. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33216. /**
  33217. * Gets wether the vignette effect is enabled.
  33218. */
  33219. get: function () {
  33220. return this._vignetteEnabled;
  33221. },
  33222. /**
  33223. * Sets wether the vignette effect is enabled.
  33224. */
  33225. set: function (value) {
  33226. if (this._vignetteEnabled === value) {
  33227. return;
  33228. }
  33229. this._vignetteEnabled = value;
  33230. this._updateParameters();
  33231. },
  33232. enumerable: true,
  33233. configurable: true
  33234. });
  33235. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33236. /**
  33237. * Gets wether the image processing is applied through a post process or not.
  33238. */
  33239. get: function () {
  33240. return this._applyByPostProcess;
  33241. },
  33242. /**
  33243. * Sets wether the image processing is applied through a post process or not.
  33244. */
  33245. set: function (value) {
  33246. if (this._applyByPostProcess === value) {
  33247. return;
  33248. }
  33249. this._applyByPostProcess = value;
  33250. this._updateParameters();
  33251. },
  33252. enumerable: true,
  33253. configurable: true
  33254. });
  33255. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33256. /**
  33257. * Gets wether the image processing is enabled or not.
  33258. */
  33259. get: function () {
  33260. return this._isEnabled;
  33261. },
  33262. /**
  33263. * Sets wether the image processing is enabled or not.
  33264. */
  33265. set: function (value) {
  33266. if (this._isEnabled === value) {
  33267. return;
  33268. }
  33269. this._isEnabled = value;
  33270. this._updateParameters();
  33271. },
  33272. enumerable: true,
  33273. configurable: true
  33274. });
  33275. /**
  33276. * Method called each time the image processing information changes requires to recompile the effect.
  33277. */
  33278. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33279. this.onUpdateParameters.notifyObservers(this);
  33280. };
  33281. ImageProcessingConfiguration.prototype.getClassName = function () {
  33282. return "ImageProcessingConfiguration";
  33283. };
  33284. /**
  33285. * Prepare the list of uniforms associated with the Image Processing effects.
  33286. * @param uniformsList The list of uniforms used in the effect
  33287. * @param defines the list of defines currently in use
  33288. */
  33289. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33290. if (defines.EXPOSURE) {
  33291. uniforms.push("exposureLinear");
  33292. }
  33293. if (defines.CONTRAST) {
  33294. uniforms.push("contrast");
  33295. }
  33296. if (defines.COLORGRADING) {
  33297. uniforms.push("colorTransformSettings");
  33298. }
  33299. if (defines.VIGNETTE) {
  33300. uniforms.push("vInverseScreenSize");
  33301. uniforms.push("vignetteSettings1");
  33302. uniforms.push("vignetteSettings2");
  33303. }
  33304. if (defines.COLORCURVES) {
  33305. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33306. }
  33307. };
  33308. /**
  33309. * Prepare the list of samplers associated with the Image Processing effects.
  33310. * @param uniformsList The list of uniforms used in the effect
  33311. * @param defines the list of defines currently in use
  33312. */
  33313. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33314. if (defines.COLORGRADING) {
  33315. samplersList.push("txColorTransform");
  33316. }
  33317. };
  33318. /**
  33319. * Prepare the list of defines associated to the shader.
  33320. * @param defines the list of defines to complete
  33321. */
  33322. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33323. if (forPostProcess === void 0) { forPostProcess = false; }
  33324. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33325. defines.VIGNETTE = false;
  33326. defines.TONEMAPPING = false;
  33327. defines.CONTRAST = false;
  33328. defines.EXPOSURE = false;
  33329. defines.COLORCURVES = false;
  33330. defines.COLORGRADING = false;
  33331. defines.COLORGRADING3D = false;
  33332. defines.IMAGEPROCESSING = false;
  33333. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33334. return;
  33335. }
  33336. defines.VIGNETTE = this.vignetteEnabled;
  33337. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33338. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33339. defines.TONEMAPPING = this.toneMappingEnabled;
  33340. defines.CONTRAST = (this.contrast !== 1.0);
  33341. defines.EXPOSURE = (this.exposure !== 1.0);
  33342. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33343. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33344. if (defines.COLORGRADING) {
  33345. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33346. }
  33347. else {
  33348. defines.COLORGRADING3D = false;
  33349. }
  33350. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33351. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33352. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33353. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33354. };
  33355. /**
  33356. * Returns true if all the image processing information are ready.
  33357. */
  33358. ImageProcessingConfiguration.prototype.isReady = function () {
  33359. // Color Grading texure can not be none blocking.
  33360. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33361. };
  33362. /**
  33363. * Binds the image processing to the shader.
  33364. * @param effect The effect to bind to
  33365. */
  33366. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33367. if (aspectRatio === void 0) { aspectRatio = 1; }
  33368. // Color Curves
  33369. if (this._colorCurvesEnabled && this.colorCurves) {
  33370. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33371. }
  33372. // Vignette
  33373. if (this._vignetteEnabled) {
  33374. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33375. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33376. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33377. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33378. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33379. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33380. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33381. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33382. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33383. var vignettePower = -2.0 * this.vignetteWeight;
  33384. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33385. }
  33386. // Exposure
  33387. effect.setFloat("exposureLinear", this.exposure);
  33388. // Contrast
  33389. effect.setFloat("contrast", this.contrast);
  33390. // Color transform settings
  33391. if (this.colorGradingTexture) {
  33392. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33393. var textureSize = this.colorGradingTexture.getSize().height;
  33394. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33395. 0.5 / textureSize, // textureOffset
  33396. textureSize, // textureSize
  33397. this.colorGradingTexture.level // weight
  33398. );
  33399. }
  33400. };
  33401. /**
  33402. * Clones the current image processing instance.
  33403. * @return The cloned image processing
  33404. */
  33405. ImageProcessingConfiguration.prototype.clone = function () {
  33406. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33407. };
  33408. /**
  33409. * Serializes the current image processing instance to a json representation.
  33410. * @return a JSON representation
  33411. */
  33412. ImageProcessingConfiguration.prototype.serialize = function () {
  33413. return BABYLON.SerializationHelper.Serialize(this);
  33414. };
  33415. /**
  33416. * Parses the image processing from a json representation.
  33417. * @param source the JSON source to parse
  33418. * @return The parsed image processing
  33419. */
  33420. ImageProcessingConfiguration.Parse = function (source) {
  33421. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33422. };
  33423. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33424. /**
  33425. * Used to apply the vignette as a mix with the pixel color.
  33426. */
  33427. get: function () {
  33428. return this._VIGNETTEMODE_MULTIPLY;
  33429. },
  33430. enumerable: true,
  33431. configurable: true
  33432. });
  33433. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33434. /**
  33435. * Used to apply the vignette as a replacement of the pixel color.
  33436. */
  33437. get: function () {
  33438. return this._VIGNETTEMODE_OPAQUE;
  33439. },
  33440. enumerable: true,
  33441. configurable: true
  33442. });
  33443. // Static constants associated to the image processing.
  33444. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33445. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33446. __decorate([
  33447. BABYLON.serializeAsColorCurves()
  33448. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33449. __decorate([
  33450. BABYLON.serialize()
  33451. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33452. __decorate([
  33453. BABYLON.serializeAsTexture()
  33454. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33455. __decorate([
  33456. BABYLON.serialize()
  33457. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33458. __decorate([
  33459. BABYLON.serialize()
  33460. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33461. __decorate([
  33462. BABYLON.serialize()
  33463. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33464. __decorate([
  33465. BABYLON.serialize()
  33466. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33467. __decorate([
  33468. BABYLON.serialize()
  33469. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33470. __decorate([
  33471. BABYLON.serialize()
  33472. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33473. __decorate([
  33474. BABYLON.serialize()
  33475. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33476. __decorate([
  33477. BABYLON.serialize()
  33478. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33479. __decorate([
  33480. BABYLON.serialize()
  33481. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33482. __decorate([
  33483. BABYLON.serialize()
  33484. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33485. __decorate([
  33486. BABYLON.serializeAsColor4()
  33487. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33488. __decorate([
  33489. BABYLON.serialize()
  33490. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33491. __decorate([
  33492. BABYLON.serialize()
  33493. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33494. __decorate([
  33495. BABYLON.serialize()
  33496. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33497. __decorate([
  33498. BABYLON.serialize()
  33499. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33500. __decorate([
  33501. BABYLON.serialize()
  33502. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33503. return ImageProcessingConfiguration;
  33504. }());
  33505. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33506. })(BABYLON || (BABYLON = {}));
  33507. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33508. var BABYLON;
  33509. (function (BABYLON) {
  33510. /**
  33511. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33512. * It can help converting any input color in a desired output one. This can then be used to create effects
  33513. * from sepia, black and white to sixties or futuristic rendering...
  33514. *
  33515. * The only supported format is currently 3dl.
  33516. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33517. */
  33518. var ColorGradingTexture = /** @class */ (function (_super) {
  33519. __extends(ColorGradingTexture, _super);
  33520. /**
  33521. * Instantiates a ColorGradingTexture from the following parameters.
  33522. *
  33523. * @param url The location of the color gradind data (currently only supporting 3dl)
  33524. * @param scene The scene the texture will be used in
  33525. */
  33526. function ColorGradingTexture(url, scene) {
  33527. var _this = _super.call(this, scene) || this;
  33528. if (!url) {
  33529. return _this;
  33530. }
  33531. _this._engine = scene.getEngine();
  33532. _this._textureMatrix = BABYLON.Matrix.Identity();
  33533. _this.name = url;
  33534. _this.url = url;
  33535. _this.hasAlpha = false;
  33536. _this.isCube = false;
  33537. _this.is3D = _this._engine.webGLVersion > 1;
  33538. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33539. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33540. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33541. _this.anisotropicFilteringLevel = 1;
  33542. _this._texture = _this._getFromCache(url, true);
  33543. if (!_this._texture) {
  33544. if (!scene.useDelayedTextureLoading) {
  33545. _this.loadTexture();
  33546. }
  33547. else {
  33548. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33549. }
  33550. }
  33551. return _this;
  33552. }
  33553. /**
  33554. * Returns the texture matrix used in most of the material.
  33555. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33556. */
  33557. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33558. return this._textureMatrix;
  33559. };
  33560. /**
  33561. * Occurs when the file being loaded is a .3dl LUT file.
  33562. */
  33563. ColorGradingTexture.prototype.load3dlTexture = function () {
  33564. var engine = this._engine;
  33565. var texture;
  33566. if (engine.webGLVersion === 1) {
  33567. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33568. }
  33569. else {
  33570. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33571. }
  33572. this._texture = texture;
  33573. var callback = function (text) {
  33574. if (typeof text !== "string") {
  33575. return;
  33576. }
  33577. var data = null;
  33578. var tempData = null;
  33579. var line;
  33580. var lines = text.split('\n');
  33581. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33582. var maxColor = 0;
  33583. for (var i = 0; i < lines.length; i++) {
  33584. line = lines[i];
  33585. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33586. continue;
  33587. if (line.indexOf('#') === 0)
  33588. continue;
  33589. var words = line.split(" ");
  33590. if (size === 0) {
  33591. // Number of space + one
  33592. size = words.length;
  33593. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33594. tempData = new Float32Array(size * size * size * 4);
  33595. continue;
  33596. }
  33597. if (size != 0) {
  33598. var r = Math.max(parseInt(words[0]), 0);
  33599. var g = Math.max(parseInt(words[1]), 0);
  33600. var b = Math.max(parseInt(words[2]), 0);
  33601. maxColor = Math.max(r, maxColor);
  33602. maxColor = Math.max(g, maxColor);
  33603. maxColor = Math.max(b, maxColor);
  33604. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33605. if (tempData) {
  33606. tempData[pixelStorageIndex + 0] = r;
  33607. tempData[pixelStorageIndex + 1] = g;
  33608. tempData[pixelStorageIndex + 2] = b;
  33609. }
  33610. pixelIndexSlice++;
  33611. if (pixelIndexSlice % size == 0) {
  33612. pixelIndexH++;
  33613. pixelIndexSlice = 0;
  33614. if (pixelIndexH % size == 0) {
  33615. pixelIndexW++;
  33616. pixelIndexH = 0;
  33617. }
  33618. }
  33619. }
  33620. }
  33621. if (tempData && data) {
  33622. for (var i = 0; i < tempData.length; i++) {
  33623. if (i > 0 && (i + 1) % 4 === 0) {
  33624. data[i] = 255;
  33625. }
  33626. else {
  33627. var value = tempData[i];
  33628. data[i] = (value / maxColor * 255);
  33629. }
  33630. }
  33631. }
  33632. if (texture.is3D) {
  33633. texture.updateSize(size, size, size);
  33634. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33635. }
  33636. else {
  33637. texture.updateSize(size * size, size);
  33638. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33639. }
  33640. };
  33641. var scene = this.getScene();
  33642. if (scene) {
  33643. scene._loadFile(this.url, callback);
  33644. }
  33645. else {
  33646. this._engine._loadFile(this.url, callback);
  33647. }
  33648. return this._texture;
  33649. };
  33650. /**
  33651. * Starts the loading process of the texture.
  33652. */
  33653. ColorGradingTexture.prototype.loadTexture = function () {
  33654. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33655. this.load3dlTexture();
  33656. }
  33657. };
  33658. /**
  33659. * Clones the color gradind texture.
  33660. */
  33661. ColorGradingTexture.prototype.clone = function () {
  33662. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33663. // Base texture
  33664. newTexture.level = this.level;
  33665. return newTexture;
  33666. };
  33667. /**
  33668. * Called during delayed load for textures.
  33669. */
  33670. ColorGradingTexture.prototype.delayLoad = function () {
  33671. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33672. return;
  33673. }
  33674. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33675. this._texture = this._getFromCache(this.url, true);
  33676. if (!this._texture) {
  33677. this.loadTexture();
  33678. }
  33679. };
  33680. /**
  33681. * Parses a color grading texture serialized by Babylon.
  33682. * @param parsedTexture The texture information being parsedTexture
  33683. * @param scene The scene to load the texture in
  33684. * @param rootUrl The root url of the data assets to load
  33685. * @return A color gradind texture
  33686. */
  33687. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33688. var texture = null;
  33689. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33690. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33691. texture.name = parsedTexture.name;
  33692. texture.level = parsedTexture.level;
  33693. }
  33694. return texture;
  33695. };
  33696. /**
  33697. * Serializes the LUT texture to json format.
  33698. */
  33699. ColorGradingTexture.prototype.serialize = function () {
  33700. if (!this.name) {
  33701. return null;
  33702. }
  33703. var serializationObject = {};
  33704. serializationObject.name = this.name;
  33705. serializationObject.level = this.level;
  33706. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33707. return serializationObject;
  33708. };
  33709. /**
  33710. * Empty line regex stored for GC.
  33711. */
  33712. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33713. return ColorGradingTexture;
  33714. }(BABYLON.BaseTexture));
  33715. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33716. })(BABYLON || (BABYLON = {}));
  33717. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33718. var BABYLON;
  33719. (function (BABYLON) {
  33720. /**
  33721. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33722. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33723. * 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;
  33724. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33725. */
  33726. var ColorCurves = /** @class */ (function () {
  33727. function ColorCurves() {
  33728. this._dirty = true;
  33729. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33730. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33731. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33732. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33733. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33734. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33735. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33736. this._globalHue = 30;
  33737. this._globalDensity = 0;
  33738. this._globalSaturation = 0;
  33739. this._globalExposure = 0;
  33740. this._highlightsHue = 30;
  33741. this._highlightsDensity = 0;
  33742. this._highlightsSaturation = 0;
  33743. this._highlightsExposure = 0;
  33744. this._midtonesHue = 30;
  33745. this._midtonesDensity = 0;
  33746. this._midtonesSaturation = 0;
  33747. this._midtonesExposure = 0;
  33748. this._shadowsHue = 30;
  33749. this._shadowsDensity = 0;
  33750. this._shadowsSaturation = 0;
  33751. this._shadowsExposure = 0;
  33752. }
  33753. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33754. /**
  33755. * Gets the global Hue value.
  33756. * 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).
  33757. */
  33758. get: function () {
  33759. return this._globalHue;
  33760. },
  33761. /**
  33762. * Sets the global Hue value.
  33763. * 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).
  33764. */
  33765. set: function (value) {
  33766. this._globalHue = value;
  33767. this._dirty = true;
  33768. },
  33769. enumerable: true,
  33770. configurable: true
  33771. });
  33772. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33773. /**
  33774. * Gets the global Density value.
  33775. * 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.
  33776. * Values less than zero provide a filter of opposite hue.
  33777. */
  33778. get: function () {
  33779. return this._globalDensity;
  33780. },
  33781. /**
  33782. * Sets the global Density value.
  33783. * 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.
  33784. * Values less than zero provide a filter of opposite hue.
  33785. */
  33786. set: function (value) {
  33787. this._globalDensity = value;
  33788. this._dirty = true;
  33789. },
  33790. enumerable: true,
  33791. configurable: true
  33792. });
  33793. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33794. /**
  33795. * Gets the global Saturation value.
  33796. * 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.
  33797. */
  33798. get: function () {
  33799. return this._globalSaturation;
  33800. },
  33801. /**
  33802. * Sets the global Saturation value.
  33803. * 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.
  33804. */
  33805. set: function (value) {
  33806. this._globalSaturation = value;
  33807. this._dirty = true;
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33813. /**
  33814. * Gets the highlights Hue value.
  33815. * 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).
  33816. */
  33817. get: function () {
  33818. return this._highlightsHue;
  33819. },
  33820. /**
  33821. * Sets the highlights Hue value.
  33822. * 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).
  33823. */
  33824. set: function (value) {
  33825. this._highlightsHue = value;
  33826. this._dirty = true;
  33827. },
  33828. enumerable: true,
  33829. configurable: true
  33830. });
  33831. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33832. /**
  33833. * Gets the highlights Density value.
  33834. * 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.
  33835. * Values less than zero provide a filter of opposite hue.
  33836. */
  33837. get: function () {
  33838. return this._highlightsDensity;
  33839. },
  33840. /**
  33841. * Sets the highlights Density value.
  33842. * 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.
  33843. * Values less than zero provide a filter of opposite hue.
  33844. */
  33845. set: function (value) {
  33846. this._highlightsDensity = value;
  33847. this._dirty = true;
  33848. },
  33849. enumerable: true,
  33850. configurable: true
  33851. });
  33852. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33853. /**
  33854. * Gets the highlights Saturation value.
  33855. * 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.
  33856. */
  33857. get: function () {
  33858. return this._highlightsSaturation;
  33859. },
  33860. /**
  33861. * Sets the highlights Saturation value.
  33862. * 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.
  33863. */
  33864. set: function (value) {
  33865. this._highlightsSaturation = value;
  33866. this._dirty = true;
  33867. },
  33868. enumerable: true,
  33869. configurable: true
  33870. });
  33871. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33872. /**
  33873. * Gets the highlights Exposure value.
  33874. * 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.
  33875. */
  33876. get: function () {
  33877. return this._highlightsExposure;
  33878. },
  33879. /**
  33880. * Sets the highlights Exposure value.
  33881. * 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.
  33882. */
  33883. set: function (value) {
  33884. this._highlightsExposure = value;
  33885. this._dirty = true;
  33886. },
  33887. enumerable: true,
  33888. configurable: true
  33889. });
  33890. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33891. /**
  33892. * Gets the midtones Hue value.
  33893. * 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).
  33894. */
  33895. get: function () {
  33896. return this._midtonesHue;
  33897. },
  33898. /**
  33899. * Sets the midtones Hue value.
  33900. * 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).
  33901. */
  33902. set: function (value) {
  33903. this._midtonesHue = value;
  33904. this._dirty = true;
  33905. },
  33906. enumerable: true,
  33907. configurable: true
  33908. });
  33909. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33910. /**
  33911. * Gets the midtones Density value.
  33912. * 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.
  33913. * Values less than zero provide a filter of opposite hue.
  33914. */
  33915. get: function () {
  33916. return this._midtonesDensity;
  33917. },
  33918. /**
  33919. * Sets the midtones Density value.
  33920. * 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.
  33921. * Values less than zero provide a filter of opposite hue.
  33922. */
  33923. set: function (value) {
  33924. this._midtonesDensity = value;
  33925. this._dirty = true;
  33926. },
  33927. enumerable: true,
  33928. configurable: true
  33929. });
  33930. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33931. /**
  33932. * Gets the midtones Saturation value.
  33933. * 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.
  33934. */
  33935. get: function () {
  33936. return this._midtonesSaturation;
  33937. },
  33938. /**
  33939. * Sets the midtones Saturation value.
  33940. * 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.
  33941. */
  33942. set: function (value) {
  33943. this._midtonesSaturation = value;
  33944. this._dirty = true;
  33945. },
  33946. enumerable: true,
  33947. configurable: true
  33948. });
  33949. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33950. /**
  33951. * Gets the midtones Exposure value.
  33952. * 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.
  33953. */
  33954. get: function () {
  33955. return this._midtonesExposure;
  33956. },
  33957. /**
  33958. * Sets the midtones Exposure value.
  33959. * 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.
  33960. */
  33961. set: function (value) {
  33962. this._midtonesExposure = value;
  33963. this._dirty = true;
  33964. },
  33965. enumerable: true,
  33966. configurable: true
  33967. });
  33968. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33969. /**
  33970. * Gets the shadows Hue value.
  33971. * 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).
  33972. */
  33973. get: function () {
  33974. return this._shadowsHue;
  33975. },
  33976. /**
  33977. * Sets the shadows Hue value.
  33978. * 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).
  33979. */
  33980. set: function (value) {
  33981. this._shadowsHue = value;
  33982. this._dirty = true;
  33983. },
  33984. enumerable: true,
  33985. configurable: true
  33986. });
  33987. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33988. /**
  33989. * Gets the shadows Density value.
  33990. * 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.
  33991. * Values less than zero provide a filter of opposite hue.
  33992. */
  33993. get: function () {
  33994. return this._shadowsDensity;
  33995. },
  33996. /**
  33997. * Sets the shadows Density value.
  33998. * 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.
  33999. * Values less than zero provide a filter of opposite hue.
  34000. */
  34001. set: function (value) {
  34002. this._shadowsDensity = value;
  34003. this._dirty = true;
  34004. },
  34005. enumerable: true,
  34006. configurable: true
  34007. });
  34008. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34009. /**
  34010. * Gets the shadows Saturation value.
  34011. * 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.
  34012. */
  34013. get: function () {
  34014. return this._shadowsSaturation;
  34015. },
  34016. /**
  34017. * Sets the shadows Saturation value.
  34018. * 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.
  34019. */
  34020. set: function (value) {
  34021. this._shadowsSaturation = value;
  34022. this._dirty = true;
  34023. },
  34024. enumerable: true,
  34025. configurable: true
  34026. });
  34027. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34028. /**
  34029. * Gets the shadows Exposure value.
  34030. * 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.
  34031. */
  34032. get: function () {
  34033. return this._shadowsExposure;
  34034. },
  34035. /**
  34036. * Sets the shadows Exposure value.
  34037. * 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.
  34038. */
  34039. set: function (value) {
  34040. this._shadowsExposure = value;
  34041. this._dirty = true;
  34042. },
  34043. enumerable: true,
  34044. configurable: true
  34045. });
  34046. ColorCurves.prototype.getClassName = function () {
  34047. return "ColorCurves";
  34048. };
  34049. /**
  34050. * Binds the color curves to the shader.
  34051. * @param colorCurves The color curve to bind
  34052. * @param effect The effect to bind to
  34053. */
  34054. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34055. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34056. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34057. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34058. if (colorCurves._dirty) {
  34059. colorCurves._dirty = false;
  34060. // Fill in global info.
  34061. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34062. // Compute highlights info.
  34063. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34064. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34065. // Compute midtones info.
  34066. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34067. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34068. // Compute shadows info.
  34069. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34070. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34071. // Compute deltas (neutral is midtones).
  34072. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34073. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34074. }
  34075. if (effect) {
  34076. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34077. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34078. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34079. }
  34080. };
  34081. /**
  34082. * Prepare the list of uniforms associated with the ColorCurves effects.
  34083. * @param uniformsList The list of uniforms used in the effect
  34084. */
  34085. ColorCurves.PrepareUniforms = function (uniformsList) {
  34086. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34087. };
  34088. /**
  34089. * Returns color grading data based on a hue, density, saturation and exposure value.
  34090. * @param filterHue The hue of the color filter.
  34091. * @param filterDensity The density of the color filter.
  34092. * @param saturation The saturation.
  34093. * @param exposure The exposure.
  34094. * @param result The result data container.
  34095. */
  34096. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34097. if (hue == null) {
  34098. return;
  34099. }
  34100. hue = ColorCurves.clamp(hue, 0, 360);
  34101. density = ColorCurves.clamp(density, -100, 100);
  34102. saturation = ColorCurves.clamp(saturation, -100, 100);
  34103. exposure = ColorCurves.clamp(exposure, -100, 100);
  34104. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34105. // so that the maximum filter density is only 50% control. This provides fine control
  34106. // for small values and reasonable range.
  34107. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34108. density *= 0.5;
  34109. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34110. if (density < 0) {
  34111. density *= -1;
  34112. hue = (hue + 180) % 360;
  34113. }
  34114. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34115. result.scaleToRef(2, result);
  34116. result.a = 1 + 0.01 * saturation;
  34117. };
  34118. /**
  34119. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34120. * @param value The input slider value in range [-100,100].
  34121. * @returns Adjusted value.
  34122. */
  34123. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34124. value /= 100;
  34125. var x = Math.abs(value);
  34126. x = Math.pow(x, 2);
  34127. if (value < 0) {
  34128. x *= -1;
  34129. }
  34130. x *= 100;
  34131. return x;
  34132. };
  34133. /**
  34134. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34135. * @param hue The hue (H) input.
  34136. * @param saturation The saturation (S) input.
  34137. * @param brightness The brightness (B) input.
  34138. * @result An RGBA color represented as Vector4.
  34139. */
  34140. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34141. var h = ColorCurves.clamp(hue, 0, 360);
  34142. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34143. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34144. if (s === 0) {
  34145. result.r = v;
  34146. result.g = v;
  34147. result.b = v;
  34148. }
  34149. else {
  34150. // sector 0 to 5
  34151. h /= 60;
  34152. var i = Math.floor(h);
  34153. // fractional part of h
  34154. var f = h - i;
  34155. var p = v * (1 - s);
  34156. var q = v * (1 - s * f);
  34157. var t = v * (1 - s * (1 - f));
  34158. switch (i) {
  34159. case 0:
  34160. result.r = v;
  34161. result.g = t;
  34162. result.b = p;
  34163. break;
  34164. case 1:
  34165. result.r = q;
  34166. result.g = v;
  34167. result.b = p;
  34168. break;
  34169. case 2:
  34170. result.r = p;
  34171. result.g = v;
  34172. result.b = t;
  34173. break;
  34174. case 3:
  34175. result.r = p;
  34176. result.g = q;
  34177. result.b = v;
  34178. break;
  34179. case 4:
  34180. result.r = t;
  34181. result.g = p;
  34182. result.b = v;
  34183. break;
  34184. default:// case 5:
  34185. result.r = v;
  34186. result.g = p;
  34187. result.b = q;
  34188. break;
  34189. }
  34190. }
  34191. result.a = 1;
  34192. };
  34193. /**
  34194. * Returns a value clamped between min and max
  34195. * @param value The value to clamp
  34196. * @param min The minimum of value
  34197. * @param max The maximum of value
  34198. * @returns The clamped value.
  34199. */
  34200. ColorCurves.clamp = function (value, min, max) {
  34201. return Math.min(Math.max(value, min), max);
  34202. };
  34203. /**
  34204. * Clones the current color curve instance.
  34205. * @return The cloned curves
  34206. */
  34207. ColorCurves.prototype.clone = function () {
  34208. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34209. };
  34210. /**
  34211. * Serializes the current color curve instance to a json representation.
  34212. * @return a JSON representation
  34213. */
  34214. ColorCurves.prototype.serialize = function () {
  34215. return BABYLON.SerializationHelper.Serialize(this);
  34216. };
  34217. /**
  34218. * Parses the color curve from a json representation.
  34219. * @param source the JSON source to parse
  34220. * @return The parsed curves
  34221. */
  34222. ColorCurves.Parse = function (source) {
  34223. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34224. };
  34225. __decorate([
  34226. BABYLON.serialize()
  34227. ], ColorCurves.prototype, "_globalHue", void 0);
  34228. __decorate([
  34229. BABYLON.serialize()
  34230. ], ColorCurves.prototype, "_globalDensity", void 0);
  34231. __decorate([
  34232. BABYLON.serialize()
  34233. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34234. __decorate([
  34235. BABYLON.serialize()
  34236. ], ColorCurves.prototype, "_globalExposure", void 0);
  34237. __decorate([
  34238. BABYLON.serialize()
  34239. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34240. __decorate([
  34241. BABYLON.serialize()
  34242. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34243. __decorate([
  34244. BABYLON.serialize()
  34245. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34246. __decorate([
  34247. BABYLON.serialize()
  34248. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34249. __decorate([
  34250. BABYLON.serialize()
  34251. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34252. __decorate([
  34253. BABYLON.serialize()
  34254. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34255. __decorate([
  34256. BABYLON.serialize()
  34257. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34258. __decorate([
  34259. BABYLON.serialize()
  34260. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34261. return ColorCurves;
  34262. }());
  34263. BABYLON.ColorCurves = ColorCurves;
  34264. })(BABYLON || (BABYLON = {}));
  34265. //# sourceMappingURL=babylon.colorCurves.js.map
  34266. //# sourceMappingURL=babylon.behavior.js.map
  34267. var BABYLON;
  34268. (function (BABYLON) {
  34269. var MaterialHelper = /** @class */ (function () {
  34270. function MaterialHelper() {
  34271. }
  34272. MaterialHelper.BindEyePosition = function (effect, scene) {
  34273. if (scene._forcedViewPosition) {
  34274. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34275. return;
  34276. }
  34277. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34278. };
  34279. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34280. defines._needUVs = true;
  34281. defines[key] = true;
  34282. if (texture.getTextureMatrix().isIdentity(true)) {
  34283. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34284. if (texture.coordinatesIndex === 0) {
  34285. defines["MAINUV1"] = true;
  34286. }
  34287. else {
  34288. defines["MAINUV2"] = true;
  34289. }
  34290. }
  34291. else {
  34292. defines[key + "DIRECTUV"] = 0;
  34293. }
  34294. };
  34295. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34296. var matrix = texture.getTextureMatrix();
  34297. if (!matrix.isIdentity(true)) {
  34298. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34299. }
  34300. };
  34301. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34302. if (defines._areMiscDirty) {
  34303. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34304. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34305. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34306. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34307. }
  34308. };
  34309. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34310. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34311. var changed = false;
  34312. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34313. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34314. changed = true;
  34315. }
  34316. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34317. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34318. changed = true;
  34319. }
  34320. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34321. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34322. changed = true;
  34323. }
  34324. if (defines["INSTANCES"] !== useInstances) {
  34325. defines["INSTANCES"] = useInstances;
  34326. changed = true;
  34327. }
  34328. if (changed) {
  34329. defines.markAsUnprocessed();
  34330. }
  34331. };
  34332. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34333. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34334. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34335. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34336. return false;
  34337. }
  34338. defines._normals = defines._needNormals;
  34339. defines._uvs = defines._needUVs;
  34340. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34341. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34342. defines["TANGENT"] = true;
  34343. }
  34344. if (defines._needUVs) {
  34345. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34346. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34347. }
  34348. else {
  34349. defines["UV1"] = false;
  34350. defines["UV2"] = false;
  34351. }
  34352. if (useVertexColor) {
  34353. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34354. defines["VERTEXCOLOR"] = hasVertexColors;
  34355. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34356. }
  34357. if (useBones) {
  34358. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34359. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34360. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34361. }
  34362. else {
  34363. defines["NUM_BONE_INFLUENCERS"] = 0;
  34364. defines["BonesPerMesh"] = 0;
  34365. }
  34366. }
  34367. if (useMorphTargets) {
  34368. var manager = mesh.morphTargetManager;
  34369. if (manager) {
  34370. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34371. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34372. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34373. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34374. }
  34375. else {
  34376. defines["MORPHTARGETS_TANGENT"] = false;
  34377. defines["MORPHTARGETS_NORMAL"] = false;
  34378. defines["MORPHTARGETS"] = false;
  34379. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34380. }
  34381. }
  34382. return true;
  34383. };
  34384. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34385. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34386. if (disableLighting === void 0) { disableLighting = false; }
  34387. if (!defines._areLightsDirty) {
  34388. return defines._needNormals;
  34389. }
  34390. var lightIndex = 0;
  34391. var needNormals = false;
  34392. var needRebuild = false;
  34393. var lightmapMode = false;
  34394. var shadowEnabled = false;
  34395. var specularEnabled = false;
  34396. if (scene.lightsEnabled && !disableLighting) {
  34397. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34398. var light = _a[_i];
  34399. needNormals = true;
  34400. if (defines["LIGHT" + lightIndex] === undefined) {
  34401. needRebuild = true;
  34402. }
  34403. defines["LIGHT" + lightIndex] = true;
  34404. defines["SPOTLIGHT" + lightIndex] = false;
  34405. defines["HEMILIGHT" + lightIndex] = false;
  34406. defines["POINTLIGHT" + lightIndex] = false;
  34407. defines["DIRLIGHT" + lightIndex] = false;
  34408. var type;
  34409. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34410. type = "SPOTLIGHT" + lightIndex;
  34411. }
  34412. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34413. type = "HEMILIGHT" + lightIndex;
  34414. }
  34415. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34416. type = "POINTLIGHT" + lightIndex;
  34417. }
  34418. else {
  34419. type = "DIRLIGHT" + lightIndex;
  34420. }
  34421. defines[type] = true;
  34422. // Specular
  34423. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34424. specularEnabled = true;
  34425. }
  34426. // Shadows
  34427. defines["SHADOW" + lightIndex] = false;
  34428. defines["SHADOWPCF" + lightIndex] = false;
  34429. defines["SHADOWESM" + lightIndex] = false;
  34430. defines["SHADOWCUBE" + lightIndex] = false;
  34431. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34432. var shadowGenerator = light.getShadowGenerator();
  34433. if (shadowGenerator) {
  34434. shadowEnabled = true;
  34435. shadowGenerator.prepareDefines(defines, lightIndex);
  34436. }
  34437. }
  34438. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34439. lightmapMode = true;
  34440. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34441. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34442. }
  34443. else {
  34444. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34445. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34446. }
  34447. lightIndex++;
  34448. if (lightIndex === maxSimultaneousLights)
  34449. break;
  34450. }
  34451. }
  34452. defines["SPECULARTERM"] = specularEnabled;
  34453. defines["SHADOWS"] = shadowEnabled;
  34454. // Resetting all other lights if any
  34455. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34456. if (defines["LIGHT" + index] !== undefined) {
  34457. defines["LIGHT" + index] = false;
  34458. defines["HEMILIGHT" + lightIndex] = false;
  34459. defines["POINTLIGHT" + lightIndex] = false;
  34460. defines["DIRLIGHT" + lightIndex] = false;
  34461. defines["SPOTLIGHT" + lightIndex] = false;
  34462. defines["SHADOW" + lightIndex] = false;
  34463. }
  34464. }
  34465. var caps = scene.getEngine().getCaps();
  34466. if (defines["SHADOWFLOAT"] === undefined) {
  34467. needRebuild = true;
  34468. }
  34469. defines["SHADOWFLOAT"] = shadowEnabled &&
  34470. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34471. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34472. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34473. if (needRebuild) {
  34474. defines.rebuild();
  34475. }
  34476. return needNormals;
  34477. };
  34478. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34479. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34480. var uniformsList;
  34481. var uniformBuffersList = null;
  34482. if (uniformsListOrOptions.uniformsNames) {
  34483. var options = uniformsListOrOptions;
  34484. uniformsList = options.uniformsNames;
  34485. uniformBuffersList = options.uniformBuffersNames;
  34486. samplersList = options.samplers;
  34487. defines = options.defines;
  34488. maxSimultaneousLights = options.maxSimultaneousLights;
  34489. }
  34490. else {
  34491. uniformsList = uniformsListOrOptions;
  34492. if (!samplersList) {
  34493. samplersList = [];
  34494. }
  34495. }
  34496. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34497. if (!defines["LIGHT" + lightIndex]) {
  34498. break;
  34499. }
  34500. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34501. if (uniformBuffersList) {
  34502. uniformBuffersList.push("Light" + lightIndex);
  34503. }
  34504. samplersList.push("shadowSampler" + lightIndex);
  34505. }
  34506. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34507. uniformsList.push("morphTargetInfluences");
  34508. }
  34509. };
  34510. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34511. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34512. if (rank === void 0) { rank = 0; }
  34513. var lightFallbackRank = 0;
  34514. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34515. if (!defines["LIGHT" + lightIndex]) {
  34516. break;
  34517. }
  34518. if (lightIndex > 0) {
  34519. lightFallbackRank = rank + lightIndex;
  34520. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34521. }
  34522. if (!defines["SHADOWS"]) {
  34523. if (defines["SHADOW" + lightIndex]) {
  34524. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34525. }
  34526. if (defines["SHADOWPCF" + lightIndex]) {
  34527. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34528. }
  34529. if (defines["SHADOWESM" + lightIndex]) {
  34530. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34531. }
  34532. }
  34533. }
  34534. return lightFallbackRank++;
  34535. };
  34536. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34537. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34538. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34539. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34540. var manager = mesh.morphTargetManager;
  34541. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34542. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34543. for (var index = 0; index < influencers; index++) {
  34544. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34545. if (normal) {
  34546. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34547. }
  34548. if (tangent) {
  34549. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34550. }
  34551. if (attribs.length > maxAttributesCount) {
  34552. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34553. }
  34554. }
  34555. }
  34556. };
  34557. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34558. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34559. fallbacks.addCPUSkinningFallback(0, mesh);
  34560. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34561. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34562. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34565. }
  34566. }
  34567. };
  34568. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34569. if (defines["INSTANCES"]) {
  34570. attribs.push("world0");
  34571. attribs.push("world1");
  34572. attribs.push("world2");
  34573. attribs.push("world3");
  34574. }
  34575. };
  34576. // Bindings
  34577. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34578. if (light.shadowEnabled && mesh.receiveShadows) {
  34579. var shadowGenerator = light.getShadowGenerator();
  34580. if (shadowGenerator) {
  34581. shadowGenerator.bindShadowLight(lightIndex, effect);
  34582. }
  34583. }
  34584. };
  34585. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34586. light.transferToEffect(effect, lightIndex + "");
  34587. };
  34588. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34589. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34590. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34591. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34592. for (var i = 0; i < len; i++) {
  34593. var light = mesh._lightSources[i];
  34594. var iAsString = i.toString();
  34595. var scaledIntensity = light.getScaledIntensity();
  34596. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34597. MaterialHelper.BindLightProperties(light, effect, i);
  34598. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34599. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34600. if (defines["SPECULARTERM"]) {
  34601. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34602. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34603. }
  34604. // Shadows
  34605. if (scene.shadowsEnabled) {
  34606. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34607. }
  34608. light._uniformBuffer.update();
  34609. }
  34610. };
  34611. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34612. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34613. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34614. effect.setColor3("vFogColor", scene.fogColor);
  34615. }
  34616. };
  34617. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34618. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34619. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34620. if (matrices && effect) {
  34621. effect.setMatrices("mBones", matrices);
  34622. }
  34623. }
  34624. };
  34625. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34626. var manager = abstractMesh.morphTargetManager;
  34627. if (!abstractMesh || !manager) {
  34628. return;
  34629. }
  34630. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34631. };
  34632. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34633. if (defines["LOGARITHMICDEPTH"]) {
  34634. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34635. }
  34636. };
  34637. MaterialHelper.BindClipPlane = function (effect, scene) {
  34638. if (scene.clipPlane) {
  34639. var clipPlane = scene.clipPlane;
  34640. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34641. }
  34642. };
  34643. return MaterialHelper;
  34644. }());
  34645. BABYLON.MaterialHelper = MaterialHelper;
  34646. })(BABYLON || (BABYLON = {}));
  34647. //# sourceMappingURL=babylon.materialHelper.js.map
  34648. var BABYLON;
  34649. (function (BABYLON) {
  34650. var PushMaterial = /** @class */ (function (_super) {
  34651. __extends(PushMaterial, _super);
  34652. function PushMaterial(name, scene) {
  34653. var _this = _super.call(this, name, scene) || this;
  34654. _this.storeEffectOnSubMeshes = true;
  34655. return _this;
  34656. }
  34657. PushMaterial.prototype.getEffect = function () {
  34658. return this._activeEffect;
  34659. };
  34660. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34661. if (!mesh) {
  34662. return false;
  34663. }
  34664. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34665. return true;
  34666. }
  34667. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34668. };
  34669. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34670. this._activeEffect.setMatrix("world", world);
  34671. };
  34672. PushMaterial.prototype.bind = function (world, mesh) {
  34673. if (!mesh) {
  34674. return;
  34675. }
  34676. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34677. };
  34678. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34679. if (effect === void 0) { effect = null; }
  34680. _super.prototype._afterBind.call(this, mesh);
  34681. this.getScene()._cachedEffect = effect;
  34682. };
  34683. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34684. if (visibility === void 0) { visibility = 1; }
  34685. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34686. };
  34687. return PushMaterial;
  34688. }(BABYLON.Material));
  34689. BABYLON.PushMaterial = PushMaterial;
  34690. })(BABYLON || (BABYLON = {}));
  34691. //# sourceMappingURL=babylon.pushMaterial.js.map
  34692. var BABYLON;
  34693. (function (BABYLON) {
  34694. var StandardMaterialDefines = /** @class */ (function (_super) {
  34695. __extends(StandardMaterialDefines, _super);
  34696. function StandardMaterialDefines() {
  34697. var _this = _super.call(this) || this;
  34698. _this.MAINUV1 = false;
  34699. _this.MAINUV2 = false;
  34700. _this.DIFFUSE = false;
  34701. _this.DIFFUSEDIRECTUV = 0;
  34702. _this.AMBIENT = false;
  34703. _this.AMBIENTDIRECTUV = 0;
  34704. _this.OPACITY = false;
  34705. _this.OPACITYDIRECTUV = 0;
  34706. _this.OPACITYRGB = false;
  34707. _this.REFLECTION = false;
  34708. _this.EMISSIVE = false;
  34709. _this.EMISSIVEDIRECTUV = 0;
  34710. _this.SPECULAR = false;
  34711. _this.SPECULARDIRECTUV = 0;
  34712. _this.BUMP = false;
  34713. _this.BUMPDIRECTUV = 0;
  34714. _this.PARALLAX = false;
  34715. _this.PARALLAXOCCLUSION = false;
  34716. _this.SPECULAROVERALPHA = false;
  34717. _this.CLIPPLANE = false;
  34718. _this.ALPHATEST = false;
  34719. _this.DEPTHPREPASS = false;
  34720. _this.ALPHAFROMDIFFUSE = false;
  34721. _this.POINTSIZE = false;
  34722. _this.FOG = false;
  34723. _this.SPECULARTERM = false;
  34724. _this.DIFFUSEFRESNEL = false;
  34725. _this.OPACITYFRESNEL = false;
  34726. _this.REFLECTIONFRESNEL = false;
  34727. _this.REFRACTIONFRESNEL = false;
  34728. _this.EMISSIVEFRESNEL = false;
  34729. _this.FRESNEL = false;
  34730. _this.NORMAL = false;
  34731. _this.UV1 = false;
  34732. _this.UV2 = false;
  34733. _this.VERTEXCOLOR = false;
  34734. _this.VERTEXALPHA = false;
  34735. _this.NUM_BONE_INFLUENCERS = 0;
  34736. _this.BonesPerMesh = 0;
  34737. _this.INSTANCES = false;
  34738. _this.GLOSSINESS = false;
  34739. _this.ROUGHNESS = false;
  34740. _this.EMISSIVEASILLUMINATION = false;
  34741. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34742. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34743. _this.LIGHTMAP = false;
  34744. _this.LIGHTMAPDIRECTUV = 0;
  34745. _this.USELIGHTMAPASSHADOWMAP = false;
  34746. _this.REFLECTIONMAP_3D = false;
  34747. _this.REFLECTIONMAP_SPHERICAL = false;
  34748. _this.REFLECTIONMAP_PLANAR = false;
  34749. _this.REFLECTIONMAP_CUBIC = false;
  34750. _this.REFLECTIONMAP_PROJECTION = false;
  34751. _this.REFLECTIONMAP_SKYBOX = false;
  34752. _this.REFLECTIONMAP_EXPLICIT = false;
  34753. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34754. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34755. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34756. _this.INVERTCUBICMAP = false;
  34757. _this.LOGARITHMICDEPTH = false;
  34758. _this.REFRACTION = false;
  34759. _this.REFRACTIONMAP_3D = false;
  34760. _this.REFLECTIONOVERALPHA = false;
  34761. _this.TWOSIDEDLIGHTING = false;
  34762. _this.SHADOWFLOAT = false;
  34763. _this.MORPHTARGETS = false;
  34764. _this.MORPHTARGETS_NORMAL = false;
  34765. _this.MORPHTARGETS_TANGENT = false;
  34766. _this.NUM_MORPH_INFLUENCERS = 0;
  34767. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34768. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34769. _this.IMAGEPROCESSING = false;
  34770. _this.VIGNETTE = false;
  34771. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34772. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34773. _this.TONEMAPPING = false;
  34774. _this.CONTRAST = false;
  34775. _this.COLORCURVES = false;
  34776. _this.COLORGRADING = false;
  34777. _this.COLORGRADING3D = false;
  34778. _this.SAMPLER3DGREENDEPTH = false;
  34779. _this.SAMPLER3DBGRMAP = false;
  34780. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34781. _this.EXPOSURE = false;
  34782. _this.rebuild();
  34783. return _this;
  34784. }
  34785. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34786. var modes = [
  34787. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34788. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34789. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34790. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34791. ];
  34792. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34793. var mode = modes_1[_i];
  34794. this[mode] = (mode === modeToEnable);
  34795. }
  34796. };
  34797. return StandardMaterialDefines;
  34798. }(BABYLON.MaterialDefines));
  34799. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34800. var StandardMaterial = /** @class */ (function (_super) {
  34801. __extends(StandardMaterial, _super);
  34802. function StandardMaterial(name, scene) {
  34803. var _this = _super.call(this, name, scene) || this;
  34804. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34805. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34806. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34807. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34808. _this.specularPower = 64;
  34809. _this._useAlphaFromDiffuseTexture = false;
  34810. _this._useEmissiveAsIllumination = false;
  34811. _this._linkEmissiveWithDiffuse = false;
  34812. _this._useSpecularOverAlpha = false;
  34813. _this._useReflectionOverAlpha = false;
  34814. _this._disableLighting = false;
  34815. _this._useParallax = false;
  34816. _this._useParallaxOcclusion = false;
  34817. _this.parallaxScaleBias = 0.05;
  34818. _this._roughness = 0;
  34819. _this.indexOfRefraction = 0.98;
  34820. _this.invertRefractionY = true;
  34821. _this._useLightmapAsShadowmap = false;
  34822. _this._useReflectionFresnelFromSpecular = false;
  34823. _this._useGlossinessFromSpecularMapAlpha = false;
  34824. _this._maxSimultaneousLights = 4;
  34825. /**
  34826. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34827. */
  34828. _this._invertNormalMapX = false;
  34829. /**
  34830. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34831. */
  34832. _this._invertNormalMapY = false;
  34833. /**
  34834. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34835. */
  34836. _this._twoSidedLighting = false;
  34837. _this._renderTargets = new BABYLON.SmartArray(16);
  34838. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34839. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34840. // Setup the default processing configuration to the scene.
  34841. _this._attachImageProcessingConfiguration(null);
  34842. _this.getRenderTargetTextures = function () {
  34843. _this._renderTargets.reset();
  34844. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34845. _this._renderTargets.push(_this._reflectionTexture);
  34846. }
  34847. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34848. _this._renderTargets.push(_this._refractionTexture);
  34849. }
  34850. return _this._renderTargets;
  34851. };
  34852. return _this;
  34853. }
  34854. ;
  34855. ;
  34856. ;
  34857. ;
  34858. ;
  34859. ;
  34860. ;
  34861. ;
  34862. ;
  34863. ;
  34864. ;
  34865. ;
  34866. ;
  34867. ;
  34868. ;
  34869. ;
  34870. ;
  34871. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34872. /**
  34873. * Gets the image processing configuration used either in this material.
  34874. */
  34875. get: function () {
  34876. return this._imageProcessingConfiguration;
  34877. },
  34878. /**
  34879. * Sets the Default image processing configuration used either in the this material.
  34880. *
  34881. * If sets to null, the scene one is in use.
  34882. */
  34883. set: function (value) {
  34884. this._attachImageProcessingConfiguration(value);
  34885. // Ensure the effect will be rebuilt.
  34886. this._markAllSubMeshesAsTexturesDirty();
  34887. },
  34888. enumerable: true,
  34889. configurable: true
  34890. });
  34891. /**
  34892. * Attaches a new image processing configuration to the Standard Material.
  34893. * @param configuration
  34894. */
  34895. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34896. var _this = this;
  34897. if (configuration === this._imageProcessingConfiguration) {
  34898. return;
  34899. }
  34900. // Detaches observer.
  34901. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34902. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34903. }
  34904. // Pick the scene configuration if needed.
  34905. if (!configuration) {
  34906. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34907. }
  34908. else {
  34909. this._imageProcessingConfiguration = configuration;
  34910. }
  34911. // Attaches observer.
  34912. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34913. _this._markAllSubMeshesAsImageProcessingDirty();
  34914. });
  34915. };
  34916. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34917. /**
  34918. * Gets wether the color curves effect is enabled.
  34919. */
  34920. get: function () {
  34921. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34922. },
  34923. /**
  34924. * Sets wether the color curves effect is enabled.
  34925. */
  34926. set: function (value) {
  34927. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34933. /**
  34934. * Gets wether the color grading effect is enabled.
  34935. */
  34936. get: function () {
  34937. return this.imageProcessingConfiguration.colorGradingEnabled;
  34938. },
  34939. /**
  34940. * Gets wether the color grading effect is enabled.
  34941. */
  34942. set: function (value) {
  34943. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34949. /**
  34950. * Gets wether tonemapping is enabled or not.
  34951. */
  34952. get: function () {
  34953. return this._imageProcessingConfiguration.toneMappingEnabled;
  34954. },
  34955. /**
  34956. * Sets wether tonemapping is enabled or not
  34957. */
  34958. set: function (value) {
  34959. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. ;
  34965. ;
  34966. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34967. /**
  34968. * The camera exposure used on this material.
  34969. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34970. * This corresponds to a photographic exposure.
  34971. */
  34972. get: function () {
  34973. return this._imageProcessingConfiguration.exposure;
  34974. },
  34975. /**
  34976. * The camera exposure used on this material.
  34977. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34978. * This corresponds to a photographic exposure.
  34979. */
  34980. set: function (value) {
  34981. this._imageProcessingConfiguration.exposure = value;
  34982. },
  34983. enumerable: true,
  34984. configurable: true
  34985. });
  34986. ;
  34987. ;
  34988. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34989. /**
  34990. * Gets The camera contrast used on this material.
  34991. */
  34992. get: function () {
  34993. return this._imageProcessingConfiguration.contrast;
  34994. },
  34995. /**
  34996. * Sets The camera contrast used on this material.
  34997. */
  34998. set: function (value) {
  34999. this._imageProcessingConfiguration.contrast = value;
  35000. },
  35001. enumerable: true,
  35002. configurable: true
  35003. });
  35004. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35005. /**
  35006. * Gets the Color Grading 2D Lookup Texture.
  35007. */
  35008. get: function () {
  35009. return this._imageProcessingConfiguration.colorGradingTexture;
  35010. },
  35011. /**
  35012. * Sets the Color Grading 2D Lookup Texture.
  35013. */
  35014. set: function (value) {
  35015. this._imageProcessingConfiguration.colorGradingTexture = value;
  35016. },
  35017. enumerable: true,
  35018. configurable: true
  35019. });
  35020. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35021. /**
  35022. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35023. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35024. * 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;
  35025. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35026. */
  35027. get: function () {
  35028. return this._imageProcessingConfiguration.colorCurves;
  35029. },
  35030. /**
  35031. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35032. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35033. * 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;
  35034. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35035. */
  35036. set: function (value) {
  35037. this._imageProcessingConfiguration.colorCurves = value;
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. StandardMaterial.prototype.getClassName = function () {
  35043. return "StandardMaterial";
  35044. };
  35045. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35046. get: function () {
  35047. return this._useLogarithmicDepth;
  35048. },
  35049. set: function (value) {
  35050. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35051. this._markAllSubMeshesAsMiscDirty();
  35052. },
  35053. enumerable: true,
  35054. configurable: true
  35055. });
  35056. StandardMaterial.prototype.needAlphaBlending = function () {
  35057. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35058. };
  35059. StandardMaterial.prototype.needAlphaTesting = function () {
  35060. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35061. };
  35062. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35063. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35064. };
  35065. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35066. return this._diffuseTexture;
  35067. };
  35068. /**
  35069. * Child classes can use it to update shaders
  35070. */
  35071. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35072. if (useInstances === void 0) { useInstances = false; }
  35073. if (subMesh.effect && this.isFrozen) {
  35074. if (this._wasPreviouslyReady && subMesh.effect) {
  35075. return true;
  35076. }
  35077. }
  35078. if (!subMesh._materialDefines) {
  35079. subMesh._materialDefines = new StandardMaterialDefines();
  35080. }
  35081. var scene = this.getScene();
  35082. var defines = subMesh._materialDefines;
  35083. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35084. if (defines._renderId === scene.getRenderId()) {
  35085. return true;
  35086. }
  35087. }
  35088. var engine = scene.getEngine();
  35089. // Lights
  35090. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35091. // Textures
  35092. if (defines._areTexturesDirty) {
  35093. defines._needUVs = false;
  35094. defines.MAINUV1 = false;
  35095. defines.MAINUV2 = false;
  35096. if (scene.texturesEnabled) {
  35097. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35098. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35099. return false;
  35100. }
  35101. else {
  35102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35103. }
  35104. }
  35105. else {
  35106. defines.DIFFUSE = false;
  35107. }
  35108. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35109. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35110. return false;
  35111. }
  35112. else {
  35113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35114. }
  35115. }
  35116. else {
  35117. defines.AMBIENT = false;
  35118. }
  35119. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35120. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35121. return false;
  35122. }
  35123. else {
  35124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35125. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35126. }
  35127. }
  35128. else {
  35129. defines.OPACITY = false;
  35130. }
  35131. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35132. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35133. return false;
  35134. }
  35135. else {
  35136. defines._needNormals = true;
  35137. defines.REFLECTION = true;
  35138. defines.ROUGHNESS = (this._roughness > 0);
  35139. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35140. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35141. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35142. switch (this._reflectionTexture.coordinatesMode) {
  35143. case BABYLON.Texture.CUBIC_MODE:
  35144. case BABYLON.Texture.INVCUBIC_MODE:
  35145. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35146. break;
  35147. case BABYLON.Texture.EXPLICIT_MODE:
  35148. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35149. break;
  35150. case BABYLON.Texture.PLANAR_MODE:
  35151. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35152. break;
  35153. case BABYLON.Texture.PROJECTION_MODE:
  35154. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35155. break;
  35156. case BABYLON.Texture.SKYBOX_MODE:
  35157. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35158. break;
  35159. case BABYLON.Texture.SPHERICAL_MODE:
  35160. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35161. break;
  35162. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35163. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35164. break;
  35165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35166. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35167. break;
  35168. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35169. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35170. break;
  35171. }
  35172. }
  35173. }
  35174. else {
  35175. defines.REFLECTION = false;
  35176. }
  35177. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35178. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35179. return false;
  35180. }
  35181. else {
  35182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35183. }
  35184. }
  35185. else {
  35186. defines.EMISSIVE = false;
  35187. }
  35188. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35189. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35190. return false;
  35191. }
  35192. else {
  35193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35194. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35195. }
  35196. }
  35197. else {
  35198. defines.LIGHTMAP = false;
  35199. }
  35200. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35201. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35202. return false;
  35203. }
  35204. else {
  35205. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35206. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35207. }
  35208. }
  35209. else {
  35210. defines.SPECULAR = false;
  35211. }
  35212. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35213. // Bump texure can not be not blocking.
  35214. if (!this._bumpTexture.isReady()) {
  35215. return false;
  35216. }
  35217. else {
  35218. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35219. defines.PARALLAX = this._useParallax;
  35220. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35221. }
  35222. }
  35223. else {
  35224. defines.BUMP = false;
  35225. }
  35226. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35227. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35228. return false;
  35229. }
  35230. else {
  35231. defines._needUVs = true;
  35232. defines.REFRACTION = true;
  35233. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35234. }
  35235. }
  35236. else {
  35237. defines.REFRACTION = false;
  35238. }
  35239. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35240. }
  35241. else {
  35242. defines.DIFFUSE = false;
  35243. defines.AMBIENT = false;
  35244. defines.OPACITY = false;
  35245. defines.REFLECTION = false;
  35246. defines.EMISSIVE = false;
  35247. defines.LIGHTMAP = false;
  35248. defines.BUMP = false;
  35249. defines.REFRACTION = false;
  35250. }
  35251. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35252. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35253. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35254. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35255. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35256. }
  35257. if (defines._areImageProcessingDirty) {
  35258. if (!this._imageProcessingConfiguration.isReady()) {
  35259. return false;
  35260. }
  35261. this._imageProcessingConfiguration.prepareDefines(defines);
  35262. }
  35263. if (defines._areFresnelDirty) {
  35264. if (StandardMaterial.FresnelEnabled) {
  35265. // Fresnel
  35266. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35267. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35268. this._reflectionFresnelParameters) {
  35269. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35270. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35271. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35272. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35273. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35274. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35275. defines._needNormals = true;
  35276. defines.FRESNEL = true;
  35277. }
  35278. }
  35279. else {
  35280. defines.FRESNEL = false;
  35281. }
  35282. }
  35283. // Misc.
  35284. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35285. // Attribs
  35286. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35287. // Values that need to be evaluated on every frame
  35288. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35289. // Get correct effect
  35290. if (defines.isDirty) {
  35291. defines.markAsProcessed();
  35292. scene.resetCachedMaterial();
  35293. // Fallbacks
  35294. var fallbacks = new BABYLON.EffectFallbacks();
  35295. if (defines.REFLECTION) {
  35296. fallbacks.addFallback(0, "REFLECTION");
  35297. }
  35298. if (defines.SPECULAR) {
  35299. fallbacks.addFallback(0, "SPECULAR");
  35300. }
  35301. if (defines.BUMP) {
  35302. fallbacks.addFallback(0, "BUMP");
  35303. }
  35304. if (defines.PARALLAX) {
  35305. fallbacks.addFallback(1, "PARALLAX");
  35306. }
  35307. if (defines.PARALLAXOCCLUSION) {
  35308. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35309. }
  35310. if (defines.SPECULAROVERALPHA) {
  35311. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35312. }
  35313. if (defines.FOG) {
  35314. fallbacks.addFallback(1, "FOG");
  35315. }
  35316. if (defines.POINTSIZE) {
  35317. fallbacks.addFallback(0, "POINTSIZE");
  35318. }
  35319. if (defines.LOGARITHMICDEPTH) {
  35320. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35321. }
  35322. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35323. if (defines.SPECULARTERM) {
  35324. fallbacks.addFallback(0, "SPECULARTERM");
  35325. }
  35326. if (defines.DIFFUSEFRESNEL) {
  35327. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35328. }
  35329. if (defines.OPACITYFRESNEL) {
  35330. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35331. }
  35332. if (defines.REFLECTIONFRESNEL) {
  35333. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35334. }
  35335. if (defines.EMISSIVEFRESNEL) {
  35336. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35337. }
  35338. if (defines.FRESNEL) {
  35339. fallbacks.addFallback(4, "FRESNEL");
  35340. }
  35341. //Attributes
  35342. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35343. if (defines.NORMAL) {
  35344. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35345. }
  35346. if (defines.UV1) {
  35347. attribs.push(BABYLON.VertexBuffer.UVKind);
  35348. }
  35349. if (defines.UV2) {
  35350. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35351. }
  35352. if (defines.VERTEXCOLOR) {
  35353. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35354. }
  35355. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35356. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35357. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35358. var shaderName = "default";
  35359. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35360. "vFogInfos", "vFogColor", "pointSize",
  35361. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35362. "mBones",
  35363. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35364. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35365. "logarithmicDepthConstant", "vTangentSpaceParams"
  35366. ];
  35367. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35368. var uniformBuffers = ["Material", "Scene"];
  35369. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35370. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35371. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35372. uniformsNames: uniforms,
  35373. uniformBuffersNames: uniformBuffers,
  35374. samplers: samplers,
  35375. defines: defines,
  35376. maxSimultaneousLights: this._maxSimultaneousLights
  35377. });
  35378. if (this.customShaderNameResolve) {
  35379. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35380. }
  35381. var join = defines.toString();
  35382. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35383. attributes: attribs,
  35384. uniformsNames: uniforms,
  35385. uniformBuffersNames: uniformBuffers,
  35386. samplers: samplers,
  35387. defines: join,
  35388. fallbacks: fallbacks,
  35389. onCompiled: this.onCompiled,
  35390. onError: this.onError,
  35391. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35392. }, engine), defines);
  35393. this.buildUniformLayout();
  35394. }
  35395. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35396. return false;
  35397. }
  35398. defines._renderId = scene.getRenderId();
  35399. this._wasPreviouslyReady = true;
  35400. return true;
  35401. };
  35402. StandardMaterial.prototype.buildUniformLayout = function () {
  35403. // Order is important !
  35404. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35405. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35406. this._uniformBuffer.addUniform("opacityParts", 4);
  35407. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35408. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35409. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35410. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35411. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35412. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35413. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35414. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35415. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35416. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35417. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35418. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35419. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35420. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35421. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35422. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35423. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35424. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35425. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35426. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35427. this._uniformBuffer.addUniform("specularMatrix", 16);
  35428. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35429. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35430. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35431. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35432. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35433. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35434. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35435. this._uniformBuffer.addUniform("pointSize", 1);
  35436. this._uniformBuffer.create();
  35437. };
  35438. StandardMaterial.prototype.unbind = function () {
  35439. if (this._activeEffect) {
  35440. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35441. this._activeEffect.setTexture("reflection2DSampler", null);
  35442. }
  35443. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35444. this._activeEffect.setTexture("refraction2DSampler", null);
  35445. }
  35446. }
  35447. _super.prototype.unbind.call(this);
  35448. };
  35449. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35450. var scene = this.getScene();
  35451. var defines = subMesh._materialDefines;
  35452. if (!defines) {
  35453. return;
  35454. }
  35455. var effect = subMesh.effect;
  35456. if (!effect) {
  35457. return;
  35458. }
  35459. this._activeEffect = effect;
  35460. // Matrices
  35461. this.bindOnlyWorldMatrix(world);
  35462. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35463. // Bones
  35464. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35465. if (mustRebind) {
  35466. this._uniformBuffer.bindToEffect(effect, "Material");
  35467. this.bindViewProjection(effect);
  35468. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35469. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35470. // Fresnel
  35471. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35472. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35473. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35474. }
  35475. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35476. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35477. }
  35478. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35479. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35480. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35481. }
  35482. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35483. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35484. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35485. }
  35486. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35487. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35488. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35489. }
  35490. }
  35491. // Textures
  35492. if (scene.texturesEnabled) {
  35493. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35494. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35495. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35496. }
  35497. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35498. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35499. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35500. }
  35501. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35502. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35503. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35504. }
  35505. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35506. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35507. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35508. }
  35509. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35510. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35511. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35512. }
  35513. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35514. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35515. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35516. }
  35517. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35518. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35519. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35520. }
  35521. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35522. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35523. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35524. if (scene._mirroredCameraPosition) {
  35525. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35526. }
  35527. else {
  35528. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35529. }
  35530. }
  35531. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35532. var depth = 1.0;
  35533. if (!this._refractionTexture.isCube) {
  35534. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35535. if (this._refractionTexture.depth) {
  35536. depth = this._refractionTexture.depth;
  35537. }
  35538. }
  35539. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35540. }
  35541. }
  35542. // Point size
  35543. if (this.pointsCloud) {
  35544. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35545. }
  35546. if (defines.SPECULARTERM) {
  35547. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35548. }
  35549. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35550. // Diffuse
  35551. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35552. }
  35553. // Textures
  35554. if (scene.texturesEnabled) {
  35555. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35556. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35557. }
  35558. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35559. effect.setTexture("ambientSampler", this._ambientTexture);
  35560. }
  35561. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35562. effect.setTexture("opacitySampler", this._opacityTexture);
  35563. }
  35564. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35565. if (this._reflectionTexture.isCube) {
  35566. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35567. }
  35568. else {
  35569. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35570. }
  35571. }
  35572. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35573. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35574. }
  35575. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35576. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35577. }
  35578. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35579. effect.setTexture("specularSampler", this._specularTexture);
  35580. }
  35581. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35582. effect.setTexture("bumpSampler", this._bumpTexture);
  35583. }
  35584. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35585. var depth = 1.0;
  35586. if (this._refractionTexture.isCube) {
  35587. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35588. }
  35589. else {
  35590. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35591. }
  35592. }
  35593. }
  35594. // Clip plane
  35595. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35596. // Colors
  35597. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35598. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35599. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35600. }
  35601. if (mustRebind || !this.isFrozen) {
  35602. // Lights
  35603. if (scene.lightsEnabled && !this._disableLighting) {
  35604. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35605. }
  35606. // View
  35607. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35608. this.bindView(effect);
  35609. }
  35610. // Fog
  35611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35612. // Morph targets
  35613. if (defines.NUM_MORPH_INFLUENCERS) {
  35614. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35615. }
  35616. // Log. depth
  35617. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35618. // image processing
  35619. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35620. this._imageProcessingConfiguration.bind(this._activeEffect);
  35621. }
  35622. }
  35623. this._uniformBuffer.update();
  35624. this._afterBind(mesh, this._activeEffect);
  35625. };
  35626. StandardMaterial.prototype.getAnimatables = function () {
  35627. var results = [];
  35628. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35629. results.push(this._diffuseTexture);
  35630. }
  35631. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35632. results.push(this._ambientTexture);
  35633. }
  35634. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35635. results.push(this._opacityTexture);
  35636. }
  35637. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35638. results.push(this._reflectionTexture);
  35639. }
  35640. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35641. results.push(this._emissiveTexture);
  35642. }
  35643. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35644. results.push(this._specularTexture);
  35645. }
  35646. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35647. results.push(this._bumpTexture);
  35648. }
  35649. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35650. results.push(this._lightmapTexture);
  35651. }
  35652. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35653. results.push(this._refractionTexture);
  35654. }
  35655. return results;
  35656. };
  35657. StandardMaterial.prototype.getActiveTextures = function () {
  35658. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35659. if (this._diffuseTexture) {
  35660. activeTextures.push(this._diffuseTexture);
  35661. }
  35662. if (this._ambientTexture) {
  35663. activeTextures.push(this._ambientTexture);
  35664. }
  35665. if (this._opacityTexture) {
  35666. activeTextures.push(this._opacityTexture);
  35667. }
  35668. if (this._reflectionTexture) {
  35669. activeTextures.push(this._reflectionTexture);
  35670. }
  35671. if (this._emissiveTexture) {
  35672. activeTextures.push(this._emissiveTexture);
  35673. }
  35674. if (this._specularTexture) {
  35675. activeTextures.push(this._specularTexture);
  35676. }
  35677. if (this._bumpTexture) {
  35678. activeTextures.push(this._bumpTexture);
  35679. }
  35680. if (this._lightmapTexture) {
  35681. activeTextures.push(this._lightmapTexture);
  35682. }
  35683. if (this._refractionTexture) {
  35684. activeTextures.push(this._refractionTexture);
  35685. }
  35686. return activeTextures;
  35687. };
  35688. StandardMaterial.prototype.hasTexture = function (texture) {
  35689. if (_super.prototype.hasTexture.call(this, texture)) {
  35690. return true;
  35691. }
  35692. if (this._diffuseTexture === texture) {
  35693. return true;
  35694. }
  35695. if (this._ambientTexture === texture) {
  35696. return true;
  35697. }
  35698. if (this._opacityTexture === texture) {
  35699. return true;
  35700. }
  35701. if (this._reflectionTexture === texture) {
  35702. return true;
  35703. }
  35704. if (this._emissiveTexture === texture) {
  35705. return true;
  35706. }
  35707. if (this._specularTexture === texture) {
  35708. return true;
  35709. }
  35710. if (this._bumpTexture === texture) {
  35711. return true;
  35712. }
  35713. if (this._lightmapTexture === texture) {
  35714. return true;
  35715. }
  35716. if (this._refractionTexture === texture) {
  35717. return true;
  35718. }
  35719. return false;
  35720. };
  35721. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35722. if (forceDisposeTextures) {
  35723. if (this._diffuseTexture) {
  35724. this._diffuseTexture.dispose();
  35725. }
  35726. if (this._ambientTexture) {
  35727. this._ambientTexture.dispose();
  35728. }
  35729. if (this._opacityTexture) {
  35730. this._opacityTexture.dispose();
  35731. }
  35732. if (this._reflectionTexture) {
  35733. this._reflectionTexture.dispose();
  35734. }
  35735. if (this._emissiveTexture) {
  35736. this._emissiveTexture.dispose();
  35737. }
  35738. if (this._specularTexture) {
  35739. this._specularTexture.dispose();
  35740. }
  35741. if (this._bumpTexture) {
  35742. this._bumpTexture.dispose();
  35743. }
  35744. if (this._lightmapTexture) {
  35745. this._lightmapTexture.dispose();
  35746. }
  35747. if (this._refractionTexture) {
  35748. this._refractionTexture.dispose();
  35749. }
  35750. }
  35751. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35752. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35753. }
  35754. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35755. };
  35756. StandardMaterial.prototype.clone = function (name) {
  35757. var _this = this;
  35758. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35759. result.name = name;
  35760. result.id = name;
  35761. return result;
  35762. };
  35763. StandardMaterial.prototype.serialize = function () {
  35764. return BABYLON.SerializationHelper.Serialize(this);
  35765. };
  35766. // Statics
  35767. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35768. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35769. };
  35770. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35771. get: function () {
  35772. return StandardMaterial._DiffuseTextureEnabled;
  35773. },
  35774. set: function (value) {
  35775. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35776. return;
  35777. }
  35778. StandardMaterial._DiffuseTextureEnabled = value;
  35779. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35780. },
  35781. enumerable: true,
  35782. configurable: true
  35783. });
  35784. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35785. get: function () {
  35786. return StandardMaterial._AmbientTextureEnabled;
  35787. },
  35788. set: function (value) {
  35789. if (StandardMaterial._AmbientTextureEnabled === value) {
  35790. return;
  35791. }
  35792. StandardMaterial._AmbientTextureEnabled = value;
  35793. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35794. },
  35795. enumerable: true,
  35796. configurable: true
  35797. });
  35798. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35799. get: function () {
  35800. return StandardMaterial._OpacityTextureEnabled;
  35801. },
  35802. set: function (value) {
  35803. if (StandardMaterial._OpacityTextureEnabled === value) {
  35804. return;
  35805. }
  35806. StandardMaterial._OpacityTextureEnabled = value;
  35807. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35808. },
  35809. enumerable: true,
  35810. configurable: true
  35811. });
  35812. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35813. get: function () {
  35814. return StandardMaterial._ReflectionTextureEnabled;
  35815. },
  35816. set: function (value) {
  35817. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35818. return;
  35819. }
  35820. StandardMaterial._ReflectionTextureEnabled = value;
  35821. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35822. },
  35823. enumerable: true,
  35824. configurable: true
  35825. });
  35826. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35827. get: function () {
  35828. return StandardMaterial._EmissiveTextureEnabled;
  35829. },
  35830. set: function (value) {
  35831. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35832. return;
  35833. }
  35834. StandardMaterial._EmissiveTextureEnabled = value;
  35835. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35836. },
  35837. enumerable: true,
  35838. configurable: true
  35839. });
  35840. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35841. get: function () {
  35842. return StandardMaterial._SpecularTextureEnabled;
  35843. },
  35844. set: function (value) {
  35845. if (StandardMaterial._SpecularTextureEnabled === value) {
  35846. return;
  35847. }
  35848. StandardMaterial._SpecularTextureEnabled = value;
  35849. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35850. },
  35851. enumerable: true,
  35852. configurable: true
  35853. });
  35854. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35855. get: function () {
  35856. return StandardMaterial._BumpTextureEnabled;
  35857. },
  35858. set: function (value) {
  35859. if (StandardMaterial._BumpTextureEnabled === value) {
  35860. return;
  35861. }
  35862. StandardMaterial._BumpTextureEnabled = value;
  35863. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35864. },
  35865. enumerable: true,
  35866. configurable: true
  35867. });
  35868. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35869. get: function () {
  35870. return StandardMaterial._LightmapTextureEnabled;
  35871. },
  35872. set: function (value) {
  35873. if (StandardMaterial._LightmapTextureEnabled === value) {
  35874. return;
  35875. }
  35876. StandardMaterial._LightmapTextureEnabled = value;
  35877. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35878. },
  35879. enumerable: true,
  35880. configurable: true
  35881. });
  35882. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35883. get: function () {
  35884. return StandardMaterial._RefractionTextureEnabled;
  35885. },
  35886. set: function (value) {
  35887. if (StandardMaterial._RefractionTextureEnabled === value) {
  35888. return;
  35889. }
  35890. StandardMaterial._RefractionTextureEnabled = value;
  35891. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35892. },
  35893. enumerable: true,
  35894. configurable: true
  35895. });
  35896. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35897. get: function () {
  35898. return StandardMaterial._ColorGradingTextureEnabled;
  35899. },
  35900. set: function (value) {
  35901. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35902. return;
  35903. }
  35904. StandardMaterial._ColorGradingTextureEnabled = value;
  35905. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35906. },
  35907. enumerable: true,
  35908. configurable: true
  35909. });
  35910. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35911. get: function () {
  35912. return StandardMaterial._FresnelEnabled;
  35913. },
  35914. set: function (value) {
  35915. if (StandardMaterial._FresnelEnabled === value) {
  35916. return;
  35917. }
  35918. StandardMaterial._FresnelEnabled = value;
  35919. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35920. },
  35921. enumerable: true,
  35922. configurable: true
  35923. });
  35924. // Flags used to enable or disable a type of texture for all Standard Materials
  35925. StandardMaterial._DiffuseTextureEnabled = true;
  35926. StandardMaterial._AmbientTextureEnabled = true;
  35927. StandardMaterial._OpacityTextureEnabled = true;
  35928. StandardMaterial._ReflectionTextureEnabled = true;
  35929. StandardMaterial._EmissiveTextureEnabled = true;
  35930. StandardMaterial._SpecularTextureEnabled = true;
  35931. StandardMaterial._BumpTextureEnabled = true;
  35932. StandardMaterial._LightmapTextureEnabled = true;
  35933. StandardMaterial._RefractionTextureEnabled = true;
  35934. StandardMaterial._ColorGradingTextureEnabled = true;
  35935. StandardMaterial._FresnelEnabled = true;
  35936. __decorate([
  35937. BABYLON.serializeAsTexture("diffuseTexture")
  35938. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35939. __decorate([
  35940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35941. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35942. __decorate([
  35943. BABYLON.serializeAsTexture("ambientTexture")
  35944. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35945. __decorate([
  35946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35947. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35948. __decorate([
  35949. BABYLON.serializeAsTexture("opacityTexture")
  35950. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35951. __decorate([
  35952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35953. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35954. __decorate([
  35955. BABYLON.serializeAsTexture("reflectionTexture")
  35956. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35957. __decorate([
  35958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35959. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35960. __decorate([
  35961. BABYLON.serializeAsTexture("emissiveTexture")
  35962. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35963. __decorate([
  35964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35965. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35966. __decorate([
  35967. BABYLON.serializeAsTexture("specularTexture")
  35968. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35969. __decorate([
  35970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35971. ], StandardMaterial.prototype, "specularTexture", void 0);
  35972. __decorate([
  35973. BABYLON.serializeAsTexture("bumpTexture")
  35974. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35975. __decorate([
  35976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35977. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35978. __decorate([
  35979. BABYLON.serializeAsTexture("lightmapTexture")
  35980. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35981. __decorate([
  35982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35983. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35984. __decorate([
  35985. BABYLON.serializeAsTexture("refractionTexture")
  35986. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35987. __decorate([
  35988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35989. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35990. __decorate([
  35991. BABYLON.serializeAsColor3("ambient")
  35992. ], StandardMaterial.prototype, "ambientColor", void 0);
  35993. __decorate([
  35994. BABYLON.serializeAsColor3("diffuse")
  35995. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35996. __decorate([
  35997. BABYLON.serializeAsColor3("specular")
  35998. ], StandardMaterial.prototype, "specularColor", void 0);
  35999. __decorate([
  36000. BABYLON.serializeAsColor3("emissive")
  36001. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36002. __decorate([
  36003. BABYLON.serialize()
  36004. ], StandardMaterial.prototype, "specularPower", void 0);
  36005. __decorate([
  36006. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36007. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36008. __decorate([
  36009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36010. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36011. __decorate([
  36012. BABYLON.serialize("useEmissiveAsIllumination")
  36013. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36014. __decorate([
  36015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36016. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36017. __decorate([
  36018. BABYLON.serialize("linkEmissiveWithDiffuse")
  36019. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36020. __decorate([
  36021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36022. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36023. __decorate([
  36024. BABYLON.serialize("useSpecularOverAlpha")
  36025. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36026. __decorate([
  36027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36028. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36029. __decorate([
  36030. BABYLON.serialize("useReflectionOverAlpha")
  36031. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36032. __decorate([
  36033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36034. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36035. __decorate([
  36036. BABYLON.serialize("disableLighting")
  36037. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36038. __decorate([
  36039. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36040. ], StandardMaterial.prototype, "disableLighting", void 0);
  36041. __decorate([
  36042. BABYLON.serialize("useParallax")
  36043. ], StandardMaterial.prototype, "_useParallax", void 0);
  36044. __decorate([
  36045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36046. ], StandardMaterial.prototype, "useParallax", void 0);
  36047. __decorate([
  36048. BABYLON.serialize("useParallaxOcclusion")
  36049. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36050. __decorate([
  36051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36052. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36053. __decorate([
  36054. BABYLON.serialize()
  36055. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36056. __decorate([
  36057. BABYLON.serialize("roughness")
  36058. ], StandardMaterial.prototype, "_roughness", void 0);
  36059. __decorate([
  36060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36061. ], StandardMaterial.prototype, "roughness", void 0);
  36062. __decorate([
  36063. BABYLON.serialize()
  36064. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36065. __decorate([
  36066. BABYLON.serialize()
  36067. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36068. __decorate([
  36069. BABYLON.serialize("useLightmapAsShadowmap")
  36070. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36071. __decorate([
  36072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36073. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36074. __decorate([
  36075. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36076. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36077. __decorate([
  36078. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36079. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36080. __decorate([
  36081. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36082. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36083. __decorate([
  36084. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36085. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36086. __decorate([
  36087. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36088. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36089. __decorate([
  36090. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36091. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36092. __decorate([
  36093. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36094. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36095. __decorate([
  36096. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36097. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36098. __decorate([
  36099. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36100. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36101. __decorate([
  36102. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36103. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36104. __decorate([
  36105. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36106. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36107. __decorate([
  36108. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36109. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36110. __decorate([
  36111. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36112. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36113. __decorate([
  36114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36115. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36116. __decorate([
  36117. BABYLON.serialize("maxSimultaneousLights")
  36118. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36119. __decorate([
  36120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36121. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36122. __decorate([
  36123. BABYLON.serialize("invertNormalMapX")
  36124. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36125. __decorate([
  36126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36127. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36128. __decorate([
  36129. BABYLON.serialize("invertNormalMapY")
  36130. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36131. __decorate([
  36132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36133. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36134. __decorate([
  36135. BABYLON.serialize("twoSidedLighting")
  36136. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36137. __decorate([
  36138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36139. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36143. return StandardMaterial;
  36144. }(BABYLON.PushMaterial));
  36145. BABYLON.StandardMaterial = StandardMaterial;
  36146. })(BABYLON || (BABYLON = {}));
  36147. //# sourceMappingURL=babylon.standardMaterial.js.map
  36148. (function() {
  36149. globalObject["BABYLON"] = globalObject["BABYLON"] || BABYLON;
  36150. module.exports = BABYLON;
  36151. })();
  36152. }